@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/kimi-hook.js CHANGED
@@ -283,7 +283,11 @@ function configuredDir(dir) {
283
283
  const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir2(), dir.slice(1)) : dir;
284
284
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
285
285
  }
286
- function isWithin(directory, configured) {
286
+ function isWithin(directory, configured, platform = process.platform) {
287
+ if (platform === "win32") {
288
+ directory = directory.toLowerCase();
289
+ configured = configured.toLowerCase();
290
+ }
287
291
  return directory === configured || directory.startsWith(configured + sep);
288
292
  }
289
293
  function mapLookup(map, directory) {
@@ -363,16 +367,93 @@ import { join as join7 } from "path";
363
367
 
364
368
  // src/core/seed.ts
365
369
  import { spawn as realSpawn } from "child_process";
366
- import { dirname as dirname4, join as join5 } from "path";
370
+ import { dirname as dirname4, join as join6 } from "path";
367
371
  import { fileURLToPath } from "url";
372
+
373
+ // src/core/util.ts
374
+ import { accessSync, constants, statSync as statSync2 } from "fs";
375
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
376
+ function binOnPath(bin, opts = {}) {
377
+ const platform = opts.platform ?? process.platform;
378
+ const env = opts.env ?? process.env;
379
+ const runnable = (file) => {
380
+ try {
381
+ if (!statSync2(file).isFile()) return false;
382
+ if (platform !== "win32") accessSync(file, constants.X_OK);
383
+ return true;
384
+ } catch {
385
+ return false;
386
+ }
387
+ };
388
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
389
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
390
+ for (const dir of (env.PATH || "").split(delimiter)) {
391
+ if (!dir) continue;
392
+ for (const name of names) {
393
+ const file = join5(dir, name);
394
+ if (runnable(file)) return resolve2(file);
395
+ }
396
+ }
397
+ return void 0;
398
+ }
399
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
400
+ function semverGte(version2, min) {
401
+ const parts = (v) => {
402
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
403
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
404
+ };
405
+ const a = version2 ? parts(version2) : void 0;
406
+ const b = parts(min);
407
+ if (!a || !b) return false;
408
+ for (let i = 0; i < 3; i++) {
409
+ if (a[i] !== b[i]) return a[i] > b[i];
410
+ }
411
+ return true;
412
+ }
413
+ async function pool(items, n, fn, onError, onProgress) {
414
+ let i = 0, done = 0;
415
+ async function worker() {
416
+ while (i < items.length) {
417
+ const idx = i++;
418
+ try {
419
+ await fn(items[idx], idx);
420
+ } catch (e) {
421
+ onError?.(idx, e);
422
+ }
423
+ onProgress?.(++done, items.length);
424
+ }
425
+ }
426
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
427
+ }
428
+ function nodeBinary() {
429
+ return process.versions.bun || process.versions.electron ? "node" : process.execPath;
430
+ }
431
+ function hookNode(opts = {}) {
432
+ const platform = opts.platform ?? process.platform;
433
+ if (platform === "win32" || binOnPath("node", opts)) return "node";
434
+ return nodeBinary();
435
+ }
436
+ function isOurMcpEntry(entry) {
437
+ if (!entry || typeof entry !== "object") return false;
438
+ const candidate = entry;
439
+ const command = typeof candidate.command === "string" ? candidate.command : "";
440
+ const bin = command.replaceAll("\\", "/").split("/").at(-1);
441
+ if (bin !== "node" && bin !== "node.exe" || !Array.isArray(candidate.args)) return false;
442
+ const script = candidate.args[0];
443
+ if (typeof script !== "string") return false;
444
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
445
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
446
+ }
447
+
448
+ // src/core/seed.ts
368
449
  var DEFAULT_SEED_LIMIT = 300;
369
450
  function startBackgroundSeed(repoDir, opts = {}) {
370
451
  try {
371
452
  const spawnFn = opts.spawn ?? realSpawn;
372
- const enginePath = opts.enginePath ?? join5(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
453
+ const enginePath = opts.enginePath ?? join6(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
373
454
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
374
455
  const child = spawnFn(
375
- "node",
456
+ nodeBinary(),
376
457
  [
377
458
  enginePath,
378
459
  "--repo",
@@ -398,7 +479,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
398
479
  import { createHash } from "crypto";
399
480
  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.";
400
481
  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.";
401
- 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.`;
482
+ 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.`;
402
483
  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.";
403
484
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
404
485
  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.";
@@ -441,14 +522,14 @@ var RETAIN_STRATEGIES = {
441
522
  retain_chunk_size: 12e3
442
523
  }
443
524
  };
444
- var KNOWLEDGE_LABELS = {
525
+ var PAGE_LABELS = {
445
526
  key: "knowledge",
446
527
  type: "multi-values",
447
528
  // 0, 1, or several — empty is normal
448
529
  optional: true,
449
530
  tag: true,
450
531
  // emits knowledge:<value> onto the fact's tags
451
- 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.",
532
+ 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.",
452
533
  values: [
453
534
  {
454
535
  value: "feature-work",
@@ -605,7 +686,7 @@ var CODING_BANK_TEMPLATE = {
605
686
  retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
606
687
  retain_default_strategy: "git",
607
688
  retain_strategies: RETAIN_STRATEGIES,
608
- entity_labels: [KNOWLEDGE_LABELS],
689
+ entity_labels: [PAGE_LABELS],
609
690
  entities_allow_free_form: true
610
691
  }
611
692
  };
@@ -657,49 +738,7 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
657
738
  }
658
739
 
659
740
  // package.json
660
- var version = "0.8.6";
661
-
662
- // src/core/util.ts
663
- import { accessSync, constants, statSync as statSync2 } from "fs";
664
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
665
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
666
- function semverGte(version2, min) {
667
- const parts = (v) => {
668
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
669
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
670
- };
671
- const a = version2 ? parts(version2) : void 0;
672
- const b = parts(min);
673
- if (!a || !b) return false;
674
- for (let i = 0; i < 3; i++) {
675
- if (a[i] !== b[i]) return a[i] > b[i];
676
- }
677
- return true;
678
- }
679
- async function pool(items, n, fn, onError, onProgress) {
680
- let i = 0, done = 0;
681
- async function worker() {
682
- while (i < items.length) {
683
- const idx = i++;
684
- try {
685
- await fn(items[idx], idx);
686
- } catch (e) {
687
- onError?.(idx, e);
688
- }
689
- onProgress?.(++done, items.length);
690
- }
691
- }
692
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
693
- }
694
- function isOurMcpEntry(entry) {
695
- if (!entry || typeof entry !== "object") return false;
696
- const candidate = entry;
697
- if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
698
- const script = candidate.args[0];
699
- if (typeof script !== "string") return false;
700
- const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
701
- return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
702
- }
741
+ var version = "0.8.8";
703
742
 
704
743
  // src/core/hindsight.ts
705
744
  var USER_AGENT = `hindsight-coding-agents/${version}`;
@@ -726,11 +765,11 @@ function retryAfterMs(header) {
726
765
  const at = Date.parse(header);
727
766
  return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
728
767
  }
729
- var KnowledgePagesUnavailableError = class extends Error {
730
- code = "knowledge_pages_unavailable";
768
+ var PagesUnavailableError = class extends Error {
769
+ code = "pages_unavailable";
731
770
  constructor() {
732
- super("Hindsight server does not support knowledge pages");
733
- this.name = "KnowledgePagesUnavailableError";
771
+ super("Hindsight server does not support pages");
772
+ this.name = "PagesUnavailableError";
734
773
  }
735
774
  };
736
775
  async function isEndpointMissing(r) {
@@ -741,6 +780,10 @@ async function isEndpointMissing(r) {
741
780
  return false;
742
781
  }
743
782
  }
783
+ function pagesPath(sub, legacy = false) {
784
+ if (!legacy) return `/pages${sub}`;
785
+ return /^\/(tree|folders|search|export|nodes)\b/.test(sub) ? `/knowledge-base${sub}` : `/knowledge-base/pages${sub}`;
786
+ }
744
787
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
745
788
  var ReflectError = class extends Error {
746
789
  constructor(message, status, timedOut, options) {
@@ -809,7 +852,7 @@ var HindsightClient = class {
809
852
  opIds = [];
810
853
  // async operation ids collected by retain(), for drain()
811
854
  /** Tri-state capability probe: unknown until the first page request, then cached. */
812
- knowledgePagesSupported;
855
+ pagesSupported;
813
856
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
814
857
  idempotentRetain;
815
858
  log;
@@ -907,7 +950,9 @@ var HindsightClient = class {
907
950
  }
908
951
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
909
952
  throw new Error(
910
- `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
953
+ // Query dropped: an encoded search query filled the 200-char error cap and pushed the
954
+ // status and the server's reason out of the tool error (#6341).
955
+ `${method} ${url.split("?")[0]} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
911
956
  );
912
957
  return r;
913
958
  }
@@ -1038,7 +1083,7 @@ var HindsightClient = class {
1038
1083
  return (j.total ?? j.items?.length ?? 0) > 0;
1039
1084
  }
1040
1085
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
1041
- * entity labels), then seed knowledge pages when the server supports them. Both halves are
1086
+ * entity labels), then seed pages when the server supports them. Both halves are
1042
1087
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
1043
1088
  * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
1044
1089
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
@@ -1053,6 +1098,15 @@ var HindsightClient = class {
1053
1098
  await this.req("DELETE", this.bankUrl());
1054
1099
  this.log(`[bank] reset ${this.bank}`);
1055
1100
  }
1101
+ await this.configureBankSettings(opts);
1102
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1103
+ }
1104
+ /** The config half of `configureBank` (missions, retain strategies, entity labels), without
1105
+ * seeding pages. Session start calls it directly when the deepen engine — the usual caller of
1106
+ * `configureBank` — will not run (`autoSeed: false`, or a directory with no git history):
1107
+ * without it such a bank never got the `conversation` strategy, and every session write-back
1108
+ * was extracted with the server's generic rules instead of the plugin's mission. */
1109
+ async configureBankSettings(opts = {}) {
1056
1110
  if (opts.manage === false) {
1057
1111
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
1058
1112
  } else {
@@ -1068,7 +1122,6 @@ var HindsightClient = class {
1068
1122
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
1069
1123
  }
1070
1124
  }
1071
- await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
1072
1125
  }
1073
1126
  /**
1074
1127
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -1220,29 +1273,45 @@ var HindsightClient = class {
1220
1273
  const j = await r.json();
1221
1274
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1222
1275
  }
1276
+ /** Set once a server answered on the deprecated `/knowledge-base/...` paths: one from before the
1277
+ * page routes moved to `/pages/...`. Remove in 2.x. */
1278
+ legacyPagesPaths = false;
1223
1279
  /**
1224
- * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1225
- * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1226
- * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1280
+ * Request a page endpoint by its `/pages` sub-path (`""`, `/tree`, `/<id>`, `/nodes/<id>`, …).
1281
+ *
1282
+ * Returns `null` — and latches `pagesSupported = false` — iff the endpoint is really absent: an
1283
+ * unrouted 404 on the `/pages` path AND on its pre-rename `/knowledge-base` twin, which a server
1284
+ * older than the rename still serves (tried once, then remembered). A bank-not-found 404 is NOT
1285
+ * a capability verdict — it is the expected answer before the bank's first retain — so it is
1286
+ * returned as-is and never caches a negative (#4607). A 404's body may already be consumed.
1227
1287
  *
1228
1288
  * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1229
1289
  * the 405/501 this used to check for never reach a caller in the first place.
1230
1290
  */
1231
- async pagesUnsupported(r) {
1232
- if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1233
- this.knowledgePagesSupported = false;
1234
- return true;
1291
+ async pagesReq(method, sub, body, tolerate = [], timeoutMs) {
1292
+ const send = (legacy) => this.req(method, this.bankUrl(pagesPath(sub, legacy)), body, tolerate, timeoutMs);
1293
+ let r = await send(this.legacyPagesPaths);
1294
+ if (r.status !== 404 || !await isEndpointMissing(r)) return r;
1295
+ if (!this.legacyPagesPaths) {
1296
+ r = await send(true);
1297
+ if (r.status !== 404 || !await isEndpointMissing(r)) {
1298
+ this.legacyPagesPaths = true;
1299
+ return r;
1300
+ }
1301
+ }
1302
+ this.pagesSupported = false;
1303
+ return null;
1235
1304
  }
1236
1305
  /**
1237
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1306
+ * The bank's page tree (folders + pages, nested). The tree carries names, source
1238
1307
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1239
1308
  */
1240
1309
  async tree() {
1241
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1242
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1243
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1310
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1311
+ const r = await this.pagesReq("GET", "/tree");
1312
+ if (!r) throw new PagesUnavailableError();
1244
1313
  if (r.status === 404) return [];
1245
- this.knowledgePagesSupported = true;
1314
+ this.pagesSupported = true;
1246
1315
  try {
1247
1316
  return (await r.json()).roots ?? [];
1248
1317
  } catch {
@@ -1250,13 +1319,13 @@ var HindsightClient = class {
1250
1319
  }
1251
1320
  }
1252
1321
  /**
1253
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1322
+ * List pages (ids + names only — no synthesized content), flattened out of the tree
1254
1323
  * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1255
1324
  * to read, and a caller enumerating pages wants leaves, not structure.
1256
1325
  *
1257
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1258
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
1259
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1326
+ * NOTE the ids are page node ids (`kp-…`), NOT the backing mental-model ids. Every
1327
+ * page read/update in this client goes through the same page ids, so a page id from
1328
+ * here, from `searchPages`, or from a `[[page:<id>]]` link all resolve identically.
1260
1329
  */
1261
1330
  async listPages() {
1262
1331
  const items = [];
@@ -1278,34 +1347,26 @@ var HindsightClient = class {
1278
1347
  return { items };
1279
1348
  }
1280
1349
  /**
1281
- * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1350
+ * Read one page's synthesized content by page id, shaped by `shapePage` so
1282
1351
  * the body arrives once. The endpoint omits the internal reflect trace that built
1283
1352
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1284
1353
  * token cap.
1285
1354
  */
1286
1355
  async getPage(pageId) {
1287
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1288
- const r = await this.req(
1289
- "GET",
1290
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1291
- );
1292
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1356
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1357
+ const r = await this.pagesReq("GET", `/${encodeURIComponent(pageId)}`);
1358
+ if (!r) throw new PagesUnavailableError();
1359
+ if (r.status === 404) throw new Error(`page not found: ${pageId}`);
1293
1360
  return shapePage(await r.json());
1294
1361
  }
1295
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1362
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's pages.
1296
1363
  * Returns page-level hits with a relevance snippet — the real search behind
1297
- * hindsight_search_knowledge_pages. */
1298
- async searchKnowledgePages(query, opts = {}) {
1299
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1364
+ * hindsight_search_pages. */
1365
+ async searchPages(query, opts = {}) {
1366
+ if (this.pagesSupported === false) throw new PagesUnavailableError();
1300
1367
  const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1301
- const r = await this.req(
1302
- "GET",
1303
- this.bankUrl(`/knowledge-base/search${q}`),
1304
- void 0,
1305
- [],
1306
- opts.timeoutMs
1307
- );
1308
- if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1368
+ const r = await this.pagesReq("GET", `/search${q}`, void 0, [], opts.timeoutMs);
1369
+ if (!r) throw new PagesUnavailableError();
1309
1370
  if (r.status === 404) return [];
1310
1371
  const j = await r.json();
1311
1372
  return (j.results ?? []).map((x) => ({
@@ -1317,9 +1378,9 @@ var HindsightClient = class {
1317
1378
  }));
1318
1379
  }
1319
1380
  /**
1320
- * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1381
+ * Seed the fixed page taxonomy as pages at the tree root, idempotently.
1321
1382
  *
1322
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1383
+ * Matched by NAME, not id: `POST /pages` mints its own `kp-…` id, so a stable
1323
1384
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1324
1385
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
1325
1386
  *
@@ -1334,8 +1395,8 @@ var HindsightClient = class {
1334
1395
  try {
1335
1396
  roots = await this.tree();
1336
1397
  } catch (e) {
1337
- if (e instanceof KnowledgePagesUnavailableError) {
1338
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1398
+ if (e instanceof PagesUnavailableError) {
1399
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1339
1400
  return;
1340
1401
  }
1341
1402
  throw e;
@@ -1358,11 +1419,9 @@ var HindsightClient = class {
1358
1419
  trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1359
1420
  };
1360
1421
  if (!hit) {
1361
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1362
- if (await this.pagesUnsupported(r)) {
1363
- this.log(
1364
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1365
- );
1422
+ const r = await this.pagesReq("POST", "", body, [409]);
1423
+ if (!r) {
1424
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1366
1425
  return;
1367
1426
  }
1368
1427
  if (r.status === 404) {
@@ -1383,15 +1442,9 @@ var HindsightClient = class {
1383
1442
  );
1384
1443
  }
1385
1444
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1386
- const r = await this.req(
1387
- "PATCH",
1388
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1389
- patch
1390
- );
1391
- if (await this.pagesUnsupported(r)) {
1392
- this.log(
1393
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1394
- );
1445
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(hit.id)}`, patch);
1446
+ if (!r) {
1447
+ this.log(`[bank] pages unavailable on ${this.apiUrl}; continuing without them`);
1395
1448
  return;
1396
1449
  }
1397
1450
  if (r.status === 404) {
@@ -1403,7 +1456,7 @@ var HindsightClient = class {
1403
1456
  }
1404
1457
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1405
1458
  this.log(
1406
- `[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` : "")
1459
+ `[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` : "")
1407
1460
  );
1408
1461
  }
1409
1462
  /**
@@ -1437,12 +1490,8 @@ var HindsightClient = class {
1437
1490
  if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1438
1491
  }
1439
1492
  if (!patch.trigger && !patch.source_query) continue;
1440
- const r = await this.req(
1441
- "PATCH",
1442
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1443
- patch
1444
- );
1445
- if (r.status === 404) continue;
1493
+ const r = await this.pagesReq("PATCH", `/nodes/${encodeURIComponent(page.id)}`, patch);
1494
+ if (!r || r.status === 404) continue;
1446
1495
  updated++;
1447
1496
  }
1448
1497
  return updated;
@@ -1468,7 +1517,7 @@ var HindsightClient = class {
1468
1517
  let pageId = args.relatesToPageId;
1469
1518
  if (!pageId) {
1470
1519
  const folderId = await this.ensureFolder("Initiatives");
1471
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1520
+ const r = await this.pagesReq("POST", "", {
1472
1521
  name: args.title,
1473
1522
  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),
1474
1523
  parent_id: folderId,
@@ -1477,8 +1526,8 @@ var HindsightClient = class {
1477
1526
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1478
1527
  });
1479
1528
  try {
1480
- const j = await r.json();
1481
- pageId = j.page_id ?? j.id;
1529
+ const j = await r?.json();
1530
+ pageId = j?.page_id ?? j?.id;
1482
1531
  } catch {
1483
1532
  }
1484
1533
  pageId ||= `initiative-${this.slugify(args.title)}`;
@@ -1496,16 +1545,17 @@ var HindsightClient = class {
1496
1545
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1497
1546
  async ensureFolder(name) {
1498
1547
  try {
1499
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1500
- const hit = (tree.roots || []).find(
1548
+ const r = await this.pagesReq("GET", "/tree");
1549
+ const tree = await r?.json();
1550
+ const hit = (tree?.roots || []).find(
1501
1551
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1502
1552
  );
1503
1553
  if (hit?.id) return hit.id;
1504
1554
  } catch {
1505
1555
  }
1506
1556
  try {
1507
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1508
- return (await r.json()).id;
1557
+ const r = await this.pagesReq("POST", "/folders", { name });
1558
+ return (await r?.json())?.id;
1509
1559
  } catch {
1510
1560
  return void 0;
1511
1561
  }
@@ -1903,6 +1953,63 @@ function resolvePartial(cfg, patch) {
1903
1953
  return out;
1904
1954
  }
1905
1955
 
1956
+ // src/core/transcript-util.ts
1957
+ var TOOL_TEXT_CAP = 2e3;
1958
+ 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;
1959
+ function stripInjectedMemory(s) {
1960
+ return s.replace(MEMORY_TAG_RE, "");
1961
+ }
1962
+ function truncate(s, max = TOOL_TEXT_CAP) {
1963
+ return s.length > max ? `${s.slice(0, max)}\u2026 (truncated)` : s;
1964
+ }
1965
+ var TARGET_KEYS = [
1966
+ "file_path",
1967
+ "path",
1968
+ "notebook_path",
1969
+ "command",
1970
+ "pattern",
1971
+ "query",
1972
+ "url",
1973
+ "name",
1974
+ "id"
1975
+ ];
1976
+ var ACTION_TARGET_CAP = 100;
1977
+ function actionLine(tool, input) {
1978
+ let target = "";
1979
+ if (input && typeof input === "object") {
1980
+ const rec = input;
1981
+ for (const k of TARGET_KEYS) {
1982
+ const v = rec[k];
1983
+ if (typeof v === "string" && v.trim()) {
1984
+ target = v.trim().split("\n")[0];
1985
+ break;
1986
+ }
1987
+ }
1988
+ } else if (typeof input === "string") {
1989
+ target = input.trim().split("\n")[0];
1990
+ }
1991
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1992
+ const line = target ? `${tool} ${target}` : tool;
1993
+ const note = memoryNoteText(input);
1994
+ return note ? `${line}
1995
+ ${truncate(note, MEMORY_NOTE_CAP)}` : line;
1996
+ }
1997
+ var MEMORY_NOTE_CAP = 8e3;
1998
+ var MEMORY_NOTE_PATH_RE = /(^|[\\/])(memory|memories)[\\/]|(^|[\\/])MEMORY\.md$/i;
1999
+ var MEMORY_SHELL_WRITE_RE = /[\\/](memory|memories)([\\/\s"']|$)|MEMORY\.md/i;
2000
+ var SHELL_WRITE_RE = /(^|[^0-9&>])>>?(?!&)|\btee\b/;
2001
+ function memoryNoteText(input) {
2002
+ if (!input || typeof input !== "object") return "";
2003
+ const rec = input;
2004
+ const cmd = rec.command;
2005
+ if (typeof cmd === "string")
2006
+ return MEMORY_SHELL_WRITE_RE.test(cmd) && SHELL_WRITE_RE.test(cmd) ? cmd.trim() : "";
2007
+ const path = rec.file_path ?? rec.path;
2008
+ if (typeof path !== "string" || !MEMORY_NOTE_PATH_RE.test(path)) return "";
2009
+ const text = rec.content ?? rec.new_string;
2010
+ return typeof text === "string" ? text.trim() : "";
2011
+ }
2012
+
1906
2013
  // src/core/brand.ts
1907
2014
  function brandWord() {
1908
2015
  const start = [0, 116, 217];
@@ -1933,8 +2040,8 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
1933
2040
  - 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.
1934
2041
  - If the bank holds nothing that bears on the goal, say so in one line.`;
1935
2042
  }
1936
- 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.)";
1937
- var PAGE_INJECT_LEAD = "(These knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)";
2043
+ 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.)";
2044
+ var PAGE_INJECT_LEAD = "(These pages matched the goal by search. Read one with hindsight_read_page(<id>) if it looks relevant.)";
1938
2045
  function formatPageFallback(hits, lead = PAGE_FALLBACK_LEAD) {
1939
2046
  return `${lead}
1940
2047
  ` + hits.map((h) => {
@@ -1961,7 +2068,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
1961
2068
  ` + memory + "\n</hindsight_memory>";
1962
2069
  }
1963
2070
 
1964
- // src/core/knowledge-injection.ts
2071
+ // src/core/page-injection.ts
1965
2072
  function parsePageList(raw) {
1966
2073
  const items = raw?.items;
1967
2074
  if (!Array.isArray(items)) return [];
@@ -1974,22 +2081,22 @@ function parsePageList(raw) {
1974
2081
  return out;
1975
2082
  }
1976
2083
  function indexLine(pages) {
1977
- const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1978
- 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.`;
2084
+ const count = pages.length === 1 ? "1 page covers" : `${pages.length} pages cover`;
2085
+ 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.`;
1979
2086
  }
1980
- 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:
2087
+ 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:
1981
2088
  \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);
1982
2089
  \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);
1983
2090
  \u2022 you are implementing something new, or two parts have to fit together;
1984
2091
  \u2022 the user asks why something is the way it is, or what is left to do;
1985
2092
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1986
- 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.
2093
+ 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.
1987
2094
  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.
1988
- - 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.
2095
+ - 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.
1989
2096
  - 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>").
1990
2097
  - 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.
1991
2098
  - 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).`;
1992
- 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";
2099
+ 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";
1993
2100
  function toolGuide(opts) {
1994
2101
  const extra = opts?.extra?.trim();
1995
2102
  return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
@@ -1998,9 +2105,9 @@ ${extra}` : "");
1998
2105
  function buildRosterRefresh(pages, opts) {
1999
2106
  const rosterBlock = pages.length ? `${indexLine(pages)}
2000
2107
  ` : "";
2001
- return "<hindsight_knowledge_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2108
+ return "<hindsight_page_refresh>\n" + rosterBlock + `Reminder \u2014 this repo's Hindsight tools are available; call them at the right moments:
2002
2109
  ${toolGuide(opts)}
2003
- </hindsight_knowledge_refresh>`;
2110
+ </hindsight_page_refresh>`;
2004
2111
  }
2005
2112
 
2006
2113
  // src/core/session-cache.ts
@@ -2089,43 +2196,6 @@ function sessionRootDir(harness, sessionId, cwd) {
2089
2196
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
2090
2197
  import { tmpdir as tmpdir2 } from "os";
2091
2198
  import { dirname as dirname6, join as join9 } from "path";
2092
-
2093
- // src/core/transcript-util.ts
2094
- 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;
2095
- function stripInjectedMemory(s) {
2096
- return s.replace(MEMORY_TAG_RE, "");
2097
- }
2098
- var TARGET_KEYS = [
2099
- "file_path",
2100
- "path",
2101
- "notebook_path",
2102
- "command",
2103
- "pattern",
2104
- "query",
2105
- "url",
2106
- "name",
2107
- "id"
2108
- ];
2109
- var ACTION_TARGET_CAP = 100;
2110
- function actionLine(tool, input) {
2111
- let target = "";
2112
- if (input && typeof input === "object") {
2113
- const rec = input;
2114
- for (const k of TARGET_KEYS) {
2115
- const v = rec[k];
2116
- if (typeof v === "string" && v.trim()) {
2117
- target = v.trim().split("\n")[0];
2118
- break;
2119
- }
2120
- }
2121
- } else if (typeof input === "string") {
2122
- target = input.trim().split("\n")[0];
2123
- }
2124
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
2125
- return target ? `${tool} ${target}` : tool;
2126
- }
2127
-
2128
- // src/core/turn-journal.ts
2129
2199
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
2130
2200
  function journalPath(harness, sessionId) {
2131
2201
  return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
@@ -2204,7 +2274,7 @@ function boundRecallQuery(prompt) {
2204
2274
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
2205
2275
  const t0 = Date.now();
2206
2276
  try {
2207
- const hits = await client.searchKnowledgePages(prompt.slice(0, 500), { timeoutMs });
2277
+ const hits = await client.searchPages(prompt.slice(0, 500), { timeoutMs });
2208
2278
  diag(harness, event, { ms: Date.now() - t0, count: hits.length });
2209
2279
  return hits.length ? formatPageFallback(hits, lead) : null;
2210
2280
  } catch (e) {
@@ -2318,14 +2388,10 @@ async function buildHookOutput(args) {
2318
2388
  pages = parsePageList(await client.listPages());
2319
2389
  diag(harness, "pages_ok", { ms: Date.now() - t0, count: pages.length });
2320
2390
  } catch (e) {
2321
- diag(
2322
- harness,
2323
- client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
2324
- {
2325
- ms: Date.now() - t0,
2326
- error: describeError(e)
2327
- }
2328
- );
2391
+ diag(harness, client.pagesSupported === false ? "pages_unavailable" : "pages_failed", {
2392
+ ms: Date.now() - t0,
2393
+ error: describeError(e)
2394
+ });
2329
2395
  }
2330
2396
  }
2331
2397
  writeSessionCache(cacheFile, {
@@ -2336,7 +2402,7 @@ async function buildHookOutput(args) {
2336
2402
  });
2337
2403
  const blocks = [];
2338
2404
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
2339
- if (cadence > 0 && turns % cadence === 0) {
2405
+ if (cadence > 0 && turns % cadence === 0 && !(turns === 1 && args.preambleOnFirstTurn)) {
2340
2406
  blocks.push(
2341
2407
  buildRosterRefresh(pages, {
2342
2408
  reflectOnNewGoals: cfg.autoInject !== "reflect",
@@ -2372,7 +2438,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2372
2438
  }
2373
2439
  if (spec.requireCwd && !rawCwd) return;
2374
2440
  const cwd = rawCwd || process.cwd();
2375
- const prompt = (rawPrompt || "").trim();
2441
+ const prompt = stripInjectedMemory(rawPrompt || "").trim();
2376
2442
  if (!prompt) return;
2377
2443
  let cfg = loadConfig({ harness: spec.harness });
2378
2444
  setLogLevel(cfg.logLevel);
@@ -2408,7 +2474,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2408
2474
  startBackgroundSeed(cwd, { limit: cfg.seedLimit, harness: spec.harness });
2409
2475
  }
2410
2476
  const output = await buildHookOutput({ harness: spec.harness, prompt, cfg, client, cacheFile });
2411
- if (cfg.autoSeed !== false && client.knowledgePagesSupported !== false && output.pages.length === 0) {
2477
+ if (cfg.autoSeed !== false && client.pagesSupported !== false && output.pages.length === 0) {
2412
2478
  startBackgroundSeed(cwd, { limit: cfg.seedLimit, harness: spec.harness });
2413
2479
  }
2414
2480
  let context = output.context;
@@ -2659,7 +2725,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2659
2725
  }
2660
2726
  const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2661
2727
  const entry = {
2662
- command: "node",
2728
+ command: hookNode(),
2663
2729
  args: [script],
2664
2730
  env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2665
2731
  };
@@ -2970,6 +3036,27 @@ function readAntigravityTranscript(path) {
2970
3036
  }
2971
3037
  return turns;
2972
3038
  }
3039
+ function readAntigravityPromptTurn(path) {
3040
+ if (!path) return void 0;
3041
+ let lastRole;
3042
+ let lastUserPrompt;
3043
+ for (const line of readJsonl(path)) {
3044
+ try {
3045
+ const event = JSON.parse(line);
3046
+ const role = event.role ?? event.message?.role ?? event.type;
3047
+ if (!role || role === "CHECKPOINT" || role === "EPHEMERAL_MESSAGE") continue;
3048
+ lastRole = role;
3049
+ if (role === "user" || role === "USER_INPUT") {
3050
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
3051
+ const text = typeof content === "string" ? stripInjectedMemory(content) : "";
3052
+ const clean = unwrapUserRequest(text).trim();
3053
+ lastUserPrompt = clean || void 0;
3054
+ }
3055
+ } catch {
3056
+ }
3057
+ }
3058
+ return lastRole === "user" || lastRole === "USER_INPUT" ? lastUserPrompt : void 0;
3059
+ }
2973
3060
 
2974
3061
  // src/core/transcript-copilot.ts
2975
3062
  function readCopilotTranscript(path) {
@@ -3694,9 +3781,10 @@ var antigravityPrompt = {
3694
3781
  harness: "antigravity-cli",
3695
3782
  requireCwd: true,
3696
3783
  parse: (ev) => ({
3697
- // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
3698
- // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
3699
- prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
3784
+ // Antigravity's PreInvocation payload omits the prompt and fires before EVERY planner step in
3785
+ // the agent loop (including after every tool call). Read the transcript's trailing record so
3786
+ // only a genuine user submission returns a prompt and tool-result continuations are suppressed.
3787
+ prompt: readAntigravityPromptTurn(ev.transcriptPath),
3700
3788
  cwd: antigravityCwd(ev),
3701
3789
  sessionId: ev.conversationId
3702
3790
  }),