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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +67 -6
  2. package/dist/antigravity-hook.js +441 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +441 -95
  5. package/dist/claude-hook.js +441 -80
  6. package/dist/claude-sessionstart-hook.js +473 -93
  7. package/dist/claude-stop-hook.js +441 -95
  8. package/dist/cline.js +290 -95
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +441 -80
  13. package/dist/codex-sessionstart-hook.js +473 -93
  14. package/dist/codex-stop-hook.js +441 -95
  15. package/dist/copilot-hook.js +441 -80
  16. package/dist/copilot-sessionstart-hook.js +473 -93
  17. package/dist/copilot-stop-hook.js +441 -95
  18. package/dist/cursor-hook.js +441 -80
  19. package/dist/cursor-sessionstart-hook.js +473 -93
  20. package/dist/cursor-stop-hook.js +441 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +441 -80
  23. package/dist/dcode-sessionstart-hook.js +473 -93
  24. package/dist/dcode-stop-hook.js +441 -95
  25. package/dist/deepen.js +140 -49
  26. package/dist/devin-hook.js +441 -80
  27. package/dist/devin-sessionstart-hook.js +473 -93
  28. package/dist/devin-stop-hook.js +441 -95
  29. package/dist/droid-hook.js +441 -80
  30. package/dist/droid-sessionstart-hook.js +473 -93
  31. package/dist/droid-stop-hook.js +441 -95
  32. package/dist/dsh.js +297 -95
  33. package/dist/grok-hook.js +441 -80
  34. package/dist/grok-sessionstart-hook.js +473 -93
  35. package/dist/grok-stop-hook.js +441 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +299 -104
  38. package/dist/installer.js +1043 -647
  39. package/dist/kilo.js +299 -104
  40. package/dist/kimi-hook.js +441 -80
  41. package/dist/kimi-sessionstart-hook.js +473 -93
  42. package/dist/kimi-stop-hook.js +441 -95
  43. package/dist/mcp-server.js +261 -86
  44. package/dist/opencode2.js +296 -101
  45. package/dist/pi.js +352 -107
  46. package/dist/prime-agent.js +352 -107
  47. package/dist/qwen-hook.js +441 -80
  48. package/dist/qwen-sessionstart-hook.js +473 -93
  49. package/dist/qwen-stop-hook.js +441 -95
  50. package/dist/status.js +115 -42
  51. package/dist/traecode-hook.js +441 -80
  52. package/dist/traecode-sessionstart-hook.js +473 -93
  53. package/dist/traecode-stop-hook.js +441 -95
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +441 -80
  58. package/dist/zcode-sessionstart-hook.js +473 -93
  59. package/dist/zcode-stop-hook.js +441 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +4 -4
package/dist/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.1";
660
+
642
661
  // src/core/util.ts
643
662
  import { accessSync, constants } from "fs";
644
663
  import { delimiter, join as join6 } from "path";
@@ -662,12 +681,12 @@ function binOnPath(bin) {
662
681
  }
663
682
  }
