@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/deepen.js CHANGED
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/deepen.ts
4
- import { execFileSync as execFileSync3 } from "child_process";
5
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
4
+ import { execFileSync as execFileSync4 } from "child_process";
6
5
  import { tmpdir as tmpdir2 } from "os";
7
6
  import { join as join10 } from "path";
8
7
 
@@ -12,6 +11,7 @@ import { homedir as homedir2 } from "os";
12
11
  import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
13
12
 
14
13
  // src/core/diag.ts
14
+ import { readFileSync } from "fs";
15
15
  import { join as join2 } from "path";
16
16
 
17
17
  // src/core/log.ts
@@ -87,7 +87,7 @@ function diag(harness, event, extra = {}) {
87
87
  }
88
88
 
89
89
  // src/core/git-layout.ts
90
- import { lstatSync, readFileSync, realpathSync } from "fs";
90
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
91
91
  import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
92
92
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
93
93
  var ATTEMPTS = 3;
@@ -111,7 +111,7 @@ function entryKind(path) {
111
111
  }
112
112
  function readTextOrNull(path) {
113
113
  try {
114
- return readFileSync(path, "utf8");
114
+ return readFileSync2(path, "utf8");
115
115
  } catch (error) {
116
116
  if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
117
117
  return null;
@@ -273,13 +273,13 @@ function isWithin(directory, configured) {
273
273
  function mapLookup(map, directory) {
274
274
  const cwd = normalize(directory);
275
275
  let best;
276
- for (const [dir, bank] of Object.entries(map)) {
276
+ for (const [dir, value] of Object.entries(map)) {
277
277
  const p = configuredDir(dir);
278
278
  if (isWithin(cwd, p)) {
279
- if (!best || p.length > best.len) best = { len: p.length, bank };
279
+ if (!best || p.length > best.len) best = { len: p.length, value };
280
280
  }
281
281
  }
282
- return best?.bank;
282
+ return best?.value;
283
283
  }
284
284
  function lookupDirectories(config, directory, sessionRoot = "") {
285
285
  const directories = [normalize(directory)];
@@ -303,6 +303,10 @@ function isOptedIn(config, directory) {
303
303
  const pathMap = config.mapPathToBank;
304
304
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
305
305
  }
306
+ function pathSection(config, paths, directory) {
307
+ if (!directory || !paths) return void 0;
308
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
309
+ }
306
310
  function mappedBank(config, directory, sessionRoot) {
307
311
  const pathMap = config.mapPathToBank;
308
312
  if (!directory || !pathMap) return void 0;
@@ -352,7 +356,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
352
356
  // src/core/missions.ts
353
357
  import { createHash } from "crypto";
354
358
  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.";
355
- 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.";
359
+ 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.";
356
360
  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.`;
357
361
  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.";
358
362
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -428,6 +432,8 @@ var KNOWLEDGE_LABELS = {
428
432
  ]
429
433
  };
430
434
  function pageScopeRule(project) {
435
+ if (project === void 0)
436
+ 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.`;
431
437
  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.`;
432
438
  }
433
439
  var PAGE_TAXONOMY = [
@@ -563,12 +569,17 @@ var CODING_BANK_TEMPLATE = {
563
569
  }
564
570
  };
565
571
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
572
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
573
+ "retain_strategies",
574
+ "entity_labels",
575
+ "retain_extraction_mode"
576
+ ];
566
577
  function isSet(v) {
567
578
  if (v === null || v === void 0) return false;
568
579
  if (typeof v === "string") return v.trim() !== "";
569
580
  return true;
570
581
  }
571
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
582
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
572
583
  const current2 = overrides ?? {};
573
584
  const template = CODING_BANK_TEMPLATE.bank;
574
585
  const bank = {};
@@ -597,19 +608,26 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
597
608
  const [knowledgeGroup] = template.entity_labels;
598
609
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
599
610
  bank.entity_labels = [...labels, knowledgeGroup];
611
+ for (const [key, value] of Object.entries(defaults)) {
612
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
613
+ bank[key] = value;
614
+ }
600
615
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
601
616
  }
602
617
 
618
+ // package.json
619
+ var version = "0.8.1";
620
+
603
621
  // src/core/util.ts
604
622
  import { accessSync, constants } from "fs";
605
623
  import { delimiter, join as join5 } from "path";
606
624
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
607
- function semverGte(version, min) {
625
+ function semverGte(version2, min) {
608
626
  const parts = (v) => {
609
627
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
610
628
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
611
629
  };
612
- const a = version ? parts(version) : void 0;
630
+ const a = version2 ? parts(version2) : void 0;
613
631
  const b = parts(min);
614
632
  if (!a || !b) return false;
615
633
  for (let i = 0; i < 3; i++) {
@@ -634,6 +652,7 @@ async function pool(items, n, fn, onError, onProgress) {
634
652
  }
635
653
 
636
654
  // src/core/hindsight.ts
655
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
637
656
  function resolveRetainScopes(tags, configured) {
638
657
  if (configured !== "per_source") return configured;
639
658
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -669,7 +688,7 @@ async function isEndpointMissing(r) {
669
688
  const j = await r.json();
670
689
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
671
690
  } catch {
672
- return true;
691
+ return false;
673
692
  }
674
693
  }
675
694
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -688,6 +707,12 @@ var ReflectError = class extends Error {
688
707
  get fallbackEligible() {
689
708
  return this.timedOut || this.status !== void 0 && this.status >= 500;
690
709
  }
710
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
711
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
712
+ get permanent() {
713
+ const s = this.status;
714
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
715
+ }
691
716
  };
692
717
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
693
718
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -698,8 +723,31 @@ var DEFAULT_RECALL_OPTIONS = {
698
723
  include: { entities: null }
699
724
  };
700
725
  var POLL_CYCLE_MS = 5e3;
726
+ var POLL_MAX_SERVER_ERRORS = 12;
701
727
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
702
728
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
729
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
730
+ function shapePage(page) {
731
+ const p = page ?? {};
732
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
733
+ return {
734
+ id: p.id,
735
+ name: p.name,
736
+ ...p.description ? { description: p.description } : {},
737
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
738
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
739
+ body
740
+ };
741
+ }
742
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
743
+ function signalOnlyDispatcher() {
744
+ void globalThis.Headers;
745
+ const d = globalThis[GLOBAL_DISPATCHER];
746
+ if (typeof d?.compose !== "function") return void 0;
747
+ return d.compose(
748
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
749
+ );
750
+ }
703
751
  var HindsightClient = class {
704
752
  apiUrl;
705
753
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -719,6 +767,7 @@ var HindsightClient = class {
719
767
  observationScopes;
720
768
  pageSearchLimit;
721
769
  recallOptions;
770
+ rateLimitPatienceMs;
722
771
  constructor(o) {
723
772
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
724
773
  this.token = o.apiToken;
@@ -731,13 +780,18 @@ var HindsightClient = class {
731
780
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
732
781
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
733
782
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
783
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
734
784
  }
735
785
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
736
786
  get apiToken() {
737
787
  return this.token;
738
788
  }
739
789
  headers() {
740
- const h = { "Content-Type": "application/json" };
790
+ const h = {
791
+ "Content-Type": "application/json",
792
+ "Accept-Encoding": "identity",
793
+ "User-Agent": USER_AGENT
794
+ };
741
795
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
742
796
  return h;
743
797
  }
@@ -768,7 +822,8 @@ var HindsightClient = class {
768
822
  * bounds the whole call.
769
823
  */
770
824
  async fetchWithAuth(url, init) {
771
- const send = () => fetch(url, { ...init, headers: this.headers() });
825
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
826
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
772
827
  const r = await send();
773
828
  if (r.status !== 401 || !this.refreshToken()) return r;
774
829
  return send();
@@ -784,13 +839,22 @@ var HindsightClient = class {
784
839
  }
785
840
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
786
841
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
787
- const r = await this.fetchWithAuth(url, {
788
- method,
789
- body: body ? JSON.stringify(body) : void 0,
790
- signal: AbortSignal.timeout(timeoutMs)
791
- });
792
- if (r.status === 429 && !tolerate.includes(429))
793
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
842
+ const payload = body ? JSON.stringify(body) : void 0;
843
+ let r;
844
+ for (let attempt = 0, waited = 0; ; attempt++) {
845
+ r = await this.fetchWithAuth(url, {
846
+ method,
847
+ body: payload,
848
+ signal: AbortSignal.timeout(timeoutMs)
849
+ });
850
+ if (r.status !== 429 || tolerate.includes(429)) break;
851
+ const asked = retryAfterMs(r.headers.get("retry-after"));
852
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
853
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
854
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
855
+ await sleep(wait);
856
+ waited += wait;
857
+ }
794
858
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
795
859
  throw new Error(
796
860
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -825,7 +889,7 @@ var HindsightClient = class {
825
889
  }
826
890
  /**
827
891
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
828
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
892
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
829
893
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
830
894
  */
831
895
  async supportsIdempotentRetain() {
@@ -835,14 +899,37 @@ var HindsightClient = class {
835
899
  }
836
900
  return this.idempotentRetain;
837
901
  }
902
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
903
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
904
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
905
+ * `/version`, so that stays as the fallback. */
838
906
  async probeIdempotentRetain() {
907
+ for (const path of ["/v1/version", "/version"]) {
908
+ try {
909
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
910
+ if (!r.ok) continue;
911
+ const j = await r.json();
912
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
913
+ } catch {
914
+ }
915
+ }
916
+ return false;
917
+ }
918
+ /**
919
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
920
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
921
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
922
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
923
+ */
924
+ async supportsAppendRetain() {
925
+ if (!await this.supportsIdempotentRetain()) return false;
839
926
  try {
840
- const r = await this.req("GET", `${this.apiUrl}/version`);
841
- if (!r.ok) return false;
927
+ const r = await this.req("GET", this.bankUrl("/config"));
928
+ if (!r.ok) return true;
842
929
  const j = await r.json();
843
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
930
+ return j.config?.store_document_text !== false;
844
931
  } catch {
845
- return false;
932
+ return true;
846
933
  }
847
934
  }
848
935
  /**
@@ -870,6 +957,32 @@ var HindsightClient = class {
870
957
  }
871
958
  return ids;
872
959
  }
960
+ /**
961
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
962
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
963
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
964
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
965
+ */
966
+ async documentTags(documentId) {
967
+ const limit = 100;
968
+ for (let offset = 0; ; offset += limit) {
969
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
970
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
971
+ const j = await r.json();
972
+ const items = j.items ?? [];
973
+ const hit = items.find((it) => it.id === documentId);
974
+ if (hit) return hit.tags ?? [];
975
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
976
+ }
977
+ }
978
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
979
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
980
+ async hasDocuments() {
981
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
982
+ if (r.status === 404) return false;
983
+ const j = await r.json();
984
+ return (j.total ?? j.items?.length ?? 0) > 0;
985
+ }
873
986
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
874
987
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
875
988
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -891,7 +1004,8 @@ var HindsightClient = class {
891
1004
  } else {
892
1005
  const manifest = codingBankManifest(
893
1006
  opts.reset ? void 0 : await this.readBankOverrides(),
894
- opts.extractionMode
1007
+ opts.extractionMode,
1008
+ opts.defaults
895
1009
  );
896
1010
  if (!manifest) {
897
1011
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -950,7 +1064,13 @@ var HindsightClient = class {
950
1064
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
951
1065
  const start = Date.now();
952
1066
  const pending = new Set(ids);
1067
+ const serverErrors = /* @__PURE__ */ new Map();
953
1068
  let failed = 0;
1069
+ const giveUp = (id, status) => {
1070
+ pending.delete(id);
1071
+ failed++;
1072
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1073
+ };
954
1074
  while (pending.size && Date.now() - start < maxMs) {
955
1075
  let backoffMs = POLL_CYCLE_MS;
956
1076
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -963,7 +1083,14 @@ var HindsightClient = class {
963
1083
  );
964
1084
  return;
965
1085
  }
966
- if (!r.ok) return;
1086
+ if (r.status >= 500) {
1087
+ const n = (serverErrors.get(id) ?? 0) + 1;
1088
+ serverErrors.set(id, n);
1089
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1090
+ return;
1091
+ }
1092
+ if (!r.ok) return giveUp(id, r.status);
1093
+ serverErrors.delete(id);
967
1094
  const st = ((await r.json()).status || "").toLowerCase();
968
1095
  if (TERMINAL.has(st)) {
969
1096
  pending.delete(id);
@@ -1097,8 +1224,8 @@ var HindsightClient = class {
1097
1224
  return { items };
1098
1225
  }
1099
1226
  /**
1100
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1101
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1227
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1228
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1102
1229
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1103
1230
  * token cap.
1104
1231
  */
@@ -1109,7 +1236,7 @@ var HindsightClient = class {
1109
1236
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1110
1237
  );
1111
1238
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1112
- return await r.json();
1239
+ return shapePage(await r.json());
1113
1240
  }
1114
1241
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1115
1242
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1130,6 +1257,7 @@ var HindsightClient = class {
1130
1257
  return (j.results ?? []).map((x) => ({
1131
1258
  id: x.id,
1132
1259
  name: x.name,
1260
+ ...x.source_query ? { source_query: x.source_query } : {},
1133
1261
  snippet: x.snippet ?? "",
1134
1262
  score: x.score ?? 0
1135
1263
  }));
@@ -1146,7 +1274,7 @@ var HindsightClient = class {
1146
1274
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1147
1275
  */
1148
1276
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1149
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1277
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1150
1278
  const existing = /* @__PURE__ */ new Map();
1151
1279
  let roots;
1152
1280
  try {
@@ -1221,7 +1349,7 @@ var HindsightClient = class {
1221
1349
  }
1222
1350
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1223
1351
  this.log(
1224
- `[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` : "")
1352
+ `[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` : "")
1225
1353
  );
1226
1354
  }
1227
1355
  /**
@@ -1232,23 +1360,33 @@ var HindsightClient = class {
1232
1360
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1233
1361
  * consolidation under the auto-refresh that used to be the default (#3506).
1234
1362
  *
1235
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1236
- * initiative's own title, and re-stating either would rebuild a page whose question never
1237
- * changed. The tree read above is reused rather than re-fetched.
1363
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1364
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1365
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1366
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1367
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1368
+ * reused rather than re-fetched.
1238
1369
  */
1239
1370
  async resyncInitiativeTriggers(roots, pageTrigger) {
1240
1371
  const folder = roots.find(
1241
1372
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1242
1373
  );
1374
+ const bankScope = pageScopeRule(this.bank);
1243
1375
  let updated = 0;
1244
1376
  for (const page of folder?.children ?? []) {
1245
- if (page.kind !== "page" || page.trigger == null) continue;
1246
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1247
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1377
+ if (page.kind !== "page") continue;
1378
+ const patch = {};
1379
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1380
+ if (query !== page.description) patch.source_query = query;
1381
+ if (page.trigger != null) {
1382
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1383
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1384
+ }
1385
+ if (!patch.trigger && !patch.source_query) continue;
1248
1386
  const r = await this.req(
1249
1387
  "PATCH",
1250
1388
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1251
- { trigger: pageTriggerPatch(desired) }
1389
+ patch
1252
1390
  );
1253
1391
  if (r.status === 404) continue;
1254
1392
  updated++;
@@ -1276,10 +1414,9 @@ var HindsightClient = class {
1276
1414
  let pageId = args.relatesToPageId;
1277
1415
  if (!pageId) {
1278
1416
  const folderId = await this.ensureFolder("Initiatives");
1279
- const subject = this.project ?? this.bank;
1280
1417
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1281
1418
  name: args.title,
1282
- 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),
1419
+ 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),
1283
1420
  parent_id: folderId,
1284
1421
  tags: ["knowledge:feature-work"],
1285
1422
  max_tokens: PAGE_MAX_TOKENS,
@@ -1294,7 +1431,7 @@ var HindsightClient = class {
1294
1431
  }
1295
1432
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1296
1433
  const content = `${verb}: ${args.title}. ${args.summary}`;
1297
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1434
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1298
1435
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1299
1436
  const context = `initiative marker for [[page:${pageId}]]`;
1300
1437
  await this.retain(content, context, markerId, tags, "document", {
@@ -1350,13 +1487,15 @@ async function ingestChats(client, sessions, opts = {}) {
1350
1487
  const id = s.id || `s${i}`;
1351
1488
  const stamp = opts.stampFor?.(id);
1352
1489
  const sessBase = NOW - (sessions.length - 1 - i) * 36e5;
1353
- const baseIso = new Date(sessBase).toISOString();
1490
+ const sourceTs = (s.turns || []).map((t) => t.timestamp).find((v) => typeof v === "string" && !Number.isNaN(Date.parse(v)));
1491
+ const anchorMs = sourceTs ? Date.parse(sourceTs) : sessBase;
1492
+ const baseIso = sourceTs ?? new Date(sessBase).toISOString();
1354
1493
  const turns = withRefId(
1355
1494
  `chat:${id}`,
1356
1495
  (s.turns || []).map((t, j) => ({
1357
1496
  role: t.role,
1358
1497
  content: t.text,
1359
- timestamp: t.timestamp || new Date(sessBase + (j + 1) * 6e4).toISOString()
1498
+ timestamp: t.timestamp || new Date(anchorMs + (j + 1) * 6e4).toISOString()
1360
1499
  })),
1361
1500
  baseIso
1362
1501
  );
@@ -1387,7 +1526,7 @@ async function ingestChats(client, sessions, opts = {}) {
1387
1526
  }
1388
1527
 
1389
1528
  // src/core/config.ts
1390
- import { readFileSync as readFileSync2 } from "fs";
1529
+ import { readFileSync as readFileSync3 } from "fs";
1391
1530
  import { homedir as homedir3 } from "os";
1392
1531
  import { join as join7 } from "path";
1393
1532
 
@@ -1476,6 +1615,7 @@ function resolveCustomPages(raw) {
1476
1615
  }
1477
1616
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1478
1617
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1618
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1479
1619
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1480
1620
  function resolveReflectBudget(raw) {
1481
1621
  const value = raw.reflectBudget;
@@ -1502,6 +1642,22 @@ function resolveObservationScopes(raw) {
1502
1642
  }
1503
1643
  return DEFAULT_OBSERVATION_SCOPES;
1504
1644
  }
1645
+ function resolveDefaultBankConfig(raw) {
1646
+ const value = raw;
1647
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1648
+ const out = {};
1649
+ for (const [key, v] of Object.entries(value)) {
1650
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1651
+ log.warn(
1652
+ "config",
1653
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1654
+ );
1655
+ continue;
1656
+ }
1657
+ out[key] = v;
1658
+ }
1659
+ return out;
1660
+ }
1505
1661
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1506
1662
  function resolveAutoInject(raw) {
1507
1663
  if (raw.autoReflect !== void 0) {
@@ -1541,18 +1697,21 @@ function resolveConfig(raw = {}) {
1541
1697
  // write sessions back by default, every harness
1542
1698
  manageBankConfig: raw.manageBankConfig ?? true,
1543
1699
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1700
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1544
1701
  maxParallelRetains: raw.maxParallelRetains || 10,
1545
1702
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1546
1703
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1547
1704
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1548
1705
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1549
1706
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1707
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1550
1708
  reflectBudget: resolveReflectBudget(raw),
1551
1709
  autoInject: resolveAutoInject(raw),
1552
1710
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1553
1711
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1554
1712
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1555
1713
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1714
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1556
1715
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1557
1716
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1558
1717
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1572,18 +1731,22 @@ function resolveConfig(raw = {}) {
1572
1731
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1573
1732
  // nested object cannot reach the API as a tag and fail the whole retain.
1574
1733
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1734
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1735
+ // the built-in default) from a configured value, and an empty context would strip the default.
1736
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1575
1737
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1576
1738
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1577
1739
  ) : {},
1578
1740
  observationScopes: resolveObservationScopes(raw.observationScopes),
1579
1741
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1742
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1580
1743
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1581
1744
  autoUpdate: raw.autoUpdate ?? true
1582
1745
  };
1583
1746
  }
1584
1747
  function readRaw(path) {
1585
1748
  try {
1586
- return JSON.parse(readFileSync2(path, "utf8"));
1749
+ return JSON.parse(readFileSync3(path, "utf8"));
1587
1750
  } catch (e) {
1588
1751
  if (e?.code !== "ENOENT") {
1589
1752
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1593,7 +1756,12 @@ function readRaw(path) {
1593
1756
  }
1594
1757
  function mergeRaw(a, b) {
1595
1758
  const { harnesses: _drop, ...flat } = b;
1596
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1759
+ return {
1760
+ ...a,
1761
+ ...flat,
1762
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1763
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1764
+ };
1597
1765
  }
1598
1766
  function applyLayer(raw, layer, harness) {
1599
1767
  let out = mergeRaw(raw, layer);
@@ -1624,9 +1792,11 @@ var ENV_KEYS = {
1624
1792
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1625
1793
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1626
1794
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1795
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1627
1796
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1628
1797
  autoInject: "HINDSIGHT_AUTO_INJECT",
1629
1798
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1799
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1630
1800
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1631
1801
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1632
1802
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1668,6 +1838,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1668
1838
  "maxParallelRetains",
1669
1839
  "reflectTimeoutMs",
1670
1840
  "reflectToolTimeoutMs",
1841
+ "injectTimeoutMs",
1671
1842
  "pageSearchLimit",
1672
1843
  "pageRefreshEveryTurns",
1673
1844
  "seedLimit",
@@ -1716,15 +1887,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1716
1887
  function applyBankConfig(cfg2, resolvedId, directory) {
1717
1888
  if (directory !== void 0 && !isOptedIn(cfg2, directory))
1718
1889
  return { cfg: { ...cfg2, disabled: true }, bankId: resolvedId };
1890
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg2, cfg2.paths, directory);
1891
+ if (byPath) {
1892
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1893
+ cfg2 = { ...cfg2, ...resolvePartial(cfg2, rest) };
1894
+ }
1719
1895
  const section = cfg2.banks[resolvedId];
1720
1896
  if (!section) return { cfg: cfg2, bankId: resolvedId };
1721
- const safe = { ...section };
1722
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1723
- delete safe.banks;
1897
+ const safe = overrideFields(section);
1724
1898
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1725
1899
  delete safe.bank;
1726
1900
  return { cfg: { ...cfg2, ...resolvePartial(cfg2, safe) }, bankId };
1727
1901
  }
1902
+ function overrideFields(section) {
1903
+ const safe = { ...section };
1904
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1905
+ delete safe.banks;
1906
+ delete safe.paths;
1907
+ return safe;
1908
+ }
1728
1909
  function resolvePartial(cfg2, patch) {
1729
1910
  const full = resolveConfig(patch);
1730
1911
  const out = {};
@@ -1733,6 +1914,16 @@ function resolvePartial(cfg2, patch) {
1733
1914
  out[key] = full[key];
1734
1915
  }
1735
1916
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1917
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1918
+ const conn = resolveConfig({
1919
+ serverMode: patch.serverMode ?? cfg2.serverMode,
1920
+ apiPort: patch.apiPort ?? cfg2.apiPort,
1921
+ apiUrl: patch.apiUrl ?? (cfg2.serverMode === "daemon" ? void 0 : cfg2.apiUrl)
1922
+ });
1923
+ out.serverMode = conn.serverMode;
1924
+ out.apiUrl = conn.apiUrl;
1925
+ out.apiPort = conn.apiPort;
1926
+ }
1736
1927
  return out;
1737
1928
  }
1738
1929
 
@@ -1741,8 +1932,9 @@ import { execFileSync } from "child_process";
1741
1932
  import { resolve as resolve2 } from "path";
1742
1933
  var US = "";
1743
1934
  var RS = "";
1935
+ var GITLOG_HEAD = "gitlog-head:";
1744
1936
  function git(repo, ...args) {
1745
- return execFileSync("git", ["-C", repo, ...args], {
1937
+ return execFileSync("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
1746
1938
  encoding: "utf8",
1747
1939
  maxBuffer: 1 << 28,
1748
1940
  windowsHide: true,
@@ -1762,6 +1954,7 @@ function gitHeadSha(dir) {
1762
1954
  }
1763
1955
  }
1764
1956
  function commitsSince(dir, sinceSha) {
1957
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
1765
1958
  try {
1766
1959
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
1767
1960
  return Number.isFinite(n) ? n : null;
@@ -1814,12 +2007,17 @@ ${diff}`;
1814
2007
  function gitLogText(repo, limit) {
1815
2008
  let raw;
1816
2009
  try {
2010
+ const total = Number(git(repo, "rev-list", "--count", "--no-merges", "HEAD").trim());
2011
+ const step = Math.max(1, Math.ceil(limit / 2));
2012
+ const start = total > limit ? Math.ceil((total - limit) / step) * step : 0;
1817
2013
  raw = git(
1818
2014
  repo,
1819
2015
  "log",
1820
2016
  `-n`,
1821
- String(limit),
2017
+ String(total - start),
1822
2018
  "--no-merges",
2019
+ "--reverse",
2020
+ // applied after -n: the newest N, printed oldest first
1823
2021
  "--date=short",
1824
2022
  `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`
1825
2023
  );
@@ -1860,7 +2058,7 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1860
2058
  ...stamp?.tags ?? [],
1861
2059
  "source:git",
1862
2060
  "source:git-log",
1863
- ...head ? [`gitlog-head:${head}`] : []
2061
+ ...head ? [`${GITLOG_HEAD}${head}`] : []
1864
2062
  ])
1865
2063
  ];
1866
2064
  await client.retain(
@@ -1886,12 +2084,20 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1886
2084
  return 1;
1887
2085
  }
1888
2086
  }
2087
+ async function gitLogIsCurrent(client, repo, head) {
2088
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
2089
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
2090
+ return true;
2091
+ const tags = await client.documentTags?.(canonical2) ?? [];
2092
+ return tags.some(
2093
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
2094
+ );
2095
+ }
1889
2096
  async function syncGitLog(client, repo, opts) {
1890
2097
  const log3 = opts.log ?? (() => {
1891
2098
  });
1892
2099
  const head = gitHeadSha(repo);
1893
- const canonical2 = `gitlog:${repoNameOf(repo)}`;
1894
- const current2 = head !== null && (await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").catch(() => /* @__PURE__ */ new Set())).has(canonical2);
2100
+ const current2 = head !== null && await gitLogIsCurrent(client, repo, head).catch(() => false);
1895
2101
  if (current2) {
1896
2102
  log3("[gitlog] current with HEAD \u2014 skipping");
1897
2103
  return 0;
@@ -1900,7 +2106,7 @@ async function syncGitLog(client, repo, opts) {
1900
2106
  }
1901
2107
 
1902
2108
  // src/core/survey.ts
1903
- import { spawn as realSpawn3 } from "child_process";
2109
+ import { execFileSync as execFileSync2, spawn as realSpawn3 } from "child_process";
1904
2110
  import { createHash as createHash4 } from "crypto";
1905
2111
  import { existsSync as existsSync2 } from "fs";
1906
2112
  import { homedir as homedir4, tmpdir } from "os";
@@ -1923,6 +2129,70 @@ import {
1923
2129
  writeFileSync
1924
2130
  } from "fs";
1925
2131
  import { join as join8 } from "path";
2132
+ var LEASE_HEARTBEAT_MS = 5e3;
2133
+ var LEASE_STALE_MS = 3e4;
2134
+ function tryRename(from, to) {
2135
+ try {
2136
+ renameSync2(from, to);
2137
+ return true;
2138
+ } catch {
2139
+ return false;
2140
+ }
2141
+ }
2142
+ function releaseLease(lease2) {
2143
+ try {
2144
+ unlinkSync(join8(lease2.directory, lease2.owner));
2145
+ } catch {
2146
+ return;
2147
+ }
2148
+ try {
2149
+ rmdirSync(lease2.directory);
2150
+ } catch {
2151
+ }
2152
+ }
2153
+ function heartbeatLease(lease2) {
2154
+ try {
2155
+ const now = /* @__PURE__ */ new Date();
2156
+ utimesSync(join8(lease2.directory, lease2.owner), now, now);
2157
+ return true;
2158
+ } catch (error) {
2159
+ return error.code !== "ENOENT";
2160
+ }
2161
+ }
2162
+ function reclaimIfStale(directory, staleMs) {
2163
+ const owners = readdirSync(directory);
2164
+ if (owners.length === 0) {
2165
+ try {
2166
+ rmdirSync(directory);
2167
+ } catch {
2168
+ }
2169
+ return true;
2170
+ }
2171
+ if (owners.length !== 1) return false;
2172
+ const age = Date.now() - statSync2(join8(directory, owners[0])).mtimeMs;
2173
+ if (Math.abs(age) <= staleMs) return false;
2174
+ releaseLease({ directory, owner: owners[0] });
2175
+ return true;
2176
+ }
2177
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
2178
+ let staging;
2179
+ try {
2180
+ mkdirSync2(root, { recursive: true, mode: 448 });
2181
+ staging = mkdtempSync(join8(root, "claim-"));
2182
+ const owner = randomUUID();
2183
+ writeFileSync(join8(staging, owner), "", { flag: "wx", mode: 384 });
2184
+ const directory = join8(root, `survey-${key}.lock`);
2185
+ if (!tryRename(staging, directory)) {
2186
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
2187
+ if (!tryRename(staging, directory)) return void 0;
2188
+ }
2189
+ return { directory, owner };
2190
+ } catch {
2191
+ return void 0;
2192
+ } finally {
2193
+ if (staging) rmSync(staging, { recursive: true, force: true });
2194
+ }
2195
+ }
1926
2196
 
1927
2197
  // src/core/survey.ts
1928
2198
  var SURVEY_DOC_IDS = [
@@ -1933,16 +2203,16 @@ var SURVEY_DOC_IDS = [
1933
2203
  ];
1934
2204
 
1935
2205
  // src/core/status.ts
1936
- import { execFileSync as execFileSync2 } from "child_process";
2206
+ import { execFileSync as execFileSync3 } from "child_process";
1937
2207
  var DEEPEN_DIFF_TARGET = 300;
1938
2208
 
1939
2209
  // src/harness/registry.ts
1940
- import { readFileSync as readFileSync3 } from "fs";
2210
+ import { readFileSync as readFileSync4 } from "fs";
1941
2211
  var jsonChatReader = (harness) => ({
1942
2212
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
1943
2213
  async read(opts) {
1944
2214
  if (!opts.conversations) return [];
1945
- return JSON.parse(readFileSync3(opts.conversations, "utf8"));
2215
+ return JSON.parse(readFileSync4(opts.conversations, "utf8"));
1946
2216
  }
1947
2217
  });
1948
2218
  var noRuntimeAdapter = (name, hint) => ({
@@ -1983,7 +2253,18 @@ var HARNESS_NAMES = [
1983
2253
  "factory-droid",
1984
2254
  // ZCode is a per-prompt HOOK host too, registered in its own CLI config
1985
2255
  // (~/.zcode/cli/config.json) under `hooks.events` — never the user's real Claude Code settings.
1986
- "zcode"
2256
+ "zcode",
2257
+ // TraeCode is a per-prompt HOOK host registered in ~/.trae-cn/hooks.json (see src/installer.ts).
2258
+ "traecode",
2259
+ "kimi-code",
2260
+ // WorkBuddy is a per-prompt HOOK host too: the installer wires ~/.workbuddy/settings.json and
2261
+ // the stdio MCP registration in ~/.workbuddy/mcp.json (see src/installer.ts).
2262
+ "workbuddy",
2263
+ // CodeBuddy Code is the SAME @genie/agent-cli HOOK host, one product config apart (WorkBuddy only
2264
+ // renames the home folder): the installer wires ~/.codebuddy/settings.json and the stdio MCP
2265
+ // registration in CodeBuddy's priority-chained MCP file (see src/installer.ts). The CLI
2266
+ // writes WorkBuddy's transcript format; the CodeBuddy IDE has a reader of its own.
2267
+ "codebuddy"
1987
2268
  ];
1988
2269
  var HOOK_BINS = {
1989
2270
  "claude-code": "hindsight-claude-hook",
@@ -1996,7 +2277,11 @@ var HOOK_BINS = {
1996
2277
  "grok-build": "hindsight-grok-hook",
1997
2278
  "qwen-code": "hindsight-qwen-hook",
1998
2279
  "factory-droid": "hindsight-droid-hook",
1999
- zcode: "hindsight-zcode-hook"
2280
+ zcode: "hindsight-zcode-hook",
2281
+ traecode: "hindsight-traecode-hook",
2282
+ "kimi-code": "hindsight-kimi-hook",
2283
+ workbuddy: "hindsight-workbuddy-hook",
2284
+ codebuddy: "hindsight-codebuddy-hook"
2000
2285
  // more hook harnesses: add a HookSpec entry point (see src/cursor-hook.ts) + a registration here.
2001
2286
  };
2002
2287
  var PLUGIN_ENTRYPOINTS = {
@@ -2046,7 +2331,8 @@ function resolversFor(ctx) {
2046
2331
  function buildRetainStamp(cfg2, ctx) {
2047
2332
  const hasTags = Boolean(cfg2.retainTags?.length);
2048
2333
  const hasMetadata = Boolean(cfg2.retainMetadata && Object.keys(cfg2.retainMetadata).length);
2049
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2334
+ const hasContext = Boolean(cfg2.retainContext?.trim());
2335
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2050
2336
  const base = resolversFor(ctx);
2051
2337
  const cache = /* @__PURE__ */ new Map();
2052
2338
  const resolvers = Object.fromEntries(
@@ -2070,12 +2356,12 @@ function buildRetainStamp(cfg2, ctx) {
2070
2356
  for (const [key, value] of Object.entries(cfg2.retainMetadata ?? {})) {
2071
2357
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2072
2358
  }
2073
- return { tags, metadata };
2359
+ const context = hasContext ? applyTemplate(cfg2.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2360
+ return { tags, metadata, context };
2074
2361
  }
2075
2362
 
2076
2363
  // src/deepen.ts
2077
2364
  var DIFF_BATCH = 50;
2078
- var LOCK_STALE_MS = 30 * 60 * 1e3;
2079
2365
  function arg(name, def) {
2080
2366
  const i = process.argv.indexOf(`--${name}`);
2081
2367
  if (i >= 0 && i + 1 < process.argv.length) return process.argv[i + 1];
@@ -2110,35 +2396,16 @@ var log2 = (m) => {
2110
2396
  console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${m}`);
2111
2397
  log.info("deepen", m);
2112
2398
  };
2113
- var LOCK_DIR = join10(tmpdir2(), "hindsight-coding-agent");
2114
- var LOCK = join10(LOCK_DIR, `deepen-${encodeURIComponent(FINAL_BANK ?? "")}.lock`);
2115
- function acquireLock() {
2116
- try {
2117
- const held = JSON.parse(readFileSync4(LOCK, "utf8"));
2118
- if (held.ts && Date.now() - held.ts < LOCK_STALE_MS) {
2119
- let holderAlive = false;
2120
- if (held.pid) {
2121
- try {
2122
- process.kill(held.pid, 0);
2123
- holderAlive = true;
2124
- } catch {
2125
- }
2126
- }
2127
- if (holderAlive) return false;
2128
- }
2129
- } catch {
2130
- }
2131
- try {
2132
- mkdirSync3(LOCK_DIR, { recursive: true });
2133
- writeFileSync2(LOCK, JSON.stringify({ pid: process.pid, ts: Date.now() }));
2134
- return true;
2135
- } catch {
2136
- return false;
2137
- }
2399
+ var LEASE_ROOT = join10(tmpdir2(), "hindsight-coding-agent", "deepen");
2400
+ var lease = acquireLease(LEASE_ROOT, encodeURIComponent(FINAL_BANK ?? ""));
2401
+ if (lease) {
2402
+ setInterval(() => {
2403
+ if (!heartbeatLease(lease)) process.exit(0);
2404
+ }, LEASE_HEARTBEAT_MS).unref();
2138
2405
  }
2139
2406
  async function main() {
2140
- if (!acquireLock()) {
2141
- log2(`deepen: another run holds the lock for ${FINAL_BANK} \u2014 nothing to do`);
2407
+ if (!lease) {
2408
+ log2(`deepen: another run holds the lease for ${FINAL_BANK} \u2014 nothing to do`);
2142
2409
  return;
2143
2410
  }
2144
2411
  const t0 = Date.now();
@@ -2156,10 +2423,13 @@ async function main() {
2156
2423
  // outlive the session, so a bank several repos share must not be told it is whichever one
2157
2424
  // ran last (#4146). `bankProjectName` answers only when the bank IS this repo's; the
2158
2425
  // `banks.<id>.bank` rename below it can point many repos at one destination, so a renamed
2159
- // bank is not this repo's either. Undefined leaves the client to fall back to the bank id.
2426
+ // bank is not this repo's either. Undefined gives the shared-bank scope (#4490).
2160
2427
  project: PAGE_PROJECT,
2161
2428
  maxParallelRetains: cfg.maxParallelRetains,
2162
2429
  observationScopes: cfg.observationScopes,
2430
+ // Nobody waits on a background seed, and a 429 it gives up on is history missing from the
2431
+ // bank until some later session happens to re-run it.
2432
+ rateLimitPatienceMs: 10 * 60 * 1e3,
2163
2433
  log: log2
2164
2434
  });
2165
2435
  log2(`deepen -> ${client.apiUrl} bank=${FINAL_BANK} harness=${harness.name}`);
@@ -2174,7 +2444,8 @@ async function main() {
2174
2444
  pages: cfg.pages,
2175
2445
  customPages: cfg.customPages,
2176
2446
  manage: cfg.manageBankConfig,
2177
- extractionMode: cfg.retainExtractionMode
2447
+ extractionMode: cfg.retainExtractionMode,
2448
+ defaults: cfg.defaultBankConfig
2178
2449
  });
2179
2450
  if (client.knowledgePagesSupported === false) {
2180
2451
  diag(harness.name, "knowledge_pages_unavailable", {
@@ -2207,10 +2478,11 @@ async function main() {
2207
2478
  gitFails += await syncGitLog(client, REPO, { limit: GITLOG_LIMIT, log: log2, stampFor });
2208
2479
  if (GIT_INGEST === "full") {
2209
2480
  try {
2210
- const shas = execFileSync3(
2481
+ const shas = execFileSync4(
2211
2482
  "git",
2212
2483
  ["-C", REPO, "rev-list", `-n`, String(DEEPEN_DIFF_TARGET), "HEAD"],
2213
- { encoding: "utf8", windowsHide: true }
2484
+ // `install` runs this with inherited stdio: an empty repo's HEAD error must not print.
2485
+ { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }
2214
2486
  ).trim().split("\n").filter(Boolean).filter((sha) => !gitIds.has(`git:${sha}`)).slice(0, DIFF_BATCH);
2215
2487
  if (shas.length) {
2216
2488
  const repoName = repoNameOf(REPO);
@@ -2287,10 +2559,7 @@ async function main() {
2287
2559
  \u2705 deepen complete in ${((Date.now() - t0) / 1e3).toFixed(1)}s${failures ? ` (${failures} items failed to enqueue)` : ""}.`
2288
2560
  );
2289
2561
  } finally {
2290
- try {
2291
- unlinkSync2(LOCK);
2292
- } catch {
2293
- }
2562
+ releaseLease(lease);
2294
2563
  }
2295
2564
  }
2296
2565
  main().catch((e) => {
@@ -2299,9 +2568,6 @@ main().catch((e) => {
2299
2568
  error: describeError(e)
2300
2569
  });
2301
2570
  console.error("deepen failed:", e.message || e);
2302
- try {
2303
- unlinkSync2(LOCK);
2304
- } catch {
2305
- }
2571
+ if (lease) releaseLease(lease);
2306
2572
  process.exit(1);
2307
2573
  });