@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
@@ -286,7 +286,11 @@ function configuredDir(dir) {
286
286
  const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir2(), dir.slice(1)) : dir;
287
287
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
288
288
  }
289
- function isWithin(directory, configured) {
289
+ function isWithin(directory, configured, platform = process.platform) {
290
+ if (platform === "win32") {
291
+ directory = directory.toLowerCase();
292
+ configured = configured.toLowerCase();
293
+ }
290
294
  return directory === configured || directory.startsWith(configured + sep);
291
295
  }
292
296
  function mapLookup(map, directory) {
@@ -379,16 +383,93 @@ import { join as join7 } from "path";
379
383
 
380
384
  // src/core/seed.ts
381
385
  import { spawn as realSpawn } from "child_process";
382
- import { dirname as dirname4, join as join5 } from "path";
386
+ import { dirname as dirname4, join as join6 } from "path";
383
387
  import { fileURLToPath } from "url";
388
+
389
+ // src/core/util.ts
390
+ import { accessSync, constants, statSync as statSync2 } from "fs";
391
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
392
+ function binOnPath(bin, opts = {}) {
393
+ const platform = opts.platform ?? process.platform;
394
+ const env = opts.env ?? process.env;
395
+ const runnable = (file) => {
396
+ try {
397
+ if (!statSync2(file).isFile()) return false;
398
+ if (platform !== "win32") accessSync(file, constants.X_OK);
399
+ return true;
400
+ } catch {
401
+ return false;
402
+ }
403
+ };
404
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
405
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
406
+ for (const dir of (env.PATH || "").split(delimiter)) {
407
+ if (!dir) continue;
408
+ for (const name of names) {
409
+ const file = join5(dir, name);
410
+ if (runnable(file)) return resolve2(file);
411
+ }
412
+ }
413
+ return void 0;
414
+ }
415
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
416
+ function semverGte(version2, min) {
417
+ const parts = (v) => {
418
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
419
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
420
+ };
421
+ const a = version2 ? parts(version2) : void 0;
422
+ const b = parts(min);
423
+ if (!a || !b) return false;
424
+ for (let i = 0; i < 3; i++) {
425
+ if (a[i] !== b[i]) return a[i] > b[i];
426
+ }
427
+ return true;
428
+ }
429
+ async function pool(items, n, fn, onError, onProgress) {
430
+ let i = 0, done = 0;
431
+ async function worker() {
432
+ while (i < items.length) {
433
+ const idx = i++;
434
+ try {
435
+ await fn(items[idx], idx);
436
+ } catch (e) {
437
+ onError?.(idx, e);
438
+ }
439
+ onProgress?.(++done, items.length);
440
+ }
441
+ }
442
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
443
+ }
444
+ function nodeBinary() {
445
+ return process.versions.bun || process.versions.electron ? "node" : process.execPath;
446
+ }
447
+ function hookNode(opts = {}) {
448
+ const platform = opts.platform ?? process.platform;
449
+ if (platform === "win32" || binOnPath("node", opts)) return "node";
450
+ return nodeBinary();
451
+ }
452
+ function isOurMcpEntry(entry) {
453
+ if (!entry || typeof entry !== "object") return false;
454
+ const candidate = entry;
455
+ const command = typeof candidate.command === "string" ? candidate.command : "";
456
+ const bin = command.replaceAll("\\", "/").split("/").at(-1);
457
+ if (bin !== "node" && bin !== "node.exe" || !Array.isArray(candidate.args)) return false;
458
+ const script = candidate.args[0];
459
+ if (typeof script !== "string") return false;
460
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
461
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
462
+ }
463
+
464
+ // src/core/seed.ts
384
465
  var DEFAULT_SEED_LIMIT = 300;
385
466
  function startBackgroundSeed(repoDir, opts = {}) {
386
467
  try {
387
468
  const spawnFn = opts.spawn ?? realSpawn;
388
- const enginePath = opts.enginePath ?? join5(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
469
+ const enginePath = opts.enginePath ?? join6(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
389
470
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
390
471
  const child = spawnFn(
391
- "node",
472
+ nodeBinary(),
392
473
  [
393
474
  enginePath,
394
475
  "--repo",
@@ -414,7 +495,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
414
495
  import { createHash } from "crypto";
415
496
  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.";
416
497
  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.";
417
- 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.`;
498
+ 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.`;
418
499
  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.";
419
500
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
420
501
  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.";
@@ -457,14 +538,14 @@ var RETAIN_STRATEGIES = {
457
538
  retain_chunk_size: 12e3
458
539
  }
459
540
  };
460
- var KNOWLEDGE_LABELS = {
541
+ var PAGE_LABELS = {
461
542
  key: "knowledge",
462
543
  type: "multi-values",
463
544
  // 0, 1, or several — empty is normal
464
545
  optional: true,
465
546
  tag: true,
466
547
  // emits knowledge:<value> onto the fact's tags
467
- 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.",
548
+ 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.",
468
549
  values: [
469
550
  {
470
551
  value: "feature-work",
@@ -621,7 +702,7 @@ var CODING_BANK_TEMPLATE = {
621
702
  retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
622
703
  retain_default_strategy: "git",
623
704
  retain_strategies: RETAIN_STRATEGIES,
624
- entity_labels: [KNOWLEDGE_LABELS],
705
+ entity_labels: [PAGE_LABELS],
625
706
  entities_allow_free_form: true
626
707
  }
627
708
  };
@@ -673,72 +754,7 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
673
754
  }
674
755
 
675
756
  // package.json
676
- var version = "0.8.6";
677
-
678
- // src/core/util.ts
679
- import { accessSync, constants, statSync as statSync2 } from "fs";
680
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
681
- function binOnPath(bin, opts = {}) {
682
- const platform = opts.platform ?? process.platform;
683
- const env = opts.env ?? process.env;
684
- const runnable = (file) => {
685
- try {
686
- if (!statSync2(file).isFile()) return false;
687
- if (platform !== "win32") accessSync(file, constants.X_OK);
688
- return true;
689
- } catch {
690
- return false;
691
- }
692
- };
693
- if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
694
- const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
695
- for (const dir of (env.PATH || "").split(delimiter)) {
696
- if (!dir) continue;
697
- for (const name of names) {
698
- const file = join6(dir, name);
699
- if (runnable(file)) return resolve2(file);
700
- }
701
- }
702
- return void 0;
703
- }
704
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
705
- function semverGte(version2, min) {
706
- const parts = (v) => {
707
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
708
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
709
- };
710
- const a = version2 ? parts(version2) : void 0;
711
- const b = parts(min);
712
- if (!a || !b) return false;
713
- for (let i = 0; i < 3; i++) {
714
- if (a[i] !== b[i]) return a[i] > b[i];
715
- }
716
- return true;
717
- }
718
- async function pool(items, n, fn, onError, onProgress) {
719
- let i = 0, done = 0;
720
- async function worker() {
721
- while (i < items.length) {
722
- const idx = i++;
723
- try {
724
- await fn(items[idx], idx);
725
- } catch (e) {
726
- onError?.(idx, e);
727
- }
728
- onProgress?.(++done, items.length);
729
- }
730
- }
731
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
732
- }
733
- function isOurMcpEntry(entry) {
734
- if (!entry || typeof entry !== "object") return false;
735
- const candidate = entry;
736
- if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
737
- const script = candidate.args[0];
738
- if (typeof script !== "string") return false;
739
- const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
740
- return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
741
- }
757
+ var version = "0.8.8";
742
758
 
743
759
  // src/core/hindsight.ts
744
760
  var USER_AGENT = `hindsight-coding-agents/${version}`;
@@ -765,11 +781,11 @@ function retryAfterMs(header) {
765
781
  const at = Date.parse(header);
766
782
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
767
783
  }
768
- var KnowledgePagesUnavailableError = class extends Error {
769
- code = "knowledge_pages_unavailable";
784
+ var PagesUnavailableError = class extends Error {
785
+ code = "pages_unavailable";
770
786
  constructor() {
771
- super("Hindsight server does not support knowledge pages");
772
- this.name = "KnowledgePagesUnavailableError";
787
+ super("Hindsight server does not support pages");
788
+ this.name = "PagesUnavailableError";
773
789
  }
774
790
  };
775
791
  async function isEndpointMissing(r) {
@@ -780,6 +796,10 @@ async function isEndpointMissing(r) {
780
796
  return false;
781
797
  }
782
798
  }
799
+ function pagesPath(sub, legacy = false) {
800
+ if (!legacy) return `/pages${sub}`;
801
+ return /^\/(tree|folders|search|export|nodes)\b/.test(sub) ? `/knowledge-base${sub}` : `/knowledge-base/pages${sub}`;
802
+ }
783
803
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
784
804
  var ReflectError = class extends Error {
785
805
  constructor(message, status, timedOut, options) {
@@ -848,7 +868,7 @@ var HindsightClient = class {
848
868
  opIds = [];
849
869
  // async operation ids collected by retain(), for drain()
850
870
  /** Tri-state capability probe: unknown until the first page request, then cached. */
851
- knowledgePagesSupported;
871
+ pagesSupported;
852
872
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
853
873
  idempotentRetain;
854
874
  log;
@@ -946,7 +966,9 @@ var HindsightClient = class {
946
966
  }
947
967
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
948
968
  throw new Error(
949
- `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
969
+ // Query dropped: an encoded search query filled the 200-char error cap and pushed the
970
+ // status and the server's reason out of the tool error (#6341).
971
+ `${method} ${url.split("?")[0]} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
950
972
  );
951
973
  return r;
952
974
  }
@@ -1077,7 +1099,7 @@ var HindsightClient = class {
1077
1099
  return (j.total ?? j.items?.length ?? 0) > 0;
1078
1100
  }
1079
1101
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
1080
- * entity labels), then seed knowledge pages when the server supports them. Both halves are
1102
+ * entity labels), then seed pages when the server supports them. Both halves are
1081
1103
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
1082
1104
  * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
1083
1105
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
@@ -1092,6 +1114,15 @@ var HindsightClient = class {
1092
1114
  await this.req("DELETE", this.bankUrl());
1093
1115
  this.log(`[bank] reset ${this.bank}`);
1094
1116
  }
1117
+ await this.configureBankSettings(opts);
1118
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1119
+ }
1120
+ /** The config half of `configureBank` (missions, retain strategies, entity labels), without
1121
+ * seeding pages. Session start calls it directly when the deepen engine — the usual caller of
1122
+ * `configureBank` — will not run (`autoSeed: false`, or a directory with no git history):
1123
+ * without it such a bank never got the `conversation` strategy, and every session write-back
1124
+ * was extracted with the server's generic rules instead of the plugin's mission. */
1125
+ async configureBankSettings(opts = {}) {
1095
1126
  if (opts.manage === false) {
1096
1127
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
1097
1128
  } else {
@@ -1107,7 +1138,6 @@ var HindsightClient = class {
1107
1138
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
1108
1139
  }
1109
1140
  }
1110
- await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1111
1141
  }
1112
1142
  /**
1113
1143
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -1259,29 +1289,45 @@ var HindsightClient = class {
1259
1289
  const j = await r.json();
1260
1290
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1261
1291
  }
1292
+ /** Set once a server answered on the deprecated `/knowledge-base/...` paths: one from before the
1293
+ * page routes moved to `/pages/...`. Remove in 2.x. */
1294
+ legacyPagesPaths = false;
1262
1295
  /**
1263
- * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1264
- * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1265
- * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1296
+ * Request a page endpoint by its `/pages` sub-path (`""`, `/tree`, `/<id>`, `/nodes/<id>`, …).
1297
+ *
1298
+ * Returns `null` — and latches `pagesSupported = false` — iff the endpoint is really absent: an
1299
+ * unrouted 404 on the `/pages` path AND on its pre-rename `/knowledge-base` twin, which a server
1300
+ * older than the rename still serves (tried once, then remembered). A bank-not-found 404 is NOT
1301
+ * a capability verdict — it is the expected answer before the bank's first retain — so it is
1302
+ * returned as-is and never caches a negative (#4607). A 404's body may already be consumed.
1266
1303
  *
1267
1304
  * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1268
1305
  * the 405/501 this used to check for never reach a caller in the first place.
1269
1306
  */
1270
- async pagesUnsupported(r) {
1271
- if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1272
- this.knowledgePagesSupported = false;
1273
- return true;
1307
+ async pagesReq(method, sub, body, tolerate = [], timeoutMs) {
1308
+ const send = (legacy) => this.req(method, this.bankUrl(pagesPath(sub, legacy)), body, tolerate, timeoutMs);
1309
+ let r = await send(this.legacyPagesPaths);
1310
+ if (r.status !== 404 || !await isEndpointMissing(r)) return r;
1311
+ if (!this.legacyPagesPaths) {
1312
+ r = await send(true);
1313
+ if (r.status !== 404 || !await isEndpointMissing(r)) {
1314
+ this.legacyPagesPaths = true;
1315
+ return r;
1316
+ }
1317
+ }
1318
+ this.pagesSupported = false;
1319
+ return null;
1274
1320
  }
1275
1321
  /**
1276
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1322
+ * The bank's page tree (folders + pages, nested). The tree carries names, source
1277
1323
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1278
1324
  */
1279
1325
  async tree() {
1280
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1281
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1282
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1326
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1327
+ const r = await this.pagesReq("GET", "/tree");
1328
+ if (!r) throw new PagesUnavailableError();
1283
1329
  if (r.status === 404) return [];
1284
- this.knowledgePagesSupported = true;
1330
+ this.pagesSupported = true;
1285
1331
  try {
1286
1332
  return (await r.json()).roots ?? [];
1287
1333
  } catch {
@@ -1289,13 +1335,13 @@ var HindsightClient = class {
1289
1335
  }
1290
1336
  }
1291
1337
  /**
1292
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1338
+ * List pages (ids + names only — no synthesized content), flattened out of the tree
1293
1339
  * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1294
1340
  * to read, and a caller enumerating pages wants leaves, not structure.
1295
1341
  *
1296
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1297
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
1298
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1342
+ * NOTE the ids are page node ids (`kp-…`), NOT the backing mental-model ids. Every
1343
+ * page read/update in this client goes through the same page ids, so a page id from
1344
+ * here, from `searchPages`, or from a `[[page:<id>]]` link all resolve identically.
1299
1345
  */
1300
1346
  async listPages() {
1301
1347
  const items = [];
@@ -1317,34 +1363,26 @@ var HindsightClient = class {
1317
1363
  return { items };
1318
1364
  }
1319
1365
  /**
1320
- * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1366
+ * Read one page's synthesized content by page id, shaped by `shapePage` so
1321
1367
  * the body arrives once. The endpoint omits the internal reflect trace that built
1322
1368
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1323
1369
  * token cap.
1324
1370
  */
1325
1371
  async getPage(pageId) {
1326
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1327
- const r = await this.req(
1328
- "GET",
1329
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1330
- );
1331
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1372
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1373
+ const r = await this.pagesReq("GET", `/${encodeURIComponent(pageId)}`);
1374
+ if (!r) throw new PagesUnavailableError();
1375
+ if (r.status === 404) throw new Error(`page not found: ${pageId}`);
1332
1376
  return shapePage(await r.json());
1333
1377
  }
1334
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1378
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's pages.
1335
1379
  * Returns page-level hits with a relevance snippet — the real search behind
1336
- * hindsight_search_knowledge_pages. */
1337
- async searchKnowledgePages(query, opts = {}) {
1338
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1380
+ * hindsight_search_pages. */
1381
+ async searchPages(query, opts = {}) {
1382
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1339
1383
  const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1340
- const r = await this.req(
1341
- "GET",
1342
- this.bankUrl(`/knowledge-base/search${q}`),
1343
- void 0,
1344
- [],
1345
- opts.timeoutMs
1346
- );
1347
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1384
+ const r = await this.pagesReq("GET", `/search${q}`, void 0, [], opts.timeoutMs);
1385
+ if (!r) throw new PagesUnavailableError();
1348
1386
  if (r.status === 404) return [];
1349
1387
  const j = await r.json();
1350
1388
  return (j.results ?? []).map((x) => ({
@@ -1356,9 +1394,9 @@ var HindsightClient = class {
1356
1394
  }));
1357
1395
  }
1358
1396
  /**
1359
- * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1397
+ * Seed the fixed page taxonomy as pages at the tree root, idempotently.
1360
1398
  *
1361
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1399
+ * Matched by NAME, not id: `POST /pages` mints its own `kp-…` id, so a stable
1362
1400
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1363
1401
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
1364
1402
  *
@@ -1373,8 +1411,8 @@ var HindsightClient = class {
1373
1411
  try {
1374
1412
  roots = await this.tree();
1375
1413
  } catch (e) {
1376
- if (e instanceof KnowledgePagesUnavailableError) {
1377
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1414
+ if (e instanceof PagesUnavailableError) {
1415
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1378
1416
  return;
1379
1417
  }
1380
1418
  throw e;
@@ -1397,11 +1435,9 @@ var HindsightClient = class {
1397
1435
  trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1398
1436
  };
1399
1437
  if (!hit) {
1400
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1401
- if (await this.pagesUnsupported(r)) {
1402
- this.log(
1403
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1404
- );
1438
+ const r = await this.pagesReq("POST", "", body, [409]);
1439
+ if (!r) {
1440
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1405
1441
  return;
1406
1442
  }
1407
1443
  if (r.status === 404) {
@@ -1422,15 +1458,9 @@ var HindsightClient = class {
1422
1458
  );
1423
1459
  }
1424
1460
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1425
- const r = await this.req(
1426
- "PATCH",
1427
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1428
- patch
1429
- );
1430
- if (await this.pagesUnsupported(r)) {
1431
- this.log(
1432
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1433
- );
1461
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(hit.id)}`, patch);
1462
+ if (!r) {
1463
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1434
1464
  return;
1435
1465
  }
1436
1466
  if (r.status === 404) {
@@ -1442,7 +1472,7 @@ var HindsightClient = class {
1442
1472
  }
1443
1473
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1444
1474
  this.log(
1445
- `[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` : "")
1475
+ `[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` : "")
1446
1476
  );
1447
1477
  }
1448
1478
  /**
@@ -1476,12 +1506,8 @@ var HindsightClient = class {
1476
1506
  if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1477
1507
  }
1478
1508
  if (!patch.trigger && !patch.source_query) continue;
1479
- const r = await this.req(
1480
- "PATCH",
1481
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1482
- patch
1483
- );
1484
- if (r.status === 404) continue;
1509
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(page.id)}`, patch);
1510
+ if (!r || r.status === 404) continue;
1485
1511
  updated++;
1486
1512
  }
1487
1513
  return updated;
@@ -1507,7 +1533,7 @@ var HindsightClient = class {
1507
1533
  let pageId = args.relatesToPageId;
1508
1534
  if (!pageId) {
1509
1535
  const folderId = await this.ensureFolder("Initiatives");
1510
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1536
+ const r = await this.pagesReq("POST", "", {
1511
1537
  name: args.title,
1512
1538
  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),
1513
1539
  parent_id: folderId,
@@ -1516,8 +1542,8 @@ var HindsightClient = class {
1516
1542
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1517
1543
  });
1518
1544
  try {
1519
- const j = await r.json();
1520
- pageId = j.page_id ?? j.id;
1545
+ const j = await r?.json();
1546
+ pageId = j?.page_id ?? j?.id;
1521
1547
  } catch {
1522
1548
  }
1523
1549
  pageId ||= `initiative-${this.slugify(args.title)}`;
@@ -1535,16 +1561,17 @@ var HindsightClient = class {
1535
1561
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1536
1562
  async ensureFolder(name) {
1537
1563
  try {
1538
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1539
- const hit = (tree.roots || []).find(
1564
+ const r = await this.pagesReq("GET", "/tree");
1565
+ const tree = await r?.json();
1566
+ const hit = (tree?.roots || []).find(
1540
1567
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1541
1568
  );
1542
1569
  if (hit?.id) return hit.id;
1543
1570
  } catch {
1544
1571
  }
1545
1572
  try {
1546
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1547
- return (await r.json()).id;
1573
+ const r = await this.pagesReq("POST", "/folders", { name });
1574
+ return (await r?.json())?.id;
1548
1575
  } catch {
1549
1576
  return void 0;
1550
1577
  }
@@ -1942,6 +1969,63 @@ function resolvePartial(cfg, patch) {
1942
1969
  return out;
1943
1970
  }
1944
1971
 
1972
+ // src/core/transcript-util.ts
1973
+ var TOOL_TEXT_CAP = 2e3;
1974
+ 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;
1975
+ function stripInjectedMemory(s) {
1976
+ return s.replace(MEMORY_TAG_RE, "");
1977
+ }
1978
+ function truncate(s, max = TOOL_TEXT_CAP) {
1979
+ return s.length > max ? `${s.slice(0, max)}\u2026 (truncated)` : s;
1980
+ }
1981
+ var TARGET_KEYS = [
1982
+ "file_path",
1983
+ "path",
1984
+ "notebook_path",
1985
+ "command",
1986
+ "pattern",
1987
+ "query",
1988
+ "url",
1989
+ "name",
1990
+ "id"
1991
+ ];
1992
+ var ACTION_TARGET_CAP = 100;
1993
+ function actionLine(tool, input) {
1994
+ let target = "";
1995
+ if (input && typeof input === "object") {
1996
+ const rec = input;
1997
+ for (const k of TARGET_KEYS) {
1998
+ const v = rec[k];
1999
+ if (typeof v === "string" && v.trim()) {
2000
+ target = v.trim().split("\n")[0];
2001
+ break;
2002
+ }
2003
+ }
2004
+ } else if (typeof input === "string") {
2005
+ target = input.trim().split("\n")[0];
2006
+ }
2007
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
2008
+ const line = target ? `${tool} ${target}` : tool;
2009
+ const note = memoryNoteText(input);
2010
+ return note ? `${line}
2011
+ ${truncate(note, MEMORY_NOTE_CAP)}` : line;
2012
+ }
2013
+ var MEMORY_NOTE_CAP = 8e3;
2014
+ var MEMORY_NOTE_PATH_RE = /(^|[\\/])(memory|memories)[\\/]|(^|[\\/])MEMORY\.md$/i;
2015
+ var MEMORY_SHELL_WRITE_RE = /[\\/](memory|memories)([\\/\s"']|$)|MEMORY\.md/i;
2016
+ var SHELL_WRITE_RE = /(^|[^0-9&>])>>?(?!&)|\btee\b/;
2017
+ function memoryNoteText(input) {
2018
+ if (!input || typeof input !== "object") return "";
2019
+ const rec = input;
2020
+ const cmd = rec.command;
2021
+ if (typeof cmd === "string")
2022
+ return MEMORY_SHELL_WRITE_RE.test(cmd) && SHELL_WRITE_RE.test(cmd) ? cmd.trim() : "";
2023
+ const path = rec.file_path ?? rec.path;
2024
+ if (typeof path !== "string" || !MEMORY_NOTE_PATH_RE.test(path)) return "";
2025
+ const text = rec.content ?? rec.new_string;
2026
+ return typeof text === "string" ? text.trim() : "";
2027
+ }
2028
+
1945
2029
  // src/core/brand.ts
1946
2030
  function brandWord() {
1947
2031
  const start = [0, 116, 217];
@@ -1956,7 +2040,7 @@ function brandWord() {
1956
2040
  return `${out}\x1B[0m`;
1957
2041
  }
1958
2042
 
1959
- // src/core/knowledge-injection.ts
2043
+ // src/core/page-injection.ts
1960
2044
  function parsePageList(raw) {
1961
2045
  const items = raw?.items;
1962
2046
  if (!Array.isArray(items)) return [];
@@ -1968,38 +2052,38 @@ function parsePageList(raw) {
1968
2052
  }
1969
2053
  return out;
1970
2054
  }
1971
- var EMPTY_STATE = "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
2055
+ var EMPTY_STATE = "No pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
1972
2056
  function indexLine(pages) {
1973
- const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1974
- 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.`;
2057
+ const count = pages.length === 1 ? "1 page covers" : `${pages.length} pages cover`;
2058
+ 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.`;
1975
2059
  }
1976
- 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:
2060
+ 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:
1977
2061
  \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);
1978
2062
  \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);
1979
2063
  \u2022 you are implementing something new, or two parts have to fit together;
1980
2064
  \u2022 the user asks why something is the way it is, or what is left to do;
1981
2065
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1982
- 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.
2066
+ 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.
1983
2067
  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.
1984
- - 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.
2068
+ - 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.
1985
2069
  - 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>").
1986
2070
  - 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.
1987
2071
  - 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).`;
1988
- 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";
2072
+ 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";
1989
2073
  function toolGuide(opts) {
1990
2074
  const extra = opts?.extra?.trim();
1991
2075
  return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1992
2076
  ${extra}` : "");
1993
2077
  }
1994
- function buildKnowledgePreamble(pages, opts) {
2078
+ function buildPagesPreamble(pages, opts) {
1995
2079
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
1996
- return `<hindsight_knowledge>
1997
- 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:
2080
+ return `<hindsight_pages>
2081
+ 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:
1998
2082
  ${toolGuide(opts)}
1999
2083
  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.
2000
2084
  ${body}
2001
2085
  This tool guide and the page list are re-injected for you periodically as things change.
2002
- </hindsight_knowledge>`;
2086
+ </hindsight_pages>`;
2003
2087
  }
2004
2088
 
2005
2089
  // src/core/session-cache.ts
@@ -2069,43 +2153,6 @@ function sessionRootDir(harness, sessionId, cwd) {
2069
2153
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
2070
2154
  import { tmpdir as tmpdir2 } from "os";
2071
2155
  import { dirname as dirname6, join as join9 } from "path";
2072
-
2073
- // src/core/transcript-util.ts
2074
- 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;
2075
- function stripInjectedMemory(s) {
2076
- return s.replace(MEMORY_TAG_RE, "");
2077
- }
2078
- var TARGET_KEYS = [
2079
- "file_path",
2080
- "path",
2081
- "notebook_path",
2082
- "command",
2083
- "pattern",
2084
- "query",
2085
- "url",
2086
- "name",
2087
- "id"
2088
- ];
2089
- var ACTION_TARGET_CAP = 100;
2090
- function actionLine(tool, input) {
2091
- let target = "";
2092
- if (input && typeof input === "object") {
2093
- const rec = input;
2094
- for (const k of TARGET_KEYS) {
2095
- const v = rec[k];
2096
- if (typeof v === "string" && v.trim()) {
2097
- target = v.trim().split("\n")[0];
2098
- break;
2099
- }
2100
- }
2101
- } else if (typeof input === "string") {
2102
- target = input.trim().split("\n")[0];
2103
- }
2104
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
2105
- return target ? `${tool} ${target}` : tool;
2106
- }
2107
-
2108
- // src/core/turn-journal.ts
2109
2156
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
2110
2157
 
2111
2158
  // src/core/retain-cursor.ts
@@ -2193,13 +2240,18 @@ function onPath(bin) {
2193
2240
  return false;
2194
2241
  }
2195
2242
  }
2243
+ var DAEMON_CONFIG_ENV = "HINDSIGHT_CODING_AGENTS_DAEMON_CONFIG";
2196
2244
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
2197
2245
  try {
2198
2246
  const starter = join10(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
2199
- const child = spawnFn("node", [starter, "--harness", harness], {
2247
+ const child = spawnFn(nodeBinary(), [starter, "--harness", harness], {
2200
2248
  detached: true,
2201
2249
  stdio: "ignore",
2202
- windowsHide: true
2250
+ windowsHide: true,
2251
+ // The caller's config is already resolved for its directory and bank. Re-reading the file in
2252
+ // the starter lost `paths` / `banks` overrides, so a daemon enabled only there never started
2253
+ // (#6334).
2254
+ env: { ...process.env, [DAEMON_CONFIG_ENV]: JSON.stringify(cfg) }
2203
2255
  });
2204
2256
  child.on("error", () => {
2205
2257
  });
@@ -2783,7 +2835,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
2783
2835
  const mcpConfig = JSON.stringify({
2784
2836
  mcpServers: {
2785
2837
  hindsight: {
2786
- command: "node",
2838
+ command: nodeBinary(),
2787
2839
  args: [opts.mcpServerPath],
2788
2840
  // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
2789
2841
  // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
@@ -2824,7 +2876,7 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
2824
2876
  "--sandbox",
2825
2877
  "read-only",
2826
2878
  "-c",
2827
- `mcp_servers.hindsight.command="node"`,
2879
+ `mcp_servers.hindsight.command=${tomlValue(nodeBinary())}`,
2828
2880
  "-c",
2829
2881
  `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
2830
2882
  "-c",
@@ -2911,7 +2963,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2911
2963
  const supervisorPath = opts.supervisorPath ?? join13(dirname8(fileURLToPath3(import.meta.url)), "survey-supervisor.js");
2912
2964
  return await new Promise((resolve4) => {
2913
2965
  try {
2914
- const child = spawnFn("node", [supervisorPath], {
2966
+ const child = spawnFn(nodeBinary(), [supervisorPath], {
2915
2967
  cwd: repoDir,
2916
2968
  detached: true,
2917
2969
  stdio: "ignore",
@@ -3282,10 +3334,15 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")
3282
3334
  const registry = readJson(join17(claudeDir, "plugins", "installed_plugins.json"));
3283
3335
  const plugins = registry?.plugins;
3284
3336
  if (!plugins || typeof plugins !== "object") return void 0;
3285
- const enabled = readJson(join17(claudeDir, "settings.json"))?.enabledPlugins;
3337
+ const enabledMaps = [
3338
+ join17(cwd, ".claude", "settings.local.json"),
3339
+ join17(cwd, ".claude", "settings.json"),
3340
+ join17(claudeDir, "settings.json")
3341
+ ].map((path) => readJson(path)?.enabledPlugins);
3286
3342
  for (const [key, raw] of Object.entries(plugins)) {
3287
3343
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
3288
- if (enabled && enabled[key] === false) continue;
3344
+ const setting = enabledMaps.find((m) => m && typeof m[key] === "boolean")?.[key];
3345
+ if (setting === false) continue;
3289
3346
  const installs = Array.isArray(raw) ? raw : [raw];
3290
3347
  const active = installs.some((i) => {
3291
3348
  if (!i || typeof i !== "object") return false;
@@ -3348,6 +3405,7 @@ async function buildSessionStartContext(args) {
3348
3405
  let cold;
3349
3406
  let gitDocIds;
3350
3407
  let bankEmpty = false;
3408
+ let deepening = false;
3351
3409
  const harness = args.harness ?? "claude-code";
3352
3410
  const hasGit = args.hasGit ?? hasGitHistory;
3353
3411
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -3401,6 +3459,7 @@ async function buildSessionStartContext(args) {
3401
3459
  }
3402
3460
  if (docIds !== void 0) {
3403
3461
  startSeed(cwd, { limit: cfg.seedLimit, harness });
3462
+ deepening = true;
3404
3463
  if (cold) {
3405
3464
  if (cfg.codebaseSurvey !== false) {
3406
3465
  const sha = resolveHeadSha(cwd);
@@ -3450,15 +3509,23 @@ async function buildSessionStartContext(args) {
3450
3509
  }
3451
3510
  }
3452
3511
  }
3512
+ if (!deepening) {
3513
+ await client.configureBankSettings?.({
3514
+ manage: cfg.manageBankConfig,
3515
+ extractionMode: cfg.retainExtractionMode,
3516
+ defaults: cfg.defaultBankConfig
3517
+ }).catch(() => {
3518
+ });
3519
+ }
3453
3520
  let pages = [];
3454
3521
  try {
3455
3522
  pages = parsePageList(await client.listPages());
3456
3523
  } catch {
3457
- if (client.knowledgePagesSupported === false) {
3458
- diag(harness, "knowledge_pages_unavailable", { bank: bankId });
3524
+ if (client.pagesSupported === false) {
3525
+ diag(harness, "pages_unavailable", { bank: bankId });
3459
3526
  }
3460
3527
  }
3461
- const additionalContext = buildKnowledgePreamble(pages, {
3528
+ const additionalContext = buildPagesPreamble(pages, {
3462
3529
  reflectOnNewGoals: cfg.autoInject !== "reflect",
3463
3530
  extra: cfg.toolGuideExtra
3464
3531
  });
@@ -3648,7 +3715,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3648
3715
  }
3649
3716
  const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
3650
3717
  const entry = {
3651
- command: "node",
3718
+ command: hookNode(),
3652
3719
  args: [script],
3653
3720
  env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
3654
3721
  };
@@ -3959,6 +4026,27 @@ function readAntigravityTranscript(path) {
3959
4026
  }
3960
4027
  return turns;
3961
4028
  }
4029
+ function readAntigravityPromptTurn(path) {
4030
+ if (!path) return void 0;
4031
+ let lastRole;
4032
+ let lastUserPrompt;
4033
+ for (const line of readJsonl(path)) {
4034
+ try {
4035
+ const event = JSON.parse(line);
4036
+ const role = event.role ?? event.message?.role ?? event.type;
4037
+ if (!role || role === "CHECKPOINT" || role === "EPHEMERAL_MESSAGE") continue;
4038
+ lastRole = role;
4039
+ if (role === "user" || role === "USER_INPUT") {
4040
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
4041
+ const text = typeof content === "string" ? stripInjectedMemory(content) : "";
4042
+ const clean = unwrapUserRequest(text).trim();
4043
+ lastUserPrompt = clean || void 0;
4044
+ }
4045
+ } catch {
4046
+ }
4047
+ }
4048
+ return lastRole === "user" || lastRole === "USER_INPUT" ? lastUserPrompt : void 0;
4049
+ }
3962
4050
 
3963
4051
  // src/core/transcript-copilot.ts
3964
4052
  function readCopilotTranscript(path) {
@@ -4683,9 +4771,10 @@ var antigravityPrompt = {
4683
4771
  harness: "antigravity-cli",
4684
4772
  requireCwd: true,
4685
4773
  parse: (ev) => ({
4686
- // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
4687
- // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
4688
- prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
4774
+ // Antigravity's PreInvocation payload omits the prompt and fires before EVERY planner step in
4775
+ // the agent loop (including after every tool call). Read the transcript's trailing record so
4776
+ // only a genuine user submission returns a prompt and tool-result continuations are suppressed.
4777
+ prompt: readAntigravityPromptTurn(ev.transcriptPath),
4689
4778
  cwd: antigravityCwd(ev),
4690
4779
  sessionId: ev.conversationId
4691
4780
  }),