@vectorize-io/hindsight-coding-agents 0.8.6 → 0.8.8

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 +31 -21
  2. package/dist/antigravity-hook.js +278 -190
  3. package/dist/antigravity-statusline.js +30 -24
  4. package/dist/antigravity-stop-hook.js +271 -169
  5. package/dist/claude-hook.js +278 -190
  6. package/dist/claude-sessionstart-hook.js +301 -212
  7. package/dist/claude-stop-hook.js +271 -169
  8. package/dist/cline.js +258 -214
  9. package/dist/codebuddy-hook.js +278 -190
  10. package/dist/codebuddy-sessionstart-hook.js +301 -212
  11. package/dist/codebuddy-stop-hook.js +271 -169
  12. package/dist/codex-hook.js +278 -190
  13. package/dist/codex-sessionstart-hook.js +301 -212
  14. package/dist/codex-stop-hook.js +271 -169
  15. package/dist/copilot-hook.js +278 -190
  16. package/dist/copilot-sessionstart-hook.js +301 -212
  17. package/dist/copilot-stop-hook.js +271 -169
  18. package/dist/cursor-hook.js +278 -190
  19. package/dist/cursor-sessionstart-hook.js +301 -212
  20. package/dist/cursor-stop-hook.js +271 -169
  21. package/dist/daemon-start.js +20 -16
  22. package/dist/dcode-hook.js +278 -190
  23. package/dist/dcode-sessionstart-hook.js +301 -212
  24. package/dist/dcode-stop-hook.js +271 -169
  25. package/dist/deepen.js +98 -83
  26. package/dist/devin-hook.js +278 -190
  27. package/dist/devin-sessionstart-hook.js +301 -212
  28. package/dist/devin-stop-hook.js +271 -169
  29. package/dist/droid-hook.js +278 -190
  30. package/dist/droid-sessionstart-hook.js +301 -212
  31. package/dist/droid-stop-hook.js +271 -169
  32. package/dist/dsh.js +309 -251
  33. package/dist/grok-hook.js +278 -190
  34. package/dist/grok-sessionstart-hook.js +301 -212
  35. package/dist/grok-stop-hook.js +271 -169
  36. package/dist/hindsight-seed.js +35 -26
  37. package/dist/index.js +310 -252
  38. package/dist/installer.js +172 -68
  39. package/dist/kilo.js +310 -252
  40. package/dist/kimi-hook.js +278 -190
  41. package/dist/kimi-sessionstart-hook.js +301 -212
  42. package/dist/kimi-stop-hook.js +271 -169
  43. package/dist/mcp-server.js +165 -148
  44. package/dist/opencode2.js +310 -252
  45. package/dist/pi.js +309 -251
  46. package/dist/prime-agent.js +309 -251
  47. package/dist/qwen-hook.js +278 -190
  48. package/dist/qwen-sessionstart-hook.js +301 -212
  49. package/dist/qwen-stop-hook.js +271 -169
  50. package/dist/status.js +134 -117
  51. package/dist/traecode-hook.js +278 -190
  52. package/dist/traecode-sessionstart-hook.js +301 -212
  53. package/dist/traecode-stop-hook.js +271 -169
  54. package/dist/workbuddy-hook.js +278 -190
  55. package/dist/workbuddy-sessionstart-hook.js +301 -212
  56. package/dist/workbuddy-stop-hook.js +271 -169
  57. package/dist/zcode-hook.js +278 -190
  58. package/dist/zcode-sessionstart-hook.js +301 -212
  59. package/dist/zcode-stop-hook.js +271 -169
  60. package/package.json +2 -1
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +31 -26
package/dist/cline.js CHANGED
@@ -11,16 +11,77 @@ import { join as join7 } from "path";
11
11
 
12
12
  // src/core/seed.ts
13
13
  import { spawn as realSpawn } from "child_process";
14
- import { dirname, join } from "path";
14
+ import { dirname, join as join2 } from "path";
15
15
  import { fileURLToPath } from "url";