664
683
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
665
- function semverGte(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(),
@@ -16826,14 +16923,14 @@ import { homedir as homedir6 } from "os";
16826
16923
  import { join as join12 } from "path";
16827
16924
 
16828
16925
  // src/core/status.ts
16829
- import { execFileSync as execFileSync3 } from "child_process";
16926
+ import { execFileSync as execFileSync4 } from "child_process";
16830
16927
 
16831
16928
  // src/core/git.ts
16832
16929
  import { execFileSync as execFileSync2 } from "child_process";
16833
16930
  import { resolve as resolve2 } from "path";
16834
16931
  var GITLOG_HEAD = "gitlog-head:";
16835
16932
  function git(repo, ...args) {
16836
- return execFileSync2("git", ["-C", repo, ...args], {
16933
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16837
16934
  encoding: "utf8",
16838
16935
  maxBuffer: 1 << 28,
16839
16936
  windowsHide: true,
@@ -16879,7 +16976,7 @@ async function gitLogIsCurrent(client, repo, head) {
16879
16976
  }
16880
16977
 
16881
16978
  // src/core/survey.ts
16882
- import { spawn as realSpawn5 } from "child_process";
16979
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16883
16980
  import { createHash as createHash2 } from "crypto";
16884
16981
  import { existsSync as existsSync3 } from "fs";
16885
16982
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
@@ -16988,6 +17085,19 @@ function resolveAgentBin(harness, claudeBin) {
16988
17085
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16989
17086
  }
16990
17087
  }
17088
+ function opencodeCanDefineSurveyAgent(bin) {
17089
+ try {
17090
+ const out = execFileSync3(bin, ["--version"], {
17091
+ encoding: "utf8",
17092
+ timeout: 5e3,
17093
+ windowsHide: true,
17094
+ stdio: ["ignore", "pipe", "ignore"]
17095
+ });
17096
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17097
+ } catch {
17098
+ return false;
17099
+ }
17100
+ }
16991
17101
  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
17102
  var SURVEY_DISALLOWED_TOOLS = [
16993
17103
  "Bash",
@@ -17101,6 +17211,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17101
17211
  seen.add(harness);
17102
17212
  const bin = resolveAgentBin(harness, opts.claudeBin);
17103
17213
  if (!exists(bin)) continue;
17214
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17215
+ continue;
17104
17216
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17105
17217
  model: opts.model,
17106
17218
  budgetUsd: opts.budgetUsd,
@@ -17157,7 +17269,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17157
17269
  var DEEPEN_DIFF_TARGET = 300;
17158
17270
  function commitCount(repoDir) {
17159
17271
  try {
17160
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17272
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17161
17273
  encoding: "utf8",
17162
17274
  windowsHide: true,
17163
17275
  stdio: ["ignore", "pipe", "pipe"]
@@ -17422,6 +17534,7 @@ function pendingReplayable(cursor, now) {
17422
17534
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17423
17535
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17424
17536
  }
17537
+ var MAX_CURSOR_OPS = 8;
17425
17538
  function fingerprintTurns(turns, count) {
17426
17539
  const h = createHash4("sha1").update(String(count));
17427
17540
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -17482,6 +17595,31 @@ async function supportsAppend(client) {
17482
17595
  return false;
17483
17596
  }
17484
17597
  }
17598
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17599
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17600
+ async function settleOps(client, cursor) {
17601
+ const ops = cursor.ops ?? [];
17602
+ const statuses = await Promise.all(
17603
+ ops.map(async (id) => {
17604
+ try {
17605
+ const r = await client.req(
17606
+ "GET",
17607
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17608
+ void 0,
17609
+ [],
17610
+ OP_CHECK_TIMEOUT_MS
17611
+ );
17612
+ if (r.status === 404) return "not_found";
17613
+ return String((await r.json()).status ?? "").toLowerCase();
17614
+ } catch {
17615
+ return "";
17616
+ }
17617
+ })
17618
+ );
17619
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17620
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17621
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17622
+ }
17485
17623
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17486
17624
  var RETAIN_RETRY_ATTEMPTS = 2;
17487
17625
  var REQUEST_BUDGET_MS = 15e3;
@@ -17545,13 +17683,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
17545
17683
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17546
17684
  if (!turns.length) return;
17547
17685
  const refId = `conversation:${sessionId}`;
17548
- const cursor = cursors?.read(sessionId);
17686
+ let cursor = cursors?.read(sessionId);
17687
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17549
17688
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17689
+ let ops = [];
17690
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17691
+ ({ cursor, ops } = await settleOps(client, cursor));
17550
17692
  const plan = planRetain(turns, cursor, {
17551
17693
  appendSupported,
17552
17694
  bank: client.bank,
17553
17695
  path: transcriptPath
17554
17696
  });
17697
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17555
17698
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17556
17699
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17557
17700
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17597,6 +17740,10 @@ ${content}`);
17597
17740
  ...paths ? { paths } : {},
17598
17741
  ...appendSupported ? { appendSupported: true } : {}
17599
17742
  };
17743
+ const accepted = (id) => {
17744
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17745
+ return ops.length ? { ...next, ops } : next;
17746
+ };
17600
17747
  const stillOurs = () => {
17601
17748
  if (!cursors) return true;
17602
17749
  const now = cursors.read(sessionId);
@@ -17605,12 +17752,10 @@ ${content}`);
17605
17752
  if (plan.mode === "replace") {
17606
17753
  const content = renderSessionJsonl(refId, turns, startTs);
17607
17754
  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);
17755
+ const operationId = opId("replace", content);
17756
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17757
+ ops = [];
17758
+ cursors?.write(sessionId, accepted(operationId));
17614
17759
  return;
17615
17760
  }
17616
17761
  const queue = [...outbox];
@@ -17618,7 +17763,7 @@ ${content}`);
17618
17763
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17619
17764
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17620
17765
  }
17621
- cursors?.write(sessionId, { ...next, pending: queue });
17766
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
17622
17767
  for (let i = 0; i < queue.length; i++) {
17623
17768
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17624
17769
  const entry = queue[i];
@@ -17628,12 +17773,13 @@ ${content}`);
17628
17773
  retryUntil
17629
17774
  );
17630
17775
  const remaining = queue.slice(i + 1);
17631
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17776
+ const done = accepted(entry.operationId);
17777
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
17632
17778
  }
17633
17779
  }
