@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
@@ -1598,10 +1598,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
1598
1598
  var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1599
1599
  var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1600
1600
  var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1601
- var uuid = (version2) => {
1602
- if (!version2)
1601
+ var uuid = (version3) => {
1602
+ if (!version3)
1603
1603
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1604
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1604
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1605
1605
  };
1606
1606
  var uuid4 = /* @__PURE__ */ uuid(4);
1607
1607
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -14477,10 +14477,10 @@ function fromJSONSchema(schema, params) {
14477
14477
  } catch {
14478
14478
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
14479
14479
  }
14480
- const version2 = detectVersion(normalized, params?.defaultTarget);
14480
+ const version3 = detectVersion(normalized, params?.defaultTarget);
14481
14481
  const defs = normalized.$defs || normalized.definitions || {};
14482
14482
  const ctx = {
14483
- version: version2,
14483
+ version: version3,
14484
14484
  defs,
14485
14485
  refs: /* @__PURE__ */ new Map(),
14486
14486
  processing: /* @__PURE__ */ new Set(),
@@ -14519,7 +14519,7 @@ function date4(params) {
14519
14519
  config(en_default());
14520
14520
 
14521
14521
  // src/core/config.ts
14522
- import { readFileSync as readFileSync2 } from "fs";
14522
+ import { readFileSync as readFileSync3 } from "fs";
14523
14523
  import { homedir as homedir3 } from "os";
14524
14524
  import { join as join7 } from "path";
14525
14525
 
@@ -14562,6 +14562,7 @@ import { homedir as homedir2 } from "os";
14562
14562
  import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
14563
14563
 
14564
14564
  // src/core/diag.ts
14565
+ import { readFileSync } from "fs";
14565
14566
  import { join as join3 } from "path";
14566
14567
 
14567
14568
  // src/core/log.ts
@@ -14637,7 +14638,7 @@ function diag(harness, event, extra = {}) {
14637
14638
  }
14638
14639
 
14639
14640
  // src/core/git-layout.ts
14640
- import { lstatSync, readFileSync, realpathSync } from "fs";
14641
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
14641
14642
  import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
14642
14643
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
14643
14644
  var ATTEMPTS = 3;
@@ -14661,7 +14662,7 @@ function entryKind(path) {
14661
14662
  }
14662
14663
  function readTextOrNull(path) {
14663
14664
  try {
14664
- return readFileSync(path, "utf8");
14665
+ return readFileSync2(path, "utf8");
14665
14666
  } catch (error51) {
14666
14667
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
14667
14668
  return null;
@@ -14823,13 +14824,13 @@ function isWithin(directory, configured) {
14823
14824
  function mapLookup(map2, directory) {
14824
14825
  const cwd = normalize(directory);
14825
14826
  let best;
14826
- for (const [dir, bank] of Object.entries(map2)) {
14827
+ for (const [dir, value] of Object.entries(map2)) {
14827
14828
  const p = configuredDir(dir);
14828
14829
  if (isWithin(cwd, p)) {
14829
- if (!best || p.length > best.len) best = { len: p.length, bank };
14830
+ if (!best || p.length > best.len) best = { len: p.length, value };
14830
14831
  }
14831
14832
  }
14832
- return best?.bank;
14833
+ return best?.value;
14833
14834
  }
14834
14835
  function lookupDirectories(config2, directory, sessionRoot = "") {
14835
14836
  const directories = [normalize(directory)];
@@ -14853,6 +14854,10 @@ function isOptedIn(config2, directory) {
14853
14854
  const pathMap = config2.mapPathToBank;
14854
14855
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
14855
14856
  }
14857
+ function pathSection(config2, paths, directory) {
14858
+ if (!directory || !paths) return void 0;
14859
+ return lookupDirectories(config2, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
14860
+ }
14856
14861
  function mappedBank(config2, directory, sessionRoot) {
14857
14862
  const pathMap = config2.mapPathToBank;
14858
14863
  if (!directory || !pathMap) return void 0;
@@ -14872,6 +14877,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
14872
14877
  };
14873
14878
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14874
14879
  }
14880
+ function bankProjectName(config2, directory, sessionRoot) {
14881
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
14882
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
14883
+ if (!dynamic) return void 0;
14884
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
14885
+ if (!template.includes("{gitProject}")) return void 0;
14886
+ try {
14887
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
14888
+ } catch (error51) {
14889
+ if (error51 instanceof BankResolutionError) return void 0;
14890
+ throw error51;
14891
+ }
14892
+ }
14875
14893
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
14876
14894
  try {
14877
14895
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -14889,7 +14907,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
14889
14907
  // src/core/missions.ts
14890
14908
  import { createHash } from "crypto";
14891
14909
  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.";
14892
- 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.";
14910
+ 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.";
14893
14911
  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.`;
14894
14912
  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.";
14895
14913
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -14965,6 +14983,8 @@ var KNOWLEDGE_LABELS = {
14965
14983
  ]
14966
14984
  };
14967
14985
  function pageScopeRule(project) {
14986
+ if (project === void 0)
14987
+ 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.`;
14968
14988
  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.`;
14969
14989
  }
14970
14990
  var PAGE_TAXONOMY = [
@@ -15100,12 +15120,17 @@ var CODING_BANK_TEMPLATE = {
15100
15120
  }
15101
15121
  };
15102
15122
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
15123
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
15124
+ "retain_strategies",
15125
+ "entity_labels",
15126
+ "retain_extraction_mode"
15127
+ ];
15103
15128
  function isSet(v) {
15104
15129
  if (v === null || v === void 0) return false;
15105
15130
  if (typeof v === "string") return v.trim() !== "";
15106
15131
  return true;
15107
15132
  }
15108
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
15133
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
15109
15134
  const current2 = overrides ?? {};
15110
15135
  const template = CODING_BANK_TEMPLATE.bank;
15111
15136
  const bank = {};
@@ -15134,9 +15159,16 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
15134
15159
  const [knowledgeGroup] = template.entity_labels;
15135
15160
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
15136
15161
  bank.entity_labels = [...labels, knowledgeGroup];
15162
+ for (const [key, value] of Object.entries(defaults)) {
15163
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
15164
+ bank[key] = value;
15165
+ }
15137
15166
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
15138
15167
  }
15139
15168
 
15169
+ // package.json
15170
+ var version2 = "0.8.1";
15171
+
15140
15172
  // src/core/util.ts
15141
15173
  import { accessSync, constants } from "fs";
15142
15174
  import { delimiter, join as join6 } from "path";
@@ -15160,12 +15192,12 @@ function binOnPath(bin) {
15160
15192
  }
15161
15193
  }
15162
15194
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15163
- function semverGte(version2, min) {
15195
+ function semverGte(version3, min) {
15164
15196
  const parts = (v) => {
15165
15197
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
15166
15198
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
15167
15199
  };
15168
- const a = version2 ? parts(version2) : void 0;
15200
+ const a = version3 ? parts(version3) : void 0;
15169
15201
  const b = parts(min);
15170
15202
  if (!a || !b) return false;
15171
15203
  for (let i = 0; i < 3; i++) {
@@ -15190,6 +15222,7 @@ async function pool(items, n, fn, onError, onProgress) {
15190
15222
  }
15191
15223
 
15192
15224
  // src/core/hindsight.ts
15225
+ var USER_AGENT = `hindsight-coding-agents/${version2}`;
15193
15226
  function resolveRetainScopes(tags, configured) {
15194
15227
  if (configured !== "per_source") return configured;
15195
15228
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -15225,7 +15258,7 @@ async function isEndpointMissing(r) {
15225
15258
  const j = await r.json();
15226
15259
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
15227
15260
  } catch {
15228
- return true;
15261
+ return false;
15229
15262
  }
15230
15263
  }
15231
15264
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -15244,6 +15277,12 @@ var ReflectError = class extends Error {
15244
15277
  get fallbackEligible() {
15245
15278
  return this.timedOut || this.status !== void 0 && this.status >= 500;
15246
15279
  }
15280
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
15281
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
15282
+ get permanent() {
15283
+ const s = this.status;
15284
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
15285
+ }
15247
15286
  };
15248
15287
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
15249
15288
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -15254,8 +15293,31 @@ var DEFAULT_RECALL_OPTIONS = {
15254
15293
  include: { entities: null }
15255
15294
  };
15256
15295
  var POLL_CYCLE_MS = 5e3;
15296
+ var POLL_MAX_SERVER_ERRORS = 12;
15257
15297
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
15258
15298
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
15299
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
15300
+ function shapePage(page) {
15301
+ const p = page ?? {};
15302
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
15303
+ return {
15304
+ id: p.id,
15305
+ name: p.name,
15306
+ ...p.description ? { description: p.description } : {},
15307
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
15308
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
15309
+ body
15310
+ };
15311
+ }
15312
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
15313
+ function signalOnlyDispatcher() {
15314
+ void globalThis.Headers;
15315
+ const d = globalThis[GLOBAL_DISPATCHER];
15316
+ if (typeof d?.compose !== "function") return void 0;
15317
+ return d.compose(
15318
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
15319
+ );
15320
+ }
15259
15321
  var HindsightClient = class {
15260
15322
  apiUrl;
15261
15323
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -15275,6 +15337,7 @@ var HindsightClient = class {
15275
15337
  observationScopes;
15276
15338
  pageSearchLimit;
15277
15339
  recallOptions;
15340
+ rateLimitPatienceMs;
15278
15341
  constructor(o) {
15279
15342
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
15280
15343
  this.token = o.apiToken;
@@ -15287,13 +15350,18 @@ var HindsightClient = class {
15287
15350
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
15288
15351
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
15289
15352
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
15353
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
15290
15354
  }
15291
15355
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
15292
15356
  get apiToken() {
15293
15357
  return this.token;
15294
15358
  }
15295
15359
  headers() {
15296
- const h = { "Content-Type": "application/json" };
15360
+ const h = {
15361
+ "Content-Type": "application/json",
15362
+ "Accept-Encoding": "identity",
15363
+ "User-Agent": USER_AGENT
15364
+ };
15297
15365
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
15298
15366
  return h;
15299
15367
  }
@@ -15324,7 +15392,8 @@ var HindsightClient = class {
15324
15392
  * bounds the whole call.
15325
15393
  */
15326
15394
  async fetchWithAuth(url2, init) {
15327
- const send = () => fetch(url2, { ...init, headers: this.headers() });
15395
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
15396
+ const send = () => fetch(url2, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
15328
15397
  const r = await send();
15329
15398
  if (r.status !== 401 || !this.refreshToken()) return r;
15330
15399
  return send();
@@ -15340,13 +15409,22 @@ var HindsightClient = class {
15340
15409
  }
15341
15410
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15342
15411
  async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
15343
- const r = await this.fetchWithAuth(url2, {
15344
- method,
15345
- body: body ? JSON.stringify(body) : void 0,
15346
- signal: AbortSignal.timeout(timeoutMs)
15347
- });
15348
- if (r.status === 429 && !tolerate.includes(429))
15349
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
15412
+ const payload = body ? JSON.stringify(body) : void 0;
15413
+ let r;
15414
+ for (let attempt = 0, waited = 0; ; attempt++) {
15415
+ r = await this.fetchWithAuth(url2, {
15416
+ method,
15417
+ body: payload,
15418
+ signal: AbortSignal.timeout(timeoutMs)
15419
+ });
15420
+ if (r.status !== 429 || tolerate.includes(429)) break;
15421
+ const asked = retryAfterMs(r.headers.get("retry-after"));
15422
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
15423
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
15424
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
15425
+ await sleep(wait);
15426
+ waited += wait;
15427
+ }
15350
15428
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
15351
15429
  throw new Error(
15352
15430
  `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -15381,7 +15459,7 @@ var HindsightClient = class {
15381
15459
  }
15382
15460
  /**
15383
15461
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
15384
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
15462
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
15385
15463
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
15386
15464
  */
15387
15465
  async supportsIdempotentRetain() {
@@ -15391,14 +15469,37 @@ var HindsightClient = class {
15391
15469
  }
15392
15470
  return this.idempotentRetain;
15393
15471
  }
15472
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
15473
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
15474
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
15475
+ * `/version`, so that stays as the fallback. */
15394
15476
  async probeIdempotentRetain() {
15477
+ for (const path of ["/v1/version", "/version"]) {
15478
+ try {
15479
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
15480
+ if (!r.ok) continue;
15481
+ const j = await r.json();
15482
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
15483
+ } catch {
15484
+ }
15485
+ }
15486
+ return false;
15487
+ }
15488
+ /**
15489
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
15490
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
15491
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
15492
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
15493
+ */
15494
+ async supportsAppendRetain() {
15495
+ if (!await this.supportsIdempotentRetain()) return false;
15395
15496
  try {
15396
- const r = await this.req("GET", `${this.apiUrl}/version`);
15397
- if (!r.ok) return false;
15497
+ const r = await this.req("GET", this.bankUrl("/config"));
15498
+ if (!r.ok) return true;
15398
15499
  const j = await r.json();
15399
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
15500
+ return j.config?.store_document_text !== false;
15400
15501
  } catch {
15401
- return false;
15502
+ return true;
15402
15503
  }
15403
15504
  }
15404
15505
  /**
@@ -15426,6 +15527,32 @@ var HindsightClient = class {
15426
15527
  }
15427
15528
  return ids;
15428
15529
  }
15530
+ /**
15531
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
15532
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
15533
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
15534
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
15535
+ */
15536
+ async documentTags(documentId) {
15537
+ const limit = 100;
15538
+ for (let offset = 0; ; offset += limit) {
15539
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
15540
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
15541
+ const j = await r.json();
15542
+ const items = j.items ?? [];
15543
+ const hit = items.find((it) => it.id === documentId);
15544
+ if (hit) return hit.tags ?? [];
15545
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
15546
+ }
15547
+ }
15548
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
15549
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
15550
+ async hasDocuments() {
15551
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
15552
+ if (r.status === 404) return false;
15553
+ const j = await r.json();
15554
+ return (j.total ?? j.items?.length ?? 0) > 0;
15555
+ }
15429
15556
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
15430
15557
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
15431
15558
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -15447,7 +15574,8 @@ var HindsightClient = class {
15447
15574
  } else {
15448
15575
  const manifest = codingBankManifest(
15449
15576
  opts.reset ? void 0 : await this.readBankOverrides(),
15450
- opts.extractionMode
15577
+ opts.extractionMode,
15578
+ opts.defaults
15451
15579
  );
15452
15580
  if (!manifest) {
15453
15581
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -15506,7 +15634,13 @@ var HindsightClient = class {
15506
15634
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
15507
15635
  const start = Date.now();
15508
15636
  const pending = new Set(ids);
15637
+ const serverErrors = /* @__PURE__ */ new Map();
15509
15638
  let failed = 0;
15639
+ const giveUp = (id, status) => {
15640
+ pending.delete(id);
15641
+ failed++;
15642
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
15643
+ };
15510
15644
  while (pending.size && Date.now() - start < maxMs) {
15511
15645
  let backoffMs = POLL_CYCLE_MS;
15512
15646
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -15519,7 +15653,14 @@ var HindsightClient = class {
15519
15653
  );
15520
15654
  return;
15521
15655
  }
15522
- if (!r.ok) return;
15656
+ if (r.status >= 500) {
15657
+ const n = (serverErrors.get(id) ?? 0) + 1;
15658
+ serverErrors.set(id, n);
15659
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
15660
+ return;
15661
+ }
15662
+ if (!r.ok) return giveUp(id, r.status);
15663
+ serverErrors.delete(id);
15523
15664
  const st = ((await r.json()).status || "").toLowerCase();
15524
15665
  if (TERMINAL.has(st)) {
15525
15666
  pending.delete(id);
@@ -15653,8 +15794,8 @@ var HindsightClient = class {
15653
15794
  return { items };
15654
15795
  }
15655
15796
  /**
15656
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
15657
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
15797
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
15798
+ * the body arrives once. The endpoint omits the internal reflect trace that built
15658
15799
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15659
15800
  * token cap.
15660
15801
  */
@@ -15665,7 +15806,7 @@ var HindsightClient = class {
15665
15806
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15666
15807
  );
15667
15808
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15668
- return await r.json();
15809
+ return shapePage(await r.json());
15669
15810
  }
15670
15811
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15671
15812
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -15686,6 +15827,7 @@ var HindsightClient = class {
15686
15827
  return (j.results ?? []).map((x) => ({
15687
15828
  id: x.id,
15688
15829
  name: x.name,
15830
+ ...x.source_query ? { source_query: x.source_query } : {},
15689
15831
  snippet: x.snippet ?? "",
15690
15832
  score: x.score ?? 0
15691
15833
  }));
@@ -15702,7 +15844,7 @@ var HindsightClient = class {
15702
15844
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
15703
15845
  */
15704
15846
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
15705
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
15847
+ const pages = pagesFor(this.project, pagesConfig, customPages);
15706
15848
  const existing = /* @__PURE__ */ new Map();
15707
15849
  let roots;
15708
15850
  try {
@@ -15777,7 +15919,7 @@ var HindsightClient = class {
15777
15919
  }
15778
15920
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
15779
15921
  this.log(
15780
- `[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` : "")
15922
+ `[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` : "")
15781
15923
  );
15782
15924
  }
15783
15925
  /**
@@ -15788,23 +15930,33 @@ var HindsightClient = class {
15788
15930
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
15789
15931
  * consolidation under the auto-refresh that used to be the default (#3506).
15790
15932
  *
15791
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
15792
- * initiative's own title, and re-stating either would rebuild a page whose question never
15793
- * changed. The tree read above is reused rather than re-fetched.
15933
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
15934
+ * re-stating either would rebuild a page whose question never changed. The one exception is
15935
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
15936
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
15937
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
15938
+ * reused rather than re-fetched.
15794
15939
  */
15795
15940
  async resyncInitiativeTriggers(roots, pageTrigger) {
15796
15941
  const folder = roots.find(
15797
15942
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
15798
15943
  );
15944
+ const bankScope = pageScopeRule(this.bank);
15799
15945
  let updated = 0;
15800
15946
  for (const page of folder?.children ?? []) {
15801
- if (page.kind !== "page" || page.trigger == null) continue;
15802
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
15803
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
15947
+ if (page.kind !== "page") continue;
15948
+ const patch = {};
15949
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
15950
+ if (query !== page.description) patch.source_query = query;
15951
+ if (page.trigger != null) {
15952
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
15953
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
15954
+ }
15955
+ if (!patch.trigger && !patch.source_query) continue;
15804
15956
  const r = await this.req(
15805
15957
  "PATCH",
15806
15958
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
15807
- { trigger: pageTriggerPatch(desired) }
15959
+ patch
15808
15960
  );
15809
15961
  if (r.status === 404) continue;
15810
15962
  updated++;
@@ -15832,10 +15984,9 @@ var HindsightClient = class {
15832
15984
  let pageId = args.relatesToPageId;
15833
15985
  if (!pageId) {
15834
15986
  const folderId = await this.ensureFolder("Initiatives");
15835
- const subject = this.project ?? this.bank;
15836
15987
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
15837
15988
  name: args.title,
15838
- 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),
15989
+ 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),
15839
15990
  parent_id: folderId,
15840
15991
  tags: ["knowledge:feature-work"],
15841
15992
  max_tokens: PAGE_MAX_TOKENS,
@@ -15850,7 +16001,7 @@ var HindsightClient = class {
15850
16001
  }
15851
16002
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
15852
16003
  const content = `${verb}: ${args.title}. ${args.summary}`;
15853
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
16004
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
15854
16005
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
15855
16006
  const context = `initiative marker for [[page:${pageId}]]`;
15856
16007
  await this.retain(content, context, markerId, tags, "document", {
@@ -15956,6 +16107,7 @@ function resolveCustomPages(raw) {
15956
16107
  }
15957
16108
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
15958
16109
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
16110
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
15959
16111
  var REFLECT_BUDGETS = ["low", "mid", "high"];
15960
16112
  function resolveReflectBudget(raw) {
15961
16113
  const value = raw.reflectBudget;
@@ -15982,6 +16134,22 @@ function resolveObservationScopes(raw) {
15982
16134
  }
15983
16135
  return DEFAULT_OBSERVATION_SCOPES;
15984
16136
  }
16137
+ function resolveDefaultBankConfig(raw) {
16138
+ const value = raw;
16139
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
16140
+ const out = {};
16141
+ for (const [key, v] of Object.entries(value)) {
16142
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
16143
+ log.warn(
16144
+ "config",
16145
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
16146
+ );
16147
+ continue;
16148
+ }
16149
+ out[key] = v;
16150
+ }
16151
+ return out;
16152
+ }
15985
16153
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
15986
16154
  function resolveAutoInject(raw) {
15987
16155
  if (raw.autoReflect !== void 0) {
@@ -16021,18 +16189,21 @@ function resolveConfig(raw = {}) {
16021
16189
  // write sessions back by default, every harness
16022
16190
  manageBankConfig: raw.manageBankConfig ?? true,
16023
16191
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
16192
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
16024
16193
  maxParallelRetains: raw.maxParallelRetains || 10,
16025
16194
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
16026
16195
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
16027
16196
  // reflect already set), but never let it LOWER the tool below the default — a short window is
16028
16197
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
16029
16198
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
16199
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
16030
16200
  reflectBudget: resolveReflectBudget(raw),
16031
16201
  autoInject: resolveAutoInject(raw),
16032
16202
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
16033
16203
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
16034
16204
  // keys and reach the API as garbage, so it is rejected like any other non-object.
16035
16205
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
16206
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
16036
16207
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
16037
16208
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
16038
16209
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -16052,18 +16223,22 @@ function resolveConfig(raw = {}) {
16052
16223
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
16053
16224
  // nested object cannot reach the API as a tag and fail the whole retain.
16054
16225
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
16226
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
16227
+ // the built-in default) from a configured value, and an empty context would strip the default.
16228
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
16055
16229
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
16056
16230
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
16057
16231
  ) : {},
16058
16232
  observationScopes: resolveObservationScopes(raw.observationScopes),
16059
16233
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
16234
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
16060
16235
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
16061
16236
  autoUpdate: raw.autoUpdate ?? true
16062
16237
  };
16063
16238
  }
16064
16239
  function readRaw(path) {
16065
16240
  try {
16066
- return JSON.parse(readFileSync2(path, "utf8"));
16241
+ return JSON.parse(readFileSync3(path, "utf8"));
16067
16242
  } catch (e) {
16068
16243
  if (e?.code !== "ENOENT") {
16069
16244
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -16073,7 +16248,12 @@ function readRaw(path) {
16073
16248
  }
16074
16249
  function mergeRaw(a, b) {
16075
16250
  const { harnesses: _drop, ...flat } = b;
16076
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
16251
+ return {
16252
+ ...a,
16253
+ ...flat,
16254
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
16255
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
16256
+ };
16077
16257
  }
16078
16258
  function applyLayer(raw, layer, harness) {
16079
16259
  let out = mergeRaw(raw, layer);
@@ -16104,9 +16284,11 @@ var ENV_KEYS = {
16104
16284
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
16105
16285
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
16106
16286
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
16287
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
16107
16288
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
16108
16289
  autoInject: "HINDSIGHT_AUTO_INJECT",
16109
16290
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
16291
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
16110
16292
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
16111
16293
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
16112
16294
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -16148,6 +16330,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
16148
16330
  "maxParallelRetains",
16149
16331
  "reflectTimeoutMs",
16150
16332
  "reflectToolTimeoutMs",
16333
+ "injectTimeoutMs",
16151
16334
  "pageSearchLimit",
16152
16335
  "pageRefreshEveryTurns",
16153
16336
  "seedLimit",
@@ -16196,15 +16379,25 @@ var BANK_OVERRIDE_EXCLUDED = [
16196
16379
  function applyBankConfig(cfg, resolvedId, directory) {
16197
16380
  if (directory !== void 0 && !isOptedIn(cfg, directory))
16198
16381
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
16382
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
16383
+ if (byPath) {
16384
+ const { bank: _rename, ...rest } = overrideFields(byPath);
16385
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
16386
+ }
16199
16387
  const section = cfg.banks[resolvedId];
16200
16388
  if (!section) return { cfg, bankId: resolvedId };
16201
- const safe = { ...section };
16202
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
16203
- delete safe.banks;
16389
+ const safe = overrideFields(section);
16204
16390
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
16205
16391
  delete safe.bank;
16206
16392
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
16207
16393
  }
16394
+ function overrideFields(section) {
16395
+ const safe = { ...section };
16396
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
16397
+ delete safe.banks;
16398
+ delete safe.paths;
16399
+ return safe;
16400
+ }
16208
16401
  function resolvePartial(cfg, patch) {
16209
16402
  const full = resolveConfig(patch);
16210
16403
  const out = {};
@@ -16213,6 +16406,16 @@ function resolvePartial(cfg, patch) {
16213
16406
  out[key] = full[key];
16214
16407
  }
16215
16408
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
16409
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
16410
+ const conn = resolveConfig({
16411
+ serverMode: patch.serverMode ?? cfg.serverMode,
16412
+ apiPort: patch.apiPort ?? cfg.apiPort,
16413
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
16414
+ });
16415
+ out.serverMode = conn.serverMode;
16416
+ out.apiUrl = conn.apiUrl;
16417
+ out.apiPort = conn.apiPort;
16418
+ }
16216
16419
  return out;
16217
16420
  }
16218
16421
 
@@ -16222,10 +16425,12 @@ function resolveHostConfig(harness, directory) {
16222
16425
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
16223
16426
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
16224
16427
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
16225
- return applyBankConfig(cfg0, bankId, directory);
16428
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
16429
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
16430
+ return { ...resolved2, project };
16226
16431
  }
16227
16432
  function resolveHostMemory(harness, directory) {
16228
- const { cfg, bankId } = resolveHostConfig(harness, directory);
16433
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
16229
16434
  return {
16230
16435
  cfg,
16231
16436
  bankId,
@@ -16233,6 +16438,8 @@ function resolveHostMemory(harness, directory) {
16233
16438
  apiUrl: cfg.apiUrl,
16234
16439
  apiToken: cfg.apiToken,
16235
16440
  bank: bankId,
16441
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
16442
+ project,
16236
16443
  maxParallelRetains: cfg.maxParallelRetains,
16237
16444
  observationScopes: cfg.observationScopes,
16238
16445
  pageSearchLimit: cfg.pageSearchLimit,
@@ -16241,7 +16448,12 @@ function resolveHostMemory(harness, directory) {
16241
16448
  // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
16242
16449
  // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
16243
16450
  // honoured on re-resolution exactly as it was on the first one.
16244
- tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
16451
+ // The URL stays the one this client was built with, so a token re-read after the config
16452
+ // moved this directory to ANOTHER server is that server's credential: never send it here.
16453
+ tokenProvider: () => {
16454
+ const live = resolveHostConfig(harness, directory).cfg;
16455
+ return live.apiUrl === cfg.apiUrl ? live.apiToken : cfg.apiToken;
16456
+ }
16245
16457
  })
16246
16458
  };
16247
16459
  }
@@ -16251,7 +16463,7 @@ import { spawn as realSpawn2 } from "child_process";
16251
16463
  import {
16252
16464
  existsSync as existsSync2,
16253
16465
  mkdirSync as mkdirSync2,
16254
- readFileSync as readFileSync3,
16466
+ readFileSync as readFileSync4,
16255
16467
  realpathSync as realpathSync2,
16256
16468
  unlinkSync,
16257
16469
  writeFileSync
@@ -16282,7 +16494,7 @@ function sameDir(a, b) {
16282
16494
  }
16283
16495
  function stagedVersion(pkgRoot) {
16284
16496
  try {
16285
- const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
16497
+ const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
16286
16498
  return typeof pkg.version === "string" ? pkg.version : "";
16287
16499
  } catch {
16288
16500
  return "";
@@ -16307,7 +16519,7 @@ function isNewer(candidate, current2) {
16307
16519
  }
16308
16520
  function dueForCheck(file2, now) {
16309
16521
  try {
16310
- const state = JSON.parse(readFileSync3(file2, "utf8"));
16522
+ const state = JSON.parse(readFileSync4(file2, "utf8"));
16311
16523
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
16312
16524
  } catch {
16313
16525
  return true;
@@ -16316,7 +16528,7 @@ function dueForCheck(file2, now) {
16316
16528
  var ORIGIN_FILE = ".install-origin.json";
16317
16529
  function selfUpdatable(runtimeDir) {
16318
16530
  try {
16319
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
16531
+ const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
16320
16532
  if (typeof origin.source !== "string" || !origin.source) return false;
16321
16533
  return origin.source.split(/[\\/]/).includes("_npx");
16322
16534
  } catch {
@@ -16329,7 +16541,7 @@ function lockFile() {
16329
16541
  }
16330
16542
  function acquireUpdateLock(file2, now) {
16331
16543
  try {
16332
- const held = JSON.parse(readFileSync3(file2, "utf8"));
16544
+ const held = JSON.parse(readFileSync4(file2, "utf8"));
16333
16545
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
16334
16546
  let holderAlive = false;
16335
16547
  if (held.pid) {
@@ -16370,6 +16582,9 @@ function stampCheck(file2, now, latest) {
16370
16582
  } catch {
16371
16583
  }
16372
16584
  }
16585
+ function spawnNpm(spawnImpl, bin, args, opts) {
16586
+ return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
16587
+ }
16373
16588
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
16374
16589
  return new Promise((resolve3) => {
16375
16590
  let out = "";
@@ -16383,7 +16598,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
16383
16598
  resolve3(v);
16384
16599
  };
16385
16600
  try {
16386
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
16601
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
16387
16602
  timeout: NPM_VIEW_TIMEOUT_MS,
16388
16603
  stdio: ["ignore", "pipe", "ignore"],
16389
16604
  windowsHide: true
@@ -16452,7 +16667,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
16452
16667
  return "";
16453
16668
  }
16454
16669
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
16455
- const child = (opts.spawn ?? realSpawn2)(
16670
+ const child = spawnNpm(
16671
+ opts.spawn ?? realSpawn2,
16456
16672
  "npx",
16457
16673
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
16458
16674
  {
@@ -16485,7 +16701,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
16485
16701
  var DAEMON_WAIT_RETAIN_MS = 4e4;
16486
16702
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
16487
16703
  try {
16488
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
16704
+ const res = await fetch(`${baseUrl}/health`, {
16705
+ headers: { "User-Agent": USER_AGENT },
16706
+ signal: AbortSignal.timeout(timeoutMs)
16707
+ });
16489
16708
  return res.ok;
16490
16709
  } catch {
16491
16710
  return false;
@@ -16567,12 +16786,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
16567
16786
  } catch {
16568
16787
  }
16569
16788
  }
16789
+ var coldStarts = /* @__PURE__ */ new Map();
16790
+ async function waitBounded(p, ms) {
16791
+ let timer;
16792
+ try {
16793
+ await Promise.race([
16794
+ p,
16795
+ new Promise((resolve3) => {
16796
+ timer = setTimeout(resolve3, Math.max(ms, 0));
16797
+ })
16798
+ ]);
16799
+ } finally {
16800
+ clearTimeout(timer);
16801
+ }
16802
+ }
16570
16803
  async function ensureDaemon(cfg, harness, opts = {}) {
16571
16804
  if (cfg.serverMode !== "daemon") return;
16572
16805
  if (await isServerHealthy(cfg.apiUrl)) return;
16573
16806
  if (!preflightDaemon(cfg, harness)) return;
16574
- startDaemonDetached(cfg, harness, opts.spawnFn);
16575
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
16807
+ const waitMs = opts.waitMs ?? 0;
16808
+ const running = coldStarts.get(cfg.apiUrl);
16809
+ if (running) {
16810
+ const startedAt = Date.now();
16811
+ await waitBounded(
16812
+ running.catch(() => void 0),
16813
+ waitMs
16814
+ );
16815
+ const remaining = waitMs - (Date.now() - startedAt);
16816
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
16817
+ return;
16818
+ }
16819
+ const attempt = (async () => {
16820
+ startDaemonDetached(cfg, harness, opts.spawnFn);
16821
+ await waitForHealth(cfg.apiUrl, waitMs);
16822
+ })();
16823
+ coldStarts.set(cfg.apiUrl, attempt);
16824
+ try {
16825
+ await attempt;
16826
+ } finally {
16827
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
16828
+ }
16576
16829
  }
16577
16830
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
16578
16831
  const deadline = Date.now() + budgetMs;
@@ -16624,13 +16877,13 @@ function indexLine(pages) {
16624
16877
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
16625
16878
  return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
16626
16879
  }
16627
- var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today, never what was decided or why, so work built from code alone quietly re-litigates settled questions. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
16628
- \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, is usually already decided);
16880
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
16881
+ \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
16629
16882
  \u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
16630
16883
  \u2022 you are implementing something new, or two parts have to fit together;
16631
16884
  \u2022 the user asks why something is the way it is, or what is left to do;
16632
16885
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
16633
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
16886
+ It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
16634
16887
  CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
16635
16888
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
16636
16889
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
@@ -16638,7 +16891,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
16638
16891
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
16639
16892
  var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
16640
16893
  function toolGuide(opts) {
16641
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
16894
+ const extra = opts?.extra?.trim();
16895
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
16896
+ ${extra}` : "");
16642
16897
  }
16643
16898
  function buildKnowledgePreamble(pages, opts) {
16644
16899
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
@@ -16665,13 +16920,14 @@ import { homedir as homedir6 } from "os";
16665
16920
  import { join as join12 } from "path";
16666
16921
 
16667
16922
  // src/core/status.ts
16668
- import { execFileSync as execFileSync3 } from "child_process";
16923
+ import { execFileSync as execFileSync4 } from "child_process";
16669
16924
 
16670
16925
  // src/core/git.ts
16671
16926
  import { execFileSync as execFileSync2 } from "child_process";
16672
16927
  import { resolve as resolve2 } from "path";
16928
+ var GITLOG_HEAD = "gitlog-head:";
16673
16929
  function git(repo, ...args) {
16674
- return execFileSync2("git", ["-C", repo, ...args], {
16930
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16675
16931
  encoding: "utf8",
16676
16932
  maxBuffer: 1 << 28,
16677
16933
  windowsHide: true,
@@ -16691,6 +16947,7 @@ function gitHeadSha(dir) {
16691
16947
  }
16692
16948
  }
16693
16949
  function commitsSince(dir, sinceSha) {
16950
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16694
16951
  try {
16695
16952
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16696
16953
  return Number.isFinite(n) ? n : null;
@@ -16705,9 +16962,18 @@ function hasGitHistory(dir) {
16705
16962
  return false;
16706
16963
  }
16707
16964
  }
16965
+ async function gitLogIsCurrent(client, repo, head) {
16966
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
16967
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
16968
+ return true;
16969
+ const tags = await client.documentTags?.(canonical2) ?? [];
16970
+ return tags.some(
16971
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
16972
+ );
16973
+ }
16708
16974
 
16709
16975
  // src/core/survey.ts
16710
- import { spawn as realSpawn5 } from "child_process";
16976
+ import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
16711
16977
  import { createHash as createHash2 } from "crypto";
16712
16978
  import { existsSync as existsSync3 } from "fs";
16713
16979
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
@@ -16816,6 +17082,19 @@ function resolveAgentBin(harness, claudeBin) {
16816
17082
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16817
17083
  }
16818
17084
  }
17085
+ function opencodeCanDefineSurveyAgent(bin) {
17086
+ try {
17087
+ const out = execFileSync3(bin, ["--version"], {
17088
+ encoding: "utf8",
17089
+ timeout: 5e3,
17090
+ windowsHide: true,
17091
+ stdio: ["ignore", "pipe", "ignore"]
17092
+ });
17093
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17094
+ } catch {
17095
+ return false;
17096
+ }
17097
+ }
16819
17098
  var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
16820
17099
  var SURVEY_DISALLOWED_TOOLS = [
16821
17100
  "Bash",
@@ -16929,6 +17208,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16929
17208
  seen.add(harness);
16930
17209
  const bin = resolveAgentBin(harness, opts.claudeBin);
16931
17210
  if (!exists(bin)) continue;
17211
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17212
+ continue;
16932
17213
  const plan = buildSurveyPlan(harness, bin, repoDir, {
16933
17214
  model: opts.model,
16934
17215
  budgetUsd: opts.budgetUsd,
@@ -16985,7 +17266,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16985
17266
  var DEEPEN_DIFF_TARGET = 300;
16986
17267
  function commitCount(repoDir) {
16987
17268
  try {
16988
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
17269
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16989
17270
  encoding: "utf8",
16990
17271
  windowsHide: true,
16991
17272
  stdio: ["ignore", "pipe", "pipe"]
@@ -17056,19 +17337,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
17056
17337
  idempotentHint: false,
17057
17338
  openWorldHint: false
17058
17339
  };
17059
- var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention.';
17060
- function shapePage(page) {
17061
- const p = page ?? {};
17062
- const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
17063
- return {
17064
- id: p.id,
17065
- name: p.name,
17066
- ...p.description ? { description: p.description } : {},
17067
- ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
17068
- ...p.timestamp ? { last_updated_at: p.timestamp } : {},
17069
- body
17070
- };
17071
- }
17340
+ var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention. These are past records: check a claim that something was fixed or works against the code before relying on it.';
17072
17341
  function ok(value) {
17073
17342
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
17074
17343
  }
@@ -17086,6 +17355,8 @@ function guarded(fn) {
17086
17355
  };
17087
17356
  }
17088
17357
  function buildKnowledgeTools(client, bankId, opts = {}) {
17358
+ const extra = opts.toolGuideExtra?.trim();
17359
+ const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17089
17360
  return [
17090
17361
  {
17091
17362
  name: "hindsight_sync_status",
@@ -17145,7 +17416,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17145
17416
  },
17146
17417
  {
17147
17418
  name: "hindsight_search_knowledge_pages",
17148
- description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + CREDIT_REMINDER,
17419
+ description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + crediting,
17149
17420
  inputSchema: { query: external_exports.string().describe("what to look for") },
17150
17421
  annotations: READ_ONLY_ANNOTATIONS,
17151
17422
  handler: async (args) => {
@@ -17155,9 +17426,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17155
17426
  pages: hits.map((h) => ({
17156
17427
  page: h.name,
17157
17428
  page_id: h.id,
17429
+ // The question the page answers — the same `description` the list and read tools
17430
+ // carry, so a hit says what the page is FOR, not just how it opens.
17431
+ ...h.source_query ? { description: h.source_query } : {},
17158
17432
  snippet: h.snippet
17159
17433
  })),
17160
- crediting: CREDIT_REMINDER
17434
+ crediting
17161
17435
  });
17162
17436
  } catch (e) {
17163
17437
  return err(e);
@@ -17176,7 +17450,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17176
17450
  description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
17177
17451
  inputSchema: { page_id: external_exports.string() },
17178
17452
  annotations: READ_ONLY_ANNOTATIONS,
17179
- handler: guarded(async ({ page_id }) => shapePage(await client.getPage(page_id)))
17453
+ handler: guarded(async ({ page_id }) => client.getPage(page_id))
17180
17454
  },
17181
17455
  {
17182
17456
  name: "hindsight_reflect",
@@ -17246,12 +17520,18 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17246
17520
  import { createHash as createHash4 } from "crypto";
17247
17521
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
17248
17522
  var PENDING_MAX_BYTES = 256 * 1024;
17523
+ var MAX_CURSOR_PATHS = 16;
17524
+ function advancePaths(seen, path) {
17525
+ if (!path) return seen;
17526
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
17527
+ }
17249
17528
  function pendingReplayable(cursor, now) {
17250
17529
  const pending = cursor.pending ?? [];
17251
17530
  if (!pending.length) return true;
17252
17531
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17253
17532
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17254
17533
  }
17534
+ var MAX_CURSOR_OPS = 8;
17255
17535
  function fingerprintTurns(turns, count) {
17256
17536
  const h = createHash4("sha1").update(String(count));
17257
17537
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -17262,8 +17542,10 @@ function planRetain(turns, cursor, opts) {
17262
17542
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17263
17543
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17264
17544
  if (cursor.bank !== opts.bank) return { mode: "replace" };
17265
- if (cursor.turns > turns.length) return { mode: "replace" };
17266
- if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
17545
+ const seen = cursor.paths ?? [];
17546
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17547
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
17548
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
17267
17549
  if (cursor.turns === turns.length) return { mode: "skip" };
17268
17550
  return { mode: "append", fromTurn: cursor.turns };
17269
17551
  }
@@ -17305,11 +17587,36 @@ function renderSessionJsonl(refId, turns, baseTs) {
17305
17587
  }
17306
17588
  async function supportsAppend(client) {
17307
17589
  try {
17308
- return await client.supportsIdempotentRetain();
17590
+ return await client.supportsAppendRetain();
17309
17591
  } catch {
17310
17592
  return false;
17311
17593
  }
17312
17594
  }
17595
+ var OP_CHECK_TIMEOUT_MS = 5e3;
17596
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
17597
+ async function settleOps(client, cursor) {
17598
+ const ops = cursor.ops ?? [];
17599
+ const statuses = await Promise.all(
17600
+ ops.map(async (id) => {
17601
+ try {
17602
+ const r = await client.req(
17603
+ "GET",
17604
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
17605
+ void 0,
17606
+ [],
17607
+ OP_CHECK_TIMEOUT_MS
17608
+ );
17609
+ if (r.status === 404) return "not_found";
17610
+ return String((await r.json()).status ?? "").toLowerCase();
17611
+ } catch {
17612
+ return "";
17613
+ }
17614
+ })
17615
+ );
17616
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
17617
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
17618
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
17619
+ }
17313
17620
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
17314
17621
  var RETAIN_RETRY_ATTEMPTS = 2;
17315
17622
  var REQUEST_BUDGET_MS = 15e3;
@@ -17339,6 +17646,7 @@ function serialize(cursors, sessionId, write2) {
17339
17646
  });
17340
17647
  return next;
17341
17648
  }
17649
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
17342
17650
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
17343
17651
  const cursors = opts.cursors;
17344
17652
  if (!cursors)
@@ -17350,20 +17658,41 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
17350
17658
  harness,
17351
17659
  opts.stamp,
17352
17660
  void 0,
17353
- opts.retryUntil
17661
+ opts.retryUntil,
17662
+ opts.transcriptPath
17354
17663
  );
17355
17664
  return serialize(
17356
17665
  cursors,
17357
17666
  sessionId,
17358
- () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
17667
+ () => writeSession(
17668
+ client,
17669
+ sessionId,
17670
+ turns,
17671
+ startTs,
17672
+ harness,
17673
+ opts.stamp,
17674
+ cursors,
17675
+ opts.retryUntil,
17676
+ opts.transcriptPath
17677
+ )
17359
17678
  );
17360
17679
  }
17361
- async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
17680
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
17362
17681
  if (!turns.length) return;
17363
17682
  const refId = `conversation:${sessionId}`;
17364
- const cursor = cursors?.read(sessionId);
17683
+ let cursor = cursors?.read(sessionId);
17684
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17365
17685
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17366
- const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
17686
+ let ops = [];
17687
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17688
+ ({ cursor, ops } = await settleOps(client, cursor));
17689
+ const plan = planRetain(turns, cursor, {
17690
+ appendSupported,
17691
+ bank: client.bank,
17692
+ path: transcriptPath
17693
+ });
17694
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17695
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17367
17696
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17368
17697
  if (plan.mode === "skip" && !outbox.length) return;
17369
17698
  const opId = (mode, content) => uuidV5(`${client.bank}
@@ -17372,7 +17701,10 @@ ${mode}
17372
17701
  ${content}`);
17373
17702
  const submit = (content, operationId, append) => client.retain(
17374
17703
  content,
17375
- "coding agent session",
17704
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
17705
+ // default names both speakers: the previous "coding agent session" said nothing about
17706
+ // authorship and let an assistant's proposal be recorded as the user's decision.
17707
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
17376
17708
  refId,
17377
17709
  // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
17378
17710
  // the documents list filters and draws its agent logo from, so a template cannot displace them.
@@ -17402,8 +17734,13 @@ ${content}`);
17402
17734
  turns: turns.length,
17403
17735
  fingerprint: fingerprintTurns(turns, turns.length),
17404
17736
  bank: client.bank,
17737
+ ...paths ? { paths } : {},
17405
17738
  ...appendSupported ? { appendSupported: true } : {}
17406
17739
  };
17740
+ const accepted = (id) => {
17741
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
17742
+ return ops.length ? { ...next, ops } : next;
17743
+ };
17407
17744
  const stillOurs = () => {
17408
17745
  if (!cursors) return true;
17409
17746
  const now = cursors.read(sessionId);
@@ -17412,12 +17749,10 @@ ${content}`);
17412
17749
  if (plan.mode === "replace") {
17413
17750
  const content = renderSessionJsonl(refId, turns, startTs);
17414
17751
  cursors?.write(sessionId, { ...next, dirty: true });
17415
- await submitWithRetry(
17416
- () => submit(content, opId("replace", content), false),
17417
- stillOurs,
17418
- retryUntil
17419
- );
17420
- cursors?.write(sessionId, next);
17752
+ const operationId = opId("replace", content);
17753
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17754
+ ops = [];
17755
+ cursors?.write(sessionId, accepted(operationId));
17421
17756
  return;
17422
17757
  }
17423
17758
  const queue = [...outbox];
@@ -17425,7 +17760,7 @@ ${content}`);
17425
17760
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
17426
17761
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
17427
17762
  }
17428
- cursors?.write(sessionId, { ...next, pending: queue });
17763
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
17429
17764
  for (let i = 0; i < queue.length; i++) {
17430
17765
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17431
17766
  const entry = queue[i];
@@ -17435,12 +17770,13 @@ ${content}`);
17435
17770
  retryUntil
17436
17771
  );
17437
17772
  const remaining = queue.slice(i + 1);
17438
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17773
+ const done = accepted(entry.operationId);
17774
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
17439
17775
  }
17440
17776
  }
17441
17777
 
17442
17778
  // src/core/usage.ts
17443
- import { readFileSync as readFileSync4 } from "fs";
17779
+ import { readFileSync as readFileSync5 } from "fs";
17444
17780
  import { join as join13 } from "path";
17445
17781
  function usageFilePath() {
17446
17782
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17518,7 +17854,8 @@ function resolversFor(ctx) {
17518
17854
  function buildRetainStamp(cfg, ctx) {
17519
17855
  const hasTags = Boolean(cfg.retainTags?.length);
17520
17856
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
17521
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
17857
+ const hasContext = Boolean(cfg.retainContext?.trim());
17858
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
17522
17859
  const base = resolversFor(ctx);
17523
17860
  const cache = /* @__PURE__ */ new Map();
17524
17861
  const resolvers = Object.fromEntries(
@@ -17542,19 +17879,19 @@ function buildRetainStamp(cfg, ctx) {
17542
17879
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
17543
17880
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
17544
17881
  }
17545
- return { tags, metadata };
17882
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
17883
+ return { tags, metadata, context };
17546
17884
  }
17547
17885
 
17548
- // src/core/session-start.ts
17549
- import { readFileSync as readFileSync8 } from "fs";
17550
-
17551
17886
  // src/core/skill-sync.ts
17552
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17887
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17553
17888
  import { homedir as homedir7 } from "os";
17554
- import { dirname as dirname8, join as join14 } from "path";
17889
+ import { dirname as dirname8, join as join15 } from "path";
17555
17890
  import { fileURLToPath as fileURLToPath5 } from "url";
17556
17891
 
17557
17892
  // src/core/skill-dirs.ts
17893
+ import { existsSync as existsSync5 } from "fs";
17894
+ import { join as join14 } from "path";
17558
17895
  var SKILL_DIRS = {
17559
17896
  "claude-code": [".claude", "skills"],
17560
17897
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -17567,6 +17904,8 @@ var SKILL_DIRS = {
17567
17904
  "cline-cli": [".cline", "data", "settings", "skills"],
17568
17905
  "qwen-code": [".qwen", "skills"],
17569
17906
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
17907
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
17908
+ "kimi-code": [".kimi-code", "skills"],
17570
17909
  "factory-droid": [".factory", "skills"],
17571
17910
  // Droid's user-level skills root
17572
17911
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -17574,31 +17913,53 @@ var SKILL_DIRS = {
17574
17913
  // skill removal is by fixed directory name, so installing into the shared root would make
17575
17914
  // `uninstall zcode` take Codex's and dsh's copy with it.
17576
17915
  zcode: [".zcode", "skills"],
17916
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
17917
+ // its own, never the shared agentskills root other hosts install into.
17918
+ traecode: [".trae-cn", "skills"],
17577
17919
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
17578
17920
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
17579
17921
  // and dsh's copy with it.
17580
17922
  pi: [".pi", "agent", "skills"],
17581
- "prime-agent": [".prime", "agent", "skills"]
17923
+ "prime-agent": [".prime", "agent", "skills"],
17924
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
17925
+ workbuddy: [".workbuddy", "skills"],
17926
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
17927
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
17928
+ codebuddy: [".codebuddy", "skills"]
17929
+ };
17930
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
17931
+ var traecodeDotDirName = (home, exists = existsSync5) => {
17932
+ for (const dir of TRAE_DOT_DIRS) {
17933
+ if (exists(join14(home, dir))) return dir;
17934
+ }
17935
+ return ".trae-cn";
17936
+ };
17937
+ var resolveSkillDirs = (harness, home) => {
17938
+ const parts = SKILL_DIRS[harness];
17939
+ if (harness === "traecode" && parts) {
17940
+ return [traecodeDotDirName(home), ...parts.slice(1)];
17941
+ }
17942
+ return parts;
17582
17943
  };
17583
17944
 
17584
17945
  // src/core/skill-sync.ts
17585
17946
  function packagedSkillDir() {
17586
17947
  const here = dirname8(fileURLToPath5(import.meta.url));
17587
- const dist = join14(here, "..", "skill");
17588
- return existsSync5(join14(dist, "SKILL.md")) ? dist : join14(here, "..", "..", "skill");
17948
+ const dist = join15(here, "..", "skill");
17949
+ return existsSync6(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
17589
17950
  }
17590
17951
  function syncCompanionSkill(harness, opts = {}) {
17591
17952
  try {
17592
- const parts = SKILL_DIRS[harness];
17953
+ const parts = resolveSkillDirs(harness, opts.home ?? homedir7());
17593
17954
  if (!parts) return;
17594
17955
  const src = opts.srcDir ?? packagedSkillDir();
17595
- const srcMd = join14(src, "SKILL.md");
17596
- if (!existsSync5(srcMd)) return;
17597
- const dst = join14(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
17598
- const dstMd = join14(dst, "SKILL.md");
17599
- const installed = existsSync5(dstMd);
17956
+ const srcMd = join15(src, "SKILL.md");
17957
+ if (!existsSync6(srcMd)) return;
17958
+ const dst = join15(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
17959
+ const dstMd = join15(dst, "SKILL.md");
17960
+ const installed = existsSync6(dstMd);
17600
17961
  if (!installed && !opts.install) return;
17601
- if (!installed || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17962
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17602
17963
  cpSync(src, dst, { recursive: true });
17603
17964
  }
17604
17965
  } catch {
@@ -17620,15 +17981,15 @@ function brandWord() {
17620
17981
  }
17621
17982
 
17622
17983
  // src/core/legacy.ts
17623
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17984
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17624
17985
  import { homedir as homedir8 } from "os";
17625
- import { join as join15, relative, isAbsolute as isAbsolute2 } from "path";
17986
+ import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17626
17987
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17627
- function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")) {
17628
- const registry2 = readJson(join15(claudeDir, "plugins", "installed_plugins.json"));
17988
+ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
17989
+ const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
17629
17990
  const plugins = registry2?.plugins;
17630
17991
  if (!plugins || typeof plugins !== "object") return void 0;
17631
- const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
17992
+ const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
17632
17993
  for (const [key, raw] of Object.entries(plugins)) {
17633
17994
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17634
17995
  if (enabled && enabled[key] === false) continue;
@@ -17645,7 +18006,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")
17645
18006
  }
17646
18007
  function readJson(path) {
17647
18008
  try {
17648
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18009
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17649
18010
  return parsed && typeof parsed === "object" ? parsed : void 0;
17650
18011
  } catch {
17651
18012
  return void 0;
@@ -17657,15 +18018,15 @@ function legacyClaudePluginWarning(key) {
17657
18018
  }
17658
18019
 
17659
18020
  // src/core/session-cache.ts
17660
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18021
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17661
18022
  import { tmpdir as tmpdir3 } from "os";
17662
- import { dirname as dirname9, join as join16 } from "path";
18023
+ import { dirname as dirname9, join as join17 } from "path";
17663
18024
  function sessionCacheFile(harness, sessionId) {
17664
- return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
18025
+ return join17(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17665
18026
  }
17666
18027
  function readSessionCache(cacheFile) {
17667
18028
  try {
17668
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18029
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17669
18030
  } catch {
17670
18031
  return {};
17671
18032
  }
@@ -17703,15 +18064,15 @@ async function gitSyncNote(args) {
17703
18064
  if (mode === "none" || cold) return void 0;
17704
18065
  const head = gitHeadSha(cwd);
17705
18066
  if (!head) return void 0;
17706
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
18067
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
17707
18068
  if (gitlogCurrent === void 0) return void 0;
17708
18069
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
17709
18070
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17710
18071
  let target = DEEPEN_DIFF_TARGET;
17711
18072
  try {
17712
- const { execFileSync: execFileSync4 } = await import("child_process");
18073
+ const { execFileSync: execFileSync5 } = await import("child_process");
17713
18074
  const n = Number(
17714
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18075
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17715
18076
  encoding: "utf8",
17716
18077
  windowsHide: true,
17717
18078
  stdio: ["ignore", "pipe", "pipe"]
@@ -17728,6 +18089,7 @@ async function buildSessionStartContext(args) {
17728
18089
  const t0 = Date.now();
17729
18090
  let cold;
17730
18091
  let gitDocIds;
18092
+ let bankEmpty = false;
17731
18093
  const harness = args.harness ?? "claude-code";
17732
18094
  const hasGit = args.hasGit ?? hasGitHistory;
17733
18095
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17767,11 +18129,21 @@ async function buildSessionStartContext(args) {
17767
18129
  } catch {
17768
18130
  docIds = void 0;
17769
18131
  }
17770
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18132
+ let baselines;
18133
+ if (docIds?.size === 0) {
18134
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18135
+ }
18136
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17771
18137
  gitDocIds = docIds;
18138
+ if (cold === true && client.hasDocuments) {
18139
+ bankEmpty = await client.hasDocuments().then(
18140
+ (has) => !has,
18141
+ () => false
18142
+ );
18143
+ }
17772
18144
  if (docIds !== void 0) {
17773
18145
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17774
- if (docIds.size === 0) {
18146
+ if (cold) {
17775
18147
  if (cfg.codebaseSurvey !== false) {
17776
18148
  const started = await startSurvey(cwd, {
17777
18149
  harness,
@@ -17785,7 +18157,7 @@ async function buildSessionStartContext(args) {
17785
18157
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17786
18158
  const sha = resolveHeadSha(cwd);
17787
18159
  if (sha) {
17788
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18160
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
17789
18161
  const counts = [];
17790
18162
  for (const id of markers) {
17791
18163
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -17819,19 +18191,18 @@ async function buildSessionStartContext(args) {
17819
18191
  }
17820
18192
  }
17821
18193
  let pages = [];
17822
- let pageListKnown = false;
17823
18194
  try {
17824
18195
  pages = parsePageList(await client.listPages());
17825
- pageListKnown = true;
17826
18196
  } catch {
17827
18197
  if (client.knowledgePagesSupported === false) {
17828
18198
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
17829
18199
  }
17830
18200
  }
17831
18201
  const additionalContext = buildKnowledgePreamble(pages, {
17832
- reflectOnNewGoals: cfg.autoInject !== "reflect"
18202
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18203
+ extra: cfg.toolGuideExtra
17833
18204
  });
17834
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18205
+ const deferInitialReflect = bankEmpty;
17835
18206
  let gitNote;
17836
18207
  if (gitDocIds) {
17837
18208
  gitNote = await gitSyncNote({
@@ -17855,7 +18226,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17855
18226
  }
17856
18227
 
17857
18228
  // src/core/hook.ts
17858
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
18229
+ import { existsSync as existsSync8 } from "fs";
17859
18230
 
17860
18231
  // src/core/inject.ts
17861
18232
  function buildReflectQuery(prompt) {
@@ -17904,7 +18275,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17904
18275
  // src/core/turn-journal.ts
17905
18276
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
17906
18277
  import { tmpdir as tmpdir4 } from "os";
17907
- import { dirname as dirname10, join as join17 } from "path";
18278
+ import { dirname as dirname10, join as join18 } from "path";
17908
18279
 
17909
18280
  // src/core/transcript-util.ts
17910
18281
  var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
@@ -17945,11 +18316,24 @@ function actionLine(tool, input) {
17945
18316
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17946
18317
 
17947
18318
  // src/core/hook.ts
17948
- var HOOK_FALLBACK_BUDGET_MS = 7e3;
17949
18319
  var HOOK_INJECT_ATTEMPTS = 2;
18320
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
17950
18321
  function resolveInjection(got, attempts) {
17951
18322
  if (got != null) return got;
17952
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18323
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18324
+ return attempts >= budget ? "" : void 0;
18325
+ }
18326
+ var RECALL_QUERY_MAX_TOKENS = 500;
18327
+ function boundRecallQuery(prompt) {
18328
+ let cost = 0;
18329
+ let end = 0;
18330
+ for (const ch of prompt) {
18331
+ const cp = ch.codePointAt(0);
18332
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18333
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18334
+ end += ch.length;
18335
+ }
18336
+ return prompt.slice(0, end);
17953
18337
  }
17954
18338
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17955
18339
  const t0 = Date.now();
@@ -17965,7 +18349,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17965
18349
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17966
18350
  const t0 = Date.now();
17967
18351
  try {
17968
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18352
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
17969
18353
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
17970
18354
  return observations.length ? formatRecallFallback(observations, lead) : null;
17971
18355
  } catch (e) {
@@ -17973,8 +18357,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17973
18357
  return void 0;
17974
18358
  }
17975
18359
  }
17976
- async function reflectFallback(harness, prompt, client) {
17977
- const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
18360
+ async function reflectFallback(harness, prompt, client, timeoutMs) {
18361
+ const deadline = Date.now() + timeoutMs;
17978
18362
  const remaining = () => Math.max(deadline - Date.now(), 1);
17979
18363
  return await injectPages(harness, prompt, client, remaining(), "reflect_fallback_pages") ?? // Event name predates the `injectRecall` rename and is kept: it is a logged contract that
17980
18364
  // other tools read, so renaming it would silently break them.
@@ -17999,7 +18383,7 @@ async function buildHookOutput(args) {
17999
18383
  harness,
18000
18384
  prompt,
18001
18385
  client,
18002
- HOOK_FALLBACK_BUDGET_MS,
18386
+ cfg.injectTimeoutMs,
18003
18387
  "inject_pages",
18004
18388
  PAGE_INJECT_LEAD
18005
18389
  );
@@ -18012,7 +18396,7 @@ async function buildHookOutput(args) {
18012
18396
  harness,
18013
18397
  prompt,
18014
18398
  client,
18015
- HOOK_FALLBACK_BUDGET_MS,
18399
+ cfg.injectTimeoutMs,
18016
18400
  "inject_recall",
18017
18401
  RECALL_INJECT_LEAD
18018
18402
  );
@@ -18040,7 +18424,7 @@ async function buildHookOutput(args) {
18040
18424
  answer: reflectAnswer.slice(0, 8e3)
18041
18425
  });
18042
18426
  } catch (e) {
18043
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18427
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18044
18428
  reflectFailed = true;
18045
18429
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18046
18430
  error: describeError(e)
@@ -18054,7 +18438,7 @@ async function buildHookOutput(args) {
18054
18438
  query: prompt.slice(0, 80)
18055
18439
  });
18056
18440
  if (e instanceof ReflectError && e.fallbackEligible) {
18057
- fallback = await reflectFallback(harness, prompt, client);
18441
+ fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
18058
18442
  if (fallback) reflectAnswer = fallback;
18059
18443
  }
18060
18444
  }
@@ -18087,7 +18471,12 @@ async function buildHookOutput(args) {
18087
18471
  const blocks = [];
18088
18472
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18089
18473
  if (cadence > 0 && turns % cadence === 0) {
18090
- blocks.push(buildRosterRefresh(pages, { reflectOnNewGoals: cfg.autoInject !== "reflect" }));
18474
+ blocks.push(
18475
+ buildRosterRefresh(pages, {
18476
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18477
+ extra: cfg.toolGuideExtra
18478
+ })
18479
+ );
18091
18480
  }
18092
18481
  const kept = blocks.filter(Boolean);
18093
18482
  let notice;
@@ -18107,6 +18496,7 @@ async function buildHookOutput(args) {
18107
18496
 
18108
18497
  // src/core/runtime.ts
18109
18498
  var HARNESS = "opencode";
18499
+ var FLUSH_TIMEOUT_MS = 1e4;
18110
18500
  var RuntimeCore = class {
18111
18501
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18112
18502
  this.client = client;
@@ -18132,6 +18522,8 @@ var RuntimeCore = class {
18132
18522
  usageCursors = memoryUsageCursorStore();
18133
18523
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18134
18524
  fetchTranscript;
18525
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18526
+ inFlight = /* @__PURE__ */ new Set();
18135
18527
  lastInjection = "";
18136
18528
  // most recent turn's injection block, keyed by nothing (see getInjection)
18137
18529
  deferInitialReflect = false;
@@ -18156,6 +18548,7 @@ var RuntimeCore = class {
18156
18548
  pageTrigger: buildPageTrigger(this.cfg),
18157
18549
  reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
18158
18550
  reflectBudget: this.cfg.reflectBudget,
18551
+ toolGuideExtra: this.cfg.toolGuideExtra,
18159
18552
  stampFor: () => buildRetainStamp(this.cfg, {
18160
18553
  directory: this.projectDir,
18161
18554
  harness: this.harness,
@@ -18223,7 +18616,8 @@ var RuntimeCore = class {
18223
18616
  if (turns === 1) {
18224
18617
  blocks.push(
18225
18618
  buildKnowledgePreamble(output.pages, {
18226
- reflectOnNewGoals: this.cfg.autoInject !== "reflect"
18619
+ reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18620
+ extra: this.cfg.toolGuideExtra
18227
18621
  })
18228
18622
  );
18229
18623
  }
@@ -18262,8 +18656,9 @@ var RuntimeCore = class {
18262
18656
  */
18263
18657
  async onTranscript(sessionId, turns, lastTurnComplete) {
18264
18658
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18265
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18659
+ if (!sessionId || !turns.length) return;
18266
18660
  this.recordUsage(sessionId, turns, lastTurnComplete);
18661
+ if (!this.writeBackEnabled) return;
18267
18662
  const st = this.stateFor(sessionId);
18268
18663
  this.retain(sessionId, turns, st.startTs);
18269
18664
  }
@@ -18281,7 +18676,7 @@ var RuntimeCore = class {
18281
18676
  */
18282
18677
  async onSessionIdle(sessionId) {
18283
18678
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18284
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18679
+ if (!sessionId || !this.fetchTranscript) return;
18285
18680
  let turns;
18286
18681
  try {
18287
18682
  turns = await this.fetchTranscript(sessionId);
@@ -18294,6 +18689,7 @@ var RuntimeCore = class {
18294
18689
  }
18295
18690
  if (!turns.length) return;
18296
18691
  this.recordUsage(sessionId, turns, true);
18692
+ if (!this.writeBackEnabled) return;
18297
18693
  const st = this.stateFor(sessionId);
18298
18694
  if (turns.length <= st.retainedTurns) return;
18299
18695
  st.retainedTurns = turns.length;
@@ -18321,10 +18717,27 @@ var RuntimeCore = class {
18321
18717
  }
18322
18718
  return st;
18323
18719
  }
18720
+ /**
18721
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18722
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18723
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18724
+ * stalled server cannot hold the host's exit open. Never throws.
18725
+ */
18726
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18727
+ if (!this.inFlight.size) return;
18728
+ let timer;
18729
+ await Promise.race([
18730
+ Promise.all(this.inFlight),
18731
+ new Promise((r) => {
18732
+ timer = setTimeout(r, timeoutMs);
18733
+ })
18734
+ ]);
18735
+ clearTimeout(timer);
18736
+ }
18324
18737
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18325
18738
  retain(sessionId, turns, startTs, trigger = "turn") {
18326
18739
  const t0 = Date.now();
18327
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18740
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18328
18741
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18329
18742
  cursors: this.cursors,
18330
18743
  stamp: buildRetainStamp(this.cfg, {
@@ -18349,6 +18762,8 @@ var RuntimeCore = class {
18349
18762
  trigger
18350
18763
  })
18351
18764
  );
18765
+ this.inFlight.add(write2);
18766
+ void write2.finally(() => this.inFlight.delete(write2));
18352
18767
  }
18353
18768
  };
18354
18769
 
@@ -18388,17 +18803,32 @@ function renderMessage(m) {
18388
18803
  function readPiMessages(messages) {
18389
18804
  return (messages || []).flatMap((m) => renderMessage(m));
18390
18805
  }
18806
+ function readPiEntries(entries) {
18807
+ const turns = [];
18808
+ for (const entry of entries) {
18809
+ if (!entry || entry.type !== "message" || !entry.message) continue;
18810
+ for (const turn of renderMessage(entry.message)) {
18811
+ turns.push(entry.timestamp ? { ...turn, timestamp: entry.timestamp } : turn);
18812
+ }
18813
+ }
18814
+ return turns;
18815
+ }
18391
18816
 
18392
18817
  // src/harness/pi-extension.ts
18393
- function toPiTool(spec) {
18818
+ function toPiTool(spec, bind = () => spec) {
18394
18819
  const parameters = external_exports.toJSONSchema(external_exports.object(spec.inputSchema));
18395
18820
  return {
18396
18821
  name: spec.name,
18397
18822
  label: spec.name,
18398
18823
  description: spec.description,
18399
18824
  parameters,
18400
- async execute(_toolCallId, params) {
18401
- const r = await spec.handler(params);
18825
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
18826
+ const bound = bind(ctx);
18827
+ if (!bound) {
18828
+ const text2 = "Hindsight memory is disabled for this workspace.";
18829
+ return { content: [{ type: "text", text: text2 }], details: null };
18830
+ }
18831
+ const r = await bound.handler(params);
18402
18832
  const text = r.content?.map((c) => c.text).join("\n") || "";
18403
18833
  return { content: [{ type: "text", text }], details: null };
18404
18834
  }
@@ -18420,14 +18850,22 @@ function createPiHooks(core, harness, sessionStart) {
18420
18850
  return void 0;
18421
18851
  }
18422
18852
  diag(harness, "inject_ok", { session: sessionId, chars: injection.length });
18853
+ if (event.systemPromptOptions?.sections) {
18854
+ event.systemPromptOptions.sections.hindsight = injection;
18855
+ return void 0;
18856
+ }
18423
18857
  return { systemPrompt: `${event.systemPrompt}
18424
18858
 
18425
18859
  ${injection}` };
18426
18860
  },
18427
- async agentEnd(event, sessionId) {
18428
- const turns = readPiMessages(event.messages);
18861
+ /** `branch` is the session's entries (`sessionManager.getBranch()`): the event alone holds only
18862
+ * the latest run, and writing that back replaced the session's earlier runs (#4963). */
18863
+ async agentEnd(event, sessionId, branch) {
18864
+ const turns = branch ? readPiEntries(branch) : readPiMessages(event.messages);
18429
18865
  if (turns.length) await core.onTranscript(sessionId, turns, true);
18430
- }
18866
+ },
18867
+ /** The host is exiting: the last agent_end's write-back is still in flight (#5081). */
18868
+ sessionShutdown: () => core.flush()
18431
18869
  };
18432
18870
  }
18433
18871
  function createRuntime(harness, repoPath) {
@@ -18435,19 +18873,50 @@ function createRuntime(harness, repoPath) {
18435
18873
  if (cfg.disabled) return void 0;
18436
18874
  return new RuntimeCore(client, bankId, cfg, harness, repoPath);
18437
18875
  }
18438
- function createPiExtension(harness) {
18876
+ function createPiExtension(harness, makeRuntime = createRuntime) {
18439
18877
  return (pi) => {
18440
- const repoPath = process.cwd();
18441
- const core = createRuntime(harness, repoPath);
18442
- if (!core) return;
18443
- for (const spec of core.toolSpecs()) pi.registerTool(toPiTool(spec));
18444
- const sessionStart = core.seedIfCold(repoPath);
18445
- const hooks = createPiHooks(core, harness, sessionStart);
18878
+ const launchDir = process.cwd();
18879
+ const dirOf = (ctx) => ctx?.cwd || launchDir;
18880
+ const workspaces = /* @__PURE__ */ new Map();
18881
+ const workspaceFor = (dir) => {
18882
+ const cached2 = workspaces.get(dir);
18883
+ if (cached2 !== void 0) return cached2 ?? void 0;
18884
+ const core = makeRuntime(harness, dir);
18885
+ const ws = core ? { hooks: createPiHooks(core, harness, core.seedIfCold(dir)), tools: core.toolSpecs() } : null;
18886
+ workspaces.set(dir, ws);
18887
+ return ws ?? void 0;
18888
+ };
18889
+ let toolsRegistered = false;
18890
+ const at = (ctx) => {
18891
+ const ws = workspaceFor(dirOf(ctx));
18892
+ if (ws && !toolsRegistered) {
18893
+ toolsRegistered = true;
18894
+ for (const spec of ws.tools)
18895
+ pi.registerTool(
18896
+ toPiTool(spec, (c) => workspaceFor(dirOf(c))?.tools.find((t) => t.name === spec.name))
18897
+ );
18898
+ }
18899
+ return ws;
18900
+ };
18901
+ at(void 0);
18902
+ pi.on("session_start", (_event, ctx) => {
18903
+ at(ctx);
18904
+ });
18446
18905
  pi.on(
18447
18906
  "before_agent_start",
18448
- (event, ctx) => hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
18907
+ async (event, ctx) => at(ctx)?.hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
18449
18908
  );
18450
- pi.on("agent_end", (event, ctx) => hooks.agentEnd(event, ctx.sessionManager.getSessionId()));
18909
+ pi.on(
18910
+ "agent_end",
18911
+ async (event, ctx) => at(ctx)?.hooks.agentEnd(
18912
+ event,
18913
+ ctx.sessionManager.getSessionId(),
18914
+ ctx.sessionManager.getBranch?.()
18915
+ )
18916
+ );
18917
+ pi.on("session_shutdown", async () => {
18918
+ await Promise.all([...workspaces.values()].map((ws) => ws?.hooks.sessionShutdown()));
18919
+ });
18451
18920
  };
18452
18921
  }
18453
18922