@vectorize-io/hindsight-coding-agents 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +201 -16
  2. package/dist/antigravity-hook.js +1132 -115
  3. package/dist/antigravity-statusline.js +77 -11
  4. package/dist/antigravity-stop-hook.js +1193 -133
  5. package/dist/claude-hook.js +1132 -115
  6. package/dist/claude-sessionstart-hook.js +1241 -140
  7. package/dist/claude-stop-hook.js +1193 -133
  8. package/dist/cline.js +578 -163
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +1132 -115
  13. package/dist/codex-sessionstart-hook.js +1241 -140
  14. package/dist/codex-stop-hook.js +1193 -133
  15. package/dist/copilot-hook.js +1132 -115
  16. package/dist/copilot-sessionstart-hook.js +1241 -140
  17. package/dist/copilot-stop-hook.js +1193 -133
  18. package/dist/cursor-hook.js +1132 -115
  19. package/dist/cursor-sessionstart-hook.js +1241 -140
  20. package/dist/cursor-stop-hook.js +1193 -133
  21. package/dist/daemon-start.js +54 -9
  22. package/dist/dcode-hook.js +1132 -115
  23. package/dist/dcode-sessionstart-hook.js +1241 -140
  24. package/dist/dcode-stop-hook.js +1193 -133
  25. package/dist/deepen.js +370 -104
  26. package/dist/devin-hook.js +1132 -115
  27. package/dist/devin-sessionstart-hook.js +1241 -140
  28. package/dist/devin-stop-hook.js +1193 -133
  29. package/dist/droid-hook.js +1132 -115
  30. package/dist/droid-sessionstart-hook.js +1241 -140
  31. package/dist/droid-stop-hook.js +1193 -133
  32. package/dist/dsh.js +586 -164
  33. package/dist/grok-hook.js +1132 -115
  34. package/dist/grok-sessionstart-hook.js +1241 -140
  35. package/dist/grok-stop-hook.js +1193 -133
  36. package/dist/hindsight-seed.js +50 -8
  37. package/dist/index.js +587 -172
  38. package/dist/installer.js +2010 -769
  39. package/dist/kilo.js +587 -172
  40. package/dist/kimi-hook.js +4270 -0
  41. package/dist/kimi-sessionstart-hook.js +5030 -0
  42. package/dist/kimi-stop-hook.js +4564 -0
  43. package/dist/mcp-server.js +419 -115
  44. package/dist/opencode2.js +586 -169
  45. package/dist/pi.js +644 -175
  46. package/dist/prime-agent.js +644 -175
  47. package/dist/qwen-hook.js +1132 -115
  48. package/dist/qwen-sessionstart-hook.js +1241 -140
  49. package/dist/qwen-stop-hook.js +1193 -133
  50. package/dist/status.js +243 -52
  51. package/dist/traecode-hook.js +4270 -0
  52. package/dist/traecode-sessionstart-hook.js +5030 -0
  53. package/dist/traecode-stop-hook.js +4564 -0
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +1132 -115
  58. package/dist/zcode-sessionstart-hook.js +1241 -140
  59. package/dist/zcode-stop-hook.js +1193 -133
  60. package/package.json +22 -12
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +73 -14
package/dist/opencode2.js CHANGED
@@ -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 = (version3) => {
1602
- if (!version3)
1601
+ var uuid = (version4) => {
1602
+ if (!version4)
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}-${version3}[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}-${version4}[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 version3 = detectVersion(normalized, params?.defaultTarget);
14480
+ const version4 = detectVersion(normalized, params?.defaultTarget);
14481
14481
  const defs = normalized.$defs || normalized.definitions || {};
14482
14482
  const ctx = {
14483
- version: version3,
14483
+ version: version4,
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 (error95) {
14666
14667
  if (TRANSIENT.has(errorCode(error95))) throw new TransientProbeError(errorCode(error95));
14667
14668
  return null;
@@ -14823,13 +14824,13 @@ function isWithin(directory, configured) {
14823
14824
  function mapLookup(map3, directory) {
14824
14825
  const cwd = normalize(directory);
14825
14826
  let best;
14826
- for (const [dir, bank] of Object.entries(map3)) {
14827
+ for (const [dir, value] of Object.entries(map3)) {
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(config3, directory, sessionRoot = "") {
14835
14836
  const directories = [normalize(directory)];
@@ -14853,6 +14854,10 @@ function isOptedIn(config3, directory) {
14853
14854
  const pathMap = config3.mapPathToBank;
14854
14855
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
14855
14856
  }
14857
+ function pathSection(config3, paths, directory) {
14858
+ if (!directory || !paths) return void 0;
14859
+ return lookupDirectories(config3, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
14860
+ }
14856
14861
  function mappedBank(config3, directory, sessionRoot) {
14857
14862
  const pathMap = config3.mapPathToBank;
14858
14863
  if (!directory || !pathMap) return void 0;
@@ -14872,6 +14877,19 @@ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
14872
14877
  };
14873
14878
  return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14874
14879
  }
14880
+ function bankProjectName(config3, directory, sessionRoot) {
14881
+ if (mappedBank(config3, directory, sessionRoot)) return void 0;
14882
+ const dynamic = config3.dynamicBankId ?? !config3.bankId;
14883
+ if (!dynamic) return void 0;
14884
+ const template = config3.bankIdTemplate || DEFAULT_TEMPLATE;
14885
+ if (!template.includes("{gitProject}")) return void 0;
14886
+ try {
14887
+ return gitProjectName(directory, config3.resolveWorktrees ?? true, sessionRoot);
14888
+ } catch (error95) {
14889
+ if (error95 instanceof BankResolutionError) return void 0;
14890
+ throw error95;
14891
+ }
14892
+ }
14875
14893
  function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot) {
14876
14894
  try {
14877
14895
  return deriveBankId(config3, directory, harness, sessionRoot);
@@ -14889,7 +14907,7 @@ function deriveBankIdOrSkip(config3, 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(version3, min) {
15195
+ function semverGte(version4, 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 = version3 ? parts(version3) : void 0;
15200
+ const a = version4 ? parts(version4) : 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(url3, init) {
15327
- const send = () => fetch(url3, { ...init, headers: this.headers() });
15395
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
15396
+ const send = () => fetch(url3, { ...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, url3, body, tolerate = [], timeoutMs = 15e3) {
15343
- const r = await this.fetchWithAuth(url3, {
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(url3, {
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} ${url3} -> ${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(file3, now) {
16309
16521
  try {
16310
- const state = JSON.parse(readFileSync3(file3, "utf8"));
16522
+ const state = JSON.parse(readFileSync4(file3, "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(file3, 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(file3, now) {
16331
16543
  try {
16332
- const held = JSON.parse(readFileSync3(file3, "utf8"));
16544
+ const held = JSON.parse(readFileSync4(file3, "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(file3, 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 {
@@ -17606,10 +17967,12 @@ function syncCompanionSkill(harness, opts = {}) {
17606
17967
  }
17607
17968
  function readPackagedSkill(srcDir = packagedSkillDir()) {
17608
17969
  try {
17609
- const raw = readFileSync5(join14(srcDir, "SKILL.md"), "utf8");
17970
+ const path = join15(srcDir, "SKILL.md");
17971
+ const raw = readFileSync6(path, "utf8");
17610
17972
  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
17611
17973
  return {
17612
17974
  location: srcDir,
17975
+ path,
17613
17976
  description: frontmatter ? /^description:\s*(.+)$/m.exec(frontmatter[1])?.[1] ?? "" : "",
17614
17977
  content: frontmatter ? raw.slice(frontmatter[0].length) : raw
17615
17978
  };
@@ -17633,15 +17996,15 @@ function brandWord() {
17633
17996
  }
17634
17997
 
17635
17998
  // src/core/legacy.ts
17636
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17999
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17637
18000
  import { homedir as homedir8 } from "os";
17638
- import { join as join15, relative, isAbsolute as isAbsolute2 } from "path";
18001
+ import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17639
18002
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17640
- function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")) {
17641
- const registry3 = readJson(join15(claudeDir, "plugins", "installed_plugins.json"));
18003
+ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
18004
+ const registry3 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
17642
18005
  const plugins = registry3?.plugins;
17643
18006
  if (!plugins || typeof plugins !== "object") return void 0;
17644
- const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
18007
+ const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
17645
18008
  for (const [key, raw] of Object.entries(plugins)) {
17646
18009
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17647
18010
  if (enabled && enabled[key] === false) continue;
@@ -17658,7 +18021,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")
17658
18021
  }
17659
18022
  function readJson(path) {
17660
18023
  try {
17661
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18024
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17662
18025
  return parsed && typeof parsed === "object" ? parsed : void 0;
17663
18026
  } catch {
17664
18027
  return void 0;
@@ -17670,15 +18033,15 @@ function legacyClaudePluginWarning(key) {
17670
18033
  }
17671
18034
 
17672
18035
  // src/core/session-cache.ts
17673
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18036
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17674
18037
  import { tmpdir as tmpdir3 } from "os";
17675
- import { dirname as dirname9, join as join16 } from "path";
18038
+ import { dirname as dirname9, join as join17 } from "path";
17676
18039
  function sessionCacheFile(harness, sessionId) {
17677
- return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
18040
+ return join17(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17678
18041
  }
17679
18042
  function readSessionCache(cacheFile) {
17680
18043
  try {
17681
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18044
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17682
18045
  } catch {
17683
18046
  return {};
17684
18047
  }
@@ -17716,15 +18079,15 @@ async function gitSyncNote(args) {
17716
18079
  if (mode === "none" || cold) return void 0;
17717
18080
  const head = gitHeadSha(cwd);
17718
18081
  if (!head) return void 0;
17719
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
18082
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
17720
18083
  if (gitlogCurrent === void 0) return void 0;
17721
18084
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
17722
18085
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17723
18086
  let target = DEEPEN_DIFF_TARGET;
17724
18087
  try {
17725
- const { execFileSync: execFileSync4 } = await import("child_process");
18088
+ const { execFileSync: execFileSync5 } = await import("child_process");
17726
18089
  const n = Number(
17727
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18090
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17728
18091
  encoding: "utf8",
17729
18092
  windowsHide: true,
17730
18093
  stdio: ["ignore", "pipe", "pipe"]
@@ -17741,6 +18104,7 @@ async function buildSessionStartContext(args) {
17741
18104
  const t0 = Date.now();
17742
18105
  let cold;
17743
18106
  let gitDocIds;
18107
+ let bankEmpty = false;
17744
18108
  const harness = args.harness ?? "claude-code";
17745
18109
  const hasGit = args.hasGit ?? hasGitHistory;
17746
18110
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17780,11 +18144,21 @@ async function buildSessionStartContext(args) {
17780
18144
  } catch {
17781
18145
  docIds = void 0;
17782
18146
  }
17783
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18147
+ let baselines;
18148
+ if (docIds?.size === 0) {
18149
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18150
+ }
18151
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17784
18152
  gitDocIds = docIds;
18153
+ if (cold === true && client.hasDocuments) {
18154
+ bankEmpty = await client.hasDocuments().then(
18155
+ (has) => !has,
18156
+ () => false
18157
+ );
18158
+ }
17785
18159
  if (docIds !== void 0) {
17786
18160
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17787
- if (docIds.size === 0) {
18161
+ if (cold) {
17788
18162
  if (cfg.codebaseSurvey !== false) {
17789
18163
  const started = await startSurvey(cwd, {
17790
18164
  harness,
@@ -17798,7 +18172,7 @@ async function buildSessionStartContext(args) {
17798
18172
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17799
18173
  const sha = resolveHeadSha(cwd);
17800
18174
  if (sha) {
17801
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18175
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
17802
18176
  const counts = [];
17803
18177
  for (const id of markers) {
17804
18178
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -17832,19 +18206,18 @@ async function buildSessionStartContext(args) {
17832
18206
  }
17833
18207
  }
17834
18208
  let pages = [];
17835
- let pageListKnown = false;
17836
18209
  try {
17837
18210
  pages = parsePageList(await client.listPages());
17838
- pageListKnown = true;
17839
18211
  } catch {
17840
18212
  if (client.knowledgePagesSupported === false) {
17841
18213
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
17842
18214
  }
17843
18215
  }
17844
18216
  const additionalContext = buildKnowledgePreamble(pages, {
17845
- reflectOnNewGoals: cfg.autoInject !== "reflect"
18217
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18218
+ extra: cfg.toolGuideExtra
17846
18219
  });
17847
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18220
+ const deferInitialReflect = bankEmpty;
17848
18221
  let gitNote;
17849
18222
  if (gitDocIds) {
17850
18223
  gitNote = await gitSyncNote({
@@ -17868,7 +18241,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17868
18241
  }
17869
18242
 
17870
18243
  // src/core/hook.ts
17871
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
18244
+ import { existsSync as existsSync8 } from "fs";
17872
18245
 
17873
18246
  // src/core/inject.ts
17874
18247
  function buildReflectQuery(prompt) {
@@ -17917,7 +18290,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17917
18290
  // src/core/turn-journal.ts
17918
18291
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
17919
18292
  import { tmpdir as tmpdir4 } from "os";
17920
- import { dirname as dirname10, join as join17 } from "path";
18293
+ import { dirname as dirname10, join as join18 } from "path";
17921
18294
 
17922
18295
  // src/core/transcript-util.ts
17923
18296
  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;
@@ -17958,11 +18331,24 @@ function actionLine(tool2, input) {
17958
18331
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17959
18332
 
17960
18333
  // src/core/hook.ts
17961
- var HOOK_FALLBACK_BUDGET_MS = 7e3;
17962
18334
  var HOOK_INJECT_ATTEMPTS = 2;
18335
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
17963
18336
  function resolveInjection(got, attempts) {
17964
18337
  if (got != null) return got;
17965
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18338
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18339
+ return attempts >= budget ? "" : void 0;
18340
+ }
18341
+ var RECALL_QUERY_MAX_TOKENS = 500;
18342
+ function boundRecallQuery(prompt) {
18343
+ let cost = 0;
18344
+ let end = 0;
18345
+ for (const ch of prompt) {
18346
+ const cp = ch.codePointAt(0);
18347
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18348
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18349
+ end += ch.length;
18350
+ }
18351
+ return prompt.slice(0, end);
17966
18352
  }
17967
18353
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17968
18354
  const t0 = Date.now();
@@ -17978,7 +18364,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
17978
18364
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17979
18365
  const t0 = Date.now();
17980
18366
  try {
17981
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18367
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
17982
18368
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
17983
18369
  return observations.length ? formatRecallFallback(observations, lead) : null;
17984
18370
  } catch (e) {
@@ -17986,8 +18372,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
17986
18372
  return void 0;
17987
18373
  }
17988
18374
  }
17989
- async function reflectFallback(harness, prompt, client) {
17990
- const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
18375
+ async function reflectFallback(harness, prompt, client, timeoutMs) {
18376
+ const deadline = Date.now() + timeoutMs;
17991
18377
  const remaining = () => Math.max(deadline - Date.now(), 1);
17992
18378
  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
17993
18379
  // other tools read, so renaming it would silently break them.
@@ -18012,7 +18398,7 @@ async function buildHookOutput(args) {
18012
18398
  harness,
18013
18399
  prompt,
18014
18400
  client,
18015
- HOOK_FALLBACK_BUDGET_MS,
18401
+ cfg.injectTimeoutMs,
18016
18402
  "inject_pages",
18017
18403
  PAGE_INJECT_LEAD
18018
18404
  );
@@ -18025,7 +18411,7 @@ async function buildHookOutput(args) {
18025
18411
  harness,
18026
18412
  prompt,
18027
18413
  client,
18028
- HOOK_FALLBACK_BUDGET_MS,
18414
+ cfg.injectTimeoutMs,
18029
18415
  "inject_recall",
18030
18416
  RECALL_INJECT_LEAD
18031
18417
  );
@@ -18053,7 +18439,7 @@ async function buildHookOutput(args) {
18053
18439
  answer: reflectAnswer.slice(0, 8e3)
18054
18440
  });
18055
18441
  } catch (e) {
18056
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18442
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18057
18443
  reflectFailed = true;
18058
18444
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18059
18445
  error: describeError(e)
@@ -18067,7 +18453,7 @@ async function buildHookOutput(args) {
18067
18453
  query: prompt.slice(0, 80)
18068
18454
  });
18069
18455
  if (e instanceof ReflectError && e.fallbackEligible) {
18070
- fallback = await reflectFallback(harness, prompt, client);
18456
+ fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
18071
18457
  if (fallback) reflectAnswer = fallback;
18072
18458
  }
18073
18459
  }
@@ -18100,7 +18486,12 @@ async function buildHookOutput(args) {
18100
18486
  const blocks = [];
18101
18487
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18102
18488
  if (cadence > 0 && turns % cadence === 0) {
18103
- blocks.push(buildRosterRefresh(pages, { reflectOnNewGoals: cfg.autoInject !== "reflect" }));
18489
+ blocks.push(
18490
+ buildRosterRefresh(pages, {
18491
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
18492
+ extra: cfg.toolGuideExtra
18493
+ })
18494
+ );
18104
18495
  }
18105
18496
  const kept = blocks.filter(Boolean);
18106
18497
  let notice;
@@ -18120,6 +18511,7 @@ async function buildHookOutput(args) {
18120
18511
 
18121
18512
  // src/core/runtime.ts
18122
18513
  var HARNESS = "opencode";
18514
+ var FLUSH_TIMEOUT_MS = 1e4;
18123
18515
  var RuntimeCore = class {
18124
18516
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18125
18517
  this.client = client;
@@ -18145,6 +18537,8 @@ var RuntimeCore = class {
18145
18537
  usageCursors = memoryUsageCursorStore();
18146
18538
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18147
18539
  fetchTranscript;
18540
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18541
+ inFlight = /* @__PURE__ */ new Set();
18148
18542
  lastInjection = "";
18149
18543
  // most recent turn's injection block, keyed by nothing (see getInjection)
18150
18544
  deferInitialReflect = false;
@@ -18169,6 +18563,7 @@ var RuntimeCore = class {
18169
18563
  pageTrigger: buildPageTrigger(this.cfg),
18170
18564
  reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
18171
18565
  reflectBudget: this.cfg.reflectBudget,
18566
+ toolGuideExtra: this.cfg.toolGuideExtra,
18172
18567
  stampFor: () => buildRetainStamp(this.cfg, {
18173
18568
  directory: this.projectDir,
18174
18569
  harness: this.harness,
@@ -18236,7 +18631,8 @@ var RuntimeCore = class {
18236
18631
  if (turns === 1) {
18237
18632
  blocks.push(
18238
18633
  buildKnowledgePreamble(output.pages, {
18239
- reflectOnNewGoals: this.cfg.autoInject !== "reflect"
18634
+ reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18635
+ extra: this.cfg.toolGuideExtra
18240
18636
  })
18241
18637
  );
18242
18638
  }
@@ -18275,8 +18671,9 @@ var RuntimeCore = class {
18275
18671
  */
18276
18672
  async onTranscript(sessionId, turns, lastTurnComplete) {
18277
18673
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18278
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18674
+ if (!sessionId || !turns.length) return;
18279
18675
  this.recordUsage(sessionId, turns, lastTurnComplete);
18676
+ if (!this.writeBackEnabled) return;
18280
18677
  const st = this.stateFor(sessionId);
18281
18678
  this.retain(sessionId, turns, st.startTs);
18282
18679
  }
@@ -18294,7 +18691,7 @@ var RuntimeCore = class {
18294
18691
  */
18295
18692
  async onSessionIdle(sessionId) {
18296
18693
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18297
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18694
+ if (!sessionId || !this.fetchTranscript) return;
18298
18695
  let turns;
18299
18696
  try {
18300
18697
  turns = await this.fetchTranscript(sessionId);
@@ -18307,6 +18704,7 @@ var RuntimeCore = class {
18307
18704
  }
18308
18705
  if (!turns.length) return;
18309
18706
  this.recordUsage(sessionId, turns, true);
18707
+ if (!this.writeBackEnabled) return;
18310
18708
  const st = this.stateFor(sessionId);
18311
18709
  if (turns.length <= st.retainedTurns) return;
18312
18710
  st.retainedTurns = turns.length;
@@ -18334,10 +18732,27 @@ var RuntimeCore = class {
18334
18732
  }
18335
18733
  return st;
18336
18734
  }
18735
+ /**
18736
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18737
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18738
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18739
+ * stalled server cannot hold the host's exit open. Never throws.
18740
+ */
18741
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18742
+ if (!this.inFlight.size) return;
18743
+ let timer;
18744
+ await Promise.race([
18745
+ Promise.all(this.inFlight),
18746
+ new Promise((r) => {
18747
+ timer = setTimeout(r, timeoutMs);
18748
+ })
18749
+ ]);
18750
+ clearTimeout(timer);
18751
+ }
18337
18752
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18338
18753
  retain(sessionId, turns, startTs, trigger = "turn") {
18339
18754
  const t0 = Date.now();
18340
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18755
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18341
18756
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18342
18757
  cursors: this.cursors,
18343
18758
  stamp: buildRetainStamp(this.cfg, {
@@ -18362,6 +18777,8 @@ var RuntimeCore = class {
18362
18777
  trigger
18363
18778
  })
18364
18779
  );
18780
+ this.inFlight.add(write2);
18781
+ void write2.finally(() => this.inFlight.delete(write2));
18365
18782
  }
18366
18783
  };
18367
18784
 
@@ -18884,7 +19301,7 @@ __export(core_exports4, {
18884
19301
  toJSONSchema: () => toJSONSchema2,
18885
19302
  treeifyError: () => treeifyError2,
18886
19303
  util: () => util_exports2,
18887
- version: () => version2
19304
+ version: () => version3
18888
19305
  });
18889
19306
 
18890
19307
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
@@ -19887,10 +20304,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
19887
20304
  var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
19888
20305
  var extendedDuration2 = /^[-+]?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)?)??$/;
19889
20306
  var guid3 = /^([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})$/;
19890
- var uuid3 = (version3) => {
19891
- if (!version3)
20307
+ var uuid3 = (version4) => {
20308
+ if (!version4)
19892
20309
  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)$/;
19893
- 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})$`);
20310
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
19894
20311
  };
19895
20312
  var uuid42 = /* @__PURE__ */ uuid3(4);
19896
20313
  var uuid62 = /* @__PURE__ */ uuid3(6);
@@ -20548,7 +20965,7 @@ var Doc2 = class {
20548
20965
  };
20549
20966
 
20550
20967
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
20551
- var version2 = {
20968
+ var version3 = {
20552
20969
  major: 4,
20553
20970
  minor: 1,
20554
20971
  patch: 8
@@ -20560,7 +20977,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
20560
20977
  inst ?? (inst = {});
20561
20978
  inst._zod.def = def;
20562
20979
  inst._zod.bag = inst._zod.bag || {};
20563
- inst._zod.version = version2;
20980
+ inst._zod.version = version3;
20564
20981
  const checks = [...inst._zod.def.checks ?? []];
20565
20982
  if (inst._zod.traits.has("$ZodCheck")) {
20566
20983
  checks.unshift(inst);
@@ -30816,12 +31233,12 @@ function tool(input) {
30816
31233
  tool.schema = external_exports2;
30817
31234
 
30818
31235
  // src/harness/registry.ts
30819
- import { readFileSync as readFileSync11 } from "fs";
31236
+ import { readFileSync as readFileSync10 } from "fs";
30820
31237
  var jsonChatReader = (harness) => ({
30821
31238
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
30822
31239
  async read(opts) {
30823
31240
  if (!opts.conversations) return [];
30824
- return JSON.parse(readFileSync11(opts.conversations, "utf8"));
31241
+ return JSON.parse(readFileSync10(opts.conversations, "utf8"));
30825
31242
  }
30826
31243
  });
30827
31244