@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/pi.js CHANGED
@@ -14525,16 +14525,77 @@ import { join as join7 } from "path";
14525
14525
 
14526
14526
  // src/core/seed.ts
14527
14527
  import { spawn as realSpawn } from "child_process";
14528
- import { dirname, join } from "path";
14528
+ import { dirname, join as join2 } from "path";
14529
14529
  import { fileURLToPath } from "url";
14530
+
14531
+ // src/core/util.ts
14532
+ import { accessSync, constants, statSync } from "fs";
14533
+ import { delimiter, extname, isAbsolute, join, resolve } from "path";
14534
+ function binOnPath(bin, opts = {}) {
14535
+ const platform = opts.platform ?? process.platform;
14536
+ const env = opts.env ?? process.env;
14537
+ const runnable = (file2) => {
14538
+ try {
14539
+ if (!statSync(file2).isFile()) return false;
14540
+ if (platform !== "win32") accessSync(file2, constants.X_OK);
14541
+ return true;
14542
+ } catch {
14543
+ return false;
14544
+ }
14545
+ };
14546
+ if (isAbsolute(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve(bin) : void 0;
14547
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
14548
+ for (const dir of (env.PATH || "").split(delimiter)) {
14549
+ if (!dir) continue;
14550
+ for (const name of names) {
14551
+ const file2 = join(dir, name);
14552
+ if (runnable(file2)) return resolve(file2);
14553
+ }
14554
+ }
14555
+ return void 0;
14556
+ }
14557
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14558
+ function semverGte(version3, min) {
14559
+ const parts = (v) => {
14560
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
14561
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
14562
+ };
14563
+ const a = version3 ? parts(version3) : void 0;
14564
+ const b = parts(min);
14565
+ if (!a || !b) return false;
14566
+ for (let i = 0; i < 3; i++) {
14567
+ if (a[i] !== b[i]) return a[i] > b[i];
14568
+ }
14569
+ return true;
14570
+ }
14571
+ async function pool(items, n, fn, onError, onProgress) {
14572
+ let i = 0, done = 0;
14573
+ async function worker() {
14574
+ while (i < items.length) {
14575
+ const idx = i++;
14576
+ try {
14577
+ await fn(items[idx], idx);
14578
+ } catch (e) {
14579
+ onError?.(idx, e);
14580
+ }
14581
+ onProgress?.(++done, items.length);
14582
+ }
14583
+ }
14584
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
14585
+ }
14586
+ function nodeBinary() {
14587
+ return process.versions.bun || process.versions.electron ? "node" : process.execPath;
14588
+ }
14589
+
14590
+ // src/core/seed.ts
14530
14591
  var DEFAULT_SEED_LIMIT = 300;
14531
14592
  function startBackgroundSeed(repoDir, opts = {}) {
14532
14593
  try {
14533
14594
  const spawnFn = opts.spawn ?? realSpawn;
14534
- const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
14595
+ const enginePath = opts.enginePath ?? join2(dirname(fileURLToPath(import.meta.url)), "deepen.js");
14535
14596
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
14536
14597
  const child = spawnFn(
14537
- "node",
14598
+ nodeBinary(),
14538
14599
  [
14539
14600
  enginePath,
14540
14601
  "--repo",
@@ -14559,24 +14620,24 @@ function startBackgroundSeed(repoDir, opts = {}) {
14559
14620
  // src/core/bank.ts
14560
14621
  import { existsSync } from "fs";
14561
14622
  import { homedir as homedir2 } from "os";
14562
- import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
14623
+ import { basename, dirname as dirname4, join as join6, normalize, sep } from "path";
14563
14624
 
14564
14625
  // src/core/diag.ts
14565
14626
  import { readFileSync } from "fs";
14566
- import { join as join3 } from "path";
14627
+ import { join as join4 } from "path";
14567
14628
 
14568
14629
  // src/core/log.ts
14569
- import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
14630
+ import { appendFileSync, mkdirSync, renameSync, statSync as statSync2 } from "fs";
14570
14631
  import { homedir } from "os";
14571
- import { dirname as dirname2, join as join2 } from "path";
14632
+ import { dirname as dirname2, join as join3 } from "path";
14572
14633
  function logsDir() {
14573
- return join2(homedir(), ".hindsight", "coding-agents-logs");
14634
+ return join3(homedir(), ".hindsight", "coding-agents-logs");
14574
14635
  }
14575
14636
  var LOG_MAX_BYTES = 10 * 1024 * 1024;
14576
14637
  function appendLogLine(file2, text) {
14577
14638
  mkdirSync(dirname2(file2), { recursive: true, mode: 448 });
14578
14639
  try {
14579
- if (statSync(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
14640
+ if (statSync2(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
14580
14641
  } catch {
14581
14642
  }
14582
14643
  appendFileSync(file2, text, { mode: 384 });
@@ -14589,7 +14650,7 @@ function setLogLevel(level) {
14589
14650
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14590
14651
  }
14591
14652
  function logFilePath() {
14592
- return process.env.HINDSIGHT_LOG_FILE || join2(logsDir(), "plugin.log");
14653
+ return process.env.HINDSIGHT_LOG_FILE || join3(logsDir(), "plugin.log");
14593
14654
  }
14594
14655
  function write(level, scope, msg, extra) {
14595
14656
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -14624,7 +14685,7 @@ function describeError(value, maxChars = 200) {
14624
14685
 
14625
14686
  // src/core/diag.ts
14626
14687
  function diagFilePath() {
14627
- return process.env.HINDSIGHT_DIAG_FILE || join3(logsDir(), "diag.jsonl");
14688
+ return process.env.HINDSIGHT_DIAG_FILE || join4(logsDir(), "diag.jsonl");
14628
14689
  }
14629
14690
  function diag(harness, event, extra = {}) {
14630
14691
  log.debug(harness, `diag:${event}`, extra);
@@ -14639,7 +14700,7 @@ function diag(harness, event, extra = {}) {
14639
14700
 
14640
14701
  // src/core/git-layout.ts
14641
14702
  import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
14642
- import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
14703
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
14643
14704
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
14644
14705
  var ATTEMPTS = 3;
14645
14706
  var BACKOFF_MS = 20;
@@ -14672,19 +14733,19 @@ function gitDirFromPointer(text, holder) {
14672
14733
  const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
14673
14734
  if (!match) return null;
14674
14735
  const target = match[1];
14675
- return isAbsolute(target) ? target : resolve(holder, target);
14736
+ return isAbsolute2(target) ? target : resolve2(holder, target);
14676
14737
  }
14677
14738
  function commonDirOf(gitDir) {
14678
- const pointer = entryKind(join4(gitDir, "commondir")) === "file" ? readTextOrNull(join4(gitDir, "commondir"))?.trim() : null;
14739
+ const pointer = entryKind(join5(gitDir, "commondir")) === "file" ? readTextOrNull(join5(gitDir, "commondir"))?.trim() : null;
14679
14740
  if (!pointer) return gitDir;
14680
- return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
14741
+ return isAbsolute2(pointer) ? pointer : resolve2(gitDir, pointer);
14681
14742
  }
14682
14743
  function isBare(commonDir) {
14683
- const config2 = readTextOrNull(join4(commonDir, "config"));
14744
+ const config2 = readTextOrNull(join5(commonDir, "config"));
14684
14745
  return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
14685
14746
  }
14686
14747
  function looksLikeBareRepository(directory) {
14687
- return entryKind(join4(directory, "HEAD")) === "file" && entryKind(join4(directory, "objects")) === "dir" && entryKind(join4(directory, "refs")) === "dir";
14748
+ return entryKind(join5(directory, "HEAD")) === "file" && entryKind(join5(directory, "objects")) === "dir" && entryKind(join5(directory, "refs")) === "dir";
14688
14749
  }
14689
14750
  function canonical(path) {
14690
14751
  try {
@@ -14699,9 +14760,9 @@ function resolved(commonDir) {
14699
14760
  return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
14700
14761
  }
14701
14762
  function probeOnce(directory) {
14702
- let current2 = resolve(directory);
14763
+ let current2 = resolve2(directory);
14703
14764
  for (; ; ) {
14704
- const dotGit = join4(current2, ".git");
14765
+ const dotGit = join5(current2, ".git");
14705
14766
  const kind = entryKind(dotGit);
14706
14767
  if (kind === "dir") {
14707
14768
  const layout = resolved(commonDirOf(dotGit));
@@ -14815,10 +14876,14 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
14815
14876
  return dirName(sessionRoot || directory);
14816
14877
  }
14817
14878
  function configuredDir(dir) {
14818
- const expanded = dir === "~" || dir.startsWith("~/") ? join5(homedir2(), dir.slice(1)) : dir;
14879
+ const expanded = dir === "~" || dir.startsWith("~/") ? join6(homedir2(), dir.slice(1)) : dir;
14819
14880
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
14820
14881
  }
14821
- function isWithin(directory, configured) {
14882
+ function isWithin(directory, configured, platform = process.platform) {
14883
+ if (platform === "win32") {
14884
+ directory = directory.toLowerCase();
14885
+ configured = configured.toLowerCase();
14886
+ }
14822
14887
  return directory === configured || directory.startsWith(configured + sep);
14823
14888
  }
14824
14889
  function mapLookup(map2, directory) {
@@ -14908,7 +14973,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
14908
14973
  import { createHash } from "crypto";
14909
14974
  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.";
14910
14975
  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.";
14911
- var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
14976
+ 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.`;
14912
14977
  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.";
14913
14978
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
14914
14979
  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.";
@@ -14951,14 +15016,14 @@ var RETAIN_STRATEGIES = {
14951
15016
  retain_chunk_size: 12e3
14952
15017
  }
14953
15018
  };
14954
- var KNOWLEDGE_LABELS = {
15019
+ var PAGE_LABELS = {
14955
15020
  key: "knowledge",
14956
15021
  type: "multi-values",
14957
15022
  // 0, 1, or several — empty is normal
14958
15023
  optional: true,
14959
15024
  tag: true,
14960
15025
  // emits knowledge:<value> onto the fact's tags
14961
- 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.",
15026
+ 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.",
14962
15027
  values: [
14963
15028
  {
14964
15029
  value: "feature-work",
@@ -15115,7 +15180,7 @@ var CODING_BANK_TEMPLATE = {
15115
15180
  retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
15116
15181
  retain_default_strategy: "git",
15117
15182
  retain_strategies: RETAIN_STRATEGIES,
15118
- entity_labels: [KNOWLEDGE_LABELS],
15183
+ entity_labels: [PAGE_LABELS],
15119
15184
  entities_allow_free_form: true
15120
15185
  }
15121
15186
  };
@@ -15167,63 +15232,7 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
15167
15232
  }
15168
15233
 
15169
15234
  // package.json
15170
- var version2 = "0.8.6";
15171
-
15172
- // src/core/util.ts
15173
- import { accessSync, constants, statSync as statSync2 } from "fs";
15174
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
15175
- function binOnPath(bin, opts = {}) {
15176
- const platform = opts.platform ?? process.platform;
15177
- const env = opts.env ?? process.env;
15178
- const runnable = (file2) => {
15179
- try {
15180
- if (!statSync2(file2).isFile()) return false;
15181
- if (platform !== "win32") accessSync(file2, constants.X_OK);
15182
- return true;
15183
- } catch {
15184
- return false;
15185
- }
15186
- };
15187
- if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
15188
- const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
15189
- for (const dir of (env.PATH || "").split(delimiter)) {
15190
- if (!dir) continue;
15191
- for (const name of names) {
15192
- const file2 = join6(dir, name);
15193
- if (runnable(file2)) return resolve2(file2);
15194
- }
15195
- }
15196
- return void 0;
15197
- }
15198
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15199
- function semverGte(version3, min) {
15200
- const parts = (v) => {
15201
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
15202
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
15203
- };
15204
- const a = version3 ? parts(version3) : void 0;
15205
- const b = parts(min);
15206
- if (!a || !b) return false;
15207
- for (let i = 0; i < 3; i++) {
15208
- if (a[i] !== b[i]) return a[i] > b[i];
15209
- }
15210
- return true;
15211
- }
15212
- async function pool(items, n, fn, onError, onProgress) {
15213
- let i = 0, done = 0;
15214
- async function worker() {
15215
- while (i < items.length) {
15216
- const idx = i++;
15217
- try {
15218
- await fn(items[idx], idx);
15219
- } catch (e) {
15220
- onError?.(idx, e);
15221
- }
15222
- onProgress?.(++done, items.length);
15223
- }
15224
- }
15225
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
15226
- }
15235
+ var version2 = "0.8.8";
15227
15236
 
15228
15237
  // src/core/hindsight.ts
15229
15238
  var USER_AGENT = `hindsight-coding-agents/${version2}`;
@@ -15250,11 +15259,11 @@ function retryAfterMs(header) {
15250
15259
  const at = Date.parse(header);
15251
15260
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
15252
15261
  }
15253
- var KnowledgePagesUnavailableError = class extends Error {
15254
- code = "knowledge_pages_unavailable";
15262
+ var PagesUnavailableError = class extends Error {
15263
+ code = "pages_unavailable";
15255
15264
  constructor() {
15256
- super("Hindsight server does not support knowledge pages");
15257
- this.name = "KnowledgePagesUnavailableError";
15265
+ super("Hindsight server does not support pages");
15266
+ this.name = "PagesUnavailableError";
15258
15267
  }
15259
15268
  };
15260
15269
  async function isEndpointMissing(r) {
@@ -15265,6 +15274,10 @@ async function isEndpointMissing(r) {
15265
15274
  return false;
15266
15275
  }
15267
15276
  }
15277
+ function pagesPath(sub, legacy = false) {
15278
+ if (!legacy) return `/pages${sub}`;
15279
+ return /^\/(tree|folders|search|export|nodes)\b/.test(sub) ? `/knowledge-base${sub}` : `/knowledge-base/pages${sub}`;
15280
+ }
15268
15281
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
15269
15282
  var ReflectError = class extends Error {
15270
15283
  constructor(message, status, timedOut, options) {
@@ -15333,7 +15346,7 @@ var HindsightClient = class {
15333
15346
  opIds = [];
15334
15347
  // async operation ids collected by retain(), for drain()
15335
15348
  /** Tri-state capability probe: unknown until the first page request, then cached. */
15336
- knowledgePagesSupported;
15349
+ pagesSupported;
15337
15350
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
15338
15351
  idempotentRetain;
15339
15352
  log;
@@ -15431,7 +15444,9 @@ var HindsightClient = class {
15431
15444
  }
15432
15445
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
15433
15446
  throw new Error(
15434
- `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
15447
+ // Query dropped: an encoded search query filled the 200-char error cap and pushed the
15448
+ // status and the server's reason out of the tool error (#6341).
15449
+ `${method} ${url2.split("?")[0]} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
15435
15450
  );
15436
15451
  return r;
15437
15452
  }
@@ -15562,7 +15577,7 @@ var HindsightClient = class {
15562
15577
  return (j.total ?? j.items?.length ?? 0) > 0;
15563
15578
  }
15564
15579
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
15565
- * entity labels), then seed knowledge pages when the server supports them. Both halves are
15580
+ * entity labels), then seed pages when the server supports them. Both halves are
15566
15581
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
15567
15582
  * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
15568
15583
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
@@ -15577,6 +15592,15 @@ var HindsightClient = class {
15577
15592
  await this.req("DELETE", this.bankUrl());
15578
15593
  this.log(`[bank] reset ${this.bank}`);
15579
15594
  }
15595
+ await this.configureBankSettings(opts);
15596
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
15597
+ }
15598
+ /** The config half of `configureBank` (missions, retain strategies, entity labels), without
15599
+ * seeding pages. Session start calls it directly when the deepen engine — the usual caller of
15600
+ * `configureBank` — will not run (`autoSeed: false`, or a directory with no git history):
15601
+ * without it such a bank never got the `conversation` strategy, and every session write-back
15602
+ * was extracted with the server's generic rules instead of the plugin's mission. */
15603
+ async configureBankSettings(opts = {}) {
15580
15604
  if (opts.manage === false) {
15581
15605
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
15582
15606
  } else {
@@ -15592,7 +15616,6 @@ var HindsightClient = class {
15592
15616
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
15593
15617
  }
15594
15618
  }
15595
- await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
15596
15619
  }
15597
15620
  /**
15598
15621
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -15744,29 +15767,45 @@ var HindsightClient = class {
15744
15767
  const j = await r.json();
15745
15768
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
15746
15769
  }
15770
+ /** Set once a server answered on the deprecated `/knowledge-base/...` paths: one from before the
15771
+ * page routes moved to `/pages/...`. Remove in 2.x. */
15772
+ legacyPagesPaths = false;
15747
15773
  /**
15748
- * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
15749
- * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
15750
- * expected answer before the bank's first retain — so it must never cache a negative (#4607).
15774
+ * Request a page endpoint by its `/pages` sub-path (`""`, `/tree`, `/<id>`, `/nodes/<id>`, …).
15775
+ *
15776
+ * Returns `null` — and latches `pagesSupported = false` — iff the endpoint is really absent: an
15777
+ * unrouted 404 on the `/pages` path AND on its pre-rename `/knowledge-base` twin, which a server
15778
+ * older than the rename still serves (tried once, then remembered). A bank-not-found 404 is NOT
15779
+ * a capability verdict — it is the expected answer before the bank's first retain — so it is
15780
+ * returned as-is and never caches a negative (#4607). A 404's body may already be consumed.
15751
15781
  *
15752
15782
  * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
15753
15783
  * the 405/501 this used to check for never reach a caller in the first place.
15754
15784
  */
15755
- async pagesUnsupported(r) {
15756
- if (r.status !== 404 || !await isEndpointMissing(r)) return false;
15757
- this.knowledgePagesSupported = false;
15758
- return true;
15785
+ async pagesReq(method, sub, body, tolerate = [], timeoutMs) {
15786
+ const send = (legacy) => this.req(method, this.bankUrl(pagesPath(sub, legacy)), body, tolerate, timeoutMs);
15787
+ let r = await send(this.legacyPagesPaths);
15788
+ if (r.status !== 404 || !await isEndpointMissing(r)) return r;
15789
+ if (!this.legacyPagesPaths) {
15790
+ r = await send(true);
15791
+ if (r.status !== 404 || !await isEndpointMissing(r)) {
15792
+ this.legacyPagesPaths = true;
15793
+ return r;
15794
+ }
15795
+ }
15796
+ this.pagesSupported = false;
15797
+ return null;
15759
15798
  }
15760
15799
  /**
15761
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15800
+ * The bank's page tree (folders + pages, nested). The tree carries names, source
15762
15801
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
15763
15802
  */
15764
15803
  async tree() {
15765
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15766
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
15767
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
15804
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
15805
+ const r = await this.pagesReq("GET", "/tree");
15806
+ if (!r) throw new PagesUnavailableError();
15768
15807
  if (r.status === 404) return [];
15769
- this.knowledgePagesSupported = true;
15808
+ this.pagesSupported = true;
15770
15809
  try {
15771
15810
  return (await r.json()).roots ?? [];
15772
15811
  } catch {
@@ -15774,13 +15813,13 @@ var HindsightClient = class {
15774
15813
  }
15775
15814
  }
15776
15815
  /**
15777
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
15816
+ * List pages (ids + names only — no synthesized content), flattened out of the tree
15778
15817
  * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
15779
15818
  * to read, and a caller enumerating pages wants leaves, not structure.
15780
15819
  *
15781
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
15782
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
15783
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
15820
+ * NOTE the ids are page node ids (`kp-…`), NOT the backing mental-model ids. Every
15821
+ * page read/update in this client goes through the same page ids, so a page id from
15822
+ * here, from `searchPages`, or from a `[[page:<id>]]` link all resolve identically.
15784
15823
  */
15785
15824
  async listPages() {
15786
15825
  const items = [];
@@ -15802,34 +15841,26 @@ var HindsightClient = class {
15802
15841
  return { items };
15803
15842
  }
15804
15843
  /**
15805
- * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
15844
+ * Read one page's synthesized content by page id, shaped by `shapePage` so
15806
15845
  * the body arrives once. The endpoint omits the internal reflect trace that built
15807
15846
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15808
15847
  * token cap.
15809
15848
  */
15810
15849
  async getPage(pageId) {
15811
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15812
- const r = await this.req(
15813
- "GET",
15814
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15815
- );
15816
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15850
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
15851
+ const r = await this.pagesReq("GET", `/${encodeURIComponent(pageId)}`);
15852
+ if (!r) throw new PagesUnavailableError();
15853
+ if (r.status === 404) throw new Error(`page not found: ${pageId}`);
15817
15854
  return shapePage(await r.json());
15818
15855
  }
15819
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15856
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's pages.
15820
15857
  * Returns page-level hits with a relevance snippet — the real search behind
15821
- * hindsight_search_knowledge_pages. */
15822
- async searchKnowledgePages(query, opts = {}) {
15823
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15858
+ * hindsight_search_pages. */
15859
+ async searchPages(query, opts = {}) {
15860
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
15824
15861
  const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
15825
- const r = await this.req(
15826
- "GET",
15827
- this.bankUrl(`/knowledge-base/search${q}`),
15828
- void 0,
15829
- [],
15830
- opts.timeoutMs
15831
- );
15832
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
15862
+ const r = await this.pagesReq("GET", `/search${q}`, void 0, [], opts.timeoutMs);
15863
+ if (!r) throw new PagesUnavailableError();
15833
15864
  if (r.status === 404) return [];
15834
15865
  const j = await r.json();
15835
15866
  return (j.results ?? []).map((x) => ({
@@ -15841,9 +15872,9 @@ var HindsightClient = class {
15841
15872
  }));
15842
15873
  }
15843
15874
  /**
15844
- * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
15875
+ * Seed the fixed page taxonomy as pages at the tree root, idempotently.
15845
15876
  *
15846
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
15877
+ * Matched by NAME, not id: `POST /pages` mints its own `kp-…` id, so a stable
15847
15878
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
15848
15879
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
15849
15880
  *
@@ -15858,8 +15889,8 @@ var HindsightClient = class {
15858
15889
  try {
15859
15890
  roots = await this.tree();
15860
15891
  } catch (e) {
15861
- if (e instanceof KnowledgePagesUnavailableError) {
15862
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
15892
+ if (e instanceof PagesUnavailableError) {
15893
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
15863
15894
  return;
15864
15895
  }
15865
15896
  throw e;
@@ -15882,11 +15913,9 @@ var HindsightClient = class {
15882
15913
  trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
15883
15914
  };
15884
15915
  if (!hit) {
15885
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
15886
- if (await this.pagesUnsupported(r)) {
15887
- this.log(
15888
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15889
- );
15916
+ const r = await this.pagesReq("POST", "", body, [409]);
15917
+ if (!r) {
15918
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
15890
15919
  return;
15891
15920
  }
15892
15921
  if (r.status === 404) {
@@ -15907,15 +15936,9 @@ var HindsightClient = class {
15907
15936
  );
15908
15937
  }
15909
15938
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
15910
- const r = await this.req(
15911
- "PATCH",
15912
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
15913
- patch
15914
- );
15915
- if (await this.pagesUnsupported(r)) {
15916
- this.log(
15917
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15918
- );
15939
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(hit.id)}`, patch);
15940
+ if (!r) {
15941
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
15919
15942
  return;
15920
15943
  }
15921
15944
  if (r.status === 404) {
@@ -15927,7 +15950,7 @@ var HindsightClient = class {
15927
15950
  }
15928
15951
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
15929
15952
  this.log(
15930
- `[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` : "")
15953
+ `[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` : "")
15931
15954
  );
15932
15955
  }
15933
15956
  /**
@@ -15961,12 +15984,8 @@ var HindsightClient = class {
15961
15984
  if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
15962
15985
  }
15963
15986
  if (!patch.trigger && !patch.source_query) continue;
15964
- const r = await this.req(
15965
- "PATCH",
15966
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
15967
- patch
15968
- );
15969
- if (r.status === 404) continue;
15987
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(page.id)}`, patch);
15988
+ if (!r || r.status === 404) continue;
15970
15989
  updated++;
15971
15990
  }
15972
15991
  return updated;
@@ -15992,7 +16011,7 @@ var HindsightClient = class {
15992
16011
  let pageId = args.relatesToPageId;
15993
16012
  if (!pageId) {
15994
16013
  const folderId = await this.ensureFolder("Initiatives");
15995
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
16014
+ const r = await this.pagesReq("POST", "", {
15996
16015
  name: args.title,
15997
16016
  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),
15998
16017
  parent_id: folderId,
@@ -16001,8 +16020,8 @@ var HindsightClient = class {
16001
16020
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
16002
16021
  });
16003
16022
  try {
16004
- const j = await r.json();
16005
- pageId = j.page_id ?? j.id;
16023
+ const j = await r?.json();
16024
+ pageId = j?.page_id ?? j?.id;
16006
16025
  } catch {
16007
16026
  }
16008
16027
  pageId ||= `initiative-${this.slugify(args.title)}`;
@@ -16020,16 +16039,17 @@ var HindsightClient = class {
16020
16039
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
16021
16040
  async ensureFolder(name) {
16022
16041
  try {
16023
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
16024
- const hit = (tree.roots || []).find(
16042
+ const r = await this.pagesReq("GET", "/tree");
16043
+ const tree = await r?.json();
16044
+ const hit = (tree?.roots || []).find(
16025
16045
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
16026
16046
  );
16027
16047
  if (hit?.id) return hit.id;
16028
16048
  } catch {
16029
16049
  }
16030
16050
  try {
16031
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
16032
- return (await r.json()).id;
16051
+ const r = await this.pagesReq("POST", "/folders", { name });
16052
+ return (await r?.json())?.id;
16033
16053
  } catch {
16034
16054
  return void 0;
16035
16055
  }
@@ -16780,13 +16800,18 @@ function onPath(bin) {
16780
16800
  return false;
16781
16801
  }
16782
16802
  }
16803
+ var DAEMON_CONFIG_ENV = "HINDSIGHT_CODING_AGENTS_DAEMON_CONFIG";
16783
16804
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
16784
16805
  try {
16785
16806
  const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
16786
- const child = spawnFn("node", [starter, "--harness", harness], {
16807
+ const child = spawnFn(nodeBinary(), [starter, "--harness", harness], {
16787
16808
  detached: true,
16788
16809
  stdio: "ignore",
16789
- windowsHide: true
16810
+ windowsHide: true,
16811
+ // The caller's config is already resolved for its directory and bank. Re-reading the file in
16812
+ // the starter lost `paths` / `banks` overrides, so a daemon enabled only there never started
16813
+ // (#6334).
16814
+ env: { ...process.env, [DAEMON_CONFIG_ENV]: JSON.stringify(cfg) }
16790
16815
  });
16791
16816
  child.on("error", () => {
16792
16817
  });
@@ -16869,7 +16894,7 @@ function preflightDaemon(cfg, harness) {
16869
16894
  return true;
16870
16895
  }
16871
16896
 
16872
- // src/core/knowledge-injection.ts
16897
+ // src/core/page-injection.ts
16873
16898
  function parsePageList(raw) {
16874
16899
  const items = raw?.items;
16875
16900
  if (!Array.isArray(items)) return [];
@@ -16881,48 +16906,48 @@ function parsePageList(raw) {
16881
16906
  }
16882
16907
  return out;
16883
16908
  }
16884
- var EMPTY_STATE = "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
16909
+ var EMPTY_STATE = "No pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
16885
16910
  function indexLine(pages) {
16886
- const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
16887
- 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.`;
16911
+ const count = pages.length === 1 ? "1 page covers" : `${pages.length} pages cover`;
16912
+ 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.`;
16888
16913
  }
16889
- 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:
16914
+ 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:
16890
16915
  \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);
16891
16916
  \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);
16892
16917
  \u2022 you are implementing something new, or two parts have to fit together;
16893
16918
  \u2022 the user asks why something is the way it is, or what is left to do;
16894
16919
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
16895
- 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.
16920
+ 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.
16896
16921
  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.
16897
- - 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.
16922
+ - 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.
16898
16923
  - 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>").
16899
16924
  - 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.
16900
16925
  - 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).`;
16901
- 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";
16926
+ 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";
16902
16927
  function toolGuide(opts) {
16903
16928
  const extra = opts?.extra?.trim();
16904
16929
  return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
16905
16930
  ${extra}` : "");
16906
16931
  }
16907
- function buildKnowledgePreamble(pages, opts) {
16932
+ function buildPagesPreamble(pages, opts) {
16908
16933
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
16909
- return `<hindsight_knowledge>
16910
- 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:
16934
+ return `<hindsight_pages>
16935
+ 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:
16911
16936
  ${toolGuide(opts)}
16912
16937
  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.
16913
16938
  ${body}
16914
16939
  This tool guide and the page list are re-injected for you periodically as things change.
16915
- </hindsight_knowledge>`;
16940
+ </hindsight_pages>`;
16916
16941
  }
16917
16942
  function buildRosterRefresh(pages, opts) {
16918
16943
  const rosterBlock = pages.length ? `${indexLine(pages)}
16919
16944
  ` : "";
16920
- return "<hindsight_knowledge_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
16945
+ return "<hindsight_page_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
16921
16946
  ${toolGuide(opts)}
16922
- </hindsight_knowledge_refresh>`;
16947
+ </hindsight_page_refresh>`;
16923
16948
  }
16924
16949
 
16925
- // src/core/knowledge-tools.ts
16950
+ // src/core/page-tools.ts
16926
16951
  import { createHash as createHash4 } from "crypto";
16927
16952
  import { existsSync as existsSync4 } from "fs";
16928
16953
  import { homedir as homedir6 } from "os";
@@ -17354,7 +17379,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17354
17379
  const mcpConfig = JSON.stringify({
17355
17380
  mcpServers: {
17356
17381
  hindsight: {
17357
- command: "node",
17382
+ command: nodeBinary(),
17358
17383
  args: [opts.mcpServerPath],
17359
17384
  // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
17360
17385
  // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
@@ -17395,7 +17420,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17395
17420
  "--sandbox",
17396
17421
  "read-only",
17397
17422
  "-c",
17398
- `mcp_servers.hindsight.command="node"`,
17423
+ `mcp_servers.hindsight.command=${tomlValue(nodeBinary())}`,
17399
17424
  "-c",
17400
17425
  `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17401
17426
  "-c",
@@ -17482,7 +17507,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17482
17507
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17483
17508
  return await new Promise((resolve4) => {
17484
17509
  try {
17485
- const child = spawnFn("node", [supervisorPath], {
17510
+ const child = spawnFn(nodeBinary(), [supervisorPath], {
17486
17511
  cwd: repoDir,
17487
17512
  detached: true,
17488
17513
  stdio: "ignore",
@@ -17580,11 +17605,11 @@ async function syncStatus(client, bank, repoDir) {
17580
17605
  activeOps,
17581
17606
  // Older Hindsight servers have no page surface. They are still fully usable for the
17582
17607
  // legacy bank/retain pipeline, so page absence must not make syncStatus permanently false.
17583
- synced: gitlogPresent && (client.knowledgePagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17608
+ synced: gitlogPresent && (client.pagesSupported === false || pages.length > 0) && (activeOps ?? 0) === 0
17584
17609
  };
17585
17610
  }
17586
17611
 
17587
- // src/core/knowledge-tools.ts
17612
+ // src/core/page-tools.ts
17588
17613
  var READ_ONLY_ANNOTATIONS = {
17589
17614
  readOnlyHint: true,
17590
17615
  destructiveHint: false,
@@ -17614,13 +17639,13 @@ function guarded(fn) {
17614
17639
  }
17615
17640
  };
17616
17641
  }
17617
- function buildKnowledgeTools(client, bankId, opts = {}) {
17642
+ function buildPageTools(client, bankId, opts = {}) {
17618
17643
  const extra = opts.toolGuideExtra?.trim();
17619
17644
  const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
17620
17645
  return [
17621
17646
  {
17622
17647
  name: "hindsight_sync_status",
17623
- description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, knowledge pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
17648
+ description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
17624
17649
  inputSchema: {},
17625
17650
  annotations: READ_ONLY_ANNOTATIONS,
17626
17651
  handler: async () => {
@@ -17675,13 +17700,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17675
17700
  }
17676
17701
  },
17677
17702
  {
17678
- name: "hindsight_search_knowledge_pages",
17679
- description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + crediting,
17703
+ name: "hindsight_search_pages",
17704
+ description: "Search this repository's Hindsight pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages, each with its opening text (not the passage that matched, and not filtered by relevance); read a full page with hindsight_read_page. " + crediting,
17680
17705
  inputSchema: { query: external_exports.string().describe("what to look for") },
17681
17706
  annotations: READ_ONLY_ANNOTATIONS,
17682
17707
  handler: async (args) => {
17683
17708
  try {
17684
- const hits = await client.searchKnowledgePages(args.query);
17709
+ const hits = await client.searchPages(args.query);
17685
17710
  return ok({
17686
17711
  pages: hits.map((h) => ({
17687
17712
  page: h.name,
@@ -17699,22 +17724,22 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17699
17724
  }
17700
17725
  },
17701
17726
  {
17702
- name: "hindsight_list_knowledge_pages",
17703
- description: "List this repository's Hindsight knowledge pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
17727
+ name: "hindsight_list_pages",
17728
+ description: "List this repository's Hindsight pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
17704
17729
  inputSchema: {},
17705
17730
  annotations: READ_ONLY_ANNOTATIONS,
17706
17731
  handler: guarded(async () => client.listPages())
17707
17732
  },
17708
17733
  {
17709
- name: "hindsight_read_knowledge_page",
17710
- description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
17734
+ name: "hindsight_read_page",
17735
+ description: "Read the full content of one page by its id (from hindsight_list_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
17711
17736
  inputSchema: { page_id: external_exports.string() },
17712
17737
  annotations: READ_ONLY_ANNOTATIONS,
17713
17738
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
17714
17739
  },
17715
17740
  {
17716
17741
  name: "hindsight_reflect",
17717
- description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
17742
+ description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
17718
17743
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
17719
17744
  annotations: READ_ONLY_ANNOTATIONS,
17720
17745
  handler: guarded(
@@ -17726,7 +17751,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
17726
17751
  },
17727
17752
  {
17728
17753
  name: "hindsight_capture_initiative",
17729
- description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_knowledge_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
17754
+ description: "Record a new feature or initiative as a tracked page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
17730
17755
  inputSchema: {
17731
17756
  title: external_exports.string(),
17732
17757
  summary: external_exports.string(),
@@ -18256,10 +18281,15 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18256
18281
  const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
18257
18282
  const plugins = registry2?.plugins;
18258
18283
  if (!plugins || typeof plugins !== "object") return void 0;
18259
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
18284
+ const enabledMaps = [
18285
+ join16(cwd, ".claude", "settings.local.json"),
18286
+ join16(cwd, ".claude", "settings.json"),
18287
+ join16(claudeDir, "settings.json")
18288
+ ].map((path) => readJson(path)?.enabledPlugins);
18260
18289
  for (const [key, raw] of Object.entries(plugins)) {
18261
18290
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
18262
- if (enabled && enabled[key] === false) continue;
18291
+ const setting = enabledMaps.find((m) => m && typeof m[key] === "boolean")?.[key];
18292
+ if (setting === false) continue;
18263
18293
  const installs = Array.isArray(raw) ? raw : [raw];
18264
18294
  const active = installs.some((i) => {
18265
18295
  if (!i || typeof i !== "object") return false;
@@ -18357,6 +18387,7 @@ async function buildSessionStartContext(args) {
18357
18387
  let cold;
18358
18388
  let gitDocIds;
18359
18389
  let bankEmpty = false;
18390
+ let deepening = false;
18360
18391
  const harness = args.harness ?? "claude-code";
18361
18392
  const hasGit = args.hasGit ?? hasGitHistory;
18362
18393
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -18410,6 +18441,7 @@ async function buildSessionStartContext(args) {
18410
18441
  }
18411
18442
  if (docIds !== void 0) {
18412
18443
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18444
+ deepening = true;
18413
18445
  if (cold) {
18414
18446
  if (cfg.codebaseSurvey !== false) {
18415
18447
  const sha = resolveHeadSha(cwd);
@@ -18459,15 +18491,23 @@ async function buildSessionStartContext(args) {
18459
18491
  }
18460
18492
  }
18461
18493
  }
18494
+ if (!deepening) {
18495
+ await client.configureBankSettings?.({
18496
+ manage: cfg.manageBankConfig,
18497
+ extractionMode: cfg.retainExtractionMode,
18498
+ defaults: cfg.defaultBankConfig
18499
+ }).catch(() => {
18500
+ });
18501
+ }
18462
18502
  let pages = [];
18463
18503
  try {
18464
18504
  pages = parsePageList(await client.listPages());
18465
18505
  } catch {
18466
- if (client.knowledgePagesSupported === false) {
18467
- diag(harness, "knowledge_pages_unavailable", { bank: bankId });
18506
+ if (client.pagesSupported === false) {
18507
+ diag(harness, "pages_unavailable", { bank: bankId });
18468
18508
  }
18469
18509
  }
18470
- const additionalContext = buildKnowledgePreamble(pages, {
18510
+ const additionalContext = buildPagesPreamble(pages, {
18471
18511
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18472
18512
  extra: cfg.toolGuideExtra
18473
18513
  });
@@ -18497,6 +18537,63 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18497
18537
  // src/core/hook.ts
18498
18538
  import { existsSync as existsSync8 } from "fs";
18499
18539
 
18540
+ // src/core/transcript-util.ts
18541
+ var TOOL_TEXT_CAP = 2e3;
18542
+ 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;
18543
+ function stripInjectedMemory(s) {
18544
+ return s.replace(MEMORY_TAG_RE, "");
18545
+ }
18546
+ function truncate(s, max = TOOL_TEXT_CAP) {
18547
+ return s.length > max ? `${s.slice(0, max)}\u2026 (truncated)` : s;
18548
+ }
18549
+ var TARGET_KEYS = [
18550
+ "file_path",
18551
+ "path",
18552
+ "notebook_path",
18553
+ "command",
18554
+ "pattern",
18555
+ "query",
18556
+ "url",
18557
+ "name",
18558
+ "id"
18559
+ ];
18560
+ var ACTION_TARGET_CAP = 100;
18561
+ function actionLine(tool, input) {
18562
+ let target = "";
18563
+ if (input && typeof input === "object") {
18564
+ const rec = input;
18565
+ for (const k of TARGET_KEYS) {
18566
+ const v = rec[k];
18567
+ if (typeof v === "string" && v.trim()) {
18568
+ target = v.trim().split("\n")[0];
18569
+ break;
18570
+ }
18571
+ }
18572
+ } else if (typeof input === "string") {
18573
+ target = input.trim().split("\n")[0];
18574
+ }
18575
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18576
+ const line = target ? `${tool} ${target}` : tool;
18577
+ const note = memoryNoteText(input);
18578
+ return note ? `${line}
18579
+ ${truncate(note, MEMORY_NOTE_CAP)}` : line;
18580
+ }
18581
+ var MEMORY_NOTE_CAP = 8e3;
18582
+ var MEMORY_NOTE_PATH_RE = /(^|[\\/])(memory|memories)[\\/]|(^|[\\/])MEMORY\.md$/i;
18583
+ var MEMORY_SHELL_WRITE_RE = /[\\/](memory|memories)([\\/\s"']|$)|MEMORY\.md/i;
18584
+ var SHELL_WRITE_RE = /(^|[^0-9&>])>>?(?!&)|\btee\b/;
18585
+ function memoryNoteText(input) {
18586
+ if (!input || typeof input !== "object") return "";
18587
+ const rec = input;
18588
+ const cmd = rec.command;
18589
+ if (typeof cmd === "string")
18590
+ return MEMORY_SHELL_WRITE_RE.test(cmd) && SHELL_WRITE_RE.test(cmd) ? cmd.trim() : "";
18591
+ const path = rec.file_path ?? rec.path;
18592
+ if (typeof path !== "string" || !MEMORY_NOTE_PATH_RE.test(path)) return "";
18593
+ const text = rec.content ?? rec.new_string;
18594
+ return typeof text === "string" ? text.trim() : "";
18595
+ }
18596
+
18500
18597
  // src/core/inject.ts
18501
18598
  function buildReflectQuery(prompt) {
18502
18599
  return `A developer is starting a coding session in this repository with this goal:
@@ -18513,8 +18610,8 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
18513
18610
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
18514
18611
  - If the bank holds nothing that bears on the goal, say so in one line.`;
18515
18612
  }
18516
- var PAGE_FALLBACK_LEAD = "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18517
- var PAGE_INJECT_LEAD = "(These knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
18613
+ 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.)";
18614
+ var PAGE_INJECT_LEAD = "(These pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
18518
18615
  function formatPageFallback(hits, lead = PAGE_FALLBACK_LEAD) {
18519
18616
  return `${lead}
18520
18617
  ` + hits.map((h) => {
@@ -18545,43 +18642,6 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18545
18642
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18546
18643
  import { tmpdir as tmpdir4 } from "os";
18547
18644
  import { dirname as dirname10, join as join18 } from "path";
18548
-
18549
- // src/core/transcript-util.ts
18550
- 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;
18551
- function stripInjectedMemory(s) {
18552
- return s.replace(MEMORY_TAG_RE, "");
18553
- }
18554
- var TARGET_KEYS = [
18555
- "file_path",
18556
- "path",
18557
- "notebook_path",
18558
- "command",
18559
- "pattern",
18560
- "query",
18561
- "url",
18562
- "name",
18563
- "id"
18564
- ];
18565
- var ACTION_TARGET_CAP = 100;
18566
- function actionLine(tool, input) {
18567
- let target = "";
18568
- if (input && typeof input === "object") {
18569
- const rec = input;
18570
- for (const k of TARGET_KEYS) {
18571
- const v = rec[k];
18572
- if (typeof v === "string" && v.trim()) {
18573
- target = v.trim().split("\n")[0];
18574
- break;
18575
- }
18576
- }
18577
- } else if (typeof input === "string") {
18578
- target = input.trim().split("\n")[0];
18579
- }
18580
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
18581
- return target ? `${tool} ${target}` : tool;
18582
- }
18583
-
18584
- // src/core/turn-journal.ts
18585
18645
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18586
18646
 
18587
18647
  // src/core/hook.ts
@@ -18607,7 +18667,7 @@ function boundRecallQuery(prompt) {
18607
18667
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18608
18668
  const t0 = Date.now();
18609
18669
  try {
18610
- const hits = await client.searchKnowledgePages(prompt.slice(0, 500), { timeoutMs });
18670
+ const hits = await client.searchPages(prompt.slice(0, 500), { timeoutMs });
18611
18671
  diag(harness, event, { ms: Date.now() - t0, count: hits.length });
18612
18672
  return hits.length ? formatPageFallback(hits, lead) : null;
18613
18673
  } catch (e) {
@@ -18721,14 +18781,10 @@ async function buildHookOutput(args) {
18721
18781
  pages = parsePageList(await client.listPages());
18722
18782
  diag(harness, "pages_ok", { ms: Date.now() - t0, count: pages.length });
18723
18783
  } catch (e) {
18724
- diag(
18725
- harness,
18726
- client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
18727
- {
18728
- ms: Date.now() - t0,
18729
- error: describeError(e)
18730
- }
18731
- );
18784
+ diag(harness, client.pagesSupported === false ? "pages_unavailable" : "pages_failed", {
18785
+ ms: Date.now() - t0,
18786
+ error: describeError(e)
18787
+ });
18732
18788
  }
18733
18789
  }
18734
18790
  writeSessionCache(cacheFile, {
@@ -18739,7 +18795,7 @@ async function buildHookOutput(args) {
18739
18795
  });
18740
18796
  const blocks = [];
18741
18797
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
18742
- if (cadence > 0 && turns % cadence === 0) {
18798
+ if (cadence > 0 && turns % cadence === 0 && !(turns === 1 && args.preambleOnFirstTurn)) {
18743
18799
  blocks.push(
18744
18800
  buildRosterRefresh(pages, {
18745
18801
  reflectOnNewGoals: cfg.autoInject !== "reflect",
@@ -18807,9 +18863,9 @@ var RuntimeCore = class {
18807
18863
  setTranscriptSource(fetch2) {
18808
18864
  this.fetchTranscript = fetch2;
18809
18865
  }
18810
- /** The hindsight_* knowledge + recall tools, bound to this bank, for the harness to register natively. */
18866
+ /** The hindsight_* page + recall tools, bound to this bank, for the harness to register natively. */
18811
18867
  toolSpecs() {
18812
- return buildKnowledgeTools(this.client, this.bankId, {
18868
+ return buildPageTools(this.client, this.bankId, {
18813
18869
  repoDir: this.projectDir,
18814
18870
  harness: this.harness,
18815
18871
  pageTrigger: buildPageTrigger(this.cfg),
@@ -18831,7 +18887,7 @@ var RuntimeCore = class {
18831
18887
  * git-log seed + codebase survey. Reuses the exact hook-harness logic
18832
18888
  * (`buildSessionStartContext`) so opencode seeds identically. Never throws.
18833
18889
  *
18834
- * It deliberately does NOT keep that call's knowledge preamble. This runs once per PROCESS and
18890
+ * It deliberately does NOT keep that call's pages preamble. This runs once per PROCESS and
18835
18891
  * these hosts outlive every session, so a roster captured here is stale for every session but
18836
18892
  * the first — `onPrompt` builds its own from the session's live page list (#4607).
18837
18893
  */
@@ -18862,10 +18918,11 @@ var RuntimeCore = class {
18862
18918
  * intentionally replaces the old in-memory reflect/page state, keeping lifecycle behavior
18863
18919
  * identical across hosts while this adapter retains only delivery-specific state.
18864
18920
  */
18865
- async onPrompt(sessionId, prompt) {
18921
+ async onPrompt(sessionId, rawPrompt) {
18866
18922
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18867
18923
  if (!sessionId) return;
18868
- if (!prompt.trim()) {
18924
+ const prompt = stripInjectedMemory(rawPrompt).trim();
18925
+ if (!prompt) {
18869
18926
  this.injection.delete(sessionId);
18870
18927
  return;
18871
18928
  }
@@ -18881,12 +18938,13 @@ var RuntimeCore = class {
18881
18938
  prompt,
18882
18939
  cfg: this.cfg,
18883
18940
  client: this.client,
18884
- cacheFile
18941
+ cacheFile,
18942
+ preambleOnFirstTurn: true
18885
18943
  });
18886
18944
  const blocks = [];
18887
18945
  if (turns === 1) {
18888
18946
  blocks.push(
18889
- buildKnowledgePreamble(output.pages, {
18947
+ buildPagesPreamble(output.pages, {
18890
18948
  reflectOnNewGoals: this.cfg.autoInject !== "reflect",
18891
18949
  extra: this.cfg.toolGuideExtra
18892
18950
  })