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

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 (56) hide show
  1. package/README.md +314 -51
  2. package/dist/antigravity-hook.js +1039 -198
  3. package/dist/antigravity-statusline.js +185 -11
  4. package/dist/antigravity-stop-hook.js +1026 -163
  5. package/dist/claude-hook.js +1039 -198
  6. package/dist/claude-sessionstart-hook.js +1123 -190
  7. package/dist/claude-stop-hook.js +1026 -163
  8. package/dist/cline.js +749 -209
  9. package/dist/codex-hook.js +1039 -198
  10. package/dist/codex-sessionstart-hook.js +1123 -190
  11. package/dist/codex-stop-hook.js +1026 -163
  12. package/dist/copilot-hook.js +1039 -198
  13. package/dist/copilot-sessionstart-hook.js +1123 -190
  14. package/dist/copilot-stop-hook.js +1026 -163
  15. package/dist/cursor-hook.js +1039 -198
  16. package/dist/cursor-sessionstart-hook.js +1123 -190
  17. package/dist/cursor-stop-hook.js +1026 -163
  18. package/dist/daemon-start.js +154 -5
  19. package/dist/dcode-hook.js +1039 -198
  20. package/dist/dcode-sessionstart-hook.js +1123 -190
  21. package/dist/dcode-stop-hook.js +1026 -163
  22. package/dist/deepen.js +437 -105
  23. package/dist/devin-hook.js +1039 -198
  24. package/dist/devin-sessionstart-hook.js +1123 -190
  25. package/dist/devin-stop-hook.js +1026 -163
  26. package/dist/droid-hook.js +1039 -198
  27. package/dist/droid-sessionstart-hook.js +1123 -190
  28. package/dist/droid-stop-hook.js +1026 -163
  29. package/dist/dsh.js +750 -210
  30. package/dist/grok-hook.js +1039 -198
  31. package/dist/grok-sessionstart-hook.js +1123 -190
  32. package/dist/grok-stop-hook.js +1026 -163
  33. package/dist/hindsight-seed.js +157 -8
  34. package/dist/index.js +749 -209
  35. package/dist/installer.js +1233 -366
  36. package/dist/kilo.js +749 -209
  37. package/dist/kimi-hook.js +3909 -0
  38. package/dist/kimi-sessionstart-hook.js +4650 -0
  39. package/dist/kimi-stop-hook.js +4218 -0
  40. package/dist/mcp-server.js +373 -71
  41. package/dist/opencode2.js +778 -209
  42. package/dist/pi.js +754 -211
  43. package/dist/prime-agent.js +754 -211
  44. package/dist/qwen-hook.js +1039 -198
  45. package/dist/qwen-sessionstart-hook.js +1123 -190
  46. package/dist/qwen-stop-hook.js +1026 -163
  47. package/dist/status.js +333 -59
  48. package/dist/traecode-hook.js +3909 -0
  49. package/dist/traecode-sessionstart-hook.js +4650 -0
  50. package/dist/traecode-stop-hook.js +4218 -0
  51. package/dist/zcode-hook.js +1039 -198
  52. package/dist/zcode-sessionstart-hook.js +1123 -190
  53. package/dist/zcode-stop-hook.js +1026 -163
  54. package/package.json +15 -11
  55. package/plugin.json +1 -1
  56. package/skill/SKILL.md +241 -48
