@vectorize-io/hindsight-coding-agents 0.7.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 +201 -16
  2. package/dist/antigravity-hook.js +1132 -115
  3. package/dist/antigravity-statusline.js +77 -11
  4. package/dist/antigravity-stop-hook.js +1193 -133
  5. package/dist/claude-hook.js +1132 -115
  6. package/dist/claude-sessionstart-hook.js +1241 -140
  7. package/dist/claude-stop-hook.js +1193 -133
  8. package/dist/cline.js +578 -163
  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 +1132 -115
  13. package/dist/codex-sessionstart-hook.js +1241 -140
  14. package/dist/codex-stop-hook.js +1193 -133
  15. package/dist/copilot-hook.js +1132 -115
  16. package/dist/copilot-sessionstart-hook.js +1241 -140
  17. package/dist/copilot-stop-hook.js +1193 -133
  18. package/dist/cursor-hook.js +1132 -115
  19. package/dist/cursor-sessionstart-hook.js +1241 -140
  20. package/dist/cursor-stop-hook.js +1193 -133
  21. package/dist/daemon-start.js +54 -9
  22. package/dist/dcode-hook.js +1132 -115
  23. package/dist/dcode-sessionstart-hook.js +1241 -140
  24. package/dist/dcode-stop-hook.js +1193 -133
  25. package/dist/deepen.js +370 -104
  26. package/dist/devin-hook.js +1132 -115
  27. package/dist/devin-sessionstart-hook.js +1241 -140
  28. package/dist/devin-stop-hook.js +1193 -133
  29. package/dist/droid-hook.js +1132 -115
  30. package/dist/droid-sessionstart-hook.js +1241 -140
  31. package/dist/droid-stop-hook.js +1193 -133
  32. package/dist/dsh.js +586 -164
  33. package/dist/grok-hook.js +1132 -115
  34. package/dist/grok-sessionstart-hook.js +1241 -140
  35. package/dist/grok-stop-hook.js +1193 -133
  36. package/dist/hindsight-seed.js +50 -8
  37. package/dist/index.js +587 -172
  38. package/dist/installer.js +2010 -769
  39. package/dist/kilo.js +587 -172
  40. package/dist/kimi-hook.js +4270 -0
  41. package/dist/kimi-sessionstart-hook.js +5030 -0
  42. package/dist/kimi-stop-hook.js +4564 -0
  43. package/dist/mcp-server.js +419 -115
  44. package/dist/opencode2.js +586 -169
  45. package/dist/pi.js +644 -175
  46. package/dist/prime-agent.js +644 -175
  47. package/dist/qwen-hook.js +1132 -115
  48. package/dist/qwen-sessionstart-hook.js +1241 -140
  49. package/dist/qwen-stop-hook.js +1193 -133
  50. package/dist/status.js +243 -52
  51. package/dist/traecode-hook.js +4270 -0
  52. package/dist/traecode-sessionstart-hook.js +5030 -0
  53. package/dist/traecode-stop-hook.js +4564 -0
  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 +1132 -115
  58. package/dist/zcode-sessionstart-hook.js +1241 -140
  59. package/dist/zcode-stop-hook.js +1193 -133
  60. package/package.json +22 -12
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +73 -14
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;
@@ -309,13 +310,13 @@ function isWithin(directory, configured) {
309
310
  function mapLookup(map2, directory) {
310
311
  const cwd = normalize(directory);
311
312
  let best;
312
- for (const [dir, bank] of Object.entries(map2)) {
313
+ for (const [dir, value] of Object.entries(map2)) {
313
314
  const p = configuredDir(dir);
314
315
  if (isWithin(cwd, p)) {
315
- if (!best || p.length > best.len) best = { len: p.length, bank };
316
+ if (!best || p.length > best.len) best = { len: p.length, value };
316
317
  }
317
318
  }
318
- return best?.bank;
319
+ return best?.value;
319
320
  }
320
321
  function lookupDirectories(config2, directory, sessionRoot = "") {
321
322
  const directories = [normalize(directory)];
@@ -339,6 +340,10 @@ function isOptedIn(config2, directory) {
339
340
  const pathMap = config2.mapPathToBank;
340
341
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
341
342
  }
343
+ function pathSection(config2, paths, directory) {
344
+ if (!directory || !paths) return void 0;
345
+ return lookupDirectories(config2, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
346
+ }
342
347
  function mappedBank(config2, directory, sessionRoot) {
343
348
  const pathMap = config2.mapPathToBank;
344
349
  if (!directory || !pathMap) return void 0;
@@ -358,6 +363,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
358
363
  };
359
364
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
360
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
+ }
361
379
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
362
380
  try {
363
381
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -375,7 +393,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
375
393
  // src/core/missions.ts
376
394
  import { createHash } from "crypto";
377
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.";
378
- 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.";
379
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.`;
380
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.";
381
399
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -451,6 +469,8 @@ var KNOWLEDGE_LABELS = {
451
469
  ]
452
470
  };
453
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.`;
454
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.`;
455
475
  }
456
476
  var PAGE_TAXONOMY = [
@@ -586,12 +606,17 @@ var CODING_BANK_TEMPLATE = {
586
606
  }
587
607
  };
588
608
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
609
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
610
+ "retain_strategies",
611
+ "entity_labels",
612
+ "retain_extraction_mode"
613
+ ];
589
614
  function isSet(v) {
590
615
  if (v === null || v === void 0) return false;
591
616
  if (typeof v === "string") return v.trim() !== "";
592
617
  return true;
593
618
  }
594
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
619
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
595
620
  const current2 = overrides ?? {};
596
621
  const template = CODING_BANK_TEMPLATE.bank;
597
622
  const bank = {};
@@ -620,9 +645,16 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
620
645
  const [knowledgeGroup] = template.entity_labels;
621
646
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
622
647
  bank.entity_labels = [...labels, knowledgeGroup];
648
+ for (const [key, value] of Object.entries(defaults)) {
649
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
650
+ bank[key] = value;
651
+ }
623
652
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
624
653
  }
625
654
 
655
+ // package.json
656
+ var version = "0.8.1";
657
+
626
658
  // src/core/util.ts
627
659
  import { accessSync, constants } from "fs";
628
660
  import { delimiter, join as join6 } from "path";
@@ -646,12 +678,12 @@ function binOnPath(bin) {
646
678
  }
647
679
  }
648
680
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
649
- function semverGte(version2, min) {
681
+ function semverGte(version3, min) {
650
682
  const parts = (v) => {
651
683
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
652
684
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
653
685
  };
654
- const a = version2 ? parts(version2) : void 0;
686
+ const a = version3 ? parts(version3) : void 0;
655
687
  const b = parts(min);
656
688
  if (!a || !b) return false;
657
689
  for (let i = 0; i < 3; i++) {
@@ -676,6 +708,7 @@ async function pool(items, n, fn, onError, onProgress) {
676
708
  }
677
709
 
678
710
  // src/core/hindsight.ts
711
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
679
712
  function resolveRetainScopes(tags, configured) {
680
713
  if (configured !== "per_source") return configured;
681
714
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -711,7 +744,7 @@ async function isEndpointMissing(r) {
711
744
  const j = await r.json();
712
745
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
713
746
  } catch {
714
- return true;
747
+ return false;
715
748
  }
716
749
  }
717
750
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -730,6 +763,12 @@ var ReflectError = class extends Error {
730
763
  get fallbackEligible() {
731
764
  return this.timedOut || this.status !== void 0 && this.status >= 500;
732
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
+ }
733
772
  };
734
773
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
735
774
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -740,8 +779,31 @@ var DEFAULT_RECALL_OPTIONS = {
740
779
  include: { entities: null }
741
780
  };
742
781
  var POLL_CYCLE_MS = 5e3;
782
+ var POLL_MAX_SERVER_ERRORS = 12;
743
783
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
744
784
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
785
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
786
+ function shapePage(page) {
787
+ const p = page ?? {};
788
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
789
+ return {
790
+ id: p.id,
791
+ name: p.name,
792
+ ...p.description ? { description: p.description } : {},
793
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
794
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
795
+ body
796
+ };
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
+ }
745
807
  var HindsightClient = class {
746
808
  apiUrl;
747
809
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -761,6 +823,7 @@ var HindsightClient = class {
761
823
  observationScopes;
762
824
  pageSearchLimit;
763
825
  recallOptions;
826
+ rateLimitPatienceMs;
764
827
  constructor(o) {
765
828
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
766
829
  this.token = o.apiToken;
@@ -773,13 +836,18 @@ var HindsightClient = class {
773
836
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
774
837
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
775
838
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
839
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
776
840
  }
777
841
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
778
842
  get apiToken() {
779
843
  return this.token;
780
844
  }
781
845
  headers() {
782
- const h = { "Content-Type": "application/json" };
846
+ const h = {
847
+ "Content-Type": "application/json",
848
+ "Accept-Encoding": "identity",
849
+ "User-Agent": USER_AGENT
850
+ };
783
851
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
784
852
  return h;
785
853
  }
@@ -810,7 +878,8 @@ var HindsightClient = class {
810
878
  * bounds the whole call.
811
879
  */
812
880
  async fetchWithAuth(url2, init) {
813
- 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 } : {} });
814
883
  const r = await send();
815
884
  if (r.status !== 401 || !this.refreshToken()) return r;
816
885
  return send();
@@ -826,13 +895,22 @@ var HindsightClient = class {
826
895
  }
827
896
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
828
897
  async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
829
- const r = await this.fetchWithAuth(url2, {
830
- method,
831
- body: body ? JSON.stringify(body) : void 0,
832
- signal: AbortSignal.timeout(timeoutMs)
833
- });
834
- if (r.status === 429 && !tolerate.includes(429))
835
- 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
+ }
836
914
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
837
915
  throw new Error(
838
916
  `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -867,7 +945,7 @@ var HindsightClient = class {
867
945
  }
868
946
  /**
869
947
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
870
- * 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
871
949
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
872
950
  */
873
951
  async supportsIdempotentRetain() {
@@ -877,14 +955,37 @@ var HindsightClient = class {
877
955
  }
878
956
  return this.idempotentRetain;
879
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. */
880
962
  async probeIdempotentRetain() {
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
+ }
971
+ }
972
+ return false;
973
+ }
974
+ /**
975
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
976
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
977
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
978
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
979
+ */
980
+ async supportsAppendRetain() {
981
+ if (!await this.supportsIdempotentRetain()) return false;
881
982
  try {
882
- const r = await this.req("GET", `${this.apiUrl}/version`);
883
- if (!r.ok) return false;
983
+ const r = await this.req("GET", this.bankUrl("/config"));
984
+ if (!r.ok) return true;
884
985
  const j = await r.json();
885
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
986
+ return j.config?.store_document_text !== false;
886
987
  } catch {
887
- return false;
988
+ return true;
888
989
  }
889
990
  }
890
991
  /**
@@ -912,6 +1013,32 @@ var HindsightClient = class {
912
1013
  }
913
1014
  return ids;
914
1015
  }
1016
+ /**
1017
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
1018
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
1019
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
1020
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
1021
+ */
1022
+ async documentTags(documentId) {
1023
+ const limit = 100;
1024
+ for (let offset = 0; ; offset += limit) {
1025
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
1026
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
1027
+ const j = await r.json();
1028
+ const items = j.items ?? [];
1029
+ const hit = items.find((it) => it.id === documentId);
1030
+ if (hit) return hit.tags ?? [];
1031
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
1032
+ }
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
+ }
915
1042
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
916
1043
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
917
1044
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -933,7 +1060,8 @@ var HindsightClient = class {
933
1060
  } else {
934
1061
  const manifest = codingBankManifest(
935
1062
  opts.reset ? void 0 : await this.readBankOverrides(),
936
- opts.extractionMode
1063
+ opts.extractionMode,
1064
+ opts.defaults
937
1065
  );
938
1066
  if (!manifest) {
939
1067
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -992,7 +1120,13 @@ var HindsightClient = class {
992
1120
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
993
1121
  const start = Date.now();
994
1122
  const pending = new Set(ids);
1123
+ const serverErrors = /* @__PURE__ */ new Map();
995
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
+ };
996
1130
  while (pending.size && Date.now() - start < maxMs) {
997
1131
  let backoffMs = POLL_CYCLE_MS;
998
1132
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1005,7 +1139,14 @@ var HindsightClient = class {
1005
1139
  );
1006
1140
  return;
1007
1141
  }
1008
- 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);
1009
1150
  const st = ((await r.json()).status || "").toLowerCase();
1010
1151
  if (TERMINAL.has(st)) {
1011
1152
  pending.delete(id);
@@ -1139,8 +1280,8 @@ var HindsightClient = class {
1139
1280
  return { items };
1140
1281
  }
1141
1282
  /**
1142
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1143
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1283
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1284
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1144
1285
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1145
1286
  * token cap.
1146
1287
  */
@@ -1151,7 +1292,7 @@ var HindsightClient = class {
1151
1292
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1152
1293
  );
1153
1294
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1154
- return await r.json();
1295
+ return shapePage(await r.json());
1155
1296
  }
1156
1297
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1157
1298
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1172,6 +1313,7 @@ var HindsightClient = class {
1172
1313
  return (j.results ?? []).map((x) => ({
1173
1314
  id: x.id,
1174
1315
  name: x.name,
1316
+ ...x.source_query ? { source_query: x.source_query } : {},
1175
1317
  snippet: x.snippet ?? "",
1176
1318
  score: x.score ?? 0
1177
1319
  }));
@@ -1188,7 +1330,7 @@ var HindsightClient = class {
1188
1330
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1189
1331
  */
1190
1332
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1191
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1333
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1192
1334
  const existing = /* @__PURE__ */ new Map();
1193
1335
  let roots;
1194
1336
  try {
@@ -1263,7 +1405,7 @@ var HindsightClient = class {
1263
1405
  }
1264
1406
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1265
1407
  this.log(
1266
- `[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` : "")
1267
1409
  );
1268
1410
  }
1269
1411
  /**
@@ -1274,23 +1416,33 @@ var HindsightClient = class {
1274
1416
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1275
1417
  * consolidation under the auto-refresh that used to be the default (#3506).
1276
1418
  *
1277
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1278
- * initiative's own title, and re-stating either would rebuild a page whose question never
1279
- * 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.
1280
1425
  */
1281
1426
  async resyncInitiativeTriggers(roots, pageTrigger) {
1282
1427
  const folder = roots.find(
1283
1428
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1284
1429
  );
1430
+ const bankScope = pageScopeRule(this.bank);
1285
1431
  let updated = 0;
1286
1432
  for (const page of folder?.children ?? []) {
1287
- if (page.kind !== "page" || page.trigger == null) continue;
1288
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1289
- 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;
1290
1442
  const r = await this.req(
1291
1443
  "PATCH",
1292
1444
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1293
- { trigger: pageTriggerPatch(desired) }
1445
+ patch
1294
1446
  );
1295
1447
  if (r.status === 404) continue;
1296
1448
  updated++;
@@ -1318,10 +1470,9 @@ var HindsightClient = class {
1318
1470
  let pageId = args.relatesToPageId;
1319
1471
  if (!pageId) {
1320
1472
  const folderId = await this.ensureFolder("Initiatives");
1321
- const subject = this.project ?? this.bank;
1322
1473
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1323
1474
  name: args.title,
1324
- 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),
1325
1476
  parent_id: folderId,
1326
1477
  tags: ["knowledge:feature-work"],
1327
1478
  max_tokens: PAGE_MAX_TOKENS,
@@ -1336,7 +1487,7 @@ var HindsightClient = class {
1336
1487
  }
1337
1488
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1338
1489
  const content = `${verb}: ${args.title}. ${args.summary}`;
1339
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1490
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1340
1491
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1341
1492
  const context = `initiative marker for [[page:${pageId}]]`;
1342
1493
  await this.retain(content, context, markerId, tags, "document", {
@@ -1442,6 +1593,7 @@ function resolveCustomPages(raw) {
1442
1593
  }
1443
1594
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1444
1595
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1596
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1445
1597
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1446
1598
  function resolveReflectBudget(raw) {
1447
1599
  const value = raw.reflectBudget;
@@ -1468,6 +1620,22 @@ function resolveObservationScopes(raw) {
1468
1620
  }
1469
1621
  return DEFAULT_OBSERVATION_SCOPES;
1470
1622
  }
1623
+ function resolveDefaultBankConfig(raw) {
1624
+ const value = raw;
1625
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1626
+ const out = {};
1627
+ for (const [key, v] of Object.entries(value)) {
1628
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1629
+ log.warn(
1630
+ "config",
1631
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1632
+ );
1633
+ continue;
1634
+ }
1635
+ out[key] = v;
1636
+ }
1637
+ return out;
1638
+ }
1471
1639
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1472
1640
  function resolveAutoInject(raw) {
1473
1641
  if (raw.autoReflect !== void 0) {
@@ -1507,18 +1675,21 @@ function resolveConfig(raw = {}) {
1507
1675
  // write sessions back by default, every harness
1508
1676
  manageBankConfig: raw.manageBankConfig ?? true,
1509
1677
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1678
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1510
1679
  maxParallelRetains: raw.maxParallelRetains || 10,
1511
1680
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1512
1681
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1513
1682
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1514
1683
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1515
1684
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1685
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1516
1686
  reflectBudget: resolveReflectBudget(raw),
1517
1687
  autoInject: resolveAutoInject(raw),
1518
1688
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1519
1689
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1520
1690
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1521
1691
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1692
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1522
1693
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1523
1694
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1524
1695
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1538,18 +1709,22 @@ function resolveConfig(raw = {}) {
1538
1709
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1539
1710
  // nested object cannot reach the API as a tag and fail the whole retain.
1540
1711
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1712
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1713
+ // the built-in default) from a configured value, and an empty context would strip the default.
1714
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1541
1715
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1542
1716
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1543
1717
  ) : {},
1544
1718
  observationScopes: resolveObservationScopes(raw.observationScopes),
1545
1719
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1720
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1546
1721
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1547
1722
  autoUpdate: raw.autoUpdate ?? true
1548
1723
  };
1549
1724
  }
1550
1725
  function readRaw(path) {
1551
1726
  try {
1552
- return JSON.parse(readFileSync2(path, "utf8"));
1727
+ return JSON.parse(readFileSync3(path, "utf8"));
1553
1728
  } catch (e) {
1554
1729
  if (e?.code !== "ENOENT") {
1555
1730
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1559,7 +1734,12 @@ function readRaw(path) {
1559
1734
  }
1560
1735
  function mergeRaw(a, b) {
1561
1736
  const { harnesses: _drop, ...flat } = b;
1562
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1737
+ return {
1738
+ ...a,
1739
+ ...flat,
1740
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1741
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1742
+ };
1563
1743
  }
1564
1744
  function applyLayer(raw, layer, harness) {
1565
1745
  let out = mergeRaw(raw, layer);
@@ -1590,9 +1770,11 @@ var ENV_KEYS = {
1590
1770
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1591
1771
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1592
1772
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1773
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1593
1774
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1594
1775
  autoInject: "HINDSIGHT_AUTO_INJECT",
1595
1776
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1777
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1596
1778
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1597
1779
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1598
1780
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1634,6 +1816,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1634
1816
  "maxParallelRetains",
1635
1817
  "reflectTimeoutMs",
1636
1818
  "reflectToolTimeoutMs",
1819
+ "injectTimeoutMs",
1637
1820
  "pageSearchLimit",
1638
1821
  "pageRefreshEveryTurns",
1639
1822
  "seedLimit",
@@ -1682,15 +1865,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1682
1865
  function applyBankConfig(cfg, resolvedId, directory) {
1683
1866
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1684
1867
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1868
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1869
+ if (byPath) {
1870
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1871
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1872
+ }
1685
1873
  const section = cfg.banks[resolvedId];
1686
1874
  if (!section) return { cfg, bankId: resolvedId };
1687
- const safe = { ...section };
1688
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1689
- delete safe.banks;
1875
+ const safe = overrideFields(section);
1690
1876
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1691
1877
  delete safe.bank;
1692
1878
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1693
1879
  }
1880
+ function overrideFields(section) {
1881
+ const safe = { ...section };
1882
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1883
+ delete safe.banks;
1884
+ delete safe.paths;
1885
+ return safe;
1886
+ }
1694
1887
  function resolvePartial(cfg, patch) {
1695
1888
  const full = resolveConfig(patch);
1696
1889
  const out = {};
@@ -1699,6 +1892,16 @@ function resolvePartial(cfg, patch) {
1699
1892
  out[key] = full[key];
1700
1893
  }
1701
1894
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1895
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1896
+ const conn = resolveConfig({
1897
+ serverMode: patch.serverMode ?? cfg.serverMode,
1898
+ apiPort: patch.apiPort ?? cfg.apiPort,
1899
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1900
+ });
1901
+ out.serverMode = conn.serverMode;
1902
+ out.apiUrl = conn.apiUrl;
1903
+ out.apiPort = conn.apiPort;
1904
+ }
1702
1905
  return out;
1703
1906
  }
1704
1907
 
@@ -1708,10 +1911,12 @@ function resolveHostConfig(harness, directory) {
1708
1911
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1709
1912
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1710
1913
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1711
- 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 };
1712
1917
  }
1713
1918
  function resolveHostMemory(harness, directory) {
1714
- const { cfg, bankId } = resolveHostConfig(harness, directory);
1919
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
1715
1920
  return {
1716
1921
  cfg,
1717
1922
  bankId,
@@ -1719,6 +1924,8 @@ function resolveHostMemory(harness, directory) {
1719
1924
  apiUrl: cfg.apiUrl,
1720
1925
  apiToken: cfg.apiToken,
1721
1926
  bank: bankId,
1927
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
1928
+ project,
1722
1929
  maxParallelRetains: cfg.maxParallelRetains,
1723
1930
  observationScopes: cfg.observationScopes,
1724
1931
  pageSearchLimit: cfg.pageSearchLimit,
@@ -1727,7 +1934,12 @@ function resolveHostMemory(harness, directory) {
1727
1934
  // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
1728
1935
  // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
1729
1936
  // honoured on re-resolution exactly as it was on the first one.
1730
- tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
1937
+ // The URL stays the one this client was built with, so a token re-read after the config
1938
+ // moved this directory to ANOTHER server is that server's credential: never send it here.
1939
+ tokenProvider: () => {
1940
+ const live = resolveHostConfig(harness, directory).cfg;
1941
+ return live.apiUrl === cfg.apiUrl ? live.apiToken : cfg.apiToken;
1942
+ }
1731
1943
  })
1732
1944
  };
1733
1945
  }
@@ -1737,7 +1949,7 @@ import { spawn as realSpawn2 } from "child_process";
1737
1949
  import {
1738
1950
  existsSync as existsSync2,
1739
1951
  mkdirSync as mkdirSync2,
1740
- readFileSync as readFileSync3,
1952
+ readFileSync as readFileSync4,
1741
1953
  realpathSync as realpathSync2,
1742
1954
  unlinkSync,
1743
1955
  writeFileSync
@@ -1768,7 +1980,7 @@ function sameDir(a, b) {
1768
1980
  }
1769
1981
  function stagedVersion(pkgRoot) {
1770
1982
  try {
1771
- const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1983
+ const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
1772
1984
  return typeof pkg.version === "string" ? pkg.version : "";
1773
1985
  } catch {
1774
1986
  return "";
@@ -1793,7 +2005,7 @@ function isNewer(candidate, current2) {
1793
2005
  }
1794
2006
  function dueForCheck(file2, now) {
1795
2007
  try {
1796
- const state = JSON.parse(readFileSync3(file2, "utf8"));
2008
+ const state = JSON.parse(readFileSync4(file2, "utf8"));
1797
2009
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
1798
2010
  } catch {
1799
2011
  return true;
@@ -1802,7 +2014,7 @@ function dueForCheck(file2, now) {
1802
2014
  var ORIGIN_FILE = ".install-origin.json";
1803
2015
  function selfUpdatable(runtimeDir) {
1804
2016
  try {
1805
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
2017
+ const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1806
2018
  if (typeof origin.source !== "string" || !origin.source) return false;
1807
2019
  return origin.source.split(/[\\/]/).includes("_npx");
1808
2020
  } catch {
@@ -1815,7 +2027,7 @@ function lockFile() {
1815
2027
  }
1816
2028
  function acquireUpdateLock(file2, now) {
1817
2029
  try {
1818
- const held = JSON.parse(readFileSync3(file2, "utf8"));
2030
+ const held = JSON.parse(readFileSync4(file2, "utf8"));
1819
2031
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
1820
2032
  let holderAlive = false;
1821
2033
  if (held.pid) {
@@ -1856,6 +2068,9 @@ function stampCheck(file2, now, latest) {
1856
2068
  } catch {
1857
2069
  }
1858
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
+ }
1859
2074
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1860
2075
  return new Promise((resolve3) => {
1861
2076
  let out = "";
@@ -1869,7 +2084,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
1869
2084
  resolve3(v);
1870
2085
  };
1871
2086
  try {
1872
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2087
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
1873
2088
  timeout: NPM_VIEW_TIMEOUT_MS,
1874
2089
  stdio: ["ignore", "pipe", "ignore"],
1875
2090
  windowsHide: true
@@ -1938,7 +2153,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
1938
2153
  return "";
1939
2154
  }
1940
2155
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
1941
- const child = (opts.spawn ?? realSpawn2)(
2156
+ const child = spawnNpm(
2157
+ opts.spawn ?? realSpawn2,
1942
2158
  "npx",
1943
2159
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
1944
2160
  {
@@ -1971,7 +2187,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
1971
2187
  var DAEMON_WAIT_RETAIN_MS = 4e4;
1972
2188
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1973
2189
  try {
1974
- 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
+ });
1975
2194
  return res.ok;
1976
2195
  } catch {
1977
2196
  return false;
@@ -2053,12 +2272,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
2053
2272
  } catch {
2054
2273
  }
2055
2274
  }
2275
+ var coldStarts = /* @__PURE__ */ new Map();
2276
+ async function waitBounded(p, ms) {
2277
+ let timer;
2278
+ try {
2279
+ await Promise.race([
2280
+ p,
2281
+ new Promise((resolve3) => {
2282
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2283
+ })
2284
+ ]);
2285
+ } finally {
2286
+ clearTimeout(timer);
2287
+ }
2288
+ }
2056
2289
  async function ensureDaemon(cfg, harness, opts = {}) {
2057
2290
  if (cfg.serverMode !== "daemon") return;
2058
2291
  if (await isServerHealthy(cfg.apiUrl)) return;
2059
2292
  if (!preflightDaemon(cfg, harness)) return;
2060
- startDaemonDetached(cfg, harness, opts.spawnFn);
2061
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2293
+ const waitMs = opts.waitMs ?? 0;
2294
+ const running = coldStarts.get(cfg.apiUrl);
2295
+ if (running) {
2296
+ const startedAt = Date.now();
2297
+ await waitBounded(
2298
+ running.catch(() => void 0),
2299
+ waitMs
2300
+ );
2301
+ const remaining = waitMs - (Date.now() - startedAt);
2302
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2303
+ return;
2304
+ }
2305
+ const attempt = (async () => {
2306
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2307
+ await waitForHealth(cfg.apiUrl, waitMs);
2308
+ })();
2309
+ coldStarts.set(cfg.apiUrl, attempt);
2310
+ try {
2311
+ await attempt;
2312
+ } finally {
2313
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2314
+ }
2062
2315
  }
2063
2316
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
2064
2317
  const deadline = Date.now() + budgetMs;
@@ -2110,13 +2363,13 @@ function indexLine(pages) {
2110
2363
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
2111
2364
  return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
2112
2365
  }
2113
- var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today, never what was decided or why, so work built from code alone quietly re-litigates settled questions. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
2114
- \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, is usually already decided);
2366
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
2367
+ \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
2115
2368
  \u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
2116
2369
  \u2022 you are implementing something new, or two parts have to fit together;
2117
2370
  \u2022 the user asks why something is the way it is, or what is left to do;
2118
2371
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
2119
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
2372
+ It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
2120
2373
  CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
2121
2374
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
2122
2375
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
@@ -2124,7 +2377,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
2124
2377
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
2125
2378
  var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
2126
2379
  function toolGuide(opts) {
2127
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
2380
+ const extra = opts?.extra?.trim();
2381
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
2382
+ ${extra}` : "");
2128
2383
  }
2129
2384
  function buildKnowledgePreamble(pages, opts) {
2130
2385
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
@@ -2663,7 +2918,7 @@ __export(core_exports2, {
2663
2918
  toJSONSchema: () => toJSONSchema,
2664
2919
  treeifyError: () => treeifyError,
2665
2920
  util: () => util_exports,
2666
- version: () => version
2921
+ version: () => version2
2667
2922
  });
2668
2923
 
2669
2924
  // node_modules/zod/v4/core/core.js
@@ -3738,10 +3993,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
3738
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)?)?)$/;
3739
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)?)??$/;
3740
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})$/;
3741
- var uuid = (version2) => {
3742
- if (!version2)
3996
+ var uuid = (version3) => {
3997
+ if (!version3)
3743
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)$/;
3744
- 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})$`);
3745
4000
  };
3746
4001
  var uuid4 = /* @__PURE__ */ uuid(4);
3747
4002
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -4410,7 +4665,7 @@ var Doc = class {
4410
4665
  };
4411
4666
 
4412
4667
  // node_modules/zod/v4/core/versions.js
4413
- var version = {
4668
+ var version2 = {
4414
4669
  major: 4,
4415
4670
  minor: 4,
4416
4671
  patch: 3
@@ -4422,7 +4677,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4422
4677
  inst ?? (inst = {});
4423
4678
  inst._zod.def = def;
4424
4679
  inst._zod.bag = inst._zod.bag || {};
4425
- inst._zod.version = version;
4680
+ inst._zod.version = version2;
4426
4681
  const checks = [...inst._zod.def.checks ?? []];
4427
4682
  if (inst._zod.traits.has("$ZodCheck")) {
4428
4683
  checks.unshift(inst);
@@ -16617,10 +16872,10 @@ function fromJSONSchema(schema, params) {
16617
16872
  } catch {
16618
16873
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
16619
16874
  }
16620
- const version2 = detectVersion(normalized, params?.defaultTarget);
16875
+ const version3 = detectVersion(normalized, params?.defaultTarget);
16621
16876
  const defs = normalized.$defs || normalized.definitions || {};
16622
16877
  const ctx = {
16623
- version: version2,
16878
+ version: version3,
16624
16879
  defs,
16625
16880
  refs: /* @__PURE__ */ new Map(),
16626
16881
  processing: /* @__PURE__ */ new Set(),
@@ -16665,13 +16920,14 @@ import { homedir as homedir6 } from "os";
16665
16920
  import { join as join12 } from "path";
16666
16921
 
16667
16922
  // src/core/status.ts
16668
- import { execFileSync as execFileSync3 } from "child_process";
16923
+ import { execFileSync as execFileSync4 } from "child_process";
16669
16924
 
16670
16925
  // src/core/git.ts
16671
16926
  import { execFileSync as execFileSync2 } from "child_process";
16672
16927
  import { resolve as resolve2 } from "path";
16928
+ var GITLOG_HEAD = "gitlog-head:";
16673
16929
  function git(repo, ...args) {
16674
- return execFileSync2("git", ["-C", repo, ...args], {
16930
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16675
16931
  encoding: "utf8",
16676
16932
  maxBuffer: 1 << 28,
16677
16933
  windowsHide: true,
@@ -16691,6 +16947,7 @@ function gitHeadSha(dir) {
16691
16947
  }
16692
16948
  }
16693
16949
  function commitsSince(dir, sinceSha) {
16950
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16694
16951
  try {
16695
16952
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16696
16953
  return Number.isFinite(n) ? n : null;
@@ -16705,9 +16962,18 @@ function hasGitHistory(dir) {
16705
16962
  return false;
16706
16963
  }
16707
16964
  }
16965
+ async function gitLogIsCurrent(client, repo, head) {
16966
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
16967
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
16968
+ return true;
16969
+ const tags = await client.documentTags?.(canonical2) ?? [];
16970
+ return tags.some(
16971
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
16972
+ );
16973
+ }
16708
16974
 
16709
16975
  // src/core/survey.ts
16710
- import { spawn as realSpawn5 } from "child_process";
16976
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16711
16977
  import { createHash as createHash2 } from "crypto";
16712
16978
  import { existsSync as existsSync3 } from "fs";
16713
16979
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
@@ -16816,6 +17082,19 @@ function resolveAgentBin(harness, claudeBin) {
16816
17082
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16817
17083
  }
16818
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
+ }
16819
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.';
16820
17099
  var SURVEY_DISALLOWED_TOOLS = [
16821
17100
  "Bash",
@@ -16929,6 +17208,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16929
17208
  seen.add(harness);
16930
17209
  const bin = resolveAgentBin(harness, opts.claudeBin);
16931
17210
  if (!exists(bin)) continue;
17211
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17212
+ continue;
16932
17213
  const plan = buildSurveyPlan(harness, bin, repoDir, {
16933
17214
  model: opts.model,
16934
17215
  budgetUsd: opts.budgetUsd,
@@ -16985,7 +17266,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16985
17266
  var DEEPEN_DIFF_TARGET = 300;
16986
17267
  function commitCount(repoDir) {
16987
17268
  try {
16988
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17269
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16989
17270
  encoding: "utf8",
16990
17271
  windowsHide: true,
16991
17272
  stdio: ["ignore", "pipe", "pipe"]
@@ -17056,19 +17337,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
17056
17337
  idempotentHint: false,
17057
17338
  openWorldHint: false
17058
17339
  };
17059
- var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention.';
17060
- function shapePage(page) {
17061
- const p = page ?? {};
17062
- const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
17063
- return {
17064
- id: p.id,
17065
- name: p.name,
17066
- ...p.description ? { description: p.description } : {},
17067
- ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
17068
- ...p.timestamp ? { last_updated_at: p.timestamp } : {},
17069
- body
17070
- };
17071
- }
17340
+ var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention. These are past records: check a claim that something was fixed or works against the code before relying on it.';
17072
17341
  function ok(value) {
17073
17342
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
17074
17343
  }
@@ -17086,6 +17355,8 @@ function guarded(fn) {
17086
17355
  };
17087
17356
  }
17088
17357
  function buildKnowledgeTools(client, bankId, opts = {}) {
17358
+ const extra = opts.toolGuideExtra?.trim();
17359
+ const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17089
17360
  return [
17090
17361
  {
17091
17362
  name: "hindsight_sync_status",
@@ -17145,7 +17416,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17145
17416
  },
17146
17417
  {
17147
17418
  name: "hindsight_search_knowledge_pages",
17148
- description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + CREDIT_REMINDER,
17419
+ description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + crediting,
17149
17420
  inputSchema: { query: external_exports.string().describe("what to look for") },
17150
17421
  annotations: READ_ONLY_ANNOTATIONS,
17151
17422
  handler: async (args) => {
@@ -17155,9 +17426,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17155
17426
  pages: hits.map((h) => ({
17156
17427
  page: h.name,
17157
17428
  page_id: h.id,
17429
+ // The question the page answers — the same `description` the list and read tools
17430
+ // carry, so a hit says what the page is FOR, not just how it opens.
17431
+ ...h.source_query ? { description: h.source_query } : {},
17158
17432
  snippet: h.snippet
17159
17433
  })),
17160
- crediting: CREDIT_REMINDER
17434
+ crediting
17161
17435
  });
17162
17436
  } catch (e) {
17163
17437
  return err(e);
@@ -17176,7 +17450,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17176
17450
  description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
17177
17451
  inputSchema: { page_id: external_exports.string() },
17178
17452
  annotations: READ_ONLY_ANNOTATIONS,
17179
- handler: guarded(async ({ page_id }) => shapePage(await client.getPage(page_id)))
17453
+ handler: guarded(async ({ page_id }) => client.getPage(page_id))
17180
17454
  },
17181
17455
  {
17182
17456
  name: "hindsight_reflect",
@@ -17246,12 +17520,18 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17246
17520
  import { createHash as createHash4 } from "crypto";
17247
17521
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17248
17522
  var PENDING_MAX_BYTES = 256 * 1024;
17523
+ var MAX_CURSOR_PATHS = 16;
17524
+ function advancePaths(seen, path) {
17525
+ if (!path) return seen;
17526
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
17527
+ }
17249
17528
  function pendingReplayable(cursor, now) {
17250
17529
  const pending = cursor.pending ?? [];
17251
17530
  if (!pending.length) return true;
17252
17531
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17253
17532
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17254
17533
  }
17534
+ var MAX_CURSOR_OPS = 8;
17255
17535
  function fingerprintTurns(turns, count) {
17256
17536
  const h = createHash4("sha1").update(String(count));
17257
17537
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -17262,8 +17542,10 @@ function planRetain(turns, cursor, opts) {
17262
17542
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17263
17543
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17264
17544
  if (cursor.bank !== opts.bank) return { mode: "replace" };
17265
- if (cursor.turns > turns.length) return { mode: "replace" };
17266
- if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
17545
+ const seen = cursor.paths ?? [];
17546
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17547
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
17548
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
17267
17549
  if (cursor.turns === turns.length) return { mode: "skip" };
17268
17550
  return { mode: "append", fromTurn: cursor.turns };
17269
17551
  }
@@ -17305,11 +17587,36 @@ function renderSessionJsonl(refId, turns, baseTs) {
17305
17587
  }
17306
17588
  async function supportsAppend(client) {
17307
17589
  try {
17308
- return await client.supportsIdempotentRetain();
17590
+ return await client.supportsAppendRetain();
17309
17591
  } catch {
17310
17592
  return false;
17311
17593
  }
17312
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
+ }
17313
17620
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17314
17621
  var RETAIN_RETRY_ATTEMPTS = 2;
17315
17622
  var REQUEST_BUDGET_MS = 15e3;
@@ -17339,6 +17646,7 @@ function serialize(cursors, sessionId2, write2) {
17339
17646
  });
17340
17647
  return next;
17341
17648
  }
17649
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
17342
17650
  async function retainLiveSession(client, sessionId2, turns, startTs, harness, opts = {}) {
17343
17651
  const cursors = opts.cursors;
17344
17652
  if (!cursors)
@@ -17350,20 +17658,41 @@ async function retainLiveSession(client, sessionId2, turns, startTs, harness, op
17350
17658
  harness,
17351
17659
  opts.stamp,
17352
17660
  void 0,
17353
- opts.retryUntil
17661
+ opts.retryUntil,
17662
+ opts.transcriptPath
17354
17663
  );
17355
17664
  return serialize(
17356
17665
  cursors,
17357
17666
  sessionId2,
17358
- () => writeSession(client, sessionId2, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
17667
+ () => writeSession(
17668
+ client,
17669
+ sessionId2,
17670
+ turns,
17671
+ startTs,
17672
+ harness,
17673
+ opts.stamp,
17674
+ cursors,
17675
+ opts.retryUntil,
17676
+ opts.transcriptPath
17677
+ )
17359
17678
  );
17360
17679
  }
17361
- async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
17680
+ async function writeSession(client, sessionId2, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17362
17681
  if (!turns.length) return;
17363
17682
  const refId = `conversation:${sessionId2}`;
17364
- const cursor = cursors?.read(sessionId2);
17683
+ let cursor = cursors?.read(sessionId2);
17684
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17365
17685
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17366
- const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
17686
+ let ops = [];
17687
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17688
+ ({ cursor, ops } = await settleOps(client, cursor));
17689
+ const plan = planRetain(turns, cursor, {
17690
+ appendSupported,
17691
+ bank: client.bank,
17692
+ path: transcriptPath
17693
+ });
17694
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17695
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17367
17696
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17368
17697
  if (plan.mode === "skip" && !outbox.length) return;
17369
17698
  const opId = (mode, content) => uuidV5(`${client.bank}
@@ -17372,7 +17701,10 @@ ${mode}
17372
17701
  ${content}`);
17373
17702
  const submit = (content, operationId, append) => client.retain(
17374
17703
  content,
17375
- "coding agent session",
17704
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
17705
+ // default names both speakers: the previous "coding agent session" said nothing about
17706
+ // authorship and let an assistant's proposal be recorded as the user's decision.
17707
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
17376
17708
  refId,
17377
17709
  // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
17378
17710
  // the documents list filters and draws its agent logo from, so a template cannot displace them.
@@ -17402,8 +17734,13 @@ ${content}`);
17402
17734
  turns: turns.length,
17403
17735
  fingerprint: fingerprintTurns(turns, turns.length),
17404
17736
  bank: client.bank,
17737
+ ...paths ? { paths } : {},
17405
17738
  ...appendSupported ? { appendSupported: true } : {}
17406
17739
  };
17740
+ const accepted = (id) => {
17741
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17742
+ return ops.length ? { ...next, ops } : next;
17743
+ };
17407
17744
  const stillOurs = () => {
17408
17745
  if (!cursors) return true;
17409
17746
  const now = cursors.read(sessionId2);
@@ -17412,12 +17749,10 @@ ${content}`);
17412
17749
  if (plan.mode === "replace") {
17413
17750
  const content = renderSessionJsonl(refId, turns, startTs);
17414
17751
  cursors?.write(sessionId2, { ...next, dirty: true });
17415
- await submitWithRetry(
17416
- () => submit(content, opId("replace", content), false),
17417
- stillOurs,
17418
- retryUntil
17419
- );
17420
- 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));
17421
17756
  return;
17422
17757
  }
17423
17758
  const queue = [...outbox];
@@ -17425,7 +17760,7 @@ ${content}`);
17425
17760
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17426
17761
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17427
17762
  }
17428
- cursors?.write(sessionId2, { ...next, pending: queue });
17763
+ cursors?.write(sessionId2, { ...accepted(), pending: queue });
17429
17764
  for (let i = 0; i < queue.length; i++) {
17430
17765
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17431
17766
  const entry = queue[i];
@@ -17435,12 +17770,13 @@ ${content}`);
17435
17770
  retryUntil
17436
17771
  );
17437
17772
  const remaining = queue.slice(i + 1);
17438
- 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);
17439
17775
  }
17440
17776
  }
17441
17777
 
17442
17778
  // src/core/usage.ts
17443
- import { readFileSync as readFileSync4 } from "fs";
17779
+ import { readFileSync as readFileSync5 } from "fs";
17444
17780
  import { join as join13 } from "path";
17445
17781
  function usageFilePath() {
17446
17782
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17518,7 +17854,8 @@ function resolversFor(ctx) {
17518
17854
  function buildRetainStamp(cfg, ctx) {
17519
17855
  const hasTags = Boolean(cfg.retainTags?.length);
17520
17856
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
17521
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
17857
+ const hasContext = Boolean(cfg.retainContext?.trim());
17858
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
17522
17859
  const base = resolversFor(ctx);
17523
17860
  const cache = /* @__PURE__ */ new Map();
17524
17861
  const resolvers = Object.fromEntries(
@@ -17542,19 +17879,19 @@ function buildRetainStamp(cfg, ctx) {
17542
17879
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
17543
17880
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
17544
17881
  }
17545
- return { tags, metadata };
17882
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
17883
+ return { tags, metadata, context };
17546
17884
  }
17547
17885
 
17548
- // src/core/session-start.ts
17549
- import { readFileSync as readFileSync8 } from "fs";
17550
-
17551
17886
  // src/core/skill-sync.ts
17552
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17887
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17553
17888
  import { homedir as homedir7 } from "os";
17554
- import { dirname as dirname8, join as join14 } from "path";
17889
+ import { dirname as dirname8, join as join15 } from "path";
17555
17890
  import { fileURLToPath as fileURLToPath5 } from "url";
17556
17891
 
17557
17892
  // src/core/skill-dirs.ts
17893
+ import { existsSync as existsSync5 } from "fs";
17894
+ import { join as join14 } from "path";
17558
17895
  var SKILL_DIRS = {
17559
17896
  "claude-code": [".claude", "skills"],
17560
17897
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -17567,6 +17904,8 @@ var SKILL_DIRS = {
17567
17904
  "cline-cli": [".cline", "data", "settings", "skills"],
17568
17905
  "qwen-code": [".qwen", "skills"],
17569
17906
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
17907
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
17908
+ "kimi-code": [".kimi-code", "skills"],
17570
17909
  "factory-droid": [".factory", "skills"],
17571
17910
  // Droid's user-level skills root
17572
17911
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -17574,31 +17913,53 @@ var SKILL_DIRS = {
17574
17913
  // skill removal is by fixed directory name, so installing into the shared root would make
17575
17914
  // `uninstall zcode` take Codex's and dsh's copy with it.
17576
17915
  zcode: [".zcode", "skills"],
17916
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
17917
+ // its own, never the shared agentskills root other hosts install into.
17918
+ traecode: [".trae-cn", "skills"],
17577
17919
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
17578
17920
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17579
17921
  // and dsh's copy with it.
17580
17922
  pi: [".pi", "agent", "skills"],
17581
- "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"]
17929
+ };
17930
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17931
+ var traecodeDotDirName = (home, exists = existsSync5) => {
17932
+ for (const dir of TRAE_DOT_DIRS) {
17933
+ if (exists(join14(home, dir))) return dir;
17934
+ }
17935
+ return ".trae-cn";
17936
+ };
17937
+ var resolveSkillDirs = (harness, home) => {
17938
+ const parts = SKILL_DIRS[harness];
17939
+ if (harness === "traecode" && parts) {
17940
+ return [traecodeDotDirName(home), ...parts.slice(1)];
17941
+ }
17942
+ return parts;
17582
17943
  };
17583
17944
 
17584
17945
  // src/core/skill-sync.ts
17585
17946
  function packagedSkillDir() {
17586
17947
  const here = dirname8(fileURLToPath5(import.meta.url));
17587
- const dist = join14(here, "..", "skill");
17588
- return existsSync5(join14(dist, "SKILL.md")) ? dist : join14(here, "..", "..", "skill");
17948
+ const dist = join15(here, "..", "skill");
17949
+ return existsSync6(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
17589
17950
  }
17590
17951
  function syncCompanionSkill(harness, opts = {}) {
17591
17952
  try {
17592
- const parts = SKILL_DIRS[harness];
17953
+ const parts = resolveSkillDirs(harness, opts.home ?? homedir7());
17593
17954
  if (!parts) return;
17594
17955
  const src = opts.srcDir ?? packagedSkillDir();
17595
- const srcMd = join14(src, "SKILL.md");
17596
- if (!existsSync5(srcMd)) return;
17597
- const dst = join14(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
17598
- const dstMd = join14(dst, "SKILL.md");
17599
- const installed = existsSync5(dstMd);
17956
+ const srcMd = join15(src, "SKILL.md");
17957
+ if (!existsSync6(srcMd)) return;
17958
+ const dst = join15(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
17959
+ const dstMd = join15(dst, "SKILL.md");
17960
+ const installed = existsSync6(dstMd);
17600
17961
  if (!installed && !opts.install) return;
17601
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17962
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17602
17963
  cpSync(src, dst, { recursive: true });
17603
17964
  }
17604
17965
  } catch {
@@ -17620,15 +17981,15 @@ function brandWord() {
17620
17981
  }
17621
17982
 
17622
17983
  // src/core/legacy.ts
17623
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17984
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17624
17985
  import { homedir as homedir8 } from "os";
17625
- import { join as join15, relative, isAbsolute as isAbsolute2 } from "path";
17986
+ import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17626
17987
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17627
- function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")) {
17628
- const registry2 = readJson(join15(claudeDir, "plugins", "installed_plugins.json"));
17988
+ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
17989
+ const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
17629
17990
  const plugins = registry2?.plugins;
17630
17991
  if (!plugins || typeof plugins !== "object") return void 0;
17631
- const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
17992
+ const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
17632
17993
  for (const [key, raw] of Object.entries(plugins)) {
17633
17994
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17634
17995
  if (enabled && enabled[key] === false) continue;
@@ -17645,7 +18006,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")
17645
18006
  }
17646
18007
  function readJson(path) {
17647
18008
  try {
17648
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18009
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17649
18010
  return parsed && typeof parsed === "object" ? parsed : void 0;
17650
18011
  } catch {
17651
18012
  return void 0;
@@ -17657,15 +18018,15 @@ function legacyClaudePluginWarning(key) {
17657
18018
  }
17658
18019
 
17659
18020
  // src/core/session-cache.ts
17660
- 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";
17661
18022
  import { tmpdir as tmpdir3 } from "os";
17662
- import { dirname as dirname9, join as join16 } from "path";
18023
+ import { dirname as dirname9, join as join17 } from "path";
17663
18024
  function sessionCacheFile(harness, sessionId2) {
17664
- return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
18025
+ return join17(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
17665
18026
  }
17666
18027
  function readSessionCache(cacheFile) {
17667
18028
  try {
17668
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18029
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17669
18030
  } catch {
17670
18031
  return {};
17671
18032
  }
@@ -17703,15 +18064,15 @@ async function gitSyncNote(args) {
17703
18064
  if (mode === "none" || cold) return void 0;
17704
18065
  const head = gitHeadSha(cwd);
17705
18066
  if (!head) return void 0;
17706
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
18067
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
17707
18068
  if (gitlogCurrent === void 0) return void 0;
17708
18069
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
17709
18070
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17710
18071
  let target = DEEPEN_DIFF_TARGET;
17711
18072
  try {
17712
- const { execFileSync: execFileSync4 } = await import("child_process");
18073
+ const { execFileSync: execFileSync5 } = await import("child_process");
17713
18074
  const n = Number(
17714
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18075
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17715
18076
  encoding: "utf8",
17716
18077
  windowsHide: true,
17717
18078
  stdio: ["ignore", "pipe", "pipe"]
@@ -17728,6 +18089,7 @@ async function buildSessionStartContext(args) {
17728
18089
  const t0 = Date.now();
17729
18090
  let cold;
17730
18091
  let gitDocIds;
18092
+ let bankEmpty = false;
17731
18093
  const harness = args.harness ?? "claude-code";
17732
18094
  const hasGit = args.hasGit ?? hasGitHistory;
17733
18095
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17767,11 +18129,21 @@ async function buildSessionStartContext(args) {
17767
18129
  } catch {
17768
18130
  docIds = void 0;
17769
18131
  }
17770
- 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;
17771
18137
  gitDocIds = docIds;
18138
+ if (cold === true && client.hasDocuments) {
18139
+ bankEmpty = await client.hasDocuments().then(
18140
+ (has) => !has,
18141
+ () => false
18142
+ );
18143
+ }
17772
18144
  if (docIds !== void 0) {
17773
18145
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17774
- if (docIds.size === 0) {
18146
+ if (cold) {
17775
18147
  if (cfg.codebaseSurvey !== false) {
17776
18148
  const started = await startSurvey(cwd, {
17777
18149
  harness,
@@ -17785,7 +18157,7 @@ async function buildSessionStartContext(args) {
17785
18157
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17786
18158
  const sha = resolveHeadSha(cwd);
17787
18159
  if (sha) {
17788
- 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());
17789
18161
  const counts = [];
17790
18162
  for (const id of markers) {
17791
18163
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -17819,19 +18191,18 @@ async function buildSessionStartContext(args) {
17819
18191
  }
17820
18192
  }
17821
18193
  let pages = [];
17822
- let pageListKnown = false;
17823
18194
  try {
17824
18195
  pages = parsePageList(await client.listPages());
17825
- pageListKnown = true;
17826
18196
  } catch {
17827
18197
  if (client.knowledgePagesSupported === false) {
17828
18198
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
17829
18199
  }
17830
18200
  }
17831
18201
  const additionalContext = buildKnowledgePreamble(pages, {
17832
- reflectOnNewGoals: cfg.autoInject !== "reflect"
18202
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18203
+ extra: cfg.toolGuideExtra
17833
18204
  });
17834
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18205
+ const deferInitialReflect = bankEmpty;
17835
18206
  let gitNote;
17836
18207
  if (gitDocIds) {
17837
18208
  gitNote = await gitSyncNote({
@@ -17855,7 +18226,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17855
18226
  }
17856
18227
 
17857
18228
  // src/core/hook.ts
17858
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
18229
+ import { existsSync as existsSync8 } from "fs";
17859
18230
 
17860
18231
  // src/core/inject.ts
17861
18232
  function buildReflectQuery(prompt) {
@@ -17904,15 +18275,28 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17904
18275
  // src/core/turn-journal.ts
17905
18276
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
17906
18277
  import { tmpdir as tmpdir4 } from "os";
17907
- import { dirname as dirname10, join as join17 } from "path";
18278
+ import { dirname as dirname10, join as join18 } from "path";
17908
18279
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17909
18280
 
17910
18281
  // src/core/hook.ts
17911
- var HOOK_FALLBACK_BUDGET_MS = 7e3;
17912
18282
  var HOOK_INJECT_ATTEMPTS = 2;
18283
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
17913
18284
  function resolveInjection(got, attempts) {
17914
18285
  if (got != null) return got;
17915
- 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);
17916
18300
  }
17917
18301
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17918
18302
  const t0 = Date.now();
@@ -17928,7 +18312,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17928
18312
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17929
18313
  const t0 = Date.now();
17930
18314
  try {
17931
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18315
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
17932
18316
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
17933
18317
  return observations.length ? formatRecallFallback(observations, lead) : null;
17934
18318
  } catch (e) {
@@ -17936,8 +18320,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17936
18320
  return void 0;
17937
18321
  }
17938
18322
  }
17939
- async function reflectFallback(harness, prompt, client) {
17940
- const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
18323
+ async function reflectFallback(harness, prompt, client, timeoutMs) {
18324
+ const deadline = Date.now() + timeoutMs;
17941
18325
  const remaining = () => Math.max(deadline - Date.now(), 1);
17942
18326
  return await injectPages(harness, prompt, client, remaining(), "reflect_fallback_pages") ?? // Event name predates the `injectRecall` rename and is kept: it is a logged contract that
17943
18327
  // other tools read, so renaming it would silently break them.
@@ -17962,7 +18346,7 @@ async function buildHookOutput(args) {
17962
18346
  harness,
17963
18347
  prompt,
17964
18348
  client,
17965
- HOOK_FALLBACK_BUDGET_MS,
18349
+ cfg.injectTimeoutMs,
17966
18350
  "inject_pages",
17967
18351
  PAGE_INJECT_LEAD
17968
18352
  );
@@ -17975,7 +18359,7 @@ async function buildHookOutput(args) {
17975
18359
  harness,
17976
18360
  prompt,
17977
18361
  client,
17978
- HOOK_FALLBACK_BUDGET_MS,
18362
+ cfg.injectTimeoutMs,
17979
18363
  "inject_recall",
17980
18364
  RECALL_INJECT_LEAD
17981
18365
  );
@@ -18003,7 +18387,7 @@ async function buildHookOutput(args) {
18003
18387
  answer: reflectAnswer.slice(0, 8e3)
18004
18388
  });
18005
18389
  } catch (e) {
18006
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18390
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18007
18391
  reflectFailed = true;
18008
18392
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18009
18393
  error: describeError(e)
@@ -18017,7 +18401,7 @@ async function buildHookOutput(args) {
18017
18401
  query: prompt.slice(0, 80)
18018
18402
  });
18019
18403
  if (e instanceof ReflectError && e.fallbackEligible) {
18020
- fallback = await reflectFallback(harness, prompt, client);
18404
+ fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
18021
18405
  if (fallback) reflectAnswer = fallback;
18022
18406
  }
18023
18407
  }
@@ -18050,7 +18434,12 @@ async function buildHookOutput(args) {
18050
18434
  const blocks = [];
18051
18435
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18052
18436
  if (cadence > 0 && turns % cadence === 0) {
18053
- blocks.push(buildRosterRefresh(pages, { reflectOnNewGoals: cfg.autoInject !== "reflect" }));
18437
+ blocks.push(
18438
+ buildRosterRefresh(pages, {
18439
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18440
+ extra: cfg.toolGuideExtra
18441
+ })
18442
+ );
18054
18443
  }
18055
18444
  const kept = blocks.filter(Boolean);
18056
18445
  let notice;
@@ -18070,6 +18459,7 @@ async function buildHookOutput(args) {
18070
18459
 
18071
18460
  // src/core/runtime.ts
18072
18461
  var HARNESS = "opencode";
18462
+ var FLUSH_TIMEOUT_MS = 1e4;
18073
18463
  var RuntimeCore = class {
18074
18464
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18075
18465
  this.client = client;
@@ -18095,6 +18485,8 @@ var RuntimeCore = class {
18095
18485
  usageCursors = memoryUsageCursorStore();
18096
18486
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18097
18487
  fetchTranscript;
18488
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18489
+ inFlight = /* @__PURE__ */ new Set();
18098
18490
  lastInjection = "";
18099
18491
  // most recent turn's injection block, keyed by nothing (see getInjection)
18100
18492
  deferInitialReflect = false;
@@ -18119,6 +18511,7 @@ var RuntimeCore = class {
18119
18511
  pageTrigger: buildPageTrigger(this.cfg),
18120
18512
  reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
18121
18513
  reflectBudget: this.cfg.reflectBudget,
18514
+ toolGuideExtra: this.cfg.toolGuideExtra,
18122
18515
  stampFor: () => buildRetainStamp(this.cfg, {
18123
18516
  directory: this.projectDir,
18124
18517
  harness: this.harness,
@@ -18186,7 +18579,8 @@ var RuntimeCore = class {
18186
18579
  if (turns === 1) {
18187
18580
  blocks.push(
18188
18581
  buildKnowledgePreamble(output.pages, {
18189
- reflectOnNewGoals: this.cfg.autoInject !== "reflect"
18582
+ reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18583
+ extra: this.cfg.toolGuideExtra
18190
18584
  })
18191
18585
  );
18192
18586
  }
@@ -18225,8 +18619,9 @@ var RuntimeCore = class {
18225
18619
  */
18226
18620
  async onTranscript(sessionId2, turns, lastTurnComplete) {
18227
18621
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18228
- if (!this.writeBackEnabled || !sessionId2 || !turns.length) return;
18622
+ if (!sessionId2 || !turns.length) return;
18229
18623
  this.recordUsage(sessionId2, turns, lastTurnComplete);
18624
+ if (!this.writeBackEnabled) return;
18230
18625
  const st = this.stateFor(sessionId2);
18231
18626
  this.retain(sessionId2, turns, st.startTs);
18232
18627
  }
@@ -18244,7 +18639,7 @@ var RuntimeCore = class {
18244
18639
  */
18245
18640
  async onSessionIdle(sessionId2) {
18246
18641
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18247
- if (!this.writeBackEnabled || !sessionId2 || !this.fetchTranscript) return;
18642
+ if (!sessionId2 || !this.fetchTranscript) return;
18248
18643
  let turns;
18249
18644
  try {
18250
18645
  turns = await this.fetchTranscript(sessionId2);
@@ -18257,6 +18652,7 @@ var RuntimeCore = class {
18257
18652
  }
18258
18653
  if (!turns.length) return;
18259
18654
  this.recordUsage(sessionId2, turns, true);
18655
+ if (!this.writeBackEnabled) return;
18260
18656
  const st = this.stateFor(sessionId2);
18261
18657
  if (turns.length <= st.retainedTurns) return;
18262
18658
  st.retainedTurns = turns.length;
@@ -18284,10 +18680,27 @@ var RuntimeCore = class {
18284
18680
  }
18285
18681
  return st;
18286
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
+ }
18287
18700
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18288
18701
  retain(sessionId2, turns, startTs, trigger = "turn") {
18289
18702
  const t0 = Date.now();
18290
- 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(
18291
18704
  () => retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
18292
18705
  cursors: this.cursors,
18293
18706
  stamp: buildRetainStamp(this.cfg, {
@@ -18312,6 +18725,8 @@ var RuntimeCore = class {
18312
18725
  trigger
18313
18726
  })
18314
18727
  );
18728
+ this.inFlight.add(write2);
18729
+ void write2.finally(() => this.inFlight.delete(write2));
18315
18730
  }
18316
18731
  };
18317
18732