16
+
17
+ // src/core/util.ts
18
+ import { accessSync, constants, statSync } from "fs";
19
+ import { delimiter, extname, isAbsolute, join, resolve } from "path";
20
+ function binOnPath(bin, opts = {}) {
21
+ const platform = opts.platform ?? process.platform;
22
+ const env = opts.env ?? process.env;
23
+ const runnable = (file2) => {
24
+ try {
25
+ if (!statSync(file2).isFile()) return false;
26
+ if (platform !== "win32") accessSync(file2, constants.X_OK);
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ };
32
+ if (isAbsolute(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve(bin) : void 0;
33
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
34
+ for (const dir of (env.PATH || "").split(delimiter)) {
35
+ if (!dir) continue;
36
+ for (const name of names) {
37
+ const file2 = join(dir, name);
38
+ if (runnable(file2)) return resolve(file2);
39
+ }
40
+ }
41
+ return void 0;
42
+ }
43
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
44
+ function semverGte(version3, min) {
45
+ const parts = (v) => {
46
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
47
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
48
+ };
49
+ const a = version3 ? parts(version3) : void 0;
50
+ const b = parts(min);
51
+ if (!a || !b) return false;
52
+ for (let i = 0; i < 3; i++) {
53
+ if (a[i] !== b[i]) return a[i] > b[i];
54
+ }
55
+ return true;
56
+ }
57
+ async function pool(items, n, fn, onError, onProgress) {
58
+ let i = 0, done = 0;
59
+ async function worker() {
60
+ while (i < items.length) {
61
+ const idx = i++;
62
+ try {
63
+ await fn(items[idx], idx);
64
+ } catch (e) {
65
+ onError?.(idx, e);
66
+ }
67
+ onProgress?.(++done, items.length);
68
+ }
69
+ }
70
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
71
+ }
72
+ function nodeBinary() {
73
+ return process.versions.bun || process.versions.electron ? "node" : process.execPath;
74
+ }
75
+
76
+ // src/core/seed.ts
16
77
  var DEFAULT_SEED_LIMIT = 300;
17
78
  function startBackgroundSeed(repoDir, opts = {}) {
18
79
  try {
19
80
  const spawnFn = opts.spawn ?? realSpawn;
20
- const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
81
+ const enginePath = opts.enginePath ?? join2(dirname(fileURLToPath(import.meta.url)), "deepen.js");
21
82
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
22
83
  const child = spawnFn(
23
- "node",
84
+ nodeBinary(),
24
85
  [
25
86
  enginePath,
26
87
  "--repo",
@@ -45,24 +106,24 @@ function startBackgroundSeed(repoDir, opts = {}) {
45
106
  // src/core/bank.ts
46
107
  import { existsSync } from "fs";
47
108
  import { homedir as homedir2 } from "os";
48
- import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
109
+ import { basename, dirname as dirname4, join as join6, normalize, sep } from "path";
49
110
 
50
111
  // src/core/diag.ts
51
112
  import { readFileSync } from "fs";
52
- import { join as join3 } from "path";
113
+ import { join as join4 } from "path";
53
114
 
54
115
  // src/core/log.ts
55
- import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
116
+ import { appendFileSync, mkdirSync, renameSync, statSync as statSync2 } from "fs";
56
117
  import { homedir } from "os";
57
- import { dirname as dirname2, join as join2 } from "path";
118
+ import { dirname as dirname2, join as join3 } from "path";
58
119
  function logsDir() {
59
- return join2(homedir(), ".hindsight", "coding-agents-logs");
120
+ return join3(homedir(), ".hindsight", "coding-agents-logs");
60
121
  }
61
122
  var LOG_MAX_BYTES = 10 * 1024 * 1024;
62
123
  function appendLogLine(file2, text) {
63
124
  mkdirSync(dirname2(file2), { recursive: true, mode: 448 });
64
125
  try {
65
- if (statSync(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
126
+ if (statSync2(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
66
127
  } catch {
67
128
  }
68
129
  appendFileSync(file2, text, { mode: 384 });
@@ -75,7 +136,7 @@ function setLogLevel(level) {
75
136
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
76
137
  }
77
138
  function logFilePath() {
78
- return process.env.HINDSIGHT_LOG_FILE || join2(logsDir(), "plugin.log");
139
+ return process.env.HINDSIGHT_LOG_FILE || join3(logsDir(), "plugin.log");
79
140
  }
80
141
  function write(level, scope, msg, extra) {
81
142
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -110,7 +171,7 @@ function describeError(value, maxChars = 200) {
110
171
 
111
172
  // src/core/diag.ts
112
173
  function diagFilePath() {
113
- return process.env.HINDSIGHT_DIAG_FILE || join3(logsDir(), "diag.jsonl");
174
+ return process.env.HINDSIGHT_DIAG_FILE || join4(logsDir(), "diag.jsonl");
114
175
  }
115
176
  function diag(harness, event, extra = {}) {
116
177
  log.debug(harness, `diag:${event}`, extra);
@@ -125,7 +186,7 @@ function diag(harness, event, extra = {}) {
125
186
 
126
187
  // src/core/git-layout.ts
127
188
  import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
128
- import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
189
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
129
190
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
130
191
  var ATTEMPTS = 3;
131
192
  var BACKOFF_MS = 20;
@@ -158,19 +219,19 @@ function gitDirFromPointer(text, holder) {
158
219
  const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
159
220
  if (!match) return null;
160
221
  const target = match[1];
161
- return isAbsolute(target) ? target : resolve(holder, target);
222
+ return isAbsolute2(target) ? target : resolve2(holder, target);
162
223
  }
163
224
  function commonDirOf(gitDir) {
164
- const pointer = entryKind(join4(gitDir, "commondir")) === "file" ? readTextOrNull(join4(gitDir, "commondir"))?.trim() : null;
225
+ const pointer = entryKind(join5(gitDir, "commondir")) === "file" ? readTextOrNull(join5(gitDir, "commondir"))?.trim() : null;
165
226
  if (!pointer) return gitDir;
166
- return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
227
+ return isAbsolute2(pointer) ? pointer : resolve2(gitDir, pointer);
167
228
  }
168
229
  function isBare(commonDir) {
169
- const config2 = readTextOrNull(join4(commonDir, "config"));
230
+ const config2 = readTextOrNull(join5(commonDir, "config"));
170
231
  return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
171
232
  }
172
233
  function looksLikeBareRepository(directory) {
173
- return entryKind(join4(directory, "HEAD")) === "file" && entryKind(join4(directory, "objects")) === "dir" && entryKind(join4(directory, "refs")) === "dir";
234
+ return entryKind(join5(directory, "HEAD")) === "file" && entryKind(join5(directory, "objects")) === "dir" && entryKind(join5(directory, "refs")) === "dir";
174
235
  }
175
236
  function canonical(path) {
176
237
  try {
@@ -185,9 +246,9 @@ function resolved(commonDir) {
185
246
  return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
186
247
  }
187
248
  function probeOnce(directory) {
188
- let current2 = resolve(directory);
249
+ let current2 = resolve2(directory);
189
250
  for (; ; ) {
190
- const dotGit = join4(current2, ".git");
251
+ const dotGit = join5(current2, ".git");
191
252
  const kind = entryKind(dotGit);
192
253
  if (kind === "dir") {
193
254
  const layout = resolved(commonDirOf(dotGit));
@@ -301,10 +362,14 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
301
362
  return dirName(sessionRoot || directory);
302
363
  }
303
364
  function configuredDir(dir) {
304
- const expanded = dir === "~" || dir.startsWith("~/") ? join5(homedir2(), dir.slice(1)) : dir;
365
+ const expanded = dir === "~" || dir.startsWith("~/") ? join6(homedir2(), dir.slice(1)) : dir;
305
366
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
306
367
  }
307
- function isWithin(directory, configured) {
368
+ function isWithin(directory, configured, platform = process.platform) {
369
+ if (platform === "win32") {
370
+ directory = directory.toLowerCase();
371
+ configured = configured.toLowerCase();
372
+ }
308
373
  return directory === configured || directory.startsWith(configured + sep);
309
374
  }
310
375
  function mapLookup(map2, directory) {
@@ -394,7 +459,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
394
459
  import { createHash } from "crypto";
395
460
  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.";
396
461
  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.";
397
- var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
462
+ 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. When the session checked its work (a test passed or failed, a result was judged right or wrong), record the exact METHOD behind that outcome \u2014 which file, table, column, command or formula \u2014 and any caveat the session found in the data or code (a column mostly empty, a value in other units), so the same work repeats what worked and avoids what failed. Do not invent; capture only what was actually settled.`;
398
463
  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.";
399
464
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
400
465
  var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
@@ -437,14 +502,14 @@ var RETAIN_STRATEGIES = {
437
502
  retain_chunk_size: 12e3
438
503
  }
439
504
  };
440
- var KNOWLEDGE_LABELS = {
505
+ var PAGE_LABELS = {
441
506
  key: "knowledge",
442
507
  type: "multi-values",
443
508
  // 0, 1, or several — empty is normal
444
509
  optional: true,
445
510
  tag: true,
446
511
  // emits knowledge:<value> onto the fact's tags
447
- description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
512
+ description: "Routing labels for this project's Hindsight PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
448
513
  values: [
449
514
  {
450
515
  value: "feature-work",
@@ -601,7 +666,7 @@ var CODING_BANK_TEMPLATE = {
601
666
  retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
602
667
  retain_default_strategy: "git",
603
668
  retain_strategies: RETAIN_STRATEGIES,
604
- entity_labels: [KNOWLEDGE_LABELS],
669
+ entity_labels: [PAGE_LABELS],
605
670
  entities_allow_free_form: true
606
671
  }
607
672
  };
@@ -653,63 +718,7 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
653
718
  }
654
719
 
655
720
  // package.json
656
- var version = "0.8.6";
657
-
658
- // src/core/util.ts
659
- import { accessSync, constants, statSync as statSync2 } from "fs";
660
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
661
- function binOnPath(bin, opts = {}) {
662
- const platform = opts.platform ?? process.platform;
663
- const env = opts.env ?? process.env;
664
- const runnable = (file2) => {
665
- try {
666
- if (!statSync2(file2).isFile()) return false;
667
- if (platform !== "win32") accessSync(file2, constants.X_OK);
668
- return true;
669
- } catch {
670
- return false;
671
- }
672
- };
673
- if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
674
- const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
675
- for (const dir of (env.PATH || "").split(delimiter)) {
676
- if (!dir) continue;
677
- for (const name of names) {
678
- const file2 = join6(dir, name);
679
- if (runnable(file2)) return resolve2(file2);
680
- }
681
- }
682
- return void 0;
683
- }
684
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
685
- function semverGte(version3, min) {
686
- const parts = (v) => {
687
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
688
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
689
- };
690
- const a = version3 ? parts(version3) : void 0;
691
- const b = parts(min);
692
- if (!a || !b) return false;
693
- for (let i = 0; i < 3; i++) {
694
- if (a[i] !== b[i]) return a[i] > b[i];
695
- }
696
- return true;
697
- }
698
- async function pool(items, n, fn, onError, onProgress) {
699
- let i = 0, done = 0;
700
- async function worker() {
701
- while (i < items.length) {
702
- const idx = i++;
703
- try {
704
- await fn(items[idx], idx);
705
- } catch (e) {
706
- onError?.(idx, e);
707
- }
708
- onProgress?.(++done, items.length);
709
- }
710
- }
711
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
712
- }
721
+ var version = "0.8.8";
713
722
 
714
723
  // src/core/hindsight.ts
715
724
  var USER_AGENT = `hindsight-coding-agents/${version}`;
@@ -736,11 +745,11 @@ function retryAfterMs(header) {
736
745
  const at = Date.parse(header);
737
746
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
738
747
  }
739
- var KnowledgePagesUnavailableError = class extends Error {
740
- code = "knowledge_pages_unavailable";
748
+ var PagesUnavailableError = class extends Error {
749
+ code = "pages_unavailable";
741
750
  constructor() {
742
- super("Hindsight server does not support knowledge pages");
743
- this.name = "KnowledgePagesUnavailableError";
751
+ super("Hindsight server does not support pages");
752
+ this.name = "PagesUnavailableError";
744
753
  }
745
754
  };
746
755
  async function isEndpointMissing(r) {
@@ -751,6 +760,10 @@ async function isEndpointMissing(r) {
751
760
  return false;
752
761
  }
753
762
  }
763
+ function pagesPath(sub, legacy = false) {
764
+ if (!legacy) return `/pages${sub}`;
765
+ return /^\/(tree|folders|search|export|nodes)\b/.test(sub) ? `/knowledge-base${sub}` : `/knowledge-base/pages${sub}`;
766
+ }
754
767
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
755
768
  var ReflectError = class extends Error {
756
769
  constructor(message, status, timedOut, options) {
@@ -819,7 +832,7 @@ var HindsightClient = class {
819
832
  opIds = [];
820
833
  // async operation ids collected by retain(), for drain()
821
834
  /** Tri-state capability probe: unknown until the first page request, then cached. */
822
- knowledgePagesSupported;
835
+ pagesSupported;
823
836
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
824
837
  idempotentRetain;
825
838
  log;
@@ -917,7 +930,9 @@ var HindsightClient = class {
917
930
  }
918
931
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
919
932
  throw new Error(
920
- `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
933
+ // Query dropped: an encoded search query filled the 200-char error cap and pushed the
934
+ // status and the server's reason out of the tool error (#6341).
935
+ `${method} ${url2.split("?")[0]} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
921
936
  );
922
937
  return r;
923
938
  }
@@ -1048,7 +1063,7 @@ var HindsightClient = class {
1048
1063
  return (j.total ?? j.items?.length ?? 0) > 0;
1049
1064
  }
1050
1065
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
1051
- * entity labels), then seed knowledge pages when the server supports them. Both halves are
1066
+ * entity labels), then seed pages when the server supports them. Both halves are
1052
1067
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
1053
1068
  * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
1054
1069
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
@@ -1063,6 +1078,15 @@ var HindsightClient = class {
1063
1078
  await this.req("DELETE", this.bankUrl());
1064
1079
  this.log(`[bank] reset ${this.bank}`);
1065
1080
  }
1081
+ await this.configureBankSettings(opts);
1082
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1083
+ }
1084
+ /** The config half of `configureBank` (missions, retain strategies, entity labels), without
1085
+ * seeding pages. Session start calls it directly when the deepen engine — the usual caller of
1086
+ * `configureBank` — will not run (`autoSeed: false`, or a directory with no git history):
1087
+ * without it such a bank never got the `conversation` strategy, and every session write-back
1088
+ * was extracted with the server's generic rules instead of the plugin's mission. */
1089
+ async configureBankSettings(opts = {}) {
1066
1090
  if (opts.manage === false) {
1067
1091
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
1068
1092
  } else {
@@ -1078,7 +1102,6 @@ var HindsightClient = class {
1078
1102
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
1079
1103
  }
1080
1104
  }
1081
- await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1082
1105
  }
1083
1106
  /**
1084
1107
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -1230,29 +1253,45 @@ var HindsightClient = class {
1230
1253
  const j = await r.json();
1231
1254
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1232
1255
  }
1256
+ /** Set once a server answered on the deprecated `/knowledge-base/...` paths: one from before the
1257
+ * page routes moved to `/pages/...`. Remove in 2.x. */
1258
+ legacyPagesPaths = false;
1233
1259
  /**
1234
- * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1235
- * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1236
- * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1260
+ * Request a page endpoint by its `/pages` sub-path (`""`, `/tree`, `/<id>`, `/nodes/<id>`, …).
1261
+ *
1262
+ * Returns `null` — and latches `pagesSupported = false` — iff the endpoint is really absent: an
1263
+ * unrouted 404 on the `/pages` path AND on its pre-rename `/knowledge-base` twin, which a server
1264
+ * older than the rename still serves (tried once, then remembered). A bank-not-found 404 is NOT
1265
+ * a capability verdict — it is the expected answer before the bank's first retain — so it is
1266
+ * returned as-is and never caches a negative (#4607). A 404's body may already be consumed.
1237
1267
  *
1238
1268
  * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1239
1269
  * the 405/501 this used to check for never reach a caller in the first place.
1240
1270
  */
1241
- async pagesUnsupported(r) {
1242
- if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1243
- this.knowledgePagesSupported = false;
1244
- return true;
1271
+ async pagesReq(method, sub, body, tolerate = [], timeoutMs) {
1272
+ const send = (legacy) => this.req(method, this.bankUrl(pagesPath(sub, legacy)), body, tolerate, timeoutMs);
1273
+ let r = await send(this.legacyPagesPaths);
1274
+ if (r.status !== 404 || !await isEndpointMissing(r)) return r;
1275
+ if (!this.legacyPagesPaths) {
1276
+ r = await send(true);
1277
+ if (r.status !== 404 || !await isEndpointMissing(r)) {
1278
+ this.legacyPagesPaths = true;
1279
+ return r;
1280
+ }
1281
+ }
1282
+ this.pagesSupported = false;
1283
+ return null;
1245
1284
  }
1246
1285
  /**
1247
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1286
+ * The bank's page tree (folders + pages, nested). The tree carries names, source
1248
1287
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1249
1288
  */
1250
1289
  async tree() {
1251
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1252
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1253
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1290
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1291
+ const r = await this.pagesReq("GET", "/tree");
1292
+ if (!r) throw new PagesUnavailableError();
1254
1293
  if (r.status === 404) return [];
1255
- this.knowledgePagesSupported = true;
1294
+ this.pagesSupported = true;
1256
1295
  try {
1257
1296
  return (await r.json()).roots ?? [];
1258
1297
  } catch {
@@ -1260,13 +1299,13 @@ var HindsightClient = class {
1260
1299
  }
1261
1300
  }
1262
1301
  /**
1263
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1302
+ * List pages (ids + names only — no synthesized content), flattened out of the tree
1264
1303
  * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1265
1304
  * to read, and a caller enumerating pages wants leaves, not structure.
1266
1305
  *
1267
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1268
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
1269
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1306
+ * NOTE the ids are page node ids (`kp-…`), NOT the backing mental-model ids. Every
1307
+ * page read/update in this client goes through the same page ids, so a page id from
1308
+ * here, from `searchPages`, or from a `[[page:<id>]]` link all resolve identically.
1270
1309
  */
1271
1310
  async listPages() {
1272
1311
  const items = [];
@@ -1288,34 +1327,26 @@ var HindsightClient = class {
1288
1327
  return { items };
1289
1328
  }
1290
1329
  /**
1291
- * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1330
+ * Read one page's synthesized content by page id, shaped by `shapePage` so
1292
1331
  * the body arrives once. The endpoint omits the internal reflect trace that built
1293
1332
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1294
1333
  * token cap.
1295
1334
  */
1296
1335
  async getPage(pageId) {
1297
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1298
- const r = await this.req(
1299
- "GET",
1300
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1301
- );
1302
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1336
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1337
+ const r = await this.pagesReq("GET", `/${encodeURIComponent(pageId)}`);
1338
+ if (!r) throw new PagesUnavailableError();
1339
+ if (r.status === 404) throw new Error(`page not found: ${pageId}`);
1303
1340
  return shapePage(await r.json());
1304
1341
  }
1305
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1342
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's pages.
1306
1343
  * Returns page-level hits with a relevance snippet — the real search behind
1307
- * hindsight_search_knowledge_pages. */
1308
- async searchKnowledgePages(query, opts = {}) {
1309
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1344
+ * hindsight_search_pages. */
1345
+ async searchPages(query, opts = {}) {
1346
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1310
1347
  const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1311
- const r = await this.req(
1312
- "GET",
1313
- this.bankUrl(`/knowledge-base/search${q}`),
1314
- void 0,
1315
- [],
1316
- opts.timeoutMs
1317
- );
1318
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1348
+ const r = await this.pagesReq("GET", `/search${q}`, void 0, [], opts.timeoutMs);
1349
+ if (!r) throw new PagesUnavailableError();
1319
1350
  if (r.status === 404) return [];
1320
1351
  const j = await r.json();
1321
1352
  return (j.results ?? []).map((x) => ({
@@ -1327,9 +1358,9 @@ var HindsightClient = class {
1327
1358
  }));
1328
1359
  }
1329
1360
  /**
1330
- * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1361
+ * Seed the fixed page taxonomy as pages at the tree root, idempotently.
1331
1362
  *
1332
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1363
+ * Matched by NAME, not id: `POST /pages` mints its own `kp-…` id, so a stable
1333
1364
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1334
1365
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
1335
1366
  *
@@ -1344,8 +1375,8 @@ var HindsightClient = class {
1344
1375
  try {
1345
1376
  roots = await this.tree();
1346
1377
  } catch (e) {
1347
- if (e instanceof KnowledgePagesUnavailableError) {
1348
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1378
+ if (e instanceof PagesUnavailableError) {
1379
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1349
1380
  return;
1350
1381
  }
1351
1382
  throw e;
@@ -1368,11 +1399,9 @@ var HindsightClient = class {
1368
1399
  trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1369
1400
  };
1370
1401
  if (!hit) {
1371
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1372
- if (await this.pagesUnsupported(r)) {
1373
- this.log(
1374
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1375
- );
1402
+ const r = await this.pagesReq("POST", "", body, [409]);
1403
+ if (!r) {
1404
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1376
1405
  return;
1377
1406
  }
1378
1407
  if (r.status === 404) {
@@ -1393,15 +1422,9 @@ var HindsightClient = class {
1393
1422
  );
1394
1423
  }
1395
1424
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1396
- const r = await this.req(
1397
- "PATCH",
1398
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1399
- patch
1400
- );
1401
- if (await this.pagesUnsupported(r)) {
1402
- this.log(
1403
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1404
- );
1425
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(hit.id)}`, patch);
1426
+ if (!r) {
1427
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1405
1428
  return;
1406
1429
  }
1407
1430
  if (r.status === 404) {
@@ -1413,7 +1436,7 @@ var HindsightClient = class {
1413
1436
  }
1414
1437
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1415
1438
  this.log(
1416
- `[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` : "")
1439
+ `[bank] 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` : "")
1417
1440
  );
1418
1441
  }
1419
1442
  /**
@@ -1447,12 +1470,8 @@ var HindsightClient = class {
1447
1470
  if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1448
1471
  }
1449
1472
  if (!patch.trigger && !patch.source_query) continue;
1450
- const r = await this.req(
1451
- "PATCH",
1452
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1453
- patch
1454
- );
1455
- if (r.status === 404) continue;
1473
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(page.id)}`, patch);
1474
+ if (!r || r.status === 404) continue;
1456
1475
  updated++;
1457
1476
  }
1458
1477
  return updated;
@@ -1478,7 +1497,7 @@ var HindsightClient = class {
1478
1497
  let pageId = args.relatesToPageId;
1479
1498
  if (!pageId) {
1480
1499
  const folderId = await this.ensureFolder("Initiatives");
1481
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1500
+ const r = await this.pagesReq("POST", "", {
1482
1501
  name: args.title,
1483
1502
  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),
1484
1503
  parent_id: folderId,
@@ -1487,8 +1506,8 @@ var HindsightClient = class {
1487
1506
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1488
1507
  });
1489
1508
  try {
1490
- const j = await r.json();
1491
- pageId = j.page_id ?? j.id;
1509
+ const j = await r?.json();
1510
+ pageId = j?.page_id ?? j?.id;
1492
1511
  } catch {
1493
1512
  }
1494
1513
  pageId ||= `initiative-${this.slugify(args.title)}`;
@@ -1506,16 +1525,17 @@ var HindsightClient = class {
1506
1525
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1507
1526
  async ensureFolder(name) {
1508
1527
  try {
1509
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1510
- const hit = (tree.roots || []).find(
1528
+ const r = await this.pagesReq("GET", "/tree");
1529
+ const tree = await r?.json();
1530
+ const hit = (tree?.roots || []).find(
1511
1531
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1512
1532
  );
1513
1533
  if (hit?.id) return hit.id;
1514
1534
  } catch {
1515
1535
  }
1516
1536
  try {
1517
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1518
- return (await r.json()).id;
1537
+ const r = await this.pagesReq("POST", "/folders", { name });
1538
+ return (await r?.json())?.id;
1519
1539
  } catch {
1520
1540
  return void 0;
1521
1541
  }
@@ -2266,13 +2286,18 @@ function onPath(bin) {
2266
2286
  return false;
2267
2287
  }
2268
2288
  }
2289
+ var DAEMON_CONFIG_ENV = "HINDSIGHT_CODING_AGENTS_DAEMON_CONFIG";
2269
2290
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
2270
2291
  try {
2271
2292
  const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
2272
- const child = spawnFn("node", [starter, "--harness", harness], {
2293
+ const child = spawnFn(nodeBinary(), [starter, "--harness", harness], {
2273
2294
  detached: true,
2274
2295
  stdio: "ignore",
2275
- windowsHide: true
2296
+ windowsHide: true,
2297
+ // The caller's config is already resolved for its directory and bank. Re-reading the file in
2298
+ // the starter lost `paths` / `banks` overrides, so a daemon enabled only there never started
2299
+ // (#6334).
2300
+ env: { ...process.env, [DAEMON_CONFIG_ENV]: JSON.stringify(cfg) }
2276
2301
  });
2277
2302
  child.on("error", () => {
2278
2303
  });
@@ -2355,7 +2380,7 @@ function preflightDaemon(cfg, harness) {
2355
2380
  return true;
2356
2381
  }
2357
2382
 
2358
- // src/core/knowledge-injection.ts
2383
+ // src/core/page-injection.ts
2359
2384
  function parsePageList(raw) {
2360
2385
  const items = raw?.items;
2361
2386
  if (!Array.isArray(items)) return [];
@@ -2367,45 +2392,45 @@ function parsePageList(raw) {
2367
2392
  }
2368
2393
  return out;
2369
2394
  }
2370
- var EMPTY_STATE = "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
2395
+ var EMPTY_STATE = "No pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
2371
2396
  function indexLine(pages) {
2372
- const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
2373
- 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.`;
2397
+ const count = pages.length === 1 ? "1 page covers" : `${pages.length} pages cover`;
2398
+ return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_pages(query) to find the ones that bear on the current turn, then hindsight_read_page(<id>) on anything the results show is worth reading in full.`;
2374
2399
  }
2375
- 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:
2400
+ var TOOL_GUIDE = `- hindsight_search_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:
2376
2401
  \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);
2377
2402
  \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);
2378
2403
  \u2022 you are implementing something new, or two parts have to fit together;
2379
2404
  \u2022 the user asks why something is the way it is, or what is left to do;
2380
2405
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
2381
- 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.
2406
+ It ranks the pages by relevance and shows the opening of each; every page can come back, so the ranking, not the list, is the signal. Read the top page with hindsight_read_page before you rely on it \u2014 the opening is not the passage that matched. 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.
2382
2407
  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.
2383
- - 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.
2408
+ - hindsight_list_pages / hindsight_read_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.
2384
2409
  - 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>").
2385
2410
  - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this to record it as a tracked page; then call it AGAIN with relates_to_page_id set to that page whenever the goal, scope, or rationale materially changes mid-work, so the page tracks the current plan and not the opening one. Skip bug fixes, small tweaks, chores, and trivial course-corrections.
2386
2411
  - 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).`;
2387
- 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";
2412
+ var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the pages FIRST with hindsight_search_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";
2388
2413
  function toolGuide(opts) {
2389
2414
  const extra = opts?.extra?.trim();
2390
2415
  return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
2391
2416
  ${extra}` : "");
2392
2417
  }
2393
- function buildKnowledgePreamble(pages, opts) {
2418
+ function buildPagesPreamble(pages, opts) {
2394
2419
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
2395
- return `<hindsight_knowledge>
2396
- This repository has a Hindsight memory + knowledge base (curated, continuously-updated pages plus the raw memory behind them). The tools below are registered, but you must actually CALL them at the right moments:
2420
+ return `<hindsight_pages>
2421
+ This repository has a Hindsight memory + pages (curated, continuously-updated pages plus the raw memory behind them). The tools below are registered, but you must actually CALL them at the right moments:
2397
2422
  ${toolGuide(opts)}
2398
2423
  ALSO your correction tool: when you verify a Hindsight memory is wrong or stale, ingest a "Correction: <topic>" doc stating what memory claimed, what is true now, and the evidence \u2014 newer facts supersede older ones.
2399
2424
  ${body}
2400
2425
  This tool guide and the page list are re-injected for you periodically as things change.
2401
- </hindsight_knowledge>`;
2426
+ </hindsight_pages>`;
2402
2427
  }
2403
2428
  function buildRosterRefresh(pages, opts) {
2404
2429
  const rosterBlock = pages.length ? `${indexLine(pages)}
2405
2430
  ` : "";
2406
- return "<hindsight_knowledge_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2431
+ return "<hindsight_page_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2407
2432
  ${toolGuide(opts)}
2408
- </hindsight_knowledge_refresh>`;
2433
+ </hindsight_page_refresh>`;
2409
2434
  }
2410
2435
 
2411
2436
  // node_modules/zod/v4/classic/external.js
@@ -16922,7 +16947,7 @@ function date4(params) {
16922
16947
  // node_modules/zod/v4/classic/external.js
16923
16948
  config(en_default());
16924
16949
 
16925
- // src/core/knowledge-tools.ts
16950
+ // src/core/page-tools.ts
16926
16951
  import { createHash as createHash4 } from "crypto";
16927
16952
  import { existsSync as existsSync4 } from "fs";
16928
16953
  import { homedir as homedir6 } from "os";
@@ -17354,7 +17379,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17354
17379
  const mcpConfig = JSON.stringify({
17355
17380
  mcpServers: {
17356
17381
  hindsight: {
17357
- command: "node",
17382
+ command: nodeBinary(),
17358
17383
  args: [opts.mcpServerPath],
17359
17384
  // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
17360
17385
  // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
@@ -17395,7 +17420,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17395
17420
  "--sandbox",
17396
17421
  "read-only",
17397
17422
  "-c",
17398
- `mcp_servers.hindsight.command="node"`,
17423
+ `mcp_servers.hindsight.command=${tomlValue(nodeBinary())}`,
17399
17424
  "-c",
17400
17425
  `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17401
17426
  "-c",
@@ -17482,7 +17507,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17482
17507
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17483
17508
  return await new Promise((resolve4) => {
17484
17509
  try {
17485
- const child = spawnFn("node", [supervisorPath], {
17510
+ const child = spawnFn(nodeBinary(), [supervisorPath], {
17486
17511
  cwd: repoDir,
17487
17512
  detached: true,
17488
17513
  stdio: "ignore",
@@ -17580,11 +17605,11 @@ async function syncStatus(client, bank, repoDir) {
17580
17605
  activeOps,
17581
17606
  // Older Hindsight servers have no page surface. They are still fully usable for the
17582
17607
  // legacy bank/retain pipeline, so page absence must not make syncStatus permanently false.
17583
- synced: gitlogPresent && (client.knowledgePagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17608
+ synced: gitlogPresent && (client.pagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17584
17609
  };
17585
17610
  }
17586
17611
 
17587
- // src/core/knowledge-tools.ts
17612
+ // src/core/page-tools.ts
17588
17613
  var READ_ONLY_ANNOTATIONS = {
17589
17614
  readOnlyHint: true,
17590
17615
  destructiveHint: false,
@@ -17614,13 +17639,13 @@ function guarded(fn) {
17614
17639
  }
17615
17640
  };
17616
17641
  }
17617
- function buildKnowledgeTools(client, bankId, opts = {}) {
17642
+ function buildPageTools(client, bankId, opts = {}) {
17618
17643
  const extra = opts.toolGuideExtra?.trim();
17619
17644
  const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17620
17645
  return [
17621
17646
  {
17622
17647
  name: "hindsight_sync_status",
17623
- description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, knowledge pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
17648
+ description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
17624
17649
  inputSchema: {},
17625
17650
  annotations: READ_ONLY_ANNOTATIONS,
17626
17651
  handler: async () => {
@@ -17675,13 +17700,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17675
17700
  }
17676
17701
  },
17677
17702
  {
17678
- name: "hindsight_search_knowledge_pages",
17679
- 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,
17703
+ name: "hindsight_search_pages",
17704
+ description: "Search this repository's Hindsight 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, each with its opening text (not the passage that matched, and not filtered by relevance); read a full page with hindsight_read_page. " + crediting,
17680
17705
  inputSchema: { query: external_exports.string().describe("what to look for") },
17681
17706
  annotations: READ_ONLY_ANNOTATIONS,
17682
17707
  handler: async (args) => {
17683
17708
  try {
17684
- const hits = await client.searchKnowledgePages(args.query);
17709
+ const hits = await client.searchPages(args.query);
17685
17710
  return ok({
17686
17711
  pages: hits.map((h) => ({
17687
17712
  page: h.name,
@@ -17699,22 +17724,22 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17699
17724
  }
17700
17725
  },
17701
17726
  {
17702
- name: "hindsight_list_knowledge_pages",
17703
- description: "List this repository's Hindsight knowledge pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
17727
+ name: "hindsight_list_pages",
17728
+ description: "List this repository's Hindsight pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
17704
17729
  inputSchema: {},
17705
17730
  annotations: READ_ONLY_ANNOTATIONS,
17706
17731
  handler: guarded(async () => client.listPages())
17707
17732
  },
17708
17733
  {
17709
- name: "hindsight_read_knowledge_page",
17710
- 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.",
17734
+ name: "hindsight_read_page",
17735
+ description: "Read the full content of one page by its id (from hindsight_list_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.",
17711
17736
  inputSchema: { page_id: external_exports.string() },
17712
17737
  annotations: READ_ONLY_ANNOTATIONS,
17713
17738
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
17714
17739
  },
17715
17740
  {
17716
17741
  name: "hindsight_reflect",
17717
- description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
17742
+ description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
17718
17743
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
17719
17744
  annotations: READ_ONLY_ANNOTATIONS,
17720
17745
  handler: guarded(
@@ -17726,7 +17751,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17726
17751
  },
17727
17752
  {
17728
17753
  name: "hindsight_capture_initiative",
17729
- description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_knowledge_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
17754
+ description: "Record a new feature or initiative as a tracked page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
17730
17755
  inputSchema: {
17731
17756
  title: external_exports.string(),
17732
17757
  summary: external_exports.string(),
@@ -18256,10 +18281,15 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18256
18281
  const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
18257
18282
  const plugins = registry2?.plugins;
18258
18283
  if (!plugins || typeof plugins !== "object") return void 0;
18259
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
18284
+ const enabledMaps = [
18285
+ join16(cwd, ".claude", "settings.local.json"),
18286
+ join16(cwd, ".claude", "settings.json"),
18287
+ join16(claudeDir, "settings.json")
18288
+ ].map((path) => readJson(path)?.enabledPlugins);
18260
18289
  for (const [key, raw] of Object.entries(plugins)) {
18261
18290
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
18262
- if (enabled && enabled[key] === false) continue;
18291
+ const setting = enabledMaps.find((m) => m && typeof m[key] === "boolean")?.[key];
18292
+ if (setting === false) continue;
18263
18293
  const installs = Array.isArray(raw) ? raw : [raw];
18264
18294
  const active = installs.some((i) => {
18265
18295
  if (!i || typeof i !== "object") return false;
@@ -18357,6 +18387,7 @@ async function buildSessionStartContext(args) {
18357
18387
  let cold;
18358
18388
  let gitDocIds;
18359
18389
  let bankEmpty = false;
18390
+ let deepening = false;
18360
18391
  const harness = args.harness ?? "claude-code";
18361
18392
  const hasGit = args.hasGit ?? hasGitHistory;
18362
18393
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -18410,6 +18441,7 @@ async function buildSessionStartContext(args) {
18410
18441
  }
18411
18442
  if (docIds !== void 0) {
18412
18443
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18444
+ deepening = true;
18413
18445
  if (cold) {
18414
18446
  if (cfg.codebaseSurvey !== false) {
18415
18447
  const sha = resolveHeadSha(cwd);
@@ -18459,15 +18491,23 @@ async function buildSessionStartContext(args) {
18459
18491
  }
18460
18492
  }
18461
18493
  }
18494
+ if (!deepening) {
18495
+ await client.configureBankSettings?.({
18496
+ manage: cfg.manageBankConfig,
18497
+ extractionMode: cfg.retainExtractionMode,
18498
+ defaults: cfg.defaultBankConfig
18499
+ }).catch(() => {
18500
+ });
18501
+ }
18462
18502
  let pages = [];
18463
18503
  try {
18464
18504
  pages = parsePageList(await client.listPages());
18465
18505
  } catch {
18466
- if (client.knowledgePagesSupported === false) {
18467
- diag(harness, "knowledge_pages_unavailable", { bank: bankId });
18506
+ if (client.pagesSupported === false) {
18507
+ diag(harness, "pages_unavailable", { bank: bankId });
18468
18508
  }
18469
18509
  }
18470
- const additionalContext = buildKnowledgePreamble(pages, {
18510
+ const additionalContext = buildPagesPreamble(pages, {
18471
18511
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18472
18512
  extra: cfg.toolGuideExtra
18473
18513
  });
@@ -18497,6 +18537,12 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18497
18537
  // src/core/hook.ts
18498
18538
  import { existsSync as existsSync8 } from "fs";
18499
18539
 
18540
+ // src/core/transcript-util.ts
18541
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_pages|hindsight_page_refresh|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
18542
+ function stripInjectedMemory(s) {
18543
+ return s.replace(MEMORY_TAG_RE, "");
18544
+ }
18545
+
18500
18546
  // src/core/inject.ts
18501
18547
  function buildReflectQuery(prompt) {
18502
18548
  return `A developer is starting a coding session in this repository with this goal:
@@ -18513,8 +18559,8 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
18513
18559
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
18514
18560
  - If the bank holds nothing that bears on the goal, say so in one line.`;
18515
18561
  }
18516
- var PAGE_FALLBACK_LEAD = "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18517
- var PAGE_INJECT_LEAD = "(These knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18562
+ var PAGE_FALLBACK_LEAD = "(Hindsight's synthesis was unavailable this turn; these pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
18563
+ var PAGE_INJECT_LEAD = "(These pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
18518
18564
  function formatPageFallback(hits, lead = PAGE_FALLBACK_LEAD) {
18519
18565
  return `${lead}
18520
18566
  ` + hits.map((h) => {
@@ -18570,7 +18616,7 @@ function boundRecallQuery(prompt) {
18570
18616
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18571
18617
  const t0 = Date.now();
18572
18618
  try {
18573
- const hits = await client.searchKnowledgePages(prompt.slice(0, 500), { timeoutMs });
18619
+ const hits = await client.searchPages(prompt.slice(0, 500), { timeoutMs });
18574
18620
  diag(harness, event, { ms: Date.now() - t0, count: hits.length });
18575
18621
  return hits.length ? formatPageFallback(hits, lead) : null;
18576
18622
  } catch (e) {
@@ -18684,14 +18730,10 @@ async function buildHookOutput(args) {
18684
18730
  pages = parsePageList(await client.listPages());
18685
18731
  diag(harness, "pages_ok", { ms: Date.now() - t0, count: pages.length });
18686
18732
  } catch (e) {
18687
- diag(
18688
- harness,
18689
- client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
18690
- {
18691
- ms: Date.now() - t0,
18692
- error: describeError(e)
18693
- }
18694
- );
18733
+ diag(harness, client.pagesSupported === false ? "pages_unavailable" : "pages_failed", {
18734
+ ms: Date.now() - t0,
18735
+ error: describeError(e)
18736
+ });
18695
18737
  }
18696
18738
  }
18697
18739
  writeSessionCache(cacheFile, {
@@ -18702,7 +18744,7 @@ async function buildHookOutput(args) {
18702
18744
  });
18703
18745
  const blocks = [];
18704
18746
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18705
- if (cadence > 0 && turns % cadence === 0) {
18747
+ if (cadence > 0 && turns % cadence === 0 && !(turns === 1 && args.preambleOnFirstTurn)) {
18706
18748
  blocks.push(
18707
18749
  buildRosterRefresh(pages, {
18708
18750
  reflectOnNewGoals: cfg.autoInject !== "reflect",
@@ -18770,9 +18812,9 @@ var RuntimeCore = class {
18770
18812
  setTranscriptSource(fetch2) {
18771
18813
  this.fetchTranscript = fetch2;
18772
18814
  }
18773
- /** The hindsight_* knowledge + recall tools, bound to this bank, for the harness to register natively. */
18815
+ /** The hindsight_* page + recall tools, bound to this bank, for the harness to register natively. */
18774
18816
  toolSpecs() {
18775
- return buildKnowledgeTools(this.client, this.bankId, {
18817
+ return buildPageTools(this.client, this.bankId, {
18776
18818
  repoDir: this.projectDir,
18777
18819
  harness: this.harness,
18778
18820
  pageTrigger: buildPageTrigger(this.cfg),
@@ -18794,7 +18836,7 @@ var RuntimeCore = class {
18794
18836
  * git-log seed + codebase survey. Reuses the exact hook-harness logic
18795
18837
  * (`buildSessionStartContext`) so opencode seeds identically. Never throws.
18796
18838
  *
18797
- * It deliberately does NOT keep that call's knowledge preamble. This runs once per PROCESS and
18839
+ * It deliberately does NOT keep that call's pages preamble. This runs once per PROCESS and
18798
18840
  * these hosts outlive every session, so a roster captured here is stale for every session but
18799
18841
  * the first — `onPrompt` builds its own from the session's live page list (#4607).
18800
18842
  */
@@ -18825,10 +18867,11 @@ var RuntimeCore = class {
18825
18867
  * intentionally replaces the old in-memory reflect/page state, keeping lifecycle behavior
18826
18868
  * identical across hosts while this adapter retains only delivery-specific state.
18827
18869
  */
18828
- async onPrompt(sessionId2, prompt) {
18870
+ async onPrompt(sessionId2, rawPrompt) {
18829
18871
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18830
18872
  if (!sessionId2) return;
18831
- if (!prompt.trim()) {
18873
+ const prompt = stripInjectedMemory(rawPrompt).trim();
18874
+ if (!prompt) {
18832
18875
  this.injection.delete(sessionId2);
18833
18876
  return;
18834
18877
  }
@@ -18844,12 +18887,13 @@ var RuntimeCore = class {
18844
18887
  prompt,
18845
18888
  cfg: this.cfg,
18846
18889
  client: this.client,
18847
- cacheFile
18890
+ cacheFile,
18891
+ preambleOnFirstTurn: true
18848
18892
  });
18849
18893
  const blocks = [];
18850
18894
  if (turns === 1) {
18851
18895
  blocks.push(
18852
- buildKnowledgePreamble(output.pages, {
18896
+ buildPagesPreamble(output.pages, {
18853
18897
  reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18854
18898
  extra: this.cfg.toolGuideExtra
18855
18899
  })