@@ -31539,13 +31539,13 @@ function isWithin(directory, configured) {
31539
31539
  function mapLookup(map2, directory) {
31540
31540
  const cwd = normalize(directory);
31541
31541
  let best;
31542
- for (const [dir, bank] of Object.entries(map2)) {
31542
+ for (const [dir, value] of Object.entries(map2)) {
31543
31543
  const p = configuredDir(dir);
31544
31544
  if (isWithin(cwd, p)) {
31545
- if (!best || p.length > best.len) best = { len: p.length, bank };
31545
+ if (!best || p.length > best.len) best = { len: p.length, value };
31546
31546
  }
31547
31547
  }
31548
- return best?.bank;
31548
+ return best?.value;
31549
31549
  }
31550
31550
  function lookupDirectories(config2, directory, sessionRoot = "") {
31551
31551
  const directories = [normalize(directory)];
@@ -31569,6 +31569,10 @@ function isOptedIn(config2, directory) {
31569
31569
  const pathMap = config2.mapPathToBank;
31570
31570
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
31571
31571
  }
31572
+ function pathSection(config2, paths, directory) {
31573
+ if (!directory || !paths) return void 0;
31574
+ return lookupDirectories(config2, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
31575
+ }
31572
31576
  function mappedBank(config2, directory, sessionRoot) {
31573
31577
  const pathMap = config2.mapPathToBank;
31574
31578
  if (!directory || !pathMap) return void 0;
@@ -31610,13 +31614,15 @@ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSON
31610
31614
  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.";
31611
31615
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
31612
31616
  var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
31617
+ var RETAIN_EXTRACTION_MODES = ["concise", "verbose", "verbatim", "chunks"];
31618
+ var DEFAULT_RETAIN_EXTRACTION_MODE = "concise";
31613
31619
  var RETAIN_STRATEGIES = {
31614
- git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
31620
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE },
31615
31621
  // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
31616
31622
  // in as few chunks as possible and the extractor sees the whole history arc at once.
31617
31623
  gitlog: {
31618
31624
  retain_mission: GITLOG_MISSION,
31619
- retain_extraction_mode: "verbose",
31625
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
31620
31626
  retain_chunk_size: 12e3
31621
31627
  },
31622
31628
  // ONE strategy for ALL developer conversations — backfilled decision chats and live working
@@ -31627,15 +31633,15 @@ var RETAIN_STRATEGIES = {
31627
31633
  // the consolidation layer.
31628
31634
  conversation: {
31629
31635
  retain_mission: CONVERSATION_MISSION,
31630
- retain_extraction_mode: "verbose",
31636
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
31631
31637
  retain_chunk_size: 12e3
31632
31638
  },
31633
31639
  // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
31634
- // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
31635
- // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
31640
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. A bigger chunk
31641
+ // size (documents can run long) keeps the concrete facts/structure together instead.
31636
31642
  document: {
31637
31643
  retain_mission: DOCUMENT_MISSION,
31638
- retain_extraction_mode: "verbose",
31644
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
31639
31645
  retain_chunk_size: 12e3
31640
31646
  },
31641
31647
  // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
@@ -31708,9 +31714,22 @@ var PAGE_TAXONOMY = [
31708
31714
  tags: ["knowledge:feature-work"]
31709
31715
  }
31710
31716
  ];
31711
- function pagesFor(project) {
31717
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
31718
+ function pagesFor(project, pages = {}, customPages = {}) {
31712
31719
  const scope = pageScopeRule(project);
31713
- return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
31720
+ const byName = new Map(
31721
+ Object.entries(pages).map(([name, override]) => [name.trim().toLowerCase(), override])
31722
+ );
31723
+ const out = [];
31724
+ for (const page of PAGE_TAXONOMY) {
31725
+ const override = byName.get(page.name.toLowerCase());
31726
+ if (override === false) continue;
31727
+ out.push({ ...page, source_query: (override?.source_query || page.source_query) + scope });
31728
+ }
31729
+ for (const [name, page] of Object.entries(customPages)) {
31730
+ out.push({ name: name.trim(), source_query: page.source_query + scope, tags: page.tags ?? [] });
31731
+ }
31732
+ return out;
31714
31733
  }
31715
31734
  var PAGE_MAX_TOKENS = 4096;
31716
31735
  var PAGE_TAGS_MATCH = "all";
@@ -31793,7 +31812,7 @@ var CODING_BANK_TEMPLATE = {
31793
31812
  enable_observations: true,
31794
31813
  observations_mission: OBSERVATIONS_MISSION,
31795
31814
  retain_mission: GIT_MISSION,
31796
- retain_extraction_mode: "verbose",
31815
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
31797
31816
  retain_default_strategy: "git",
31798
31817
  retain_strategies: RETAIN_STRATEGIES,
31799
31818
  entity_labels: [KNOWLEDGE_LABELS],
@@ -31801,12 +31820,17 @@ var CODING_BANK_TEMPLATE = {
31801
31820
  }
31802
31821
  };
31803
31822
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31823
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
31824
+ "retain_strategies",
31825
+ "entity_labels",
31826
+ "retain_extraction_mode"
31827
+ ];
31804
31828
  function isSet(v) {
31805
31829
  if (v === null || v === void 0) return false;
31806
31830
  if (typeof v === "string") return v.trim() !== "";
31807
31831
  return true;
31808
31832
  }
31809
- function codingBankManifest(overrides) {
31833
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
31810
31834
  const current2 = overrides ?? {};
31811
31835
  const template = CODING_BANK_TEMPLATE.bank;
31812
31836
  const bank = {};
@@ -31815,20 +31839,30 @@ function codingBankManifest(overrides) {
31815
31839
  bank.enable_observations = template.enable_observations;
31816
31840
  bank.observations_mission = template.observations_mission;
31817
31841
  bank.retain_mission = template.retain_mission;
31818
- bank.retain_extraction_mode = template.retain_extraction_mode;
31842
+ bank.retain_extraction_mode = mode;
31819
31843
  }
31820
31844
  if (!isSet(current2.retain_default_strategy))
31821
31845
  bank.retain_default_strategy = template.retain_default_strategy;
31822
31846
  if (!isSet(current2.entities_allow_free_form))
31823
31847
  bank.entities_allow_free_form = template.entities_allow_free_form;
31824
31848
  const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
31825
- const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
31826
- if (missing.length > 0)
31827
- bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
31849
+ const updates = {};
31850
+ for (const [name, def] of Object.entries(template.retain_strategies)) {
31851
+ const synced = def.retain_extraction_mode === "custom" ? {} : { retain_extraction_mode: mode };
31852
+ const have = strategies[name];
31853
+ if (!have || typeof have !== "object") updates[name] = { ...def, ...synced };
31854
+ else if ("retain_extraction_mode" in synced && have.retain_extraction_mode !== mode)
31855
+ updates[name] = { ...have, ...synced };
31856
+ }
31857
+ if (Object.keys(updates).length > 0) bank.retain_strategies = { ...strategies, ...updates };
31828
31858
  const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
31829
31859
  const [knowledgeGroup] = template.entity_labels;
31830
31860
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
31831
31861
  bank.entity_labels = [...labels, knowledgeGroup];
31862
+ for (const [key, value] of Object.entries(defaults)) {
31863
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
31864
+ bank[key] = value;
31865
+ }
31832
31866
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
31833
31867
  }
31834
31868
 
@@ -31896,6 +31930,14 @@ var KnowledgePagesUnavailableError = class extends Error {
31896
31930
  this.name = "KnowledgePagesUnavailableError";
31897
31931
  }
31898
31932
  };
31933
+ async function isEndpointMissing(r) {
31934
+ try {
31935
+ const j = await r.json();
31936
+ return String(j?.detail ?? "").trim().toLowerCase() === "not found";
31937
+ } catch {
31938
+ return true;
31939
+ }
31940
+ }
31899
31941
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
31900
31942
  var ReflectError = class extends Error {
31901
31943
  constructor(message, status, timedOut, options) {
@@ -31914,9 +31956,28 @@ var ReflectError = class extends Error {
31914
31956
  }
31915
31957
  };
31916
31958
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
31959
+ var DEFAULT_PAGE_SEARCH_LIMIT = 10;
31960
+ var DEFAULT_RECALL_OPTIONS = {
31961
+ types: ["observation"],
31962
+ budget: "low",
31963
+ max_tokens: 2e3,
31964
+ include: { entities: null }
31965
+ };
31917
31966
  var POLL_CYCLE_MS = 5e3;
31918
31967
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
31919
31968
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
31969
+ function shapePage(page) {
31970
+ const p = page ?? {};
31971
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
31972
+ return {
31973
+ id: p.id,
31974
+ name: p.name,
31975
+ ...p.description ? { description: p.description } : {},
31976
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
31977
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
31978
+ body
31979
+ };
31980
+ }
31920
31981
  var HindsightClient = class {
31921
31982
  apiUrl;
31922
31983
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -31934,6 +31995,8 @@ var HindsightClient = class {
31934
31995
  log;
31935
31996
  maxParallelRetains;
31936
31997
  observationScopes;
31998
+ pageSearchLimit;
31999
+ recallOptions;
31937
32000
  constructor(o) {
31938
32001
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
31939
32002
  this.token = o.apiToken;
@@ -31944,13 +32007,18 @@ var HindsightClient = class {
31944
32007
  });
31945
32008
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
31946
32009
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
32010
+ this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
32011
+ this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
31947
32012
  }
31948
32013
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
31949
32014
  get apiToken() {
31950
32015
  return this.token;
31951
32016
  }
31952
32017
  headers() {
31953
- const h = { "Content-Type": "application/json" };
32018
+ const h = {
32019
+ "Content-Type": "application/json",
32020
+ "Accept-Encoding": "identity"
32021
+ };
31954
32022
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
31955
32023
  return h;
31956
32024
  }
@@ -32058,6 +32126,23 @@ var HindsightClient = class {
32058
32126
  return false;
32059
32127
  }
32060
32128
  }
32129
+ /**
32130
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
32131
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
32132
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
32133
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
32134
+ */
32135
+ async supportsAppendRetain() {
32136
+ if (!await this.supportsIdempotentRetain()) return false;
32137
+ try {
32138
+ const r = await this.req("GET", this.bankUrl("/config"));
32139
+ if (!r.ok) return true;
32140
+ const j = await r.json();
32141
+ return j.config?.store_document_text !== false;
32142
+ } catch {
32143
+ return true;
32144
+ }
32145
+ }
32061
32146
  /**
32062
32147
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
32063
32148
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -32083,9 +32168,28 @@ var HindsightClient = class {
32083
32168
  }
32084
32169
  return ids;
32085
32170
  }
32171
+ /**
32172
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
32173
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
32174
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
32175
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
32176
+ */
32177
+ async documentTags(documentId) {
32178
+ const limit = 100;
32179
+ for (let offset = 0; ; offset += limit) {
32180
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
32181
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
32182
+ const j = await r.json();
32183
+ const items = j.items ?? [];
32184
+ const hit = items.find((it) => it.id === documentId);
32185
+ if (hit) return hit.tags ?? [];
32186
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
32187
+ }
32188
+ }
32086
32189
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
32087
32190
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
32088
- * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
32191
+ * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
32192
+ * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
32089
32193
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
32090
32194
  * continue with the template-only path.
32091
32195
  *
@@ -32101,7 +32205,11 @@ var HindsightClient = class {
32101
32205
  if (opts.manage === false) {
32102
32206
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
32103
32207
  } else {
32104
- const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
32208
+ const manifest = codingBankManifest(
32209
+ opts.reset ? void 0 : await this.readBankOverrides(),
32210
+ opts.extractionMode,
32211
+ opts.defaults
32212
+ );
32105
32213
  if (!manifest) {
32106
32214
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
32107
32215
  } else {
@@ -32109,7 +32217,7 @@ var HindsightClient = class {
32109
32217
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
32110
32218
  }
32111
32219
  }
32112
- await this.seedPages(opts.pageTrigger);
32220
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
32113
32221
  }
32114
32222
  /**
32115
32223
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -32225,20 +32333,22 @@ var HindsightClient = class {
32225
32333
  }
32226
32334
  }
32227
32335
  /**
32228
- * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
32229
- * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
32336
+ * Raw recall with no LLM in the loop, so it still answers when reflect's synthesis times out or
32337
+ * 5xxs. The body is `recallOptions` (consolidated observations by default) — a bank that grows
32338
+ * no observations widens it rather than getting nothing back. Returns the texts in rank order.
32339
+ *
32340
+ * The name predates `recallOptions` (the observation type used to be hardcoded here) and is
32341
+ * kept deliberately: this is the client's published surface, so renaming it would break
32342
+ * importers for a cosmetic gain. The doc above is the contract, not the name.
32230
32343
  */
32231
32344
  async recallObservations(query, opts) {
32232
32345
  const r = await this.req(
32233
32346
  "POST",
32234
32347
  this.bankUrl("/memories/recall"),
32235
- {
32236
- query,
32237
- types: ["observation"],
32238
- budget: "low",
32239
- max_tokens: opts.maxTokens,
32240
- include: { entities: null }
32241
- },
32348
+ // `query` is applied AFTER the spread: everything else is the caller's to override, but a
32349
+ // config that could replace the goal with a fixed string would silently recall for the
32350
+ // wrong question on every turn.
32351
+ { ...this.recallOptions, query },
32242
32352
  [],
32243
32353
  opts.timeoutMs
32244
32354
  );
@@ -32246,6 +32356,19 @@ var HindsightClient = class {
32246
32356
  const j = await r.json();
32247
32357
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
32248
32358
  }
32359
+ /**
32360
+ * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
32361
+ * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
32362
+ * expected answer before the bank's first retain — so it must never cache a negative (#4607).
32363
+ *
32364
+ * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
32365
+ * the 405/501 this used to check for never reach a caller in the first place.
32366
+ */
32367
+ async pagesUnsupported(r) {
32368
+ if (r.status !== 404 || !await isEndpointMissing(r)) return false;
32369
+ this.knowledgePagesSupported = false;
32370
+ return true;
32371
+ }
32249
32372
  /**
32250
32373
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
32251
32374
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -32253,10 +32376,8 @@ var HindsightClient = class {
32253
32376
  async tree() {
32254
32377
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
32255
32378
  const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
32256
- if ([404, 405, 501].includes(r.status)) {
32257
- this.knowledgePagesSupported = false;
32258
- throw new KnowledgePagesUnavailableError();
32259
- }
32379
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
32380
+ if (r.status === 404) return [];
32260
32381
  this.knowledgePagesSupported = true;
32261
32382
  try {
32262
32383
  return (await r.json()).roots ?? [];
@@ -32293,8 +32414,8 @@ var HindsightClient = class {
32293
32414
  return { items };
32294
32415
  }
32295
32416
  /**
32296
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
32297
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
32417
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
32418
+ * the body arrives once. The endpoint omits the internal reflect trace that built
32298
32419
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
32299
32420
  * token cap.
32300
32421
  */
@@ -32305,25 +32426,28 @@ var HindsightClient = class {
32305
32426
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
32306
32427
  );
32307
32428
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
32308
- return await r.json();
32429
+ return shapePage(await r.json());
32309
32430
  }
32310
32431
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
32311
32432
  * Returns page-level hits with a relevance snippet — the real search behind
32312
32433
  * hindsight_search_knowledge_pages. */
32313
- async searchKnowledgePages(query, limit = 3, timeoutMs) {
32434
+ async searchKnowledgePages(query, opts = {}) {
32314
32435
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
32315
- const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
32436
+ const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
32316
32437
  const r = await this.req(
32317
32438
  "GET",
32318
32439
  this.bankUrl(`/knowledge-base/search${q}`),
32319
32440
  void 0,
32320
32441
  [],
32321
- timeoutMs
32442
+ opts.timeoutMs
32322
32443
  );
32444
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
32445
+ if (r.status === 404) return [];
32323
32446
  const j = await r.json();
32324
32447
  return (j.results ?? []).map((x) => ({
32325
32448
  id: x.id,
32326
32449
  name: x.name,
32450
+ ...x.source_query ? { source_query: x.source_query } : {},
32327
32451
  snippet: x.snippet ?? "",
32328
32452
  score: x.score ?? 0
32329
32453
  }));
@@ -32339,8 +32463,8 @@ var HindsightClient = class {
32339
32463
  * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
32340
32464
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
32341
32465
  */
32342
- async seedPages(pageTrigger = buildPageTrigger()) {
32343
- const pages = pagesFor(this.project ?? this.bank);
32466
+ async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
32467
+ const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
32344
32468
  const existing = /* @__PURE__ */ new Map();
32345
32469
  let roots;
32346
32470
  try {
@@ -32357,6 +32481,7 @@ var HindsightClient = class {
32357
32481
  }
32358
32482
  let created = 0;
32359
32483
  let updated = 0;
32484
+ let vanished = 0;
32360
32485
  for (const page of pages) {
32361
32486
  const hit = existing.get(page.name.toLowerCase());
32362
32487
  const body = {
@@ -32370,13 +32495,16 @@ var HindsightClient = class {
32370
32495
  };
32371
32496
  if (!hit) {
32372
32497
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
32373
- if ([404, 405, 501].includes(r.status)) {
32374
- this.knowledgePagesSupported = false;
32498
+ if (await this.pagesUnsupported(r)) {
32375
32499
  this.log(
32376
32500
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
32377
32501
  );
32378
32502
  return;
32379
32503
  }
32504
+ if (r.status === 404) {
32505
+ this.log(`[bank] ${this.bank} does not exist yet; pages seed on the next session`);
32506
+ return;
32507
+ }
32380
32508
  if (r.status !== 409) created++;
32381
32509
  } else {
32382
32510
  const sourceDrift = hit.description !== page.source_query;
@@ -32386,6 +32514,9 @@ var HindsightClient = class {
32386
32514
  if (sourceDrift) {
32387
32515
  patch.source_query = page.source_query;
32388
32516
  patch.tags = page.tags;
32517
+ this.log(
32518
+ `[bank] re-syncing "${page.name}" to its configured source_query \u2014 set pages[${JSON.stringify(page.name)}].source_query to keep your own wording`
32519
+ );
32389
32520
  }
32390
32521
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
32391
32522
  const r = await this.req(
@@ -32393,19 +32524,22 @@ var HindsightClient = class {
32393
32524
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
32394
32525
  patch
32395
32526
  );
32396
- if ([404, 405, 501].includes(r.status)) {
32397
- this.knowledgePagesSupported = false;
32527
+ if (await this.pagesUnsupported(r)) {
32398
32528
  this.log(
32399
32529
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
32400
32530
  );
32401
32531
  return;
32402
32532
  }
32533
+ if (r.status === 404) {
32534
+ vanished++;
32535
+ continue;
32536
+ }
32403
32537
  updated++;
32404
32538
  }
32405
32539
  }
32406
32540
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
32407
32541
  this.log(
32408
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged` + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
32542
+ `[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` : "")
32409
32543
  );
32410
32544
  }
32411
32545
  /**
@@ -32434,7 +32568,7 @@ var HindsightClient = class {
32434
32568
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
32435
32569
  { trigger: pageTriggerPatch(desired) }
32436
32570
  );
32437
- if ([404, 405, 501].includes(r.status)) break;
32571
+ if (r.status === 404) continue;
32438
32572
  updated++;
32439
32573
  }
32440
32574
  return updated;
@@ -32526,7 +32660,65 @@ function resolvePageTrigger(raw) {
32526
32660
  );
32527
32661
  return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
32528
32662
  }
32663
+ function resolvePages(raw) {
32664
+ const value = raw;
32665
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
32666
+ const out = {};
32667
+ for (const [name, entry] of Object.entries(value)) {
32668
+ if (!PAGE_NAMES.some((known) => known.toLowerCase() === name.trim().toLowerCase())) {
32669
+ log.warn(
32670
+ "config",
32671
+ `ignoring pages[${JSON.stringify(name)}] \u2014 no seeded page has that name; expected one of: ${PAGE_NAMES.join(", ")}`
32672
+ );
32673
+ continue;
32674
+ }
32675
+ if (entry === false) {
32676
+ out[name] = false;
32677
+ continue;
32678
+ }
32679
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
32680
+ if (typeof query === "string" && query.trim()) {
32681
+ out[name] = { source_query: query };
32682
+ continue;
32683
+ }
32684
+ log.warn(
32685
+ "config",
32686
+ `ignoring pages[${JSON.stringify(name)}]=${JSON.stringify(entry)} \u2014 expected false, or {"source_query": "<your question>"}`
32687
+ );
32688
+ }
32689
+ return out;
32690
+ }
32691
+ function resolveCustomPages(raw) {
32692
+ const value = raw;
32693
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
32694
+ const out = {};
32695
+ for (const [rawName, entry] of Object.entries(value)) {
32696
+ const name = rawName.trim();
32697
+ if (!name) continue;
32698
+ if (PAGE_NAMES.some((known) => known.toLowerCase() === name.toLowerCase())) {
32699
+ log.warn(
32700
+ "config",
32701
+ `ignoring customPages[${JSON.stringify(rawName)}] \u2014 that is a seeded page; reword it under \`pages\` instead`
32702
+ );
32703
+ continue;
32704
+ }
32705
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
32706
+ if (typeof query !== "string" || !query.trim()) {
32707
+ log.warn(
32708
+ "config",
32709
+ `ignoring customPages[${JSON.stringify(rawName)}]=${JSON.stringify(entry)} \u2014 expected {"source_query": "<your question>"}`
32710
+ );
32711
+ continue;
32712
+ }
32713
+ const rawTags = entry.tags;
32714
+ const tags = Array.isArray(rawTags) ? rawTags.filter((t) => typeof t === "string" && t.trim() !== "") : [];
32715
+ out[name] = tags.length ? { source_query: query, tags } : { source_query: query };
32716
+ }
32717
+ return out;
32718
+ }
32719
+ var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
32529
32720
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
32721
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
32530
32722
  var REFLECT_BUDGETS = ["low", "mid", "high"];
32531
32723
  function resolveReflectBudget(raw) {
32532
32724
  const value = raw.reflectBudget;
@@ -32553,6 +32745,31 @@ function resolveObservationScopes(raw) {
32553
32745
  }
32554
32746
  return DEFAULT_OBSERVATION_SCOPES;
32555
32747
  }
32748
+ function resolveDefaultBankConfig(raw) {
32749
+ const value = raw;
32750
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
32751
+ const out = {};
32752
+ for (const [key, v] of Object.entries(value)) {
32753
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
32754
+ log.warn(
32755
+ "config",
32756
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
32757
+ );
32758
+ continue;
32759
+ }
32760
+ out[key] = v;
32761
+ }
32762
+ return out;
32763
+ }
32764
+ var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
32765
+ function resolveAutoInject(raw) {
32766
+ if (raw.autoReflect !== void 0) {
32767
+ const replacement = raw.autoReflect === false ? "none" : "reflect";
32768
+ log.warn("config", `autoReflect is deprecated \u2014 use autoInject: "${replacement}" instead`);
32769
+ }
32770
+ if (AUTO_INJECT_MODES.includes(raw.autoInject)) return raw.autoInject;
32771
+ return raw.autoReflect === false ? "none" : "reflect";
32772
+ }
32556
32773
  function resolveConfig(raw = {}) {
32557
32774
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
32558
32775
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
@@ -32582,17 +32799,31 @@ function resolveConfig(raw = {}) {
32582
32799
  retainSessions: raw.retainSessions ?? true,
32583
32800
  // write sessions back by default, every harness
32584
32801
  manageBankConfig: raw.manageBankConfig ?? true,
32802
+ retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
32803
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
32585
32804
  maxParallelRetains: raw.maxParallelRetains || 10,
32586
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
32805
+ reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
32587
32806
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
32588
32807
  // reflect already set), but never let it LOWER the tool below the default — a short window is
32589
32808
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
32590
32809
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
32810
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
32591
32811
  reflectBudget: resolveReflectBudget(raw),
32592
- autoReflect: raw.autoReflect ?? true,
32593
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
32812
+ autoInject: resolveAutoInject(raw),
32813
+ pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
32814
+ // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
32815
+ // keys and reach the API as garbage, so it is rejected like any other non-object.
32816
+ recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
32817
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
32818
+ // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
32819
+ // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
32820
+ // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
32821
+ // with no wording change at all. The cost is the guide's ~2KB re-sent per turn, which caches.
32822
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 1,
32594
32823
  pageTriggerType: pageTrigger.type,
32595
32824
  pageTriggerCron: pageTrigger.cron,
32825
+ pages: resolvePages(raw.pages),
32826
+ customPages: resolveCustomPages(raw.customPages),
32596
32827
  autoSeed: raw.autoSeed ?? true,
32597
32828
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
32598
32829
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -32603,11 +32834,15 @@ function resolveConfig(raw = {}) {
32603
32834
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
32604
32835
  // nested object cannot reach the API as a tag and fail the whole retain.
32605
32836
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
32837
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
32838
+ // the built-in default) from a configured value, and an empty context would strip the default.
32839
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
32606
32840
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
32607
32841
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
32608
32842
  ) : {},
32609
32843
  observationScopes: resolveObservationScopes(raw.observationScopes),
32610
32844
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
32845
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
32611
32846
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
32612
32847
  autoUpdate: raw.autoUpdate ?? true
32613
32848
  };
@@ -32624,7 +32859,12 @@ function readRaw(path) {
32624
32859
  }
32625
32860
  function mergeRaw(a, b) {
32626
32861
  const { harnesses: _drop, ...flat } = b;
32627
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
32862
+ return {
32863
+ ...a,
32864
+ ...flat,
32865
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
32866
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
32867
+ };
32628
32868
  }
32629
32869
  function applyLayer(raw, layer, harness) {
32630
32870
  let out = mergeRaw(raw, layer);
@@ -32655,7 +32895,11 @@ var ENV_KEYS = {
32655
32895
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
32656
32896
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
32657
32897
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
32898
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
32658
32899
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
32900
+ autoInject: "HINDSIGHT_AUTO_INJECT",
32901
+ pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
32902
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
32659
32903
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
32660
32904
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
32661
32905
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -32675,7 +32919,8 @@ var ENV_KEYS = {
32675
32919
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
32676
32920
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
32677
32921
  retainTags: "HINDSIGHT_RETAIN_TAGS",
32678
- manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
32922
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG",
32923
+ retainExtractionMode: "HINDSIGHT_RETAIN_EXTRACTION_MODE"
32679
32924
  };
32680
32925
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
32681
32926
  "dynamicBankId",
@@ -32696,6 +32941,8 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
32696
32941
  "maxParallelRetains",
32697
32942
  "reflectTimeoutMs",
32698
32943
  "reflectToolTimeoutMs",
32944
+ "injectTimeoutMs",
32945
+ "pageSearchLimit",
32699
32946
  "pageRefreshEveryTurns",
32700
32947
  "seedLimit",
32701
32948
  "surveyBudgetUsd",
@@ -32743,15 +32990,25 @@ var BANK_OVERRIDE_EXCLUDED = [
32743
32990
  function applyBankConfig(cfg, resolvedId, directory) {
32744
32991
  if (directory !== void 0 && !isOptedIn(cfg, directory))
32745
32992
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
32993
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
32994
+ if (byPath) {
32995
+ const { bank: _rename, ...rest } = overrideFields(byPath);
32996
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
32997
+ }
32746
32998
  const section = cfg.banks[resolvedId];
32747
32999
  if (!section) return { cfg, bankId: resolvedId };
32748
- const safe = { ...section };
32749
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
32750
- delete safe.banks;
33000
+ const safe = overrideFields(section);
32751
33001
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
32752
33002
  delete safe.bank;
32753
33003
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
32754
33004
  }
33005
+ function overrideFields(section) {
33006
+ const safe = { ...section };
33007
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
33008
+ delete safe.banks;
33009
+ delete safe.paths;
33010
+ return safe;
33011
+ }
32755
33012
  function resolvePartial(cfg, patch) {
32756
33013
  const full = resolveConfig(patch);
32757
33014
  const out = {};
@@ -32759,6 +33016,17 @@ function resolvePartial(cfg, patch) {
32759
33016
  if (key in full)
32760
33017
  out[key] = full[key];
32761
33018
  }
33019
+ if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
33020
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
33021
+ const conn = resolveConfig({
33022
+ serverMode: patch.serverMode ?? cfg.serverMode,
33023
+ apiPort: patch.apiPort ?? cfg.apiPort,
33024
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
33025
+ });
33026
+ out.serverMode = conn.serverMode;
33027
+ out.apiUrl = conn.apiUrl;
33028
+ out.apiPort = conn.apiPort;
33029
+ }
32762
33030
  return out;
32763
33031
  }
32764
33032
 
@@ -32781,16 +33049,24 @@ function resolveHostMemory(harness, directory) {
32781
33049
  bank: bankId,
32782
33050
  maxParallelRetains: cfg.maxParallelRetains,
32783
33051
  observationScopes: cfg.observationScopes,
33052
+ pageSearchLimit: cfg.pageSearchLimit,
33053
+ recallOptions: cfg.recallOptions,
32784
33054
  // The credential a host STARTED with is not the one it must keep using: enable auth or
32785
33055
  // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
32786
33056
  // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
32787
33057
  // honoured on re-resolution exactly as it was on the first one.
32788
- tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
33058
+ // The URL stays the one this client was built with, so a token re-read after the config
33059
+ // moved this directory to ANOTHER server is that server's credential: never send it here.
33060
+ tokenProvider: () => {
33061
+ const live = resolveHostConfig(harness, directory).cfg;
33062
+ return live.apiUrl === cfg.apiUrl ? live.apiToken : cfg.apiToken;
33063
+ }
32789
33064
  })
32790
33065
  };
32791
33066
  }
32792
33067
 
32793
33068
  // src/core/knowledge-tools.ts
33069
+ import { createHash as createHash3 } from "crypto";
32794
33070
  import { existsSync as existsSync3 } from "fs";
32795
33071
  import { homedir as homedir5 } from "os";
32796
33072
  import { join as join10 } from "path";
@@ -32805,13 +33081,17 @@ function git(repo, ...args) {
32805
33081
  return execFileSync("git", ["-C", repo, ...args], {
32806
33082
  encoding: "utf8",
32807
33083
  maxBuffer: 1 << 28,
32808
- windowsHide: true
33084
+ windowsHide: true,
33085
+ // execFileSync otherwise forwards failed git stderr into the host's TUI,
33086
+ // even when callers catch the error. Keep diagnostics on the error instead.
33087
+ stdio: ["ignore", "pipe", "pipe"]
32809
33088
  });
32810
33089
  }
32811
33090
  function repoNameOf(repo) {
32812
33091
  return projectNameOf(resolve2(repo));
32813
33092
  }
32814
33093
  function commitsSince(dir, sinceSha) {
33094
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
32815
33095
  try {
32816
33096
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
32817
33097
  return Number.isFinite(n) ? n : null;
@@ -32872,7 +33152,9 @@ function commitCount(repoDir) {
32872
33152
  try {
32873
33153
  const out = execFileSync2("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
32874
33154
  encoding: "utf8",
32875
- windowsHide: true
33155
+ windowsHide: true,
33156
+ stdio: ["ignore", "pipe", "pipe"]
33157
+ // failed probes must not write into the host TUI
32876
33158
  });
32877
33159
  return Number(out.trim()) || 0;
32878
33160
  } catch {
@@ -32939,6 +33221,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
32939
33221
  idempotentHint: false,
32940
33222
  openWorldHint: false
32941
33223
  };
33224
+ 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.';
32942
33225
  function ok(value) {
32943
33226
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
32944
33227
  }
@@ -32956,6 +33239,8 @@ function guarded(fn) {
32956
33239
  };
32957
33240
  }
32958
33241
  function buildKnowledgeTools(client, bankId, opts = {}) {
33242
+ const extra = opts.toolGuideExtra?.trim();
33243
+ const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
32959
33244
  return [
32960
33245
  {
32961
33246
  name: "hindsight_sync_status",
@@ -33015,20 +33300,23 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
33015
33300
  },
33016
33301
  {
33017
33302
  name: "hindsight_search_knowledge_pages",
33018
- 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. When a result informs your answer, credit it visibly: start that part with a markdown blockquote header "> \u{1F9E0} **From Hindsight memory (<page name>)** \u2014 <the facts you drew on>".`,
33303
+ 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,
33019
33304
  inputSchema: { query: external_exports.string().describe("what to look for") },
33020
33305
  annotations: READ_ONLY_ANNOTATIONS,
33021
33306
  handler: async (args) => {
33022
33307
  try {
33023
- const hits = await client.searchKnowledgePages(args.query, 3);
33024
- return ok(
33025
- hits.map((h) => ({
33308
+ const hits = await client.searchKnowledgePages(args.query);
33309
+ return ok({
33310
+ pages: hits.map((h) => ({
33026
33311
  page: h.name,
33027
33312
  page_id: h.id,
33028
- snippet: h.snippet,
33029
- score: h.score
33030
- }))
33031
- );
33313
+ // The question the page answers — the same `description` the list and read tools
33314
+ // carry, so a hit says what the page is FOR, not just how it opens.
33315
+ ...h.source_query ? { description: h.source_query } : {},
33316
+ snippet: h.snippet
33317
+ })),
33318
+ crediting
33319
+ });
33032
33320
  } catch (e) {
33033
33321
  return err(e);
33034
33322
  }
@@ -33085,7 +33373,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
33085
33373
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
33086
33374
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
33087
33375
  handler: guarded(async ({ title, content }) => {
33088
- const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
33376
+ const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
33377
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
33089
33378
  const stamp = opts.stampFor?.();
33090
33379
  const metadata = {
33091
33380
  ...stamp?.metadata,
@@ -33131,7 +33420,8 @@ function resolversFor(ctx) {
33131
33420
  function buildRetainStamp(cfg, ctx) {
33132
33421
  const hasTags = Boolean(cfg.retainTags?.length);
33133
33422
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
33134
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
33423
+ const hasContext = Boolean(cfg.retainContext?.trim());
33424
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
33135
33425
  const base = resolversFor(ctx);
33136
33426
  const cache = /* @__PURE__ */ new Map();
33137
33427
  const resolvers = Object.fromEntries(
@@ -33155,7 +33445,8 @@ function buildRetainStamp(cfg, ctx) {
33155
33445
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
33156
33446
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
33157
33447
  }
33158
- return { tags, metadata };
33448
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
33449
+ return { tags, metadata, context };
33159
33450
  }
33160
33451
 
33161
33452
  // src/mcp-server.ts
@@ -33168,6 +33459,7 @@ function selectTools(cfg, client, bankId, opts = {}) {
33168
33459
  pageTrigger: buildPageTrigger(cfg),
33169
33460
  reflectTimeoutMs: cfg.reflectToolTimeoutMs,
33170
33461
  reflectBudget: cfg.reflectBudget,
33462
+ toolGuideExtra: cfg.toolGuideExtra,
33171
33463
  stampFor: () => buildRetainStamp(cfg, { directory: cwd, harness, bankId })
33172
33464
  });
33173
33465
  }
@@ -33180,6 +33472,15 @@ function resolveHarness(env = process.env) {
33180
33472
  }
33181
33473
  return harness;
33182
33474
  }
33475
+ function resolveProjectCwd(env = process.env, argv = process.argv, fallbackCwd = process.cwd()) {
33476
+ const override = env.HINDSIGHT_MCP_PROJECT_CWD?.trim();
33477
+ if (override && !override.includes("${")) return override;
33478
+ if (env.HINDSIGHT_MCP_HARNESS === "cursor-cli") {
33479
+ const folder = argv[2]?.trim();
33480
+ if (folder && !folder.includes("${")) return folder;
33481
+ }
33482
+ return fallbackCwd;
33483
+ }
33183
33484
  function buildMcpServer(tools) {
33184
33485
  const server = new McpServer({ name: "hindsight", version: "0.1.0" });
33185
33486
  if (tools.length === 0) {
@@ -33201,7 +33502,7 @@ function buildMcpServer(tools) {
33201
33502
  return server;
33202
33503
  }
33203
33504
  async function main() {
33204
- const cwd = process.env.HINDSIGHT_MCP_PROJECT_CWD || process.cwd();
33505
+ const cwd = resolveProjectCwd();
33205
33506
  const harness = resolveHarness();
33206
33507
  const { cfg, bankId, client } = resolveHostMemory(harness, cwd);
33207
33508
  const server = buildMcpServer(selectTools(cfg, client, bankId, { cwd, harness }));
@@ -33216,5 +33517,6 @@ if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
33216
33517
  export {
33217
33518
  buildMcpServer,
33218
33519
  resolveHarness,
33520
+ resolveProjectCwd,
33219
33521
  selectTools
33220
33522
  };