@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/kilo.js CHANGED
@@ -14,16 +14,77 @@ import { join as join7 } from "path";
14
14
 
15
15
  // src/core/seed.ts
16
16
  import { spawn as realSpawn } from "child_process";
17
- import { dirname, join } from "path";
17
+ import { dirname, join as join2 } from "path";
18
18
  import { fileURLToPath } from "url";
19
+
20
+ // src/core/util.ts
21
+ import { accessSync, constants, statSync } from "fs";
22
+ import { delimiter, extname, isAbsolute, join, resolve } from "path";
23
+ function binOnPath(bin, opts = {}) {
24
+ const platform = opts.platform ?? process.platform;
25
+ const env = opts.env ?? process.env;
26
+ const runnable = (file3) => {
27
+ try {
28
+ if (!statSync(file3).isFile()) return false;
29
+ if (platform !== "win32") accessSync(file3, constants.X_OK);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ };
35
+ if (isAbsolute(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve(bin) : void 0;
36
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
37
+ for (const dir of (env.PATH || "").split(delimiter)) {
38
+ if (!dir) continue;
39
+ for (const name of names) {
40
+ const file3 = join(dir, name);
41
+ if (runnable(file3)) return resolve(file3);
42
+ }
43
+ }
44
+ return void 0;
45
+ }
46
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
47
+ function semverGte(version4, min) {
48
+ const parts = (v) => {
49
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
50
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
51
+ };
52
+ const a = version4 ? parts(version4) : void 0;
53
+ const b = parts(min);
54
+ if (!a || !b) return false;
55
+ for (let i = 0; i < 3; i++) {
56
+ if (a[i] !== b[i]) return a[i] > b[i];
57
+ }
58
+ return true;
59
+ }
60
+ async function pool(items, n, fn, onError, onProgress) {
61
+ let i = 0, done = 0;
62
+ async function worker() {
63
+ while (i < items.length) {
64
+ const idx = i++;
65
+ try {
66
+ await fn(items[idx], idx);
67
+ } catch (e) {
68
+ onError?.(idx, e);
69
+ }
70
+ onProgress?.(++done, items.length);
71
+ }
72
+ }
73
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
74
+ }
75
+ function nodeBinary() {
76
+ return process.versions.bun || process.versions.electron ? "node" : process.execPath;
77
+ }
78
+
79
+ // src/core/seed.ts
19
80
  var DEFAULT_SEED_LIMIT = 300;
20
81
  function startBackgroundSeed(repoDir, opts = {}) {
21
82
  try {
22
83
  const spawnFn = opts.spawn ?? realSpawn;
23
- const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
84
+ const enginePath = opts.enginePath ?? join2(dirname(fileURLToPath(import.meta.url)), "deepen.js");
24
85
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
25
86
  const child = spawnFn(
26
- "node",
87
+ nodeBinary(),
27
88
  [
28
89
  enginePath,
29
90
  "--repo",
@@ -48,24 +109,24 @@ function startBackgroundSeed(repoDir, opts = {}) {
48
109
  // src/core/bank.ts
49
110
  import { existsSync } from "fs";
50
111
  import { homedir as homedir2 } from "os";
51
- import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
112
+ import { basename, dirname as dirname4, join as join6, normalize, sep } from "path";
52
113
 
53
114
  // src/core/diag.ts
54
115
  import { readFileSync } from "fs";
55
- import { join as join3 } from "path";
116
+ import { join as join4 } from "path";
56
117
 
57
118
  // src/core/log.ts
58
- import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
119
+ import { appendFileSync, mkdirSync, renameSync, statSync as statSync2 } from "fs";
59
120
  import { homedir } from "os";
60
- import { dirname as dirname2, join as join2 } from "path";
121
+ import { dirname as dirname2, join as join3 } from "path";
61
122
  function logsDir() {
62
- return join2(homedir(), ".hindsight", "coding-agents-logs");
123
+ return join3(homedir(), ".hindsight", "coding-agents-logs");
63
124
  }
64
125
  var LOG_MAX_BYTES = 10 * 1024 * 1024;
65
126
  function appendLogLine(file3, text) {
66
127
  mkdirSync(dirname2(file3), { recursive: true, mode: 448 });
67
128
  try {
68
- if (statSync(file3).size >= LOG_MAX_BYTES) renameSync(file3, `${file3}.1`);
129
+ if (statSync2(file3).size >= LOG_MAX_BYTES) renameSync(file3, `${file3}.1`);
69
130
  } catch {
70
131
  }
71
132
  appendFileSync(file3, text, { mode: 384 });
@@ -78,7 +139,7 @@ function setLogLevel(level) {
78
139
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
79
140
  }
80
141
  function logFilePath() {
81
- return process.env.HINDSIGHT_LOG_FILE || join2(logsDir(), "plugin.log");
142
+ return process.env.HINDSIGHT_LOG_FILE || join3(logsDir(), "plugin.log");
82
143
  }
83
144
  function write(level, scope, msg, extra) {
84
145
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -113,7 +174,7 @@ function describeError(value, maxChars = 200) {
113
174
 
114
175
  // src/core/diag.ts
115
176
  function diagFilePath() {
116
- return process.env.HINDSIGHT_DIAG_FILE || join3(logsDir(), "diag.jsonl");
177
+ return process.env.HINDSIGHT_DIAG_FILE || join4(logsDir(), "diag.jsonl");
117
178
  }
118
179
  function diag(harness, event, extra = {}) {
119
180
  log.debug(harness, `diag:${event}`, extra);
@@ -128,7 +189,7 @@ function diag(harness, event, extra = {}) {
128
189
 
129
190
  // src/core/git-layout.ts
130
191
  import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
131
- import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
192
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
132
193
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
133
194
  var ATTEMPTS = 3;
134
195
  var BACKOFF_MS = 20;
@@ -161,19 +222,19 @@ function gitDirFromPointer(text, holder) {
161
222
  const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
162
223
  if (!match) return null;
163
224
  const target = match[1];
164
- return isAbsolute(target) ? target : resolve(holder, target);
225
+ return isAbsolute2(target) ? target : resolve2(holder, target);
165
226
  }
166
227
  function commonDirOf(gitDir) {
167
- const pointer = entryKind(join4(gitDir, "commondir")) === "file" ? readTextOrNull(join4(gitDir, "commondir"))?.trim() : null;
228
+ const pointer = entryKind(join5(gitDir, "commondir")) === "file" ? readTextOrNull(join5(gitDir, "commondir"))?.trim() : null;
168
229
  if (!pointer) return gitDir;
169
- return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
230
+ return isAbsolute2(pointer) ? pointer : resolve2(gitDir, pointer);
170
231
  }
171
232
  function isBare(commonDir) {
172
- const config3 = readTextOrNull(join4(commonDir, "config"));
233
+ const config3 = readTextOrNull(join5(commonDir, "config"));
173
234
  return config3 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config3);
174
235
  }
175
236
  function looksLikeBareRepository(directory) {
176
- return entryKind(join4(directory, "HEAD")) === "file" && entryKind(join4(directory, "objects")) === "dir" && entryKind(join4(directory, "refs")) === "dir";
237
+ return entryKind(join5(directory, "HEAD")) === "file" && entryKind(join5(directory, "objects")) === "dir" && entryKind(join5(directory, "refs")) === "dir";
177
238
  }
178
239
  function canonical(path) {
179
240
  try {
@@ -188,9 +249,9 @@ function resolved(commonDir) {
188
249
  return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
189
250
  }
190
251
  function probeOnce(directory) {
191
- let current2 = resolve(directory);
252
+ let current2 = resolve2(directory);
192
253
  for (; ; ) {
193
- const dotGit = join4(current2, ".git");
254
+ const dotGit = join5(current2, ".git");
194
255
  const kind = entryKind(dotGit);
195
256
  if (kind === "dir") {
196
257
  const layout = resolved(commonDirOf(dotGit));
@@ -304,10 +365,14 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
304
365
  return dirName(sessionRoot || directory);
305
366
  }
306
367
  function configuredDir(dir) {
307
- const expanded = dir === "~" || dir.startsWith("~/") ? join5(homedir2(), dir.slice(1)) : dir;
368
+ const expanded = dir === "~" || dir.startsWith("~/") ? join6(homedir2(), dir.slice(1)) : dir;
308
369
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
309
370
  }
310
- function isWithin(directory, configured) {
371
+ function isWithin(directory, configured, platform = process.platform) {
372
+ if (platform === "win32") {
373
+ directory = directory.toLowerCase();
374
+ configured = configured.toLowerCase();
375
+ }
311
376
  return directory === configured || directory.startsWith(configured + sep);
312
377
  }
313
378
  function mapLookup(map3, directory) {
@@ -397,7 +462,7 @@ function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot)
397
462
  import { createHash } from "crypto";
398
463
  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.";
399
464
  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.";
400
- 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.`;
465
+ 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.`;
401
466
  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.";
402
467
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
403
468
  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.";
@@ -440,14 +505,14 @@ var RETAIN_STRATEGIES = {
440
505
  retain_chunk_size: 12e3
441
506
  }
442
507
  };
443
- var KNOWLEDGE_LABELS = {
508
+ var PAGE_LABELS = {
444
509
  key: "knowledge",
445
510
  type: "multi-values",
446
511
  // 0, 1, or several — empty is normal
447
512
  optional: true,
448
513
  tag: true,
449
514
  // emits knowledge:<value> onto the fact's tags
450
- 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.",
515
+ 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.",
451
516
  values: [
452
517
  {
453
518
  value: "feature-work",
@@ -604,7 +669,7 @@ var CODING_BANK_TEMPLATE = {
604
669
  retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
605
670
  retain_default_strategy: "git",
606
671
  retain_strategies: RETAIN_STRATEGIES,
607
- entity_labels: [KNOWLEDGE_LABELS],
672
+ entity_labels: [PAGE_LABELS],
608
673
  entities_allow_free_form: true
609
674
  }
610
675
  };
@@ -656,63 +721,7 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
656
721
  }
657
722
 
658
723
  // package.json
659
- var version = "0.8.6";
660
-
661
- // src/core/util.ts
662
- import { accessSync, constants, statSync as statSync2 } from "fs";
663
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
664
- function binOnPath(bin, opts = {}) {
665
- const platform = opts.platform ?? process.platform;
666
- const env = opts.env ?? process.env;
667
- const runnable = (file3) => {
668
- try {
669
- if (!statSync2(file3).isFile()) return false;
670
- if (platform !== "win32") accessSync(file3, constants.X_OK);
671
- return true;
672
- } catch {
673
- return false;
674
- }
675
- };
676
- if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
677
- const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
678
- for (const dir of (env.PATH || "").split(delimiter)) {
679
- if (!dir) continue;
680
- for (const name of names) {
681
- const file3 = join6(dir, name);
682
- if (runnable(file3)) return resolve2(file3);
683
- }
684
- }
685
- return void 0;
686
- }
687
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
688
- function semverGte(version4, min) {
689
- const parts = (v) => {
690
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
691
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
692
- };
693
- const a = version4 ? parts(version4) : void 0;
694
- const b = parts(min);
695
- if (!a || !b) return false;
696
- for (let i = 0; i < 3; i++) {
697
- if (a[i] !== b[i]) return a[i] > b[i];
698
- }
699
- return true;
700
- }
701
- async function pool(items, n, fn, onError, onProgress) {
702
- let i = 0, done = 0;
703
- async function worker() {
704
- while (i < items.length) {
705
- const idx = i++;
706
- try {
707
- await fn(items[idx], idx);
708
- } catch (e) {
709
- onError?.(idx, e);
710
- }
711
- onProgress?.(++done, items.length);
712
- }
713
- }
714
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
715
- }
724
+ var version = "0.8.8";
716
725
 
717
726
  // src/core/hindsight.ts
718
727
  var USER_AGENT = `hindsight-coding-agents/${version}`;
@@ -739,11 +748,11 @@ function retryAfterMs(header) {
739
748
  const at = Date.parse(header);
740
749
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
741
750
  }
742
- var KnowledgePagesUnavailableError = class extends Error {
743
- code = "knowledge_pages_unavailable";
751
+ var PagesUnavailableError = class extends Error {
752
+ code = "pages_unavailable";
744
753
  constructor() {
745
- super("Hindsight server does not support knowledge pages");
746
- this.name = "KnowledgePagesUnavailableError";
754
+ super("Hindsight server does not support pages");
755
+ this.name = "PagesUnavailableError";
747
756
  }
748
757
  };
749
758
  async function isEndpointMissing(r) {
@@ -754,6 +763,10 @@ async function isEndpointMissing(r) {
754
763
  return false;
755
764
  }
756
765
  }
766
+ function pagesPath(sub, legacy = false) {
767
+ if (!legacy) return `/pages${sub}`;
768
+ return /^\/(tree|folders|search|export|nodes)\b/.test(sub) ? `/knowledge-base${sub}` : `/knowledge-base/pages${sub}`;
769
+ }
757
770
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
758
771
  var ReflectError = class extends Error {
759
772
  constructor(message, status, timedOut, options) {
@@ -822,7 +835,7 @@ var HindsightClient = class {
822
835
  opIds = [];
823
836
  // async operation ids collected by retain(), for drain()
824
837
  /** Tri-state capability probe: unknown until the first page request, then cached. */
825
- knowledgePagesSupported;
838
+ pagesSupported;
826
839
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
827
840
  idempotentRetain;
828
841
  log;
@@ -920,7 +933,9 @@ var HindsightClient = class {
920
933
  }
921
934
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
922
935
  throw new Error(
923
- `${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
936
+ // Query dropped: an encoded search query filled the 200-char error cap and pushed the
937
+ // status and the server's reason out of the tool error (#6341).
938
+ `${method} ${url3.split("?")[0]} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
924
939
  );
925
940
  return r;
926
941
  }
@@ -1051,7 +1066,7 @@ var HindsightClient = class {
1051
1066
  return (j.total ?? j.items?.length ?? 0) > 0;
1052
1067
  }
1053
1068
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
1054
- * entity labels), then seed knowledge pages when the server supports them. Both halves are
1069
+ * entity labels), then seed pages when the server supports them. Both halves are
1055
1070
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
1056
1071
  * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
1057
1072
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
@@ -1066,6 +1081,15 @@ var HindsightClient = class {
1066
1081
  await this.req("DELETE", this.bankUrl());
1067
1082
  this.log(`[bank] reset ${this.bank}`);
1068
1083
  }
1084
+ await this.configureBankSettings(opts);
1085
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1086
+ }
1087
+ /** The config half of `configureBank` (missions, retain strategies, entity labels), without
1088
+ * seeding pages. Session start calls it directly when the deepen engine — the usual caller of
1089
+ * `configureBank` — will not run (`autoSeed: false`, or a directory with no git history):
1090
+ * without it such a bank never got the `conversation` strategy, and every session write-back
1091
+ * was extracted with the server's generic rules instead of the plugin's mission. */
1092
+ async configureBankSettings(opts = {}) {
1069
1093
  if (opts.manage === false) {
1070
1094
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
1071
1095
  } else {
@@ -1081,7 +1105,6 @@ var HindsightClient = class {
1081
1105
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
1082
1106
  }
1083
1107
  }
1084
- await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1085
1108
  }
1086
1109
  /**
1087
1110
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -1233,29 +1256,45 @@ var HindsightClient = class {
1233
1256
  const j = await r.json();
1234
1257
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1235
1258
  }
1259
+ /** Set once a server answered on the deprecated `/knowledge-base/...` paths: one from before the
1260
+ * page routes moved to `/pages/...`. Remove in 2.x. */
1261
+ legacyPagesPaths = false;
1236
1262
  /**
1237
- * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1238
- * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1239
- * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1263
+ * Request a page endpoint by its `/pages` sub-path (`""`, `/tree`, `/<id>`, `/nodes/<id>`, …).
1264
+ *
1265
+ * Returns `null` — and latches `pagesSupported = false` — iff the endpoint is really absent: an
1266
+ * unrouted 404 on the `/pages` path AND on its pre-rename `/knowledge-base` twin, which a server
1267
+ * older than the rename still serves (tried once, then remembered). A bank-not-found 404 is NOT
1268
+ * a capability verdict — it is the expected answer before the bank's first retain — so it is
1269
+ * returned as-is and never caches a negative (#4607). A 404's body may already be consumed.
1240
1270
  *
1241
1271
  * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1242
1272
  * the 405/501 this used to check for never reach a caller in the first place.
1243
1273
  */
1244
- async pagesUnsupported(r) {
1245
- if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1246
- this.knowledgePagesSupported = false;
1247
- return true;
1274
+ async pagesReq(method, sub, body, tolerate = [], timeoutMs) {
1275
+ const send = (legacy) => this.req(method, this.bankUrl(pagesPath(sub, legacy)), body, tolerate, timeoutMs);
1276
+ let r = await send(this.legacyPagesPaths);
1277
+ if (r.status !== 404 || !await isEndpointMissing(r)) return r;
1278
+ if (!this.legacyPagesPaths) {
1279
+ r = await send(true);
1280
+ if (r.status !== 404 || !await isEndpointMissing(r)) {
1281
+ this.legacyPagesPaths = true;
1282
+ return r;
1283
+ }
1284
+ }
1285
+ this.pagesSupported = false;
1286
+ return null;
1248
1287
  }
1249
1288
  /**
1250
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1289
+ * The bank's page tree (folders + pages, nested). The tree carries names, source
1251
1290
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1252
1291
  */
1253
1292
  async tree() {
1254
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1255
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1256
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1293
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1294
+ const r = await this.pagesReq("GET", "/tree");
1295
+ if (!r) throw new PagesUnavailableError();
1257
1296
  if (r.status === 404) return [];
1258
- this.knowledgePagesSupported = true;
1297
+ this.pagesSupported = true;
1259
1298
  try {
1260
1299
  return (await r.json()).roots ?? [];
1261
1300
  } catch {
@@ -1263,13 +1302,13 @@ var HindsightClient = class {
1263
1302
  }
1264
1303
  }
1265
1304
  /**
1266
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1305
+ * List pages (ids + names only — no synthesized content), flattened out of the tree
1267
1306
  * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1268
1307
  * to read, and a caller enumerating pages wants leaves, not structure.
1269
1308
  *
1270
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1271
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
1272
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1309
+ * NOTE the ids are page node ids (`kp-…`), NOT the backing mental-model ids. Every
1310
+ * page read/update in this client goes through the same page ids, so a page id from
1311
+ * here, from `searchPages`, or from a `[[page:<id>]]` link all resolve identically.
1273
1312
  */
1274
1313
  async listPages() {
1275
1314
  const items = [];
@@ -1291,34 +1330,26 @@ var HindsightClient = class {
1291
1330
  return { items };
1292
1331
  }
1293
1332
  /**
1294
- * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1333
+ * Read one page's synthesized content by page id, shaped by `shapePage` so
1295
1334
  * the body arrives once. The endpoint omits the internal reflect trace that built
1296
1335
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1297
1336
  * token cap.
1298
1337
  */
1299
1338
  async getPage(pageId) {
1300
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1301
- const r = await this.req(
1302
- "GET",
1303
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1304
- );
1305
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1339
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1340
+ const r = await this.pagesReq("GET", `/${encodeURIComponent(pageId)}`);
1341
+ if (!r) throw new PagesUnavailableError();
1342
+ if (r.status === 404) throw new Error(`page not found: ${pageId}`);
1306
1343
  return shapePage(await r.json());
1307
1344
  }
1308
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1345
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's pages.
1309
1346
  * Returns page-level hits with a relevance snippet — the real search behind
1310
- * hindsight_search_knowledge_pages. */
1311
- async searchKnowledgePages(query, opts = {}) {
1312
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1347
+ * hindsight_search_pages. */
1348
+ async searchPages(query, opts = {}) {
1349
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1313
1350
  const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1314
- const r = await this.req(
1315
- "GET",
1316
- this.bankUrl(`/knowledge-base/search${q}`),
1317
- void 0,
1318
- [],
1319
- opts.timeoutMs
1320
- );
1321
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1351
+ const r = await this.pagesReq("GET", `/search${q}`, void 0, [], opts.timeoutMs);
1352
+ if (!r) throw new PagesUnavailableError();
1322
1353
  if (r.status === 404) return [];
1323
1354
  const j = await r.json();
1324
1355
  return (j.results ?? []).map((x) => ({
@@ -1330,9 +1361,9 @@ var HindsightClient = class {
1330
1361
  }));
1331
1362
  }
1332
1363
  /**
1333
- * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1364
+ * Seed the fixed page taxonomy as pages at the tree root, idempotently.
1334
1365
  *
1335
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1366
+ * Matched by NAME, not id: `POST /pages` mints its own `kp-…` id, so a stable
1336
1367
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1337
1368
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
1338
1369
  *
@@ -1347,8 +1378,8 @@ var HindsightClient = class {
1347
1378
  try {
1348
1379
  roots = await this.tree();
1349
1380
  } catch (e) {
1350
- if (e instanceof KnowledgePagesUnavailableError) {
1351
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1381
+ if (e instanceof PagesUnavailableError) {
1382
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1352
1383
  return;
1353
1384
  }
1354
1385
  throw e;
@@ -1371,11 +1402,9 @@ var HindsightClient = class {
1371
1402
  trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1372
1403
  };
1373
1404
  if (!hit) {
1374
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1375
- if (await this.pagesUnsupported(r)) {
1376
- this.log(
1377
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1378
- );
1405
+ const r = await this.pagesReq("POST", "", body, [409]);
1406
+ if (!r) {
1407
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1379
1408
  return;
1380
1409
  }
1381
1410
  if (r.status === 404) {
@@ -1396,15 +1425,9 @@ var HindsightClient = class {
1396
1425
  );
1397
1426
  }
1398
1427
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1399
- const r = await this.req(
1400
- "PATCH",
1401
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1402
- patch
1403
- );
1404
- if (await this.pagesUnsupported(r)) {
1405
- this.log(
1406
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1407
- );
1428
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(hit.id)}`, patch);
1429
+ if (!r) {
1430
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1408
1431
  return;
1409
1432
  }
1410
1433
  if (r.status === 404) {
@@ -1416,7 +1439,7 @@ var HindsightClient = class {
1416
1439
  }
1417
1440
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1418
1441
  this.log(
1419
- `[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` : "")
1442
+ `[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` : "")
1420
1443
  );
1421
1444
  }
1422
1445
  /**
@@ -1450,12 +1473,8 @@ var HindsightClient = class {
1450
1473
  if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1451
1474
  }
1452
1475
  if (!patch.trigger && !patch.source_query) continue;
1453
- const r = await this.req(
1454
- "PATCH",
1455
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1456
- patch
1457
- );
1458
- if (r.status === 404) continue;
1476
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(page.id)}`, patch);
1477
+ if (!r || r.status === 404) continue;
1459
1478
  updated++;
1460
1479
  }
1461
1480
  return updated;
@@ -1481,7 +1500,7 @@ var HindsightClient = class {
1481
1500
  let pageId = args.relatesToPageId;
1482
1501
  if (!pageId) {
1483
1502
  const folderId = await this.ensureFolder("Initiatives");
1484
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1503
+ const r = await this.pagesReq("POST", "", {
1485
1504
  name: args.title,
1486
1505
  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),
1487
1506
  parent_id: folderId,
@@ -1490,8 +1509,8 @@ var HindsightClient = class {
1490
1509
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1491
1510
  });
1492
1511
  try {
1493
- const j = await r.json();
1494
- pageId = j.page_id ?? j.id;
1512
+ const j = await r?.json();
1513
+ pageId = j?.page_id ?? j?.id;
1495
1514
  } catch {
1496
1515
  }
1497
1516
  pageId ||= `initiative-${this.slugify(args.title)}`;
@@ -1509,16 +1528,17 @@ var HindsightClient = class {
1509
1528
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1510
1529
  async ensureFolder(name) {
1511
1530
  try {
1512
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1513
- const hit = (tree.roots || []).find(
1531
+ const r = await this.pagesReq("GET", "/tree");
1532
+ const tree = await r?.json();
1533
+ const hit = (tree?.roots || []).find(
1514
1534
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1515
1535
  );
1516
1536
  if (hit?.id) return hit.id;
1517
1537
  } catch {
1518
1538
  }
1519
1539
  try {
1520
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1521
- return (await r.json()).id;
1540
+ const r = await this.pagesReq("POST", "/folders", { name });
1541
+ return (await r?.json())?.id;
1522
1542
  } catch {
1523
1543
  return void 0;
1524
1544
  }
@@ -2269,13 +2289,18 @@ function onPath(bin) {
2269
2289
  return false;
2270
2290
  }
2271
2291
  }
2292
+ var DAEMON_CONFIG_ENV = "HINDSIGHT_CODING_AGENTS_DAEMON_CONFIG";
2272
2293
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
2273
2294
  try {
2274
2295
  const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
2275
- const child = spawnFn("node", [starter, "--harness", harness], {
2296
+ const child = spawnFn(nodeBinary(), [starter, "--harness", harness], {
2276
2297
  detached: true,
2277
2298
  stdio: "ignore",
2278
- windowsHide: true
2299
+ windowsHide: true,
2300
+ // The caller's config is already resolved for its directory and bank. Re-reading the file in
2301
+ // the starter lost `paths` / `banks` overrides, so a daemon enabled only there never started
2302
+ // (#6334).
2303
+ env: { ...process.env, [DAEMON_CONFIG_ENV]: JSON.stringify(cfg) }
2279
2304
  });
2280
2305
  child.on("error", () => {
2281
2306
  });
@@ -2358,7 +2383,7 @@ function preflightDaemon(cfg, harness) {
2358
2383
  return true;
2359
2384
  }
2360
2385
 
2361
- // src/core/knowledge-injection.ts
2386
+ // src/core/page-injection.ts
2362
2387
  function parsePageList(raw) {
2363
2388
  const items = raw?.items;
2364
2389
  if (!Array.isArray(items)) return [];
@@ -2370,45 +2395,45 @@ function parsePageList(raw) {
2370
2395
  }
2371
2396
  return out;
2372
2397
  }
2373
- var EMPTY_STATE = "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
2398
+ var EMPTY_STATE = "No pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
2374
2399
  function indexLine(pages) {
2375
- const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
2376
- 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.`;
2400
+ const count = pages.length === 1 ? "1 page covers" : `${pages.length} pages cover`;
2401
+ 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.`;
2377
2402
  }
2378
- 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:
2403
+ 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:
2379
2404
  \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);
2380
2405
  \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);
2381
2406
  \u2022 you are implementing something new, or two parts have to fit together;
2382
2407
  \u2022 the user asks why something is the way it is, or what is left to do;
2383
2408
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
2384
- 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.
2409
+ 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.
2385
2410
  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.
2386
- - 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.
2411
+ - 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.
2387
2412
  - 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>").
2388
2413
  - 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.
2389
2414
  - 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).`;
2390
- 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";
2415
+ 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";
2391
2416
  function toolGuide(opts) {
2392
2417
  const extra = opts?.extra?.trim();
2393
2418
  return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
2394
2419
  ${extra}` : "");
2395
2420
  }
2396
- function buildKnowledgePreamble(pages, opts) {
2421
+ function buildPagesPreamble(pages, opts) {
2397
2422
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
2398
- return `<hindsight_knowledge>
2399
- 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:
2423
+ return `<hindsight_pages>
2424
+ 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:
2400
2425
  ${toolGuide(opts)}
2401
2426
  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.
2402
2427
  ${body}
2403
2428
  This tool guide and the page list are re-injected for you periodically as things change.
2404
- </hindsight_knowledge>`;
2429
+ </hindsight_pages>`;
2405
2430
  }
2406
2431
  function buildRosterRefresh(pages, opts) {
2407
2432
  const rosterBlock = pages.length ? `${indexLine(pages)}
2408
2433
  ` : "";
2409
- return "<hindsight_knowledge_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2434
+ return "<hindsight_page_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2410
2435
  ${toolGuide(opts)}
2411
- </hindsight_knowledge_refresh>`;
2436
+ </hindsight_page_refresh>`;
2412
2437
  }
2413
2438
 
2414
2439
  // node_modules/zod/v4/classic/external.js
@@ -16925,7 +16950,7 @@ function date4(params) {
16925
16950
  // node_modules/zod/v4/classic/external.js
16926
16951
  config(en_default());
16927
16952
 
16928
- // src/core/knowledge-tools.ts
16953
+ // src/core/page-tools.ts
16929
16954
  import { createHash as createHash4 } from "crypto";
16930
16955
  import { existsSync as existsSync4 } from "fs";
16931
16956
  import { homedir as homedir6 } from "os";
@@ -17368,7 +17393,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17368
17393
  const mcpConfig = JSON.stringify({
17369
17394
  mcpServers: {
17370
17395
  hindsight: {
17371
- command: "node",
17396
+ command: nodeBinary(),
17372
17397
  args: [opts.mcpServerPath],
17373
17398
  // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
17374
17399
  // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
@@ -17409,7 +17434,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17409
17434
  "--sandbox",
17410
17435
  "read-only",
17411
17436
  "-c",
17412
- `mcp_servers.hindsight.command="node"`,
17437
+ `mcp_servers.hindsight.command=${tomlValue(nodeBinary())}`,
17413
17438
  "-c",
17414
17439
  `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17415
17440
  "-c",
@@ -17496,7 +17521,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17496
17521
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17497
17522
  return await new Promise((resolve4) => {
17498
17523
  try {
17499
- const child = spawnFn("node", [supervisorPath], {
17524
+ const child = spawnFn(nodeBinary(), [supervisorPath], {
17500
17525
  cwd: repoDir,
17501
17526
  detached: true,
17502
17527
  stdio: "ignore",
@@ -17594,11 +17619,11 @@ async function syncStatus(client, bank, repoDir) {
17594
17619
  activeOps,
17595
17620
  // Older Hindsight servers have no page surface. They are still fully usable for the
17596
17621
  // legacy bank/retain pipeline, so page absence must not make syncStatus permanently false.
17597
- synced: gitlogPresent && (client.knowledgePagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17622
+ synced: gitlogPresent && (client.pagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17598
17623
  };
17599
17624
  }
17600
17625
 
17601
- // src/core/knowledge-tools.ts
17626
+ // src/core/page-tools.ts
17602
17627
  var READ_ONLY_ANNOTATIONS = {
17603
17628
  readOnlyHint: true,
17604
17629
  destructiveHint: false,
@@ -17628,13 +17653,13 @@ function guarded(fn) {
17628
17653
  }
17629
17654
  };
17630
17655
  }
17631
- function buildKnowledgeTools(client, bankId, opts = {}) {
17656
+ function buildPageTools(client, bankId, opts = {}) {
17632
17657
  const extra = opts.toolGuideExtra?.trim();
17633
17658
  const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17634
17659
  return [
17635
17660
  {
17636
17661
  name: "hindsight_sync_status",
17637
- 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.",
17662
+ 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.",
17638
17663
  inputSchema: {},
17639
17664
  annotations: READ_ONLY_ANNOTATIONS,
17640
17665
  handler: async () => {
@@ -17689,13 +17714,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17689
17714
  }
17690
17715
  },
17691
17716
  {
17692
- name: "hindsight_search_knowledge_pages",
17693
- 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,
17717
+ name: "hindsight_search_pages",
17718
+ 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,
17694
17719
  inputSchema: { query: external_exports.string().describe("what to look for") },
17695
17720
  annotations: READ_ONLY_ANNOTATIONS,
17696
17721
  handler: async (args) => {
17697
17722
  try {
17698
- const hits = await client.searchKnowledgePages(args.query);
17723
+ const hits = await client.searchPages(args.query);
17699
17724
  return ok({
17700
17725
  pages: hits.map((h) => ({
17701
17726
  page: h.name,
@@ -17713,22 +17738,22 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17713
17738
  }
17714
17739
  },
17715
17740
  {
17716
- name: "hindsight_list_knowledge_pages",
17717
- 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.",
17741
+ name: "hindsight_list_pages",
17742
+ 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.",
17718
17743
  inputSchema: {},
17719
17744
  annotations: READ_ONLY_ANNOTATIONS,
17720
17745
  handler: guarded(async () => client.listPages())
17721
17746
  },
17722
17747
  {
17723
- name: "hindsight_read_knowledge_page",
17724
- 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.",
17748
+ name: "hindsight_read_page",
17749
+ 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.",
17725
17750
  inputSchema: { page_id: external_exports.string() },
17726
17751
  annotations: READ_ONLY_ANNOTATIONS,
17727
17752
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
17728
17753
  },
17729
17754
  {
17730
17755
  name: "hindsight_reflect",
17731
- 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>".`,
17756
+ 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>".`,
17732
17757
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
17733
17758
  annotations: READ_ONLY_ANNOTATIONS,
17734
17759
  handler: guarded(
@@ -17740,7 +17765,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17740
17765
  },
17741
17766
  {
17742
17767
  name: "hindsight_capture_initiative",
17743
- 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.",
17768
+ 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.",
17744
17769
  inputSchema: {
17745
17770
  title: external_exports.string(),
17746
17771
  summary: external_exports.string(),
@@ -18270,10 +18295,15 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18270
18295
  const registry3 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
18271
18296
  const plugins = registry3?.plugins;
18272
18297
  if (!plugins || typeof plugins !== "object") return void 0;
18273
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
18298
+ const enabledMaps = [
18299
+ join16(cwd, ".claude", "settings.local.json"),
18300
+ join16(cwd, ".claude", "settings.json"),
18301
+ join16(claudeDir, "settings.json")
18302
+ ].map((path) => readJson(path)?.enabledPlugins);
18274
18303
  for (const [key, raw] of Object.entries(plugins)) {
18275
18304
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
18276
- if (enabled && enabled[key] === false) continue;
18305
+ const setting = enabledMaps.find((m) => m && typeof m[key] === "boolean")?.[key];
18306
+ if (setting === false) continue;
18277
18307
  const installs = Array.isArray(raw) ? raw : [raw];
18278
18308
  const active = installs.some((i) => {
18279
18309
  if (!i || typeof i !== "object") return false;
@@ -18371,6 +18401,7 @@ async function buildSessionStartContext(args) {
18371
18401
  let cold;
18372
18402
  let gitDocIds;
18373
18403
  let bankEmpty = false;
18404
+ let deepening = false;
18374
18405
  const harness = args.harness ?? "claude-code";
18375
18406
  const hasGit = args.hasGit ?? hasGitHistory;
18376
18407
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -18424,6 +18455,7 @@ async function buildSessionStartContext(args) {
18424
18455
  }
18425
18456
  if (docIds !== void 0) {
18426
18457
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18458
+ deepening = true;
18427
18459
  if (cold) {
18428
18460
  if (cfg.codebaseSurvey !== false) {
18429
18461
  const sha = resolveHeadSha(cwd);
@@ -18473,15 +18505,23 @@ async function buildSessionStartContext(args) {
18473
18505
  }
18474
18506
  }
18475
18507
  }
18508
+ if (!deepening) {
18509
+ await client.configureBankSettings?.({
18510
+ manage: cfg.manageBankConfig,
18511
+ extractionMode: cfg.retainExtractionMode,
18512
+ defaults: cfg.defaultBankConfig
18513
+ }).catch(() => {
18514
+ });
18515
+ }
18476
18516
  let pages = [];
18477
18517
  try {
18478
18518
  pages = parsePageList(await client.listPages());
18479
18519
  } catch {
18480
- if (client.knowledgePagesSupported === false) {
18481
- diag(harness, "knowledge_pages_unavailable", { bank: bankId });
18520
+ if (client.pagesSupported === false) {
18521
+ diag(harness, "pages_unavailable", { bank: bankId });
18482
18522
  }
18483
18523
  }
18484
- const additionalContext = buildKnowledgePreamble(pages, {
18524
+ const additionalContext = buildPagesPreamble(pages, {
18485
18525
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18486
18526
  extra: cfg.toolGuideExtra
18487
18527
  });
@@ -18511,6 +18551,63 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18511
18551
  // src/core/hook.ts
18512
18552
  import { existsSync as existsSync8 } from "fs";
18513
18553
 
18554
+ // src/core/transcript-util.ts
18555
+ var TOOL_TEXT_CAP = 2e3;
18556
+ 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;
18557
+ function stripInjectedMemory(s) {
18558
+ return s.replace(MEMORY_TAG_RE, "");
18559
+ }
18560
+ function truncate(s, max = TOOL_TEXT_CAP) {
18561
+ return s.length > max ? `${s.slice(0, max)}\u2026 (truncated)` : s;
18562
+ }
18563
+ var TARGET_KEYS = [
18564
+ "file_path",
18565
+ "path",
18566
+ "notebook_path",
18567
+ "command",
18568
+ "pattern",
18569
+ "query",
18570
+ "url",
18571
+ "name",
18572
+ "id"
18573
+ ];
18574
+ var ACTION_TARGET_CAP = 100;
18575
+ function actionLine(tool2, input) {
18576
+ let target = "";
18577
+ if (input && typeof input === "object") {
18578
+ const rec = input;
18579
+ for (const k of TARGET_KEYS) {
18580
+ const v = rec[k];
18581
+ if (typeof v === "string" && v.trim()) {
18582
+ target = v.trim().split("\n")[0];
18583
+ break;
18584
+ }
18585
+ }
18586
+ } else if (typeof input === "string") {
18587
+ target = input.trim().split("\n")[0];
18588
+ }
18589
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18590
+ const line = target ? `${tool2} ${target}` : tool2;
18591
+ const note = memoryNoteText(input);
18592
+ return note ? `${line}
18593
+ ${truncate(note, MEMORY_NOTE_CAP)}` : line;
18594
+ }
18595
+ var MEMORY_NOTE_CAP = 8e3;
18596
+ var MEMORY_NOTE_PATH_RE = /(^|[\\/])(memory|memories)[\\/]|(^|[\\/])MEMORY\.md$/i;
18597
+ var MEMORY_SHELL_WRITE_RE = /[\\/](memory|memories)([\\/\s"']|$)|MEMORY\.md/i;
18598
+ var SHELL_WRITE_RE = /(^|[^0-9&>])>>?(?!&)|\btee\b/;
18599
+ function memoryNoteText(input) {
18600
+ if (!input || typeof input !== "object") return "";
18601
+ const rec = input;
18602
+ const cmd = rec.command;
18603
+ if (typeof cmd === "string")
18604
+ return MEMORY_SHELL_WRITE_RE.test(cmd) && SHELL_WRITE_RE.test(cmd) ? cmd.trim() : "";
18605
+ const path = rec.file_path ?? rec.path;
18606
+ if (typeof path !== "string" || !MEMORY_NOTE_PATH_RE.test(path)) return "";
18607
+ const text = rec.content ?? rec.new_string;
18608
+ return typeof text === "string" ? text.trim() : "";
18609
+ }
18610
+
18514
18611
  // src/core/inject.ts
18515
18612
  function buildReflectQuery(prompt) {
18516
18613
  return `A developer is starting a coding session in this repository with this goal:
@@ -18527,8 +18624,8 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
18527
18624
  - 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.
18528
18625
  - If the bank holds nothing that bears on the goal, say so in one line.`;
18529
18626
  }
18530
- 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.)";
18531
- var PAGE_INJECT_LEAD = "(These knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18627
+ 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.)";
18628
+ var PAGE_INJECT_LEAD = "(These pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
18532
18629
  function formatPageFallback(hits, lead = PAGE_FALLBACK_LEAD) {
18533
18630
  return `${lead}
18534
18631
  ` + hits.map((h) => {
@@ -18559,43 +18656,6 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18559
18656
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18560
18657
  import { tmpdir as tmpdir4 } from "os";
18561
18658
  import { dirname as dirname10, join as join18 } from "path";
18562
-
18563
- // src/core/transcript-util.ts
18564
- 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;
18565
- function stripInjectedMemory(s) {
18566
- return s.replace(MEMORY_TAG_RE, "");
18567
- }
18568
- var TARGET_KEYS = [
18569
- "file_path",
18570
- "path",
18571
- "notebook_path",
18572
- "command",
18573
- "pattern",
18574
- "query",
18575
- "url",
18576
- "name",
18577
- "id"
18578
- ];
18579
- var ACTION_TARGET_CAP = 100;
18580
- function actionLine(tool2, input) {
18581
- let target = "";
18582
- if (input && typeof input === "object") {
18583
- const rec = input;
18584
- for (const k of TARGET_KEYS) {
18585
- const v = rec[k];
18586
- if (typeof v === "string" && v.trim()) {
18587
- target = v.trim().split("\n")[0];
18588
- break;
18589
- }
18590
- }
18591
- } else if (typeof input === "string") {
18592
- target = input.trim().split("\n")[0];
18593
- }
18594
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18595
- return target ? `${tool2} ${target}` : tool2;
18596
- }
18597
-
18598
- // src/core/turn-journal.ts
18599
18659
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18600
18660
 
18601
18661
  // src/core/hook.ts
@@ -18621,7 +18681,7 @@ function boundRecallQuery(prompt) {
18621
18681
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18622
18682
  const t0 = Date.now();
18623
18683
  try {
18624
- const hits = await client.searchKnowledgePages(prompt.slice(0, 500), { timeoutMs });
18684
+ const hits = await client.searchPages(prompt.slice(0, 500), { timeoutMs });
18625
18685
  diag(harness, event, { ms: Date.now() - t0, count: hits.length });
18626
18686
  return hits.length ? formatPageFallback(hits, lead) : null;
18627
18687
  } catch (e) {
@@ -18735,14 +18795,10 @@ async function buildHookOutput(args) {
18735
18795
  pages = parsePageList(await client.listPages());
18736
18796
  diag(harness, "pages_ok", { ms: Date.now() - t0, count: pages.length });
18737
18797
  } catch (e) {
18738
- diag(
18739
- harness,
18740
- client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
18741
- {
18742
- ms: Date.now() - t0,
18743
- error: describeError(e)
18744
- }
18745
- );
18798
+ diag(harness, client.pagesSupported === false ? "pages_unavailable" : "pages_failed", {
18799
+ ms: Date.now() - t0,
18800
+ error: describeError(e)
18801
+ });
18746
18802
  }
18747
18803
  }
18748
18804
  writeSessionCache(cacheFile, {
@@ -18753,7 +18809,7 @@ async function buildHookOutput(args) {
18753
18809
  });
18754
18810
  const blocks = [];
18755
18811
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18756
- if (cadence > 0 && turns % cadence === 0) {
18812
+ if (cadence > 0 && turns % cadence === 0 && !(turns === 1 && args.preambleOnFirstTurn)) {
18757
18813
  blocks.push(
18758
18814
  buildRosterRefresh(pages, {
18759
18815
  reflectOnNewGoals: cfg.autoInject !== "reflect",
@@ -18821,9 +18877,9 @@ var RuntimeCore = class {
18821
18877
  setTranscriptSource(fetch2) {
18822
18878
  this.fetchTranscript = fetch2;
18823
18879
  }
18824
- /** The hindsight_* knowledge + recall tools, bound to this bank, for the harness to register natively. */
18880
+ /** The hindsight_* page + recall tools, bound to this bank, for the harness to register natively. */
18825
18881
  toolSpecs() {
18826
- return buildKnowledgeTools(this.client, this.bankId, {
18882
+ return buildPageTools(this.client, this.bankId, {
18827
18883
  repoDir: this.projectDir,
18828
18884
  harness: this.harness,
18829
18885
  pageTrigger: buildPageTrigger(this.cfg),
@@ -18845,7 +18901,7 @@ var RuntimeCore = class {
18845
18901
  * git-log seed + codebase survey. Reuses the exact hook-harness logic
18846
18902
  * (`buildSessionStartContext`) so opencode seeds identically. Never throws.
18847
18903
  *
18848
- * It deliberately does NOT keep that call's knowledge preamble. This runs once per PROCESS and
18904
+ * It deliberately does NOT keep that call's pages preamble. This runs once per PROCESS and
18849
18905
  * these hosts outlive every session, so a roster captured here is stale for every session but
18850
18906
  * the first — `onPrompt` builds its own from the session's live page list (#4607).
18851
18907
  */
@@ -18876,10 +18932,11 @@ var RuntimeCore = class {
18876
18932
  * intentionally replaces the old in-memory reflect/page state, keeping lifecycle behavior
18877
18933
  * identical across hosts while this adapter retains only delivery-specific state.
18878
18934
  */
18879
- async onPrompt(sessionId, prompt) {
18935
+ async onPrompt(sessionId, rawPrompt) {
18880
18936
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18881
18937
  if (!sessionId) return;
18882
- if (!prompt.trim()) {
18938
+ const prompt = stripInjectedMemory(rawPrompt).trim();
18939
+ if (!prompt) {
18883
18940
  this.injection.delete(sessionId);
18884
18941
  return;
18885
18942
  }
@@ -18895,12 +18952,13 @@ var RuntimeCore = class {
18895
18952
  prompt,
18896
18953
  cfg: this.cfg,
18897
18954
  client: this.client,
18898
- cacheFile
18955
+ cacheFile,
18956
+ preambleOnFirstTurn: true
18899
18957
  });
18900
18958
  const blocks = [];
18901
18959
  if (turns === 1) {
18902
18960
  blocks.push(
18903
- buildKnowledgePreamble(output.pages, {
18961
+ buildPagesPreamble(output.pages, {
18904
18962
  reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18905
18963
  extra: this.cfg.toolGuideExtra
18906
18964
  })
@@ -31547,7 +31605,7 @@ function createRuntime(core) {
31547
31605
  ...surveyAgentHook,
31548
31606
  tool: tools,
31549
31607
  // Each user turn: recall on the prompt, then add this turn's injection (recalled memories +
31550
- // attribution/user-feedback framing, plus the knowledge preamble on turn 1 and the roster
31608
+ // attribution/user-feedback framing, plus the pages preamble on turn 1 and the roster
31551
31609
  // refresh on cadence) to the user message as a synthetic text part. The host saves the parts
31552
31610
  // this hook leaves behind, so the block stays in the turn it was made for and every later
31553
31611
  // request repeats it byte for byte. It used to be pushed into the system prompt through