@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/dsh.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 = (file2) => {
27
+ try {
28
+ if (!statSync(file2).isFile()) return false;
29
+ if (platform !== "win32") accessSync(file2, 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 name2 of names) {
40
+ const file2 = join(dir, name2);
41
+ if (runnable(file2)) return resolve(file2);
42
+ }
43
+ }
44
+ return void 0;
45
+ }
46
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
47
+ function semverGte(version3, 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 = version3 ? parts(version3) : 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(file2, text) {
66
127
  mkdirSync(dirname2(file2), { recursive: true, mode: 448 });
67
128
  try {
68
- if (statSync(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
129
+ if (statSync2(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
69
130
  } catch {
70
131
  }
71
132
  appendFileSync(file2, 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 config2 = readTextOrNull(join4(commonDir, "config"));
233
+ const config2 = readTextOrNull(join5(commonDir, "config"));
173
234
  return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
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(map2, directory) {
@@ -397,7 +462,7 @@ function deriveBankIdOrSkip(config2, 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 = (file2) => {
668
- try {
669
- if (!statSync2(file2).isFile()) return false;
670
- if (platform !== "win32") accessSync(file2, 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 name2 of names) {
681
- const file2 = join6(dir, name2);
682
- if (runnable(file2)) return resolve2(file2);
683
- }
684
- }
685
- return void 0;
686
- }
687
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
688
- function semverGte(version3, 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 = version3 ? parts(version3) : 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} ${url2} -> ${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} ${url2.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(name2) {
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() === name2.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: name2 });
1521
- return (await r.json()).id;
1540
+ const r = await this.pagesReq("POST", "/folders", { name: name2 });
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";
@@ -17357,7 +17382,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17357
17382
  const mcpConfig = JSON.stringify({
17358
17383
  mcpServers: {
17359
17384
  hindsight: {
17360
- command: "node",
17385
+ command: nodeBinary(),
17361
17386
  args: [opts.mcpServerPath],
17362
17387
  // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
17363
17388
  // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
@@ -17398,7 +17423,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17398
17423
  "--sandbox",
17399
17424
  "read-only",
17400
17425
  "-c",
17401
- `mcp_servers.hindsight.command="node"`,
17426
+ `mcp_servers.hindsight.command=${tomlValue(nodeBinary())}`,
17402
17427
  "-c",
17403
17428
  `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17404
17429
  "-c",
@@ -17485,7 +17510,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17485
17510
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17486
17511
  return await new Promise((resolve4) => {
17487
17512
  try {
17488
- const child = spawnFn("node", [supervisorPath], {
17513
+ const child = spawnFn(nodeBinary(), [supervisorPath], {
17489
17514
  cwd: repoDir,
17490
17515
  detached: true,
17491
17516
  stdio: "ignore",
@@ -17583,11 +17608,11 @@ async function syncStatus(client, bank, repoDir) {
17583
17608
  activeOps,
17584
17609
  // Older Hindsight servers have no page surface. They are still fully usable for the
17585
17610
  // legacy bank/retain pipeline, so page absence must not make syncStatus permanently false.
17586
- synced: gitlogPresent && (client.knowledgePagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17611
+ synced: gitlogPresent && (client.pagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17587
17612
  };
17588
17613
  }
17589
17614
 
17590
- // src/core/knowledge-tools.ts
17615
+ // src/core/page-tools.ts
17591
17616
  var READ_ONLY_ANNOTATIONS = {
17592
17617
  readOnlyHint: true,
17593
17618
  destructiveHint: false,
@@ -17617,13 +17642,13 @@ function guarded(fn) {
17617
17642
  }
17618
17643
  };
17619
17644
  }
17620
- function buildKnowledgeTools(client, bankId, opts = {}) {
17645
+ function buildPageTools(client, bankId, opts = {}) {
17621
17646
  const extra = opts.toolGuideExtra?.trim();
17622
17647
  const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17623
17648
  return [
17624
17649
  {
17625
17650
  name: "hindsight_sync_status",
17626
- 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.",
17651
+ 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.",
17627
17652
  inputSchema: {},
17628
17653
  annotations: READ_ONLY_ANNOTATIONS,
17629
17654
  handler: async () => {
@@ -17678,13 +17703,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17678
17703
  }
17679
17704
  },
17680
17705
  {
17681
- name: "hindsight_search_knowledge_pages",
17682
- 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,
17706
+ name: "hindsight_search_pages",
17707
+ 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,
17683
17708
  inputSchema: { query: external_exports.string().describe("what to look for") },
17684
17709
  annotations: READ_ONLY_ANNOTATIONS,
17685
17710
  handler: async (args) => {
17686
17711
  try {
17687
- const hits = await client.searchKnowledgePages(args.query);
17712
+ const hits = await client.searchPages(args.query);
17688
17713
  return ok({
17689
17714
  pages: hits.map((h) => ({
17690
17715
  page: h.name,
@@ -17702,22 +17727,22 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17702
17727
  }
17703
17728
  },
17704
17729
  {
17705
- name: "hindsight_list_knowledge_pages",
17706
- 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.",
17730
+ name: "hindsight_list_pages",
17731
+ 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.",
17707
17732
  inputSchema: {},
17708
17733
  annotations: READ_ONLY_ANNOTATIONS,
17709
17734
  handler: guarded(async () => client.listPages())
17710
17735
  },
17711
17736
  {
17712
- name: "hindsight_read_knowledge_page",
17713
- 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.",
17737
+ name: "hindsight_read_page",
17738
+ 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.",
17714
17739
  inputSchema: { page_id: external_exports.string() },
17715
17740
  annotations: READ_ONLY_ANNOTATIONS,
17716
17741
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
17717
17742
  },
17718
17743
  {
17719
17744
  name: "hindsight_reflect",
17720
- 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>".`,
17745
+ 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>".`,
17721
17746
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
17722
17747
  annotations: READ_ONLY_ANNOTATIONS,
17723
17748
  handler: guarded(
@@ -17729,7 +17754,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17729
17754
  },
17730
17755
  {
17731
17756
  name: "hindsight_capture_initiative",
17732
- 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.",
17757
+ 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.",
17733
17758
  inputSchema: {
17734
17759
  title: external_exports.string(),
17735
17760
  summary: external_exports.string(),
@@ -18259,10 +18284,15 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18259
18284
  const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
18260
18285
  const plugins = registry2?.plugins;
18261
18286
  if (!plugins || typeof plugins !== "object") return void 0;
18262
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
18287
+ const enabledMaps = [
18288
+ join16(cwd, ".claude", "settings.local.json"),
18289
+ join16(cwd, ".claude", "settings.json"),
18290
+ join16(claudeDir, "settings.json")
18291
+ ].map((path) => readJson(path)?.enabledPlugins);
18263
18292
  for (const [key, raw] of Object.entries(plugins)) {
18264
18293
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
18265
- if (enabled && enabled[key] === false) continue;
18294
+ const setting = enabledMaps.find((m) => m && typeof m[key] === "boolean")?.[key];
18295
+ if (setting === false) continue;
18266
18296
  const installs = Array.isArray(raw) ? raw : [raw];
18267
18297
  const active = installs.some((i) => {
18268
18298
  if (!i || typeof i !== "object") return false;
@@ -18360,6 +18390,7 @@ async function buildSessionStartContext(args) {
18360
18390
  let cold;
18361
18391
  let gitDocIds;
18362
18392
  let bankEmpty = false;
18393
+ let deepening = false;
18363
18394
  const harness = args.harness ?? "claude-code";
18364
18395
  const hasGit = args.hasGit ?? hasGitHistory;
18365
18396
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -18413,6 +18444,7 @@ async function buildSessionStartContext(args) {
18413
18444
  }
18414
18445
  if (docIds !== void 0) {
18415
18446
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18447
+ deepening = true;
18416
18448
  if (cold) {
18417
18449
  if (cfg.codebaseSurvey !== false) {
18418
18450
  const sha = resolveHeadSha(cwd);
@@ -18462,15 +18494,23 @@ async function buildSessionStartContext(args) {
18462
18494
  }
18463
18495
  }
18464
18496
  }
18497
+ if (!deepening) {
18498
+ await client.configureBankSettings?.({
18499
+ manage: cfg.manageBankConfig,
18500
+ extractionMode: cfg.retainExtractionMode,
18501
+ defaults: cfg.defaultBankConfig
18502
+ }).catch(() => {
18503
+ });
18504
+ }
18465
18505
  let pages = [];
18466
18506
  try {
18467
18507
  pages = parsePageList(await client.listPages());
18468
18508
  } catch {
18469
- if (client.knowledgePagesSupported === false) {
18470
- diag(harness, "knowledge_pages_unavailable", { bank: bankId });
18509
+ if (client.pagesSupported === false) {
18510
+ diag(harness, "pages_unavailable", { bank: bankId });
18471
18511
  }
18472
18512
  }
18473
- const additionalContext = buildKnowledgePreamble(pages, {
18513
+ const additionalContext = buildPagesPreamble(pages, {
18474
18514
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18475
18515
  extra: cfg.toolGuideExtra
18476
18516
  });
@@ -18500,6 +18540,63 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18500
18540
  // src/core/hook.ts
18501
18541
  import { existsSync as existsSync8 } from "fs";
18502
18542
 
18543
+ // src/core/transcript-util.ts
18544
+ var TOOL_TEXT_CAP = 2e3;
18545
+ 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;
18546
+ function stripInjectedMemory(s) {
18547
+ return s.replace(MEMORY_TAG_RE, "");
18548
+ }
18549
+ function truncate(s, max = TOOL_TEXT_CAP) {
18550
+ return s.length > max ? `${s.slice(0, max)}\u2026 (truncated)` : s;
18551
+ }
18552
+ var TARGET_KEYS = [
18553
+ "file_path",
18554
+ "path",
18555
+ "notebook_path",
18556
+ "command",
18557
+ "pattern",
18558
+ "query",
18559
+ "url",
18560
+ "name",
18561
+ "id"
18562
+ ];
18563
+ var ACTION_TARGET_CAP = 100;
18564
+ function actionLine(tool, input) {
18565
+ let target = "";
18566
+ if (input && typeof input === "object") {
18567
+ const rec = input;
18568
+ for (const k of TARGET_KEYS) {
18569
+ const v = rec[k];
18570
+ if (typeof v === "string" && v.trim()) {
18571
+ target = v.trim().split("\n")[0];
18572
+ break;
18573
+ }
18574
+ }
18575
+ } else if (typeof input === "string") {
18576
+ target = input.trim().split("\n")[0];
18577
+ }
18578
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18579
+ const line = target ? `${tool} ${target}` : tool;
18580
+ const note = memoryNoteText(input);
18581
+ return note ? `${line}
18582
+ ${truncate(note, MEMORY_NOTE_CAP)}` : line;
18583
+ }
18584
+ var MEMORY_NOTE_CAP = 8e3;
18585
+ var MEMORY_NOTE_PATH_RE = /(^|[\\/])(memory|memories)[\\/]|(^|[\\/])MEMORY\.md$/i;
18586
+ var MEMORY_SHELL_WRITE_RE = /[\\/](memory|memories)([\\/\s"']|$)|MEMORY\.md/i;
18587
+ var SHELL_WRITE_RE = /(^|[^0-9&>])>>?(?!&)|\btee\b/;
18588
+ function memoryNoteText(input) {
18589
+ if (!input || typeof input !== "object") return "";
18590
+ const rec = input;
18591
+ const cmd = rec.command;
18592
+ if (typeof cmd === "string")
18593
+ return MEMORY_SHELL_WRITE_RE.test(cmd) && SHELL_WRITE_RE.test(cmd) ? cmd.trim() : "";
18594
+ const path = rec.file_path ?? rec.path;
18595
+ if (typeof path !== "string" || !MEMORY_NOTE_PATH_RE.test(path)) return "";
18596
+ const text = rec.content ?? rec.new_string;
18597
+ return typeof text === "string" ? text.trim() : "";
18598
+ }
18599
+
18503
18600
  // src/core/inject.ts
18504
18601
  function buildReflectQuery(prompt) {
18505
18602
  return `A developer is starting a coding session in this repository with this goal:
@@ -18516,8 +18613,8 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
18516
18613
  - 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.
18517
18614
  - If the bank holds nothing that bears on the goal, say so in one line.`;
18518
18615
  }
18519
- 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.)";
18520
- var PAGE_INJECT_LEAD = "(These knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18616
+ 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.)";
18617
+ var PAGE_INJECT_LEAD = "(These pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
18521
18618
  function formatPageFallback(hits, lead = PAGE_FALLBACK_LEAD) {
18522
18619
  return `${lead}
18523
18620
  ` + hits.map((h) => {
@@ -18548,43 +18645,6 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18548
18645
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18549
18646
  import { tmpdir as tmpdir4 } from "os";
18550
18647
  import { dirname as dirname10, join as join18 } from "path";
18551
-
18552
- // src/core/transcript-util.ts
18553
- 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;
18554
- function stripInjectedMemory(s) {
18555
- return s.replace(MEMORY_TAG_RE, "");
18556
- }
18557
- var TARGET_KEYS = [
18558
- "file_path",
18559
- "path",
18560
- "notebook_path",
18561
- "command",
18562
- "pattern",
18563
- "query",
18564
- "url",
18565
- "name",
18566
- "id"
18567
- ];
18568
- var ACTION_TARGET_CAP = 100;
18569
- function actionLine(tool, input) {
18570
- let target = "";
18571
- if (input && typeof input === "object") {
18572
- const rec = input;
18573
- for (const k of TARGET_KEYS) {
18574
- const v = rec[k];
18575
- if (typeof v === "string" && v.trim()) {
18576
- target = v.trim().split("\n")[0];
18577
- break;
18578
- }
18579
- }
18580
- } else if (typeof input === "string") {
18581
- target = input.trim().split("\n")[0];
18582
- }
18583
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18584
- return target ? `${tool} ${target}` : tool;
18585
- }
18586
-
18587
- // src/core/turn-journal.ts
18588
18648
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18589
18649
 
18590
18650
  // src/core/hook.ts
@@ -18610,7 +18670,7 @@ function boundRecallQuery(prompt) {
18610
18670
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18611
18671
  const t0 = Date.now();
18612
18672
  try {
18613
- const hits = await client.searchKnowledgePages(prompt.slice(0, 500), { timeoutMs });
18673
+ const hits = await client.searchPages(prompt.slice(0, 500), { timeoutMs });
18614
18674
  diag(harness, event, { ms: Date.now() - t0, count: hits.length });
18615
18675
  return hits.length ? formatPageFallback(hits, lead) : null;
18616
18676
  } catch (e) {
@@ -18724,14 +18784,10 @@ async function buildHookOutput(args) {
18724
18784
  pages = parsePageList(await client.listPages());
18725
18785
  diag(harness, "pages_ok", { ms: Date.now() - t0, count: pages.length });
18726
18786
  } catch (e) {
18727
- diag(
18728
- harness,
18729
- client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
18730
- {
18731
- ms: Date.now() - t0,
18732
- error: describeError(e)
18733
- }
18734
- );
18787
+ diag(harness, client.pagesSupported === false ? "pages_unavailable" : "pages_failed", {
18788
+ ms: Date.now() - t0,
18789
+ error: describeError(e)
18790
+ });
18735
18791
  }
18736
18792
  }
18737
18793
  writeSessionCache(cacheFile, {
@@ -18742,7 +18798,7 @@ async function buildHookOutput(args) {
18742
18798
  });
18743
18799
  const blocks = [];
18744
18800
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18745
- if (cadence > 0 && turns % cadence === 0) {
18801
+ if (cadence > 0 && turns % cadence === 0 && !(turns === 1 && args.preambleOnFirstTurn)) {
18746
18802
  blocks.push(
18747
18803
  buildRosterRefresh(pages, {
18748
18804
  reflectOnNewGoals: cfg.autoInject !== "reflect",
@@ -18810,9 +18866,9 @@ var RuntimeCore = class {
18810
18866
  setTranscriptSource(fetch2) {
18811
18867
  this.fetchTranscript = fetch2;
18812
18868
  }
18813
- /** The hindsight_* knowledge + recall tools, bound to this bank, for the harness to register natively. */
18869
+ /** The hindsight_* page + recall tools, bound to this bank, for the harness to register natively. */
18814
18870
  toolSpecs() {
18815
- return buildKnowledgeTools(this.client, this.bankId, {
18871
+ return buildPageTools(this.client, this.bankId, {
18816
18872
  repoDir: this.projectDir,
18817
18873
  harness: this.harness,
18818
18874
  pageTrigger: buildPageTrigger(this.cfg),
@@ -18834,7 +18890,7 @@ var RuntimeCore = class {
18834
18890
  * git-log seed + codebase survey. Reuses the exact hook-harness logic
18835
18891
  * (`buildSessionStartContext`) so opencode seeds identically. Never throws.
18836
18892
  *
18837
- * It deliberately does NOT keep that call's knowledge preamble. This runs once per PROCESS and
18893
+ * It deliberately does NOT keep that call's pages preamble. This runs once per PROCESS and
18838
18894
  * these hosts outlive every session, so a roster captured here is stale for every session but
18839
18895
  * the first — `onPrompt` builds its own from the session's live page list (#4607).
18840
18896
  */
@@ -18865,10 +18921,11 @@ var RuntimeCore = class {
18865
18921
  * intentionally replaces the old in-memory reflect/page state, keeping lifecycle behavior
18866
18922
  * identical across hosts while this adapter retains only delivery-specific state.
18867
18923
  */
18868
- async onPrompt(sessionId, prompt) {
18924
+ async onPrompt(sessionId, rawPrompt) {
18869
18925
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18870
18926
  if (!sessionId) return;
18871
- if (!prompt.trim()) {
18927
+ const prompt = stripInjectedMemory(rawPrompt).trim();
18928
+ if (!prompt) {
18872
18929
  this.injection.delete(sessionId);
18873
18930
  return;
18874
18931
  }
@@ -18884,12 +18941,13 @@ var RuntimeCore = class {
18884
18941
  prompt,
18885
18942
  cfg: this.cfg,
18886
18943
  client: this.client,
18887
- cacheFile
18944
+ cacheFile,
18945
+ preambleOnFirstTurn: true
18888
18946
  });
18889
18947
  const blocks = [];
18890
18948
  if (turns === 1) {
18891
18949
  blocks.push(
18892
- buildKnowledgePreamble(output.pages, {
18950
+ buildPagesPreamble(output.pages, {
18893
18951
  reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18894
18952
  extra: this.cfg.toolGuideExtra
18895
18953
  })