@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/cline.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/core/config.ts
8
- import { readFileSync as readFileSync2 } from "fs";
8
+ import { readFileSync as readFileSync3 } from "fs";
9
9
  import { homedir as homedir3 } from "os";
10
10
  import { join as join7 } from "path";
11
11
 
@@ -48,6 +48,7 @@ import { homedir as homedir2 } from "os";
48
48
  import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
49
49
 
50
50
  // src/core/diag.ts
51
+ import { readFileSync } from "fs";
51
52
  import { join as join3 } from "path";
52
53
 
53
54
  // src/core/log.ts
@@ -123,7 +124,7 @@ function diag(harness, event, extra = {}) {
123
124
  }
124
125
 
125
126
  // src/core/git-layout.ts
126
- import { lstatSync, readFileSync, realpathSync } from "fs";
127
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
127
128
  import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
128
129
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
129
130
  var ATTEMPTS = 3;
@@ -147,7 +148,7 @@ function entryKind(path) {
147
148
  }
148
149
  function readTextOrNull(path) {
149
150
  try {
150
- return readFileSync(path, "utf8");
151
+ return readFileSync2(path, "utf8");
151
152
  } catch (error51) {
152
153
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
153
154
  return null;
@@ -362,6 +363,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
362
363
  };
363
364
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
364
365
  }
366
+ function bankProjectName(config2, directory, sessionRoot) {
367
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
368
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
369
+ if (!dynamic) return void 0;
370
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
371
+ if (!template.includes("{gitProject}")) return void 0;
372
+ try {
373
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
374
+ } catch (error51) {
375
+ if (error51 instanceof BankResolutionError) return void 0;
376
+ throw error51;
377
+ }
378
+ }
365
379
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
366
380
  try {
367
381
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -379,7 +393,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
379
393
  // src/core/missions.ts
380
394
  import { createHash } from "crypto";
381
395
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
382
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
396
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
383
397
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
384
398
  var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
385
399
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -455,6 +469,8 @@ var KNOWLEDGE_LABELS = {
455
469
  ]
456
470
  };
457
471
  function pageScopeRule(project) {
472
+ if (project === void 0)
473
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
458
474
  return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
459
475
  }
460
476
  var PAGE_TAXONOMY = [
@@ -636,6 +652,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
636
652
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
637
653
  }
638
654
 
655
+ // package.json
656
+ var version = "0.8.1";
657
+
639
658
  // src/core/util.ts
640
659
  import { accessSync, constants } from "fs";
641
660
  import { delimiter, join as join6 } from "path";
@@ -659,12 +678,12 @@ function binOnPath(bin) {
659
678
  }
660
679
  }