17634
17780
 
17635
17781
  // src/core/usage.ts
17636
- import { readFileSync as readFileSync4 } from "fs";
17782
+ import { readFileSync as readFileSync5 } from "fs";
17637
17783
  import { join as join13 } from "path";
17638
17784
  function usageFilePath() {
17639
17785
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17740,11 +17886,8 @@ function buildRetainStamp(cfg, ctx) {
17740
17886
  return { tags, metadata, context };
17741
17887
  }
17742
17888
 
17743
- // src/core/session-start.ts
17744
- import { readFileSync as readFileSync8 } from "fs";
17745
-
17746
17889
  // src/core/skill-sync.ts
17747
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17890
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17748
17891
  import { homedir as homedir7 } from "os";
17749
17892
  import { dirname as dirname8, join as join15 } from "path";
17750
17893
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17780,7 +17923,12 @@ var SKILL_DIRS = {
17780
17923
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17781
17924
  // and dsh's copy with it.
17782
17925
  pi: [".pi", "agent", "skills"],
17783
- "prime-agent": [".prime", "agent", "skills"]
17926
+ "prime-agent": [".prime", "agent", "skills"],
17927
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17928
+ workbuddy: [".workbuddy", "skills"],
17929
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17930
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17931
+ codebuddy: [".codebuddy", "skills"]
17784
17932
  };
17785
17933
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17786
17934
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17814,7 +17962,7 @@ function syncCompanionSkill(harness, opts = {}) {
17814
17962
  const dstMd = join15(dst, "SKILL.md");
17815
17963
  const installed = existsSync6(dstMd);
17816
17964
  if (!installed && !opts.install) return;
17817
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17965
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17818
17966
  cpSync(src, dst, { recursive: true });
17819
17967
  }
17820
17968
  } catch {
@@ -17836,7 +17984,7 @@ function brandWord() {
17836
17984
  }
17837
17985
 
17838
17986
  // src/core/legacy.ts
17839
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17987
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17840
17988
  import { homedir as homedir8 } from "os";
17841
17989
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17842
17990
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17861,7 +18009,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17861
18009
  }