661
680
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
662
- function semverGte(version2, min) {
681
+ function semverGte(version3, min) {
663
682
  const parts = (v) => {
664
683
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
665
684
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
666
685
  };
667
- const a = version2 ? parts(version2) : void 0;
686
+ const a = version3 ? parts(version3) : void 0;
668
687
  const b = parts(min);
669
688
  if (!a || !b) return false;
670
689
  for (let i = 0; i < 3; i++) {
@@ -689,6 +708,7 @@ async function pool(items, n, fn, onError, onProgress) {
689
708
  }
690
709
 
691
710
  // src/core/hindsight.ts
711
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
692
712
  function resolveRetainScopes(tags, configured) {
693
713
  if (configured !== "per_source") return configured;
694
714
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -724,7 +744,7 @@ async function isEndpointMissing(r) {
724
744
  const j = await r.json();
725
745
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
726
746
  } catch {
727
- return true;
747
+ return false;
728
748
  }
729
749
  }
730
750
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -743,6 +763,12 @@ var ReflectError = class extends Error {
743
763
  get fallbackEligible() {
744
764
  return this.timedOut || this.status !== void 0 && this.status >= 500;
745
765
  }
766
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
767
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
768
+ get permanent() {
769
+ const s = this.status;
770
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
771
+ }
746
772
  };
747
773
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
748
774
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -753,8 +779,10 @@ var DEFAULT_RECALL_OPTIONS = {
753
779
  include: { entities: null }
754
780
  };
755
781
  var POLL_CYCLE_MS = 5e3;
782
+ var POLL_MAX_SERVER_ERRORS = 12;
756
783
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
757
784
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
785
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
758
786
  function shapePage(page) {
759
787
  const p = page ?? {};
760
788
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -767,6 +795,15 @@ function shapePage(page) {
767
795
  body
768
796
  };
769
797
  }
798
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
799
+ function signalOnlyDispatcher() {
800
+ void globalThis.Headers;
801
+ const d = globalThis[GLOBAL_DISPATCHER];
802
+ if (typeof d?.compose !== "function") return void 0;
803
+ return d.compose(
804
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
805
+ );
806
+ }
770
807
  var HindsightClient = class {
771
808
  apiUrl;
772
809
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -786,6 +823,7 @@ var HindsightClient = class {
786
823
  observationScopes;
787
824
  pageSearchLimit;
788
825
  recallOptions;
826
+ rateLimitPatienceMs;
789
827
  constructor(o) {
790
828
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
791
829
  this.token = o.apiToken;
@@ -798,6 +836,7 @@ var HindsightClient = class {
798
836
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
799
837
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
800
838
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
839
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
801
840
  }
802
841
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
803
842
  get apiToken() {
@@ -806,7 +845,8 @@ var HindsightClient = class {
806
845
  headers() {
807
846
  const h = {
808
847
  "Content-Type": "application/json",
809
- "Accept-Encoding": "identity"
848
+ "Accept-Encoding": "identity",
849
+ "User-Agent": USER_AGENT
810
850
  };
811
851
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
812
852
  return h;
@@ -838,7 +878,8 @@ var HindsightClient = class {
838
878
  * bounds the whole call.
839
879
  */
840
880
  async fetchWithAuth(url2, init) {
841
- const send = () => fetch(url2, { ...init, headers: this.headers() });
881
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
882
+ const send = () => fetch(url2, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
842
883
  const r = await send();
843
884
  if (r.status !== 401 || !this.refreshToken()) return r;
844
885
  return send();
@@ -854,13 +895,22 @@ var HindsightClient = class {
854
895
  }
855
896
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
856
897
  async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
857
- const r = await this.fetchWithAuth(url2, {
858
- method,
859
- body: body ? JSON.stringify(body) : void 0,
860
- signal: AbortSignal.timeout(timeoutMs)
861
- });
862
- if (r.status === 429 && !tolerate.includes(429))
863
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
898
+ const payload = body ? JSON.stringify(body) : void 0;
899
+ let r;
900
+ for (let attempt = 0, waited = 0; ; attempt++) {
901
+ r = await this.fetchWithAuth(url2, {
902
+ method,
903
+ body: payload,
904
+ signal: AbortSignal.timeout(timeoutMs)
905
+ });
906
+ if (r.status !== 429 || tolerate.includes(429)) break;
907
+ const asked = retryAfterMs(r.headers.get("retry-after"));
908
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
909
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
910
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
911
+ await sleep(wait);
912
+ waited += wait;
913
+ }
864
914
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
865
915
  throw new Error(
866
916
  `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -895,7 +945,7 @@ var HindsightClient = class {
895
945
  }
896
946
  /**
897
947
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
898
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
948
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
899
949
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
900
950
  */
901
951
  async supportsIdempotentRetain() {
@@ -905,15 +955,21 @@ var HindsightClient = class {
905
955
  }
906
956
  return this.idempotentRetain;
907
957
  }
958
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
959
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
960
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
961
+ * `/version`, so that stays as the fallback. */
908
962
  async probeIdempotentRetain() {
909
- try {
910
- const r = await this.req("GET", `${this.apiUrl}/version`);
911
- if (!r.ok) return false;
912
- const j = await r.json();
913
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
914
- } catch {
915
- return false;
963
+ for (const path of ["/v1/version", "/version"]) {
964
+ try {
965
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
966
+ if (!r.ok) continue;
967
+ const j = await r.json();
968
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
969
+ } catch {
970
+ }
916
971
  }
972
+ return false;
917
973
  }
918
974
  /**
919
975
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -975,6 +1031,14 @@ var HindsightClient = class {
975
1031
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
976
1032
  }
977
1033
  }
1034
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1035
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1036
+ async hasDocuments() {
1037
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1038
+ if (r.status === 404) return false;
1039
+ const j = await r.json();
1040
+ return (j.total ?? j.items?.length ?? 0) > 0;
1041
+ }
978
1042
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
979
1043
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
980
1044
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1056,7 +1120,13 @@ var HindsightClient = class {
1056
1120
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1057
1121
  const start = Date.now();
1058
1122
  const pending = new Set(ids);
1123
+ const serverErrors = /* @__PURE__ */ new Map();
1059
1124
  let failed = 0;
1125
+ const giveUp = (id, status) => {
1126
+ pending.delete(id);
1127
+ failed++;
1128
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1129
+ };
1060
1130
  while (pending.size && Date.now() - start < maxMs) {
1061
1131
  let backoffMs = POLL_CYCLE_MS;
1062
1132
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1069,7 +1139,14 @@ var HindsightClient = class {
1069
1139
  );
1070
1140
  return;
1071
1141
  }
1072
- if (!r.ok) return;
1142
+ if (r.status >= 500) {
1143
+ const n = (serverErrors.get(id) ?? 0) + 1;
1144
+ serverErrors.set(id, n);
1145
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1146
+ return;
1147
+ }
1148
+ if (!r.ok) return giveUp(id, r.status);
1149
+ serverErrors.delete(id);
1073
1150
  const st = ((await r.json()).status || "").toLowerCase();
1074
1151
  if (TERMINAL.has(st)) {
1075
1152
  pending.delete(id);
@@ -1253,7 +1330,7 @@ var HindsightClient = class {
1253
1330
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1254
1331
  */
1255
1332
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1256
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1333
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1257
1334
  const existing = /* @__PURE__ */ new Map();
1258
1335
  let roots;
1259
1336
  try {
@@ -1328,7 +1405,7 @@ var HindsightClient = class {
1328
1405
  }
1329
1406
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1330
1407
  this.log(
1331
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1408
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1332
1409
  );
1333
1410
  }
1334
1411
  /**
@@ -1339,23 +1416,33 @@ var HindsightClient = class {
1339
1416
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1340
1417
  * consolidation under the auto-refresh that used to be the default (#3506).
1341
1418
  *
1342
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1343
- * initiative's own title, and re-stating either would rebuild a page whose question never
1344
- * changed. The tree read above is reused rather than re-fetched.
1419
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1420
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1421
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1422
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1423
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1424
+ * reused rather than re-fetched.
1345
1425
  */
1346
1426
  async resyncInitiativeTriggers(roots, pageTrigger) {
1347
1427
  const folder = roots.find(
1348
1428
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1349
1429
  );
1430
+ const bankScope = pageScopeRule(this.bank);
1350
1431
  let updated = 0;
1351
1432
  for (const page of folder?.children ?? []) {
1352
- if (page.kind !== "page" || page.trigger == null) continue;
1353
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1354
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1433
+ if (page.kind !== "page") continue;
1434
+ const patch = {};
1435
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1436
+ if (query !== page.description) patch.source_query = query;
1437
+ if (page.trigger != null) {
1438
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1439
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1440
+ }
1441
+ if (!patch.trigger && !patch.source_query) continue;
1355
1442
  const r = await this.req(
1356
1443
  "PATCH",
1357
1444
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1358
- { trigger: pageTriggerPatch(desired) }
1445
+ patch
1359
1446
  );
1360
1447
  if (r.status === 404) continue;
1361
1448
  updated++;
@@ -1383,10 +1470,9 @@ var HindsightClient = class {
1383
1470
  let pageId = args.relatesToPageId;
1384
1471
  if (!pageId) {
1385
1472
  const folderId = await this.ensureFolder("Initiatives");
1386
- const subject = this.project ?? this.bank;
1387
1473
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1388
1474
  name: args.title,
1389
- source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(subject),
1475
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
1390
1476
  parent_id: folderId,
1391
1477
  tags: ["knowledge:feature-work"],
1392
1478
  max_tokens: PAGE_MAX_TOKENS,
@@ -1401,7 +1487,7 @@ var HindsightClient = class {
1401
1487
  }
1402
1488
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1403
1489
  const content = `${verb}: ${args.title}. ${args.summary}`;
1404
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1490
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1405
1491
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1406
1492
  const context = `initiative marker for [[page:${pageId}]]`;
1407
1493
  await this.retain(content, context, markerId, tags, "document", {
@@ -1638,7 +1724,7 @@ function resolveConfig(raw = {}) {
1638
1724
  }
1639
1725
  function readRaw(path) {
1640
1726
  try {
1641
- return JSON.parse(readFileSync2(path, "utf8"));
1727
+ return JSON.parse(readFileSync3(path, "utf8"));
1642
1728
  } catch (e) {
1643
1729
  if (e?.code !== "ENOENT") {
1644
1730
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1825,10 +1911,12 @@ function resolveHostConfig(harness, directory) {
1825
1911
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1826
1912
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1827
1913
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1828
- return applyBankConfig(cfg0, bankId, directory);
1914
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
1915
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
1916
+ return { ...resolved2, project };
1829
1917
  }
1830
1918
  function resolveHostMemory(harness, directory) {
1831
- const { cfg, bankId } = resolveHostConfig(harness, directory);
1919
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
1832
1920
  return {
1833
1921
  cfg,
1834
1922
  bankId,
@@ -1836,6 +1924,8 @@ function resolveHostMemory(harness, directory) {
1836
1924
  apiUrl: cfg.apiUrl,
1837
1925
  apiToken: cfg.apiToken,
1838
1926
  bank: bankId,
1927
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
1928
+ project,
1839
1929
  maxParallelRetains: cfg.maxParallelRetains,
1840
1930
  observationScopes: cfg.observationScopes,
1841
1931
  pageSearchLimit: cfg.pageSearchLimit,
@@ -1859,7 +1949,7 @@ import { spawn as realSpawn2 } from "child_process";
1859
1949
  import {
1860
1950
  existsSync as existsSync2,
1861
1951
  mkdirSync as mkdirSync2,
1862
- readFileSync as readFileSync3,
1952
+ readFileSync as readFileSync4,
1863
1953
  realpathSync as realpathSync2,
1864
1954
  unlinkSync,
1865
1955
  writeFileSync
@@ -1890,7 +1980,7 @@ function sameDir(a, b) {
1890
1980
  }
1891
1981
  function stagedVersion(pkgRoot) {
1892
1982
  try {
1893
- const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1983
+ const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
1894
1984
  return typeof pkg.version === "string" ? pkg.version : "";
1895
1985
  } catch {
1896
1986
  return "";
@@ -1915,7 +2005,7 @@ function isNewer(candidate, current2) {
1915
2005
  }
1916
2006
  function dueForCheck(file2, now) {
1917
2007
  try {
1918
- const state = JSON.parse(readFileSync3(file2, "utf8"));
2008
+ const state = JSON.parse(readFileSync4(file2, "utf8"));
1919
2009
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1920
2010
  } catch {
1921
2011
  return true;
@@ -1924,7 +2014,7 @@ function dueForCheck(file2, now) {
1924
2014
  var ORIGIN_FILE = ".install-origin.json";
1925
2015
  function selfUpdatable(runtimeDir) {
1926
2016
  try {
1927
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
2017
+ const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1928
2018
  if (typeof origin.source !== "string" || !origin.source) return false;
1929
2019
  return origin.source.split(/[\\/]/).includes("_npx");
1930
2020
  } catch {
@@ -1937,7 +2027,7 @@ function lockFile() {
1937
2027
  }
1938
2028
  function acquireUpdateLock(file2, now) {
1939
2029
  try {
1940
- const held = JSON.parse(readFileSync3(file2, "utf8"));
2030
+ const held = JSON.parse(readFileSync4(file2, "utf8"));
1941
2031
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
1942
2032
  let holderAlive = false;
1943
2033
  if (held.pid) {
@@ -1978,6 +2068,9 @@ function stampCheck(file2, now, latest) {
1978
2068
  } catch {
1979
2069
  }
1980
2070
  }
2071
+ function spawnNpm(spawnImpl, bin, args, opts) {
2072
+ return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2073
+ }
1981
2074
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1982
2075
  return new Promise((resolve3) => {
1983
2076
  let out = "";
@@ -1991,7 +2084,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1991
2084
  resolve3(v);
1992
2085
  };
1993
2086
  try {
1994
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2087
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
1995
2088
  timeout: NPM_VIEW_TIMEOUT_MS,
1996
2089
  stdio: ["ignore", "pipe", "ignore"],
1997
2090
  windowsHide: true
@@ -2060,7 +2153,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2060
2153
  return "";
2061
2154
  }
2062
2155
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2063
- const child = (opts.spawn ?? realSpawn2)(
2156
+ const child = spawnNpm(
2157
+ opts.spawn ?? realSpawn2,
2064
2158
  "npx",
2065
2159
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2066
2160
  {
@@ -2093,7 +2187,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
2093
2187
  var DAEMON_WAIT_RETAIN_MS = 4e4;
2094
2188
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2095
2189
  try {
2096
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2190
+ const res = await fetch(`${baseUrl}/health`, {
2191
+ headers: { "User-Agent": USER_AGENT },
2192
+ signal: AbortSignal.timeout(timeoutMs)
2193
+ });
2097
2194
  return res.ok;
2098
2195
  } catch {
2099
2196
  return false;
@@ -2821,7 +2918,7 @@ __export(core_exports2, {
2821
2918
  toJSONSchema: () => toJSONSchema,
2822
2919
  treeifyError: () => treeifyError,
2823
2920
  util: () => util_exports,
2824
- version: () => version
2921
+ version: () => version2
2825
2922
  });
2826
2923
 
2827
2924
  // node_modules/zod/v4/core/core.js
@@ -3896,10 +3993,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
3896
3993
  var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
3897
3994
  var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
3898
3995
  var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
3899
- var uuid = (version2) => {
3900
- if (!version2)
3996
+ var uuid = (version3) => {
3997
+ if (!version3)
3901
3998
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
3902
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3999
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3903
4000
  };
3904
4001
  var uuid4 = /* @__PURE__ */ uuid(4);
3905
4002
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -4568,7 +4665,7 @@ var Doc = class {
4568
4665
  };
4569
4666
 
4570
4667
  // node_modules/zod/v4/core/versions.js
4571
- var version = {
4668
+ var version2 = {
4572
4669
  major: 4,
4573
4670
  minor: 4,
4574
4671
  patch: 3
@@ -4580,7 +4677,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4580
4677
  inst ?? (inst = {});
4581
4678
  inst._zod.def = def;
4582
4679
  inst._zod.bag = inst._zod.bag || {};
4583
- inst._zod.version = version;
4680
+ inst._zod.version = version2;
4584
4681
  const checks = [...inst._zod.def.checks ?? []];
4585
4682
  if (inst._zod.traits.has("$ZodCheck")) {
4586
4683
  checks.unshift(inst);
@@ -16775,10 +16872,10 @@ function fromJSONSchema(schema, params) {
16775
16872
  } catch {
16776
16873
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
16777
16874
  }
16778
- const version2 = detectVersion(normalized, params?.defaultTarget);
16875
+ const version3 = detectVersion(normalized, params?.defaultTarget);
16779
16876
  const defs = normalized.$defs || normalized.definitions || {};
16780
16877
  const ctx = {
16781
- version: version2,
16878
+ version: version3,
16782
16879
  defs,
16783
16880
  refs: /* @__PURE__ */ new Map(),
16784
16881
  processing: /* @__PURE__ */ new Set(),
@@ -16823,14 +16920,14 @@ import { homedir as homedir6 } from "os";
16823
16920
  import { join as join12 } from "path";
16824
16921
 
16825
16922
  // src/core/status.ts
16826
- import { execFileSync as execFileSync3 } from "child_process";
16923
+ import { execFileSync as execFileSync4 } from "child_process";
16827
16924
 
16828
16925
  // src/core/git.ts
16829
16926
  import { execFileSync as execFileSync2 } from "child_process";
16830
16927
  import { resolve as resolve2 } from "path";
16831
16928
  var GITLOG_HEAD = "gitlog-head:";
16832
16929
  function git(repo, ...args) {
16833
- return execFileSync2("git", ["-C", repo, ...args], {
16930
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16834
16931
  encoding: "utf8",
16835
16932
  maxBuffer: 1 << 28,
16836
16933
  windowsHide: true,
@@ -16876,7 +16973,7 @@ async function gitLogIsCurrent(client, repo, head) {
16876
16973
  }
16877
16974
 
16878
16975
  // src/core/survey.ts
16879
- import { spawn as realSpawn5 } from "child_process";
16976
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16880
16977
  import { createHash as createHash2 } from "crypto";
16881
16978
  import { existsSync as existsSync3 } from "fs";
16882
16979
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
@@ -16985,6 +17082,19 @@ function resolveAgentBin(harness, claudeBin) {
16985
17082
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16986
17083
  }
16987
17084
  }
17085
+ function opencodeCanDefineSurveyAgent(bin) {
17086
+ try {
17087
+ const out = execFileSync3(bin, ["--version"], {
17088
+ encoding: "utf8",
17089
+ timeout: 5e3,
17090
+ windowsHide: true,
17091
+ stdio: ["ignore", "pipe", "ignore"]
17092
+ });
17093
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17094
+ } catch {
17095
+ return false;
17096
+ }
17097
+ }
16988
17098
  var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
16989
17099
  var SURVEY_DISALLOWED_TOOLS = [
16990
17100
  "Bash",
@@ -17098,6 +17208,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17098
17208
  seen.add(harness);
17099
17209
  const bin = resolveAgentBin(harness, opts.claudeBin);
17100
17210
  if (!exists(bin)) continue;
17211
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17212
+ continue;
17101
17213
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17102
17214
  model: opts.model,
17103
17215
  budgetUsd: opts.budgetUsd,
@@ -17154,7 +17266,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17154
17266
  var DEEPEN_DIFF_TARGET = 300;
17155
17267
  function commitCount(repoDir) {
17156
17268
  try {
17157
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17269
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17158
17270
  encoding: "utf8",
17159
17271
  windowsHide: true,
17160
17272
  stdio: ["ignore", "pipe", "pipe"]
@@ -17419,6 +17531,7 @@ function pendingReplayable(cursor, now) {
17419
17531
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17420
17532
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17421
17533
  }
17534
+ var MAX_CURSOR_OPS = 8;
17422
17535
  function fingerprintTurns(turns, count) {
17423
17536
  const h = createHash4("sha1").update(String(count));
17424
17537
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -17479,6 +17592,31 @@ async function supportsAppend(client) {
17479
17592
  return false;
17480
17593
  }
17481
17594
  }
17595
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17596
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17597
+ async function settleOps(client, cursor) {
17598
+ const ops = cursor.ops ?? [];
17599
+ const statuses = await Promise.all(
17600
+ ops.map(async (id) => {
17601
+ try {
17602
+ const r = await client.req(
17603
+ "GET",
17604
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17605
+ void 0,
17606
+ [],
17607
+ OP_CHECK_TIMEOUT_MS
17608
+ );
17609
+ if (r.status === 404) return "not_found";
17610
+ return String((await r.json()).status ?? "").toLowerCase();
17611
+ } catch {
17612
+ return "";
17613
+ }
17614
+ })
17615
+ );
17616
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17617
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17618
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17619
+ }
17482
17620
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17483
17621
  var RETAIN_RETRY_ATTEMPTS = 2;
17484
17622
  var REQUEST_BUDGET_MS = 15e3;
@@ -17542,13 +17680,18 @@ async function retainLiveSession(client, sessionId2, turns, startTs, harness, op
17542
17680
  async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17543
17681
  if (!turns.length) return;
17544
17682
  const refId = `conversation:${sessionId2}`;
17545
- const cursor = cursors?.read(sessionId2);
17683
+ let cursor = cursors?.read(sessionId2);
17684
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17546
17685
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17686
+ let ops = [];
17687
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17688
+ ({ cursor, ops } = await settleOps(client, cursor));
17547
17689
  const plan = planRetain(turns, cursor, {
17548
17690
  appendSupported,
17549
17691
  bank: client.bank,
17550
17692
  path: transcriptPath
17551
17693
  });
17694
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17552
17695
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17553
17696
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17554
17697
  if (plan.mode === "skip" && !outbox.length) return;
@@ -17594,6 +17737,10 @@ ${content}`);
17594
17737
  ...paths ? { paths } : {},
17595
17738
  ...appendSupported ? { appendSupported: true } : {}
17596
17739
  };
17740
+ const accepted = (id) => {
17741
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17742
+ return ops.length ? { ...next, ops } : next;
17743
+ };
17597
17744
  const stillOurs = () => {
17598
17745
  if (!cursors) return true;
17599
17746
  const now = cursors.read(sessionId2);
@@ -17602,12 +17749,10 @@ ${content}`);
17602
17749
  if (plan.mode === "replace") {
17603
17750
  const content = renderSessionJsonl(refId, turns, startTs);
17604
17751
  cursors?.write(sessionId2, { ...next, dirty: true });
17605
- await submitWithRetry(
17606
- () => submit(content, opId("replace", content), false),
17607
- stillOurs,
17608
- retryUntil
17609
- );
17610
- cursors?.write(sessionId2, next);
17752
+ const operationId = opId("replace", content);
17753
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17754
+ ops = [];
17755
+ cursors?.write(sessionId2, accepted(operationId));
17611
17756
  return;
17612
17757
  }
17613
17758
  const queue = [...outbox];
@@ -17615,7 +17760,7 @@ ${content}`);
17615
17760
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17616
17761
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17617
17762
  }
17618
- cursors?.write(sessionId2, { ...next, pending: queue });
17763
+ cursors?.write(sessionId2, { ...accepted(), pending: queue });
17619
17764
  for (let i = 0; i < queue.length; i++) {
17620
17765
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17621
17766
  const entry = queue[i];
@@ -17625,12 +17770,13 @@ ${content}`);
17625
17770
  retryUntil
17626
17771
  );
17627
17772
  const remaining = queue.slice(i + 1);
17628
- cursors?.write(sessionId2, remaining.length ? { ...next, pending: remaining } : next);
17773
+ const done = accepted(entry.operationId);
17774
+ cursors?.write(sessionId2, remaining.length ? { ...done, pending: remaining } : done);
17629
17775
  }
17630
17776
  }
17631
17777
 
17632
17778
  // src/core/usage.ts
17633
- import { readFileSync as readFileSync4 } from "fs";
17779
+ import { readFileSync as readFileSync5 } from "fs";
17634
17780
  import { join as join13 } from "path";
17635
17781
  function usageFilePath() {
17636
17782
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17737,11 +17883,8 @@ function buildRetainStamp(cfg, ctx) {
17737
17883
  return { tags, metadata, context };
17738
17884
  }
17739
17885
 
17740
- // src/core/session-start.ts
17741
- import { readFileSync as readFileSync8 } from "fs";
17742
-
17743
17886
  // src/core/skill-sync.ts
17744
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17887
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17745
17888
  import { homedir as homedir7 } from "os";
17746
17889
  import { dirname as dirname8, join as join15 } from "path";
17747
17890
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17777,7 +17920,12 @@ var SKILL_DIRS = {
17777
17920
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17778
17921
  // and dsh's copy with it.
17779
17922
  pi: [".pi", "agent", "skills"],
17780
- "prime-agent": [".prime", "agent", "skills"]
17923
+ "prime-agent": [".prime", "agent", "skills"],
17924
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17925
+ workbuddy: [".workbuddy", "skills"],
17926
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17927
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17928
+ codebuddy: [".codebuddy", "skills"]
17781
17929
  };
17782
17930
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17783
17931
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -17811,7 +17959,7 @@ function syncCompanionSkill(harness, opts = {}) {
17811
17959
  const dstMd = join15(dst, "SKILL.md");
17812
17960
  const installed = existsSync6(dstMd);
17813
17961
  if (!installed && !opts.install) return;
17814
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17962
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17815
17963
  cpSync(src, dst, { recursive: true });
17816
17964
  }
17817
17965
  } catch {
@@ -17833,7 +17981,7 @@ function brandWord() {
17833
17981
  }
17834
17982
 
17835
17983
  // src/core/legacy.ts
17836
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17984
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17837
17985
  import { homedir as homedir8 } from "os";
17838
17986
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17839
17987
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17858,7 +18006,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17858
18006
  }
17859
18007
  function readJson(path) {
17860
18008
  try {
17861
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18009
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17862
18010
  return parsed && typeof parsed === "object" ? parsed : void 0;
17863
18011
  } catch {
17864
18012
  return void 0;
@@ -17870,7 +18018,7 @@ function legacyClaudePluginWarning(key) {
17870
18018
  }
17871
18019
 
17872
18020
  // src/core/session-cache.ts
17873
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18021
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17874
18022
  import { tmpdir as tmpdir3 } from "os";
17875
18023
  import { dirname as dirname9, join as join17 } from "path";
17876
18024
  function sessionCacheFile(harness, sessionId2) {
@@ -17878,7 +18026,7 @@ function sessionCacheFile(harness, sessionId2) {
17878
18026
  }
17879
18027
  function readSessionCache(cacheFile) {
17880
18028
  try {
17881
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18029
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17882
18030
  } catch {
17883
18031
  return {};
17884
18032
  }
@@ -17922,9 +18070,9 @@ async function gitSyncNote(args) {
17922
18070
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17923
18071
  let target = DEEPEN_DIFF_TARGET;
17924
18072
  try {
17925
- const { execFileSync: execFileSync4 } = await import("child_process");
18073
+ const { execFileSync: execFileSync5 } = await import("child_process");
17926
18074
  const n = Number(
17927
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18075
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17928
18076
  encoding: "utf8",
17929
18077
  windowsHide: true,
17930
18078
  stdio: ["ignore", "pipe", "pipe"]
@@ -17941,6 +18089,7 @@ async function buildSessionStartContext(args) {
17941
18089
  const t0 = Date.now();
17942
18090
  let cold;
17943
18091
  let gitDocIds;
18092
+ let bankEmpty = false;
17944
18093
  const harness = args.harness ?? "claude-code";
17945
18094
  const hasGit = args.hasGit ?? hasGitHistory;
17946
18095
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17980,11 +18129,21 @@ async function buildSessionStartContext(args) {
17980
18129
  } catch {
17981
18130
  docIds = void 0;
17982
18131
  }
17983
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18132
+ let baselines;
18133
+ if (docIds?.size === 0) {
18134
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18135
+ }
18136
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17984
18137
  gitDocIds = docIds;
18138
+ if (cold === true && client.hasDocuments) {
18139
+ bankEmpty = await client.hasDocuments().then(
18140
+ (has) => !has,
18141
+ () => false
18142
+ );
18143
+ }
17985
18144
  if (docIds !== void 0) {
17986
18145
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17987
- if (docIds.size === 0) {
18146
+ if (cold) {
17988
18147
  if (cfg.codebaseSurvey !== false) {
17989
18148
  const started = await startSurvey(cwd, {
17990
18149
  harness,
@@ -17998,7 +18157,7 @@ async function buildSessionStartContext(args) {
17998
18157
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17999
18158
  const sha = resolveHeadSha(cwd);
18000
18159
  if (sha) {
18001
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18160
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18002
18161
  const counts = [];
18003
18162
  for (const id of markers) {
18004
18163
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18032,10 +18191,8 @@ async function buildSessionStartContext(args) {
18032
18191
  }
18033
18192
  }
18034
18193
  let pages = [];
18035
- let pageListKnown = false;
18036
18194
  try {
18037
18195
  pages = parsePageList(await client.listPages());
18038
- pageListKnown = true;
18039
18196
  } catch {
18040
18197
  if (client.knowledgePagesSupported === false) {
18041
18198
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18045,7 +18202,7 @@ async function buildSessionStartContext(args) {
18045
18202
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18046
18203
  extra: cfg.toolGuideExtra
18047
18204
  });
18048
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18205
+ const deferInitialReflect = bankEmpty;
18049
18206
  let gitNote;
18050
18207
  if (gitDocIds) {
18051
18208
  gitNote = await gitSyncNote({
@@ -18069,7 +18226,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18069
18226
  }
18070
18227
 
18071
18228
  // src/core/hook.ts
18072
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18229
+ import { existsSync as existsSync8 } from "fs";
18073
18230
 
18074
18231
  // src/core/inject.ts
18075
18232
  function buildReflectQuery(prompt) {
@@ -18123,9 +18280,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18123
18280
 
18124
18281
  // src/core/hook.ts
18125
18282
  var HOOK_INJECT_ATTEMPTS = 2;
18283
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18126
18284
  function resolveInjection(got, attempts) {
18127
18285
  if (got != null) return got;
18128
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18286
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18287
+ return attempts >= budget ? "" : void 0;
18288
+ }
18289
+ var RECALL_QUERY_MAX_TOKENS = 500;
18290
+ function boundRecallQuery(prompt) {
18291
+ let cost = 0;
18292
+ let end = 0;
18293
+ for (const ch of prompt) {
18294
+ const cp = ch.codePointAt(0);
18295
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18296
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18297
+ end += ch.length;
18298
+ }
18299
+ return prompt.slice(0, end);
18129
18300
  }
18130
18301
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18131
18302
  const t0 = Date.now();
@@ -18141,7 +18312,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18141
18312
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18142
18313
  const t0 = Date.now();
18143
18314
  try {
18144
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18315
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18145
18316
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18146
18317
  return observations.length ? formatRecallFallback(observations, lead) : null;
18147
18318
  } catch (e) {
@@ -18216,7 +18387,7 @@ async function buildHookOutput(args) {
18216
18387
  answer: reflectAnswer.slice(0, 8e3)
18217
18388
  });
18218
18389
  } catch (e) {
18219
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18390
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18220
18391
  reflectFailed = true;
18221
18392
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18222
18393
  error: describeError(e)
@@ -18288,6 +18459,7 @@ async function buildHookOutput(args) {
18288
18459
 
18289
18460
  // src/core/runtime.ts
18290
18461
  var HARNESS = "opencode";
18462
+ var FLUSH_TIMEOUT_MS = 1e4;
18291
18463
  var RuntimeCore = class {
18292
18464
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18293
18465
  this.client = client;
@@ -18313,6 +18485,8 @@ var RuntimeCore = class {
18313
18485
  usageCursors = memoryUsageCursorStore();
18314
18486
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18315
18487
  fetchTranscript;
18488
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18489
+ inFlight = /* @__PURE__ */ new Set();
18316
18490
  lastInjection = "";
18317
18491
  // most recent turn's injection block, keyed by nothing (see getInjection)
18318
18492
  deferInitialReflect = false;
@@ -18445,8 +18619,9 @@ var RuntimeCore = class {
18445
18619
  */
18446
18620
  async onTranscript(sessionId2, turns, lastTurnComplete) {
18447
18621
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18448
- if (!this.writeBackEnabled || !sessionId2 || !turns.length) return;
18622
+ if (!sessionId2 || !turns.length) return;
18449
18623
  this.recordUsage(sessionId2, turns, lastTurnComplete);
18624
+ if (!this.writeBackEnabled) return;
18450
18625
  const st = this.stateFor(sessionId2);
18451
18626
  this.retain(sessionId2, turns, st.startTs);
18452
18627
  }
@@ -18464,7 +18639,7 @@ var RuntimeCore = class {
18464
18639
  */
18465
18640
  async onSessionIdle(sessionId2) {
18466
18641
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18467
- if (!this.writeBackEnabled || !sessionId2 || !this.fetchTranscript) return;
18642
+ if (!sessionId2 || !this.fetchTranscript) return;
18468
18643
  let turns;
18469
18644
  try {
18470
18645
  turns = await this.fetchTranscript(sessionId2);
@@ -18477,6 +18652,7 @@ var RuntimeCore = class {
18477
18652
  }
18478
18653
  if (!turns.length) return;
18479
18654
  this.recordUsage(sessionId2, turns, true);
18655
+ if (!this.writeBackEnabled) return;
18480
18656
  const st = this.stateFor(sessionId2);
18481
18657
  if (turns.length <= st.retainedTurns) return;
18482
18658
  st.retainedTurns = turns.length;
@@ -18504,10 +18680,27 @@ var RuntimeCore = class {
18504
18680
  }
18505
18681
  return st;
18506
18682
  }
18683
+ /**
18684
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18685
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18686
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18687
+ * stalled server cannot hold the host's exit open. Never throws.
18688
+ */
18689
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18690
+ if (!this.inFlight.size) return;
18691
+ let timer;
18692
+ await Promise.race([
18693
+ Promise.all(this.inFlight),
18694
+ new Promise((r) => {
18695
+ timer = setTimeout(r, timeoutMs);
18696
+ })
18697
+ ]);
18698
+ clearTimeout(timer);
18699
+ }
18507
18700
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18508
18701
  retain(sessionId2, turns, startTs, trigger = "turn") {
18509
18702
  const t0 = Date.now();
18510
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18703
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18511
18704
  () => retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
18512
18705
  cursors: this.cursors,
18513
18706
  stamp: buildRetainStamp(this.cfg, {
@@ -18532,6 +18725,8 @@ var RuntimeCore = class {
18532
18725
  trigger
18533
18726
  })
18534
18727
  );
18728
+ this.inFlight.add(write2);
18729
+ void write2.finally(() => this.inFlight.delete(write2));
18535
18730
  }
18536
18731
  };
18537
18732