17862
18010
  function readJson(path) {
17863
18011
  try {
17864
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18012
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17865
18013
  return parsed && typeof parsed === "object" ? parsed : void 0;
17866
18014
  } catch {
17867
18015
  return void 0;
@@ -17873,7 +18021,7 @@ function legacyClaudePluginWarning(key) {
17873
18021
  }
17874
18022
 
17875
18023
  // src/core/session-cache.ts
17876
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18024
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17877
18025
  import { tmpdir as tmpdir3 } from "os";
17878
18026
  import { dirname as dirname9, join as join17 } from "path";
17879
18027
  function sessionCacheFile(harness, sessionId) {
@@ -17881,7 +18029,7 @@ function sessionCacheFile(harness, sessionId) {
17881
18029
  }
17882
18030
  function readSessionCache(cacheFile) {
17883
18031
  try {
17884
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18032
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17885
18033
  } catch {
17886
18034
  return {};
17887
18035
  }
@@ -17925,9 +18073,9 @@ async function gitSyncNote(args) {
17925
18073
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17926
18074
  let target = DEEPEN_DIFF_TARGET;
17927
18075
  try {
17928
- const { execFileSync: execFileSync4 } = await import("child_process");
18076
+ const { execFileSync: execFileSync5 } = await import("child_process");
17929
18077
  const n = Number(
17930
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18078
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17931
18079
  encoding: "utf8",
17932
18080
  windowsHide: true,
17933
18081
  stdio: ["ignore", "pipe", "pipe"]
@@ -17944,6 +18092,7 @@ async function buildSessionStartContext(args) {
17944
18092
  const t0 = Date.now();
17945
18093
  let cold;
17946
18094
  let gitDocIds;
18095
+ let bankEmpty = false;
17947
18096
  const harness = args.harness ?? "claude-code";
17948
18097
  const hasGit = args.hasGit ?? hasGitHistory;
17949
18098
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17983,11 +18132,21 @@ async function buildSessionStartContext(args) {
17983
18132
  } catch {
17984
18133
  docIds = void 0;
17985
18134
  }
17986
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18135
+ let baselines;
18136
+ if (docIds?.size === 0) {
18137
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18138
+ }
18139
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17987
18140
  gitDocIds = docIds;
18141
+ if (cold === true && client.hasDocuments) {
18142
+ bankEmpty = await client.hasDocuments().then(
18143
+ (has) => !has,
18144
+ () => false
18145
+ );
18146
+ }
17988
18147
  if (docIds !== void 0) {
17989
18148
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17990
- if (docIds.size === 0) {
18149
+ if (cold) {
17991
18150
  if (cfg.codebaseSurvey !== false) {
17992
18151
  const started = await startSurvey(cwd, {
17993
18152
  harness,
@@ -18001,7 +18160,7 @@ async function buildSessionStartContext(args) {
18001
18160
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
18002
18161
  const sha = resolveHeadSha(cwd);
18003
18162
  if (sha) {
18004
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18163
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18005
18164
  const counts = [];
18006
18165
  for (const id of markers) {
18007
18166
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18035,10 +18194,8 @@ async function buildSessionStartContext(args) {
18035
18194
  }
18036
18195
  }
18037
18196
  let pages = [];
18038
- let pageListKnown = false;
18039
18197
  try {
18040
18198
  pages = parsePageList(await client.listPages());
18041
- pageListKnown = true;
18042
18199
  } catch {
18043
18200
  if (client.knowledgePagesSupported === false) {
18044
18201
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18048,7 +18205,7 @@ async function buildSessionStartContext(args) {
18048
18205
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18049
18206
  extra: cfg.toolGuideExtra
18050
18207
  });
18051
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18208
+ const deferInitialReflect = bankEmpty;
18052
18209
  let gitNote;
18053
18210
  if (gitDocIds) {
18054
18211
  gitNote = await gitSyncNote({
@@ -18072,7 +18229,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18072
18229
  }
18073
18230
 
18074
18231
  // src/core/hook.ts
18075
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18232
+ import { existsSync as existsSync8 } from "fs";
18076
18233
 
18077
18234
  // src/core/inject.ts
18078
18235
  function buildReflectQuery(prompt) {
@@ -18163,9 +18320,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18163
18320
 
18164
18321
  // src/core/hook.ts
18165
18322
  var HOOK_INJECT_ATTEMPTS = 2;
18323
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18166
18324
  function resolveInjection(got, attempts) {
18167
18325
  if (got != null) return got;
18168
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18326
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18327
+ return attempts >= budget ? "" : void 0;
18328
+ }
18329
+ var RECALL_QUERY_MAX_TOKENS = 500;
18330
+ function boundRecallQuery(prompt) {
18331
+ let cost = 0;
18332
+ let end = 0;
18333
+ for (const ch of prompt) {
18334
+ const cp = ch.codePointAt(0);
18335
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18336
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18337
+ end += ch.length;
18338
+ }
18339
+ return prompt.slice(0, end);
18169
18340
  }
18170
18341
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18171
18342
  const t0 = Date.now();
@@ -18181,7 +18352,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18181
18352
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18182
18353
  const t0 = Date.now();
18183
18354
  try {
18184
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18355
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18185
18356
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18186
18357
  return observations.length ? formatRecallFallback(observations, lead) : null;
18187
18358
  } catch (e) {
@@ -18256,7 +18427,7 @@ async function buildHookOutput(args) {
18256
18427
  answer: reflectAnswer.slice(0, 8e3)
18257
18428
  });
18258
18429
  } catch (e) {
18259
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18430
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18260
18431
  reflectFailed = true;
18261
18432
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18262
18433
  error: describeError(e)
@@ -18328,6 +18499,7 @@ async function buildHookOutput(args) {
18328
18499
 
18329
18500
  // src/core/runtime.ts
18330
18501
  var HARNESS = "opencode";
18502
+ var FLUSH_TIMEOUT_MS = 1e4;
18331
18503
  var RuntimeCore = class {
18332
18504
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18333
18505
  this.client = client;
@@ -18353,6 +18525,8 @@ var RuntimeCore = class {
18353
18525
  usageCursors = memoryUsageCursorStore();
18354
18526
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18355
18527
  fetchTranscript;
18528
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18529
+ inFlight = /* @__PURE__ */ new Set();
18356
18530
  lastInjection = "";
18357
18531
  // most recent turn's injection block, keyed by nothing (see getInjection)
18358
18532
  deferInitialReflect = false;
@@ -18485,8 +18659,9 @@ var RuntimeCore = class {
18485
18659
  */
18486
18660
  async onTranscript(sessionId, turns, lastTurnComplete) {
18487
18661
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18488
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18662
+ if (!sessionId || !turns.length) return;
18489
18663
  this.recordUsage(sessionId, turns, lastTurnComplete);
18664
+ if (!this.writeBackEnabled) return;
18490
18665
  const st = this.stateFor(sessionId);
18491
18666
  this.retain(sessionId, turns, st.startTs);
18492
18667
  }
@@ -18504,7 +18679,7 @@ var RuntimeCore = class {
18504
18679
  */
18505
18680
  async onSessionIdle(sessionId) {
18506
18681
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18507
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18682
+ if (!sessionId || !this.fetchTranscript) return;
18508
18683
  let turns;
18509
18684
  try {
18510
18685
  turns = await this.fetchTranscript(sessionId);
@@ -18517,6 +18692,7 @@ var RuntimeCore = class {
18517
18692
  }
18518
18693
  if (!turns.length) return;
18519
18694
  this.recordUsage(sessionId, turns, true);
18695
+ if (!this.writeBackEnabled) return;
18520
18696
  const st = this.stateFor(sessionId);
18521
18697
  if (turns.length <= st.retainedTurns) return;
18522
18698
  st.retainedTurns = turns.length;
@@ -18544,10 +18720,27 @@ var RuntimeCore = class {
18544
18720
  }
18545
18721
  return st;
18546
18722
  }
18723
+ /**
18724
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18725
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18726
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18727
+ * stalled server cannot hold the host's exit open. Never throws.
18728
+ */
18729
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18730
+ if (!this.inFlight.size) return;
18731
+ let timer;
18732
+ await Promise.race([
18733
+ Promise.all(this.inFlight),
18734
+ new Promise((r) => {
18735
+ timer = setTimeout(r, timeoutMs);
18736
+ })
18737
+ ]);
18738
+ clearTimeout(timer);
18739
+ }
18547
18740
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18548
18741
  retain(sessionId, turns, startTs, trigger = "turn") {
18549
18742
  const t0 = Date.now();
18550
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18743
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18551
18744
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18552
18745
  cursors: this.cursors,
18553
18746
  stamp: buildRetainStamp(this.cfg, {
@@ -18572,6 +18765,8 @@ var RuntimeCore = class {
18572
18765
  trigger
18573
18766
  })
18574
18767
  );
18768
+ this.inFlight.add(write2);
18769
+ void write2.finally(() => this.inFlight.delete(write2));
18575
18770
  }
18576
18771
  };
18577
18772
 
@@ -18667,6 +18862,7 @@ function injectionMessage(text) {
18667
18862
  };
18668
18863
  }
18669
18864
  function createDshHooks(resolve3) {
18865
+ const lastInjected = /* @__PURE__ */ new Map();
18670
18866
  return {
18671
18867
  sessionStart({ agent }) {
18672
18868
  const workspace = resolve3(agent);
@@ -18690,6 +18886,11 @@ function createDshHooks(resolve3) {
18690
18886
  diag(HARNESS2, "inject_empty", { session: sessionId });
18691
18887
  return decision;
18692
18888
  }
18889
+ if (injection === lastInjected.get(sessionId)) {
18890
+ diag(HARNESS2, "inject_unchanged", { session: sessionId });
18891
+ return decision;
18892
+ }
18893
+ lastInjected.set(sessionId, injection);
18693
18894
  diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
18694
18895
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
18695
18896
  },
@@ -18702,6 +18903,7 @@ function createDshHooks(resolve3) {
18702
18903
  },
18703
18904
  disposed({ agent }) {
18704
18905
  liveAgents.delete(agent.session.header.id);
18906
+ lastInjected.delete(agent.session.header.id);
18705
18907
  }
18706
18908
  };
18707
18909
  }