@vectorize-io/hindsight-coding-agents 0.8.0 → 0.8.2

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 +73 -8
  2. package/dist/antigravity-hook.js +444 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +444 -95
  5. package/dist/claude-hook.js +444 -80
  6. package/dist/claude-sessionstart-hook.js +476 -93
  7. package/dist/claude-stop-hook.js +444 -95
  8. package/dist/cline.js +322 -122
  9. package/dist/codebuddy-hook.js +4273 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5033 -0
  11. package/dist/codebuddy-stop-hook.js +4567 -0
  12. package/dist/codex-hook.js +444 -80
  13. package/dist/codex-sessionstart-hook.js +476 -93
  14. package/dist/codex-stop-hook.js +444 -95
  15. package/dist/copilot-hook.js +444 -80
  16. package/dist/copilot-sessionstart-hook.js +476 -93
  17. package/dist/copilot-stop-hook.js +444 -95
  18. package/dist/cursor-hook.js +444 -80
  19. package/dist/cursor-sessionstart-hook.js +476 -93
  20. package/dist/cursor-stop-hook.js +444 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +444 -80
  23. package/dist/dcode-sessionstart-hook.js +476 -93
  24. package/dist/dcode-stop-hook.js +444 -95
  25. package/dist/deepen.js +252 -79
  26. package/dist/devin-hook.js +444 -80
  27. package/dist/devin-sessionstart-hook.js +476 -93
  28. package/dist/devin-stop-hook.js +444 -95
  29. package/dist/droid-hook.js +444 -80
  30. package/dist/droid-sessionstart-hook.js +476 -93
  31. package/dist/droid-stop-hook.js +444 -95
  32. package/dist/dsh.js +329 -122
  33. package/dist/grok-hook.js +444 -80
  34. package/dist/grok-sessionstart-hook.js +476 -93
  35. package/dist/grok-stop-hook.js +444 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +331 -131
  38. package/dist/installer.js +1046 -647
  39. package/dist/kilo.js +331 -131
  40. package/dist/kimi-hook.js +444 -80
  41. package/dist/kimi-sessionstart-hook.js +476 -93
  42. package/dist/kimi-stop-hook.js +444 -95
  43. package/dist/mcp-server.js +272 -89
  44. package/dist/opencode2.js +328 -128
  45. package/dist/pi.js +384 -134
  46. package/dist/prime-agent.js +384 -134
  47. package/dist/qwen-hook.js +444 -80
  48. package/dist/qwen-sessionstart-hook.js +476 -93
  49. package/dist/qwen-stop-hook.js +444 -95
  50. package/dist/status.js +124 -43
  51. package/dist/traecode-hook.js +444 -80
  52. package/dist/traecode-sessionstart-hook.js +476 -93
  53. package/dist/traecode-stop-hook.js +444 -95
  54. package/dist/workbuddy-hook.js +4273 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5033 -0
  56. package/dist/workbuddy-stop-hook.js +4567 -0
  57. package/dist/zcode-hook.js +444 -80
  58. package/dist/zcode-sessionstart-hook.js +476 -93
  59. package/dist/zcode-stop-hook.js +444 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +10 -6
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/hook.ts
4
- import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
4
+ import { existsSync as existsSync2 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
7
  import { existsSync } from "fs";
@@ -9,6 +9,7 @@ import { homedir as homedir2 } from "os";
9
9
  import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
10
10
 
11
11
  // src/core/diag.ts
12
+ import { readFileSync } from "fs";
12
13
  import { join as join2 } from "path";
13
14
 
14
15
  // src/core/log.ts
@@ -82,9 +83,30 @@ function diag(harness, event, extra = {}) {
82
83
  } catch {
83
84
  }
84
85
  }
86
+ function parseHookEvent(harness, raw) {
87
+ const text = raw.replace(/^(?:|)+/, "");
88
+ if (!text.trim()) return null;
89
+ try {
90
+ const ev = JSON.parse(text);
91
+ if (ev && typeof ev === "object" && !Array.isArray(ev)) return ev;
92
+ diag(harness, "hook_input_invalid", { error: "not a JSON object" });
93
+ } catch (e) {
94
+ diag(harness, "hook_input_invalid", { error: e.message });
95
+ }
96
+ return null;
97
+ }
98
+ function readHookEvent(harness) {
99
+ let raw;
100
+ try {
101
+ raw = readFileSync(0, "utf8");
102
+ } catch {
103
+ return null;
104
+ }
105
+ return parseHookEvent(harness, raw);
106
+ }
85
107
 
86
108
  // src/core/git-layout.ts
87
- import { lstatSync, readFileSync, realpathSync } from "fs";
109
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
88
110
  import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
89
111
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
90
112
  var ATTEMPTS = 3;
@@ -108,7 +130,7 @@ function entryKind(path) {
108
130
  }
109
131
  function readTextOrNull(path) {
110
132
  try {
111
- return readFileSync(path, "utf8");
133
+ return readFileSync2(path, "utf8");
112
134
  } catch (error) {
113
135
  if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
114
136
  return null;
@@ -338,7 +360,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
338
360
  }
339
361
 
340
362
  // src/core/config.ts
341
- import { readFileSync as readFileSync2 } from "fs";
363
+ import { readFileSync as readFileSync3 } from "fs";
342
364
  import { homedir as homedir3 } from "os";
343
365
  import { join as join7 } from "path";
344
366
 
@@ -351,7 +373,7 @@ var DEFAULT_SEED_LIMIT = 300;
351
373
  // src/core/missions.ts
352
374
  import { createHash } from "crypto";
353
375
  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.";
354
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest 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.";
376
+ 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.";
355
377
  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.`;
356
378
  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.";
357
379
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -427,6 +449,8 @@ var KNOWLEDGE_LABELS = {
427
449
  ]
428
450
  };
429
451
  function pageScopeRule(project) {
452
+ if (project === void 0)
453
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
430
454
  return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
431
455
  }
432
456
  var PAGE_TAXONOMY = [
@@ -608,16 +632,19 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
608
632
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
609
633
  }
610
634
 
635
+ // package.json
636
+ var version = "0.8.2";
637
+
611
638
  // src/core/util.ts
612
639
  import { accessSync, constants } from "fs";
613
640
  import { delimiter, join as join6 } from "path";
614
641
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
615
- function semverGte(version, min) {
642
+ function semverGte(version2, min) {
616
643
  const parts = (v) => {
617
644
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
618
645
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
619
646
  };
620
- const a = version ? parts(version) : void 0;
647
+ const a = version2 ? parts(version2) : void 0;
621
648
  const b = parts(min);
622
649
  if (!a || !b) return false;
623
650
  for (let i = 0; i < 3; i++) {
@@ -651,6 +678,7 @@ function isOurMcpEntry(entry) {
651
678
  }
652
679
 
653
680
  // src/core/hindsight.ts
681
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
654
682
  function resolveRetainScopes(tags, configured) {
655
683
  if (configured !== "per_source") return configured;
656
684
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -686,7 +714,7 @@ async function isEndpointMissing(r) {
686
714
  const j = await r.json();
687
715
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
688
716
  } catch {
689
- return true;
717
+ return false;
690
718
  }
691
719
  }
692
720
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -705,6 +733,12 @@ var ReflectError = class extends Error {
705
733
  get fallbackEligible() {
706
734
  return this.timedOut || this.status !== void 0 && this.status >= 500;
707
735
  }
736
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
737
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
738
+ get permanent() {
739
+ const s = this.status;
740
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
741
+ }
708
742
  };
709
743
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
710
744
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -715,8 +749,10 @@ var DEFAULT_RECALL_OPTIONS = {
715
749
  include: { entities: null }
716
750
  };
717
751
  var POLL_CYCLE_MS = 5e3;
752
+ var POLL_MAX_SERVER_ERRORS = 12;
718
753
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
719
754
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
755
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
720
756
  function shapePage(page) {
721
757
  const p = page ?? {};
722
758
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -729,6 +765,15 @@ function shapePage(page) {
729
765
  body
730
766
  };
731
767
  }
768
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
769
+ function signalOnlyDispatcher() {
770
+ void globalThis.Headers;
771
+ const d = globalThis[GLOBAL_DISPATCHER];
772
+ if (typeof d?.compose !== "function") return void 0;
773
+ return d.compose(
774
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
775
+ );
776
+ }
732
777
  var HindsightClient = class {
733
778
  apiUrl;
734
779
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -748,6 +793,7 @@ var HindsightClient = class {
748
793
  observationScopes;
749
794
  pageSearchLimit;
750
795
  recallOptions;
796
+ rateLimitPatienceMs;
751
797
  constructor(o) {
752
798
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
753
799
  this.token = o.apiToken;
@@ -760,6 +806,7 @@ var HindsightClient = class {
760
806
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
761
807
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
762
808
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
809
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
763
810
  }
764
811
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
765
812
  get apiToken() {
@@ -768,7 +815,8 @@ var HindsightClient = class {
768
815
  headers() {
769
816
  const h = {
770
817
  "Content-Type": "application/json",
771
- "Accept-Encoding": "identity"
818
+ "Accept-Encoding": "identity",
819
+ "User-Agent": USER_AGENT
772
820
  };
773
821
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
774
822
  return h;
@@ -800,7 +848,8 @@ var HindsightClient = class {
800
848
  * bounds the whole call.
801
849
  */
802
850
  async fetchWithAuth(url, init) {
803
- const send = () => fetch(url, { ...init, headers: this.headers() });
851
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
852
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
804
853
  const r = await send();
805
854
  if (r.status !== 401 || !this.refreshToken()) return r;
806
855
  return send();
@@ -816,13 +865,22 @@ var HindsightClient = class {
816
865
  }
817
866
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
818
867
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
819
- const r = await this.fetchWithAuth(url, {
820
- method,
821
- body: body ? JSON.stringify(body) : void 0,
822
- signal: AbortSignal.timeout(timeoutMs)
823
- });
824
- if (r.status === 429 && !tolerate.includes(429))
825
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
868
+ const payload = body ? JSON.stringify(body) : void 0;
869
+ let r;
870
+ for (let attempt = 0, waited = 0; ; attempt++) {
871
+ r = await this.fetchWithAuth(url, {
872
+ method,
873
+ body: payload,
874
+ signal: AbortSignal.timeout(timeoutMs)
875
+ });
876
+ if (r.status !== 429 || tolerate.includes(429)) break;
877
+ const asked = retryAfterMs(r.headers.get("retry-after"));
878
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
879
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
880
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
881
+ await sleep(wait);
882
+ waited += wait;
883
+ }
826
884
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
827
885
  throw new Error(
828
886
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -857,7 +915,7 @@ var HindsightClient = class {
857
915
  }
858
916
  /**
859
917
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
860
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
918
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
861
919
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
862
920
  */
863
921
  async supportsIdempotentRetain() {
@@ -867,15 +925,21 @@ var HindsightClient = class {
867
925
  }
868
926
  return this.idempotentRetain;
869
927
  }
928
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
929
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
930
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
931
+ * `/version`, so that stays as the fallback. */
870
932
  async probeIdempotentRetain() {
871
- try {
872
- const r = await this.req("GET", `${this.apiUrl}/version`);
873
- if (!r.ok) return false;
874
- const j = await r.json();
875
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
876
- } catch {
877
- return false;
933
+ for (const path of ["/v1/version", "/version"]) {
934
+ try {
935
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
936
+ if (!r.ok) continue;
937
+ const j = await r.json();
938
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
939
+ } catch {
940
+ }
878
941
  }
942
+ return false;
879
943
  }
880
944
  /**
881
945
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -937,6 +1001,14 @@ var HindsightClient = class {
937
1001
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
938
1002
  }
939
1003
  }
1004
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1005
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1006
+ async hasDocuments() {
1007
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1008
+ if (r.status === 404) return false;
1009
+ const j = await r.json();
1010
+ return (j.total ?? j.items?.length ?? 0) > 0;
1011
+ }
940
1012
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
941
1013
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
942
1014
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1018,7 +1090,13 @@ var HindsightClient = class {
1018
1090
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1019
1091
  const start = Date.now();
1020
1092
  const pending = new Set(ids);
1093
+ const serverErrors = /* @__PURE__ */ new Map();
1021
1094
  let failed = 0;
1095
+ const giveUp = (id, status) => {
1096
+ pending.delete(id);
1097
+ failed++;
1098
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1099
+ };
1022
1100
  while (pending.size && Date.now() - start < maxMs) {
1023
1101
  let backoffMs = POLL_CYCLE_MS;
1024
1102
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1031,7 +1109,14 @@ var HindsightClient = class {
1031
1109
  );
1032
1110
  return;
1033
1111
  }
1034
- if (!r.ok) return;
1112
+ if (r.status >= 500) {
1113
+ const n = (serverErrors.get(id) ?? 0) + 1;
1114
+ serverErrors.set(id, n);
1115
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1116
+ return;
1117
+ }
1118
+ if (!r.ok) return giveUp(id, r.status);
1119
+ serverErrors.delete(id);
1035
1120
  const st = ((await r.json()).status || "").toLowerCase();
1036
1121
  if (TERMINAL.has(st)) {
1037
1122
  pending.delete(id);
@@ -1215,7 +1300,7 @@ var HindsightClient = class {
1215
1300
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1216
1301
  */
1217
1302
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1218
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1303
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1219
1304
  const existing = /* @__PURE__ */ new Map();
1220
1305
  let roots;
1221
1306
  try {
@@ -1290,7 +1375,7 @@ var HindsightClient = class {
1290
1375
  }
1291
1376
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1292
1377
  this.log(
1293
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1378
+ `[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` : "")
1294
1379
  );
1295
1380
  }
1296
1381
  /**
@@ -1301,23 +1386,33 @@ var HindsightClient = class {
1301
1386
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1302
1387
  * consolidation under the auto-refresh that used to be the default (#3506).
1303
1388
  *
1304
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1305
- * initiative's own title, and re-stating either would rebuild a page whose question never
1306
- * changed. The tree read above is reused rather than re-fetched.
1389
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1390
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1391
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1392
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1393
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1394
+ * reused rather than re-fetched.
1307
1395
  */
1308
1396
  async resyncInitiativeTriggers(roots, pageTrigger) {
1309
1397
  const folder = roots.find(
1310
1398
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1311
1399
  );
1400
+ const bankScope = pageScopeRule(this.bank);
1312
1401
  let updated = 0;
1313
1402
  for (const page of folder?.children ?? []) {
1314
- if (page.kind !== "page" || page.trigger == null) continue;
1315
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1316
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1403
+ if (page.kind !== "page") continue;
1404
+ const patch = {};
1405
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1406
+ if (query !== page.description) patch.source_query = query;
1407
+ if (page.trigger != null) {
1408
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1409
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1410
+ }
1411
+ if (!patch.trigger && !patch.source_query) continue;
1317
1412
  const r = await this.req(
1318
1413
  "PATCH",
1319
1414
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1320
- { trigger: pageTriggerPatch(desired) }
1415
+ patch
1321
1416
  );
1322
1417
  if (r.status === 404) continue;
1323
1418
  updated++;
@@ -1345,10 +1440,9 @@ var HindsightClient = class {
1345
1440
  let pageId = args.relatesToPageId;
1346
1441
  if (!pageId) {
1347
1442
  const folderId = await this.ensureFolder("Initiatives");
1348
- const subject = this.project ?? this.bank;
1349
1443
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1350
1444
  name: args.title,
1351
- 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(subject),
1445
+ 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),
1352
1446
  parent_id: folderId,
1353
1447
  tags: ["knowledge:feature-work"],
1354
1448
  max_tokens: PAGE_MAX_TOKENS,
@@ -1363,7 +1457,7 @@ var HindsightClient = class {
1363
1457
  }
1364
1458
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1365
1459
  const content = `${verb}: ${args.title}. ${args.summary}`;
1366
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1460
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1367
1461
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1368
1462
  const context = `initiative marker for [[page:${pageId}]]`;
1369
1463
  await this.retain(content, context, markerId, tags, "document", {
@@ -1600,7 +1694,7 @@ function resolveConfig(raw = {}) {
1600
1694
  }
1601
1695
  function readRaw(path) {
1602
1696
  try {
1603
- return JSON.parse(readFileSync2(path, "utf8"));
1697
+ return JSON.parse(readFileSync3(path, "utf8"));
1604
1698
  } catch (e) {
1605
1699
  if (e?.code !== "ENOENT") {
1606
1700
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1782,7 +1876,7 @@ function resolvePartial(cfg, patch) {
1782
1876
  }
1783
1877
 
1784
1878
  // src/core/session-cache.ts
1785
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1879
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1786
1880
  import { tmpdir } from "os";
1787
1881
  import { dirname as dirname5, join as join8 } from "path";
1788
1882
  function writeFileAtomic(path, body) {
@@ -1806,7 +1900,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1806
1900
  if (!sessionId || !cwd) return cwd;
1807
1901
  const file = sessionRootFile(harness, sessionId);
1808
1902
  try {
1809
- const recorded = readFileSync3(file, "utf8").trim();
1903
+ const recorded = readFileSync4(file, "utf8").trim();
1810
1904
  if (recorded) return recorded;
1811
1905
  } catch {
1812
1906
  }
@@ -1821,7 +1915,7 @@ function fileUsageCursorStore(harness) {
1821
1915
  return {
1822
1916
  read: (sessionId) => {
1823
1917
  try {
1824
- const turns = JSON.parse(readFileSync3(file(sessionId), "utf8")).turns;
1918
+ const turns = JSON.parse(readFileSync4(file(sessionId), "utf8")).turns;
1825
1919
  return typeof turns === "number" ? turns : void 0;
1826
1920
  } catch {
1827
1921
  return void 0;
@@ -1842,7 +1936,7 @@ function fileCursorStore(harness) {
1842
1936
  return {
1843
1937
  read: (sessionId) => {
1844
1938
  try {
1845
- return JSON.parse(readFileSync3(cursorFile(harness, sessionId), "utf8"));
1939
+ return JSON.parse(readFileSync4(cursorFile(harness, sessionId), "utf8"));
1846
1940
  } catch {
1847
1941
  return void 0;
1848
1942
  }
@@ -1857,7 +1951,7 @@ function fileCursorStore(harness) {
1857
1951
  }
1858
1952
 
1859
1953
  // src/core/turn-journal.ts
1860
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1954
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1861
1955
  import { tmpdir as tmpdir2 } from "os";
1862
1956
  import { dirname as dirname6, join as join9 } from "path";
1863
1957
 
@@ -1926,7 +2020,7 @@ function appendJournalTurn(path, turn) {
1926
2020
  function readJournalTranscript(path) {
1927
2021
  let body;
1928
2022
  try {
1929
- body = readFileSync4(path, "utf8");
2023
+ body = readFileSync5(path, "utf8");
1930
2024
  } catch {
1931
2025
  return [];
1932
2026
  }
@@ -1952,9 +2046,6 @@ function readJournalTranscript(path) {
1952
2046
  return turns;
1953
2047
  }
1954
2048
 
1955
- // src/core/retain-hook.ts
1956
- import { readFileSync as readFileSync7 } from "fs";
1957
-
1958
2049
  // src/core/retain-cursor.ts
1959
2050
  import { createHash as createHash2 } from "crypto";
1960
2051
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
@@ -1970,6 +2061,7 @@ function pendingReplayable(cursor, now) {
1970
2061
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
1971
2062
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
1972
2063
  }
2064
+ var MAX_CURSOR_OPS = 8;
1973
2065
  function fingerprintTurns(turns, count) {
1974
2066
  const h = createHash2("sha1").update(String(count));
1975
2067
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -2023,6 +2115,31 @@ async function supportsAppend(client) {
2023
2115
  return false;
2024
2116
  }
2025
2117
  }
2118
+ var OP_CHECK_TIMEOUT_MS = 5e3;
2119
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
2120
+ async function settleOps(client, cursor) {
2121
+ const ops = cursor.ops ?? [];
2122
+ const statuses = await Promise.all(
2123
+ ops.map(async (id) => {
2124
+ try {
2125
+ const r = await client.req(
2126
+ "GET",
2127
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
2128
+ void 0,
2129
+ [],
2130
+ OP_CHECK_TIMEOUT_MS
2131
+ );
2132
+ if (r.status === 404) return "not_found";
2133
+ return String((await r.json()).status ?? "").toLowerCase();
2134
+ } catch {
2135
+ return "";
2136
+ }
2137
+ })
2138
+ );
2139
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
2140
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
2141
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
2142
+ }
2026
2143
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
2027
2144
  var RETAIN_RETRY_ATTEMPTS = 2;
2028
2145
  var REQUEST_BUDGET_MS = 15e3;
@@ -2086,13 +2203,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
2086
2203
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
2087
2204
  if (!turns.length) return;
2088
2205
  const refId = `conversation:${sessionId}`;
2089
- const cursor = cursors?.read(sessionId);
2206
+ let cursor = cursors?.read(sessionId);
2207
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
2090
2208
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
2209
+ let ops = [];
2210
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
2211
+ ({ cursor, ops } = await settleOps(client, cursor));
2091
2212
  const plan = planRetain(turns, cursor, {
2092
2213
  appendSupported,
2093
2214
  bank: client.bank,
2094
2215
  path: transcriptPath
2095
2216
  });
2217
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
2096
2218
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
2097
2219
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
2098
2220
  if (plan.mode === "skip" && !outbox.length) return;
@@ -2138,6 +2260,10 @@ ${content}`);
2138
2260
  ...paths ? { paths } : {},
2139
2261
  ...appendSupported ? { appendSupported: true } : {}
2140
2262
  };
2263
+ const accepted = (id) => {
2264
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
2265
+ return ops.length ? { ...next, ops } : next;
2266
+ };
2141
2267
  const stillOurs = () => {
2142
2268
  if (!cursors) return true;
2143
2269
  const now = cursors.read(sessionId);
@@ -2146,12 +2272,10 @@ ${content}`);
2146
2272
  if (plan.mode === "replace") {
2147
2273
  const content = renderSessionJsonl(refId, turns, startTs);
2148
2274
  cursors?.write(sessionId, { ...next, dirty: true });
2149
- await submitWithRetry(
2150
- () => submit(content, opId("replace", content), false),
2151
- stillOurs,
2152
- retryUntil
2153
- );
2154
- cursors?.write(sessionId, next);
2275
+ const operationId = opId("replace", content);
2276
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
2277
+ ops = [];
2278
+ cursors?.write(sessionId, accepted(operationId));
2155
2279
  return;
2156
2280
  }
2157
2281
  const queue = [...outbox];
@@ -2159,7 +2283,7 @@ ${content}`);
2159
2283
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
2160
2284
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
2161
2285
  }
2162
- cursors?.write(sessionId, { ...next, pending: queue });
2286
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
2163
2287
  for (let i = 0; i < queue.length; i++) {
2164
2288
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
2165
2289
  const entry = queue[i];
@@ -2169,7 +2293,8 @@ ${content}`);
2169
2293
  retryUntil
2170
2294
  );
2171
2295
  const remaining = queue.slice(i + 1);
2172
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
2296
+ const done = accepted(entry.operationId);
2297
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
2173
2298
  }
2174
2299
  }
2175
2300
 
@@ -2180,7 +2305,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
2180
2305
  var DAEMON_WAIT_RETAIN_MS = 4e4;
2181
2306
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2182
2307
  try {
2183
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2308
+ const res = await fetch(`${baseUrl}/health`, {
2309
+ headers: { "User-Agent": USER_AGENT },
2310
+ signal: AbortSignal.timeout(timeoutMs)
2311
+ });
2184
2312
  return res.ok;
2185
2313
  } catch {
2186
2314
  return false;
@@ -2550,6 +2678,7 @@ async function buildRetain(args) {
2550
2678
  // Stop, reading a complete transcript, corrects it. See recordUsage.
2551
2679
  reviseLastTurn: true
2552
2680
  });
2681
+ if (!client) return;
2553
2682
  const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
2554
2683
  const t0 = Date.now();
2555
2684
  try {
@@ -2574,12 +2703,8 @@ async function buildRetain(args) {
2574
2703
  async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2575
2704
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2576
2705
  const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2577
- let ev = {};
2578
- try {
2579
- ev = JSON.parse(readFileSync7(0, "utf8"));
2580
- } catch {
2581
- return;
2582
- }
2706
+ const ev = readHookEvent(spec.harness);
2707
+ if (!ev) return;
2583
2708
  if (spec.accept && !spec.accept(ev)) return;
2584
2709
  const parsed = spec.parse(ev);
2585
2710
  const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
@@ -2605,18 +2730,19 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2605
2730
  cfg = resolved2.cfg;
2606
2731
  const bankId = resolved2.bankId;
2607
2732
  if (cfg.disabled) return;
2733
+ let client;
2608
2734
  if (!cfg.retainSessions) {
2609
2735
  diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
2610
- return;
2736
+ } else {
2737
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2738
+ client = makeClient({
2739
+ apiUrl: cfg.apiUrl,
2740
+ apiToken: cfg.apiToken,
2741
+ bank: bankId,
2742
+ maxParallelRetains: cfg.maxParallelRetains,
2743
+ observationScopes: cfg.observationScopes
2744
+ });
2611
2745
  }
2612
- await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2613
- const client = makeClient({
2614
- apiUrl: cfg.apiUrl,
2615
- apiToken: cfg.apiToken,
2616
- bank: bankId,
2617
- maxParallelRetains: cfg.maxParallelRetains,
2618
- observationScopes: cfg.observationScopes
2619
- });
2620
2746
  await buildRetain({
2621
2747
  harness: spec.harness,
2622
2748
  sessionId: sessionId || "no-session",
@@ -2637,18 +2763,18 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2637
2763
  });
2638
2764
  }
2639
2765
 
2640
- // src/core/session-start.ts
2641
- import { readFileSync as readFileSync11 } from "fs";
2642
-
2643
2766
  // src/core/git.ts
2644
2767
  import { execFileSync as execFileSync2 } from "child_process";
2645
2768
  import { resolve as resolve2 } from "path";
2769
+ var US = "";
2770
+ var RS = "";
2771
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
2646
2772
 
2647
2773
  // src/core/status.ts
2648
- import { execFileSync as execFileSync3 } from "child_process";
2774
+ import { execFileSync as execFileSync4 } from "child_process";
2649
2775
 
2650
2776
  // src/core/survey.ts
2651
- import { spawn as realSpawn4 } from "child_process";
2777
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2652
2778
  import { createHash as createHash4 } from "crypto";
2653
2779
  import { existsSync as existsSync3 } from "fs";
2654
2780
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2677,7 +2803,7 @@ import { spawn as realSpawn5 } from "child_process";
2677
2803
  import {
2678
2804
  existsSync as existsSync4,
2679
2805
  mkdirSync as mkdirSync5,
2680
- readFileSync as readFileSync8,
2806
+ readFileSync as readFileSync7,
2681
2807
  realpathSync as realpathSync2,
2682
2808
  unlinkSync as unlinkSync2,
2683
2809
  writeFileSync as writeFileSync3
@@ -2691,7 +2817,7 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2691
2817
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2692
2818
 
2693
2819
  // src/core/skill-sync.ts
2694
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2820
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2695
2821
  import { homedir as homedir6 } from "os";
2696
2822
  import { dirname as dirname10, join as join16 } from "path";
2697
2823
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -2701,13 +2827,13 @@ import { existsSync as existsSync5 } from "fs";
2701
2827
  import { join as join15 } from "path";
2702
2828
 
2703
2829
  // src/core/legacy.ts
2704
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2830
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2705
2831
  import { homedir as homedir7 } from "os";
2706
2832
  import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2707
2833
 
2708
2834
  // src/core/traecode-mcp.ts
2709
- import { execFileSync as execFileSync4 } from "child_process";
2710
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2835
+ import { execFileSync as execFileSync5 } from "child_process";
2836
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2711
2837
  import { homedir as homedir8 } from "os";
2712
2838
  import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2713
2839
  import { fileURLToPath as fileURLToPath6 } from "url";
@@ -2744,7 +2870,7 @@ function gateStateFile() {
2744
2870
  }
2745
2871
  function readGateState(opts = {}) {
2746
2872
  try {
2747
- return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2873
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
2748
2874
  } catch {
2749
2875
  return {};
2750
2876
  }
@@ -2752,7 +2878,7 @@ function readGateState(opts = {}) {
2752
2878
  function workspaceMcpGateState(settingsPath) {
2753
2879
  let raw;
2754
2880
  try {
2755
- raw = readFileSync12(settingsPath, "utf8");
2881
+ raw = readFileSync10(settingsPath, "utf8");
2756
2882
  } catch {
2757
2883
  return "unknown";
2758
2884
  }
@@ -2792,7 +2918,7 @@ function gitignoreCovers(lines) {
2792
2918
  function ensureGitignored(repo) {
2793
2919
  const gitignore = join18(repo, ".gitignore");
2794
2920
  if (!existsSync8(gitignore)) return;
2795
- const current2 = readFileSync12(gitignore, "utf8");
2921
+ const current2 = readFileSync10(gitignore, "utf8");
2796
2922
  if (gitignoreCovers(current2.split("\n"))) return;
2797
2923
  const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2798
2924
  writeFileSync4(gitignore, current2 + addition);
@@ -2813,7 +2939,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2813
2939
  let doc = {};
2814
2940
  let exists = false;
2815
2941
  try {
2816
- doc = JSON.parse(readFileSync12(file, "utf8"));
2942
+ doc = JSON.parse(readFileSync10(file, "utf8"));
2817
2943
  exists = true;
2818
2944
  } catch {
2819
2945
  if (existsSync8(file)) return "skipped";
@@ -2869,7 +2995,7 @@ function findWorkspaceStorageDir(storage, repo) {
2869
2995
  }
2870
2996
  for (const name of entries) {
2871
2997
  try {
2872
- const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2998
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
2873
2999
  if (typeof doc.folder !== "string") continue;
2874
3000
  let folder;
2875
3001
  try {
@@ -2892,7 +3018,7 @@ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2892
3018
  if (!dir) return "failed";
2893
3019
  const db = join18(dir, "state.vscdb");
2894
3020
  if (!existsSync8(db)) return "failed";
2895
- const sqlite = opts.sqlite ?? execFileSync4;
3021
+ const sqlite = opts.sqlite ?? execFileSync5;
2896
3022
  const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2897
3023
  encoding: "utf8",
2898
3024
  timeout: SQLITE_TIMEOUT_MS,
@@ -2940,6 +3066,14 @@ function isSyntheticUserText(text) {
2940
3066
  const s = text.trimStart();
2941
3067
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2942
3068
  }
3069
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
3070
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
3071
+ function isStartupItem(text) {
3072
+ const s = text.trim();
3073
+ if (AGENTS_BLOCK_HEADER.test(s))
3074
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
3075
+ return STARTUP_TAG_BLOCK.test(s);
3076
+ }
2943
3077
  function contentText(content) {
2944
3078
  return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2945
3079
  }
@@ -2956,7 +3090,10 @@ function fallbackUserText(payload) {
2956
3090
  if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2957
3091
  return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2958
3092
  }
2959
- const text = contentText(content);
3093
+ const items = (Array.isArray(content) ? content : []).filter(
3094
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
3095
+ );
3096
+ const text = contentText(items);
2960
3097
  return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2961
3098
  }
2962
3099
  function isUserMessageEvent(line) {
@@ -3133,7 +3270,7 @@ function readCopilotTranscript(path) {
3133
3270
  }
3134
3271
 
3135
3272
  // src/core/transcript-grok.ts
3136
- import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3273
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3137
3274
  import { homedir as homedir9 } from "os";
3138
3275
  import { join as join19 } from "path";
3139
3276
  var CHAT_HISTORY = "chat_history.jsonl";
@@ -3144,7 +3281,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
3144
3281
  try {
3145
3282
  for (const candidate of readdirSync3(sessionsDir)) {
3146
3283
  const directory = join19(sessionsDir, candidate);
3147
- if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3284
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3148
3285
  return join19(directory, sessionId, CHAT_HISTORY);
3149
3286
  }
3150
3287
  }
@@ -3495,7 +3632,7 @@ function readDroidTranscript(path) {
3495
3632
  }
3496
3633
 
3497
3634
  // src/core/transcript-zcode.ts
3498
- import { readFileSync as readFileSync14 } from "fs";
3635
+ import { readFileSync as readFileSync12 } from "fs";
3499
3636
  function messageText(content) {
3500
3637
  if (typeof content === "string") return content.trim();
3501
3638
  if (!Array.isArray(content)) return "";
@@ -3505,7 +3642,7 @@ function readZcodeTranscript(path) {
3505
3642
  if (!path) return [];
3506
3643
  let body;
3507
3644
  try {
3508
- body = readFileSync14(path, "utf8");
3645
+ body = readFileSync12(path, "utf8");
3509
3646
  } catch {
3510
3647
  return [];
3511
3648
  }
@@ -3664,6 +3801,135 @@ function readKimiTranscript(path) {
3664
3801
  return turns;
3665
3802
  }
3666
3803
 
3804
+ // src/core/transcript-workbuddy.ts
3805
+ function messageText2(content) {
3806
+ if (typeof content === "string") return content;
3807
+ if (!Array.isArray(content)) return "";
3808
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
3809
+ }
3810
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
3811
+ function unwrapUserQuery(text) {
3812
+ const match = USER_QUERY_RE.exec(text);
3813
+ return (match ? match[1] : text).trim();
3814
+ }
3815
+ function isSyntheticUserText2(text) {
3816
+ const s = text.trimStart();
3817
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
3818
+ }
3819
+ function parseArgs2(raw) {
3820
+ if (!raw) return void 0;
3821
+ try {
3822
+ return JSON.parse(raw);
3823
+ } catch {
3824
+ return raw;
3825
+ }
3826
+ }
3827
+ function stampOf3(line) {
3828
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
3829
+ }
3830
+ function readWorkbuddyTranscript(path) {
3831
+ const turns = [];
3832
+ for (const rawLine of readJsonl(path)) {
3833
+ const trimmed = rawLine.trim();
3834
+ if (!trimmed) continue;
3835
+ let parsed;
3836
+ try {
3837
+ parsed = JSON.parse(trimmed);
3838
+ } catch {
3839
+ continue;
3840
+ }
3841
+ if (typeof parsed !== "object" || parsed === null) continue;
3842
+ const line = parsed;
3843
+ const stamp = stampOf3(line);
3844
+ if (line.type === "message") {
3845
+ if (line.role !== "user" && line.role !== "assistant") continue;
3846
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
3847
+ if (!text) continue;
3848
+ if (line.role === "user") {
3849
+ if (isSyntheticUserText2(text)) continue;
3850
+ text = unwrapUserQuery(text);
3851
+ if (!text) continue;
3852
+ }
3853
+ turns.push({ role: line.role, content: text, ...stamp });
3854
+ } else if (line.type === "function_call" && typeof line.name === "string") {
3855
+ turns.push({
3856
+ role: "action",
3857
+ content: actionLine(line.name, parseArgs2(line.arguments)),
3858
+ ...stamp
3859
+ });
3860
+ }
3861
+ }
3862
+ return turns;
3863
+ }
3864
+
3865
+ // src/core/transcript-codebuddy-ide.ts
3866
+ import { readFileSync as readFileSync13 } from "fs";
3867
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
3868
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
3869
+ function readJson(path) {
3870
+ try {
3871
+ return JSON.parse(readFileSync13(path, "utf8"));
3872
+ } catch {
3873
+ return void 0;
3874
+ }
3875
+ }
3876
+ function ideUserText(raw) {
3877
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
3878
+ if (!text || isSyntheticUserText2(text)) return "";
3879
+ return unwrapUserQuery(text).trim();
3880
+ }
3881
+ function readCodebuddyIdeTranscript(indexPath) {
3882
+ const index = readJson(indexPath);
3883
+ const entries = index?.messages;
3884
+ if (!Array.isArray(entries)) return [];
3885
+ const messagesDir = join22(dirname12(indexPath), "messages");
3886
+ const turns = [];
3887
+ for (const entry of entries) {
3888
+ const id = entry?.id;
3889
+ if (typeof id !== "string") continue;
3890
+ const file = readJson(join22(messagesDir, `${id}.json`));
3891
+ const encoded = file?.message;
3892
+ if (typeof encoded !== "string") continue;
3893
+ let inner;
3894
+ try {
3895
+ inner = JSON.parse(encoded);
3896
+ } catch {
3897
+ continue;
3898
+ }
3899
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
3900
+ const isUser = role === "user";
3901
+ const isAssistant = role === "assistant";
3902
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
3903
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
3904
+ const texts = [];
3905
+ const calls = [];
3906
+ for (const block of blocks) {
3907
+ if (!block || typeof block !== "object") continue;
3908
+ const { type, text, toolName, args } = block;
3909
+ if (type === "text" && typeof text === "string") texts.push(text);
3910
+ else if (type === "tool-call" && typeof toolName === "string")
3911
+ calls.push({ name: toolName, args });
3912
+ }
3913
+ if (texts.length) {
3914
+ const raw = texts.join("\n");
3915
+ if (isUser) {
3916
+ const text = ideUserText(raw);
3917
+ if (text) turns.push({ role: "user", content: text, ...stamp });
3918
+ } else if (isAssistant) {
3919
+ const text = stripInjectedMemory(raw).trim();
3920
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
3921
+ }
3922
+ }
3923
+ for (const call of calls) {
3924
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
3925
+ }
3926
+ }
3927
+ return turns;
3928
+ }
3929
+ function readCodebuddyTranscript(path) {
3930
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
3931
+ }
3932
+
3667
3933
  // src/harness/hook-lifecycle.ts
3668
3934
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3669
3935
  var claudePrompt = {
@@ -3769,6 +4035,35 @@ var standardSessionStart = (harness) => ({
3769
4035
  }
3770
4036
  })
3771
4037
  });
4038
+ var genieSessionStart = (harness) => {
4039
+ const base = standardSessionStart(harness);
4040
+ return {
4041
+ ...base,
4042
+ parse: (ev) => ({
4043
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
4044
+ sessionId: ev.session_id
4045
+ }),
4046
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
4047
+ };
4048
+ };
4049
+ var geniePrompt = (harness) => ({
4050
+ ...claudePrompt,
4051
+ harness,
4052
+ emit: (context, notice, ev) => ({
4053
+ ...claudePrompt.emit(context, notice, ev),
4054
+ suppressOutput: true
4055
+ })
4056
+ });
4057
+ var genieRetain = (harness, readTranscript) => ({
4058
+ hostTimeoutSec: 60,
4059
+ harness,
4060
+ parse: (ev) => ({
4061
+ sessionId: ev.session_id,
4062
+ transcriptPath: ev.transcript_path,
4063
+ cwd: ev.cwd
4064
+ }),
4065
+ readTranscript
4066
+ });
3772
4067
  var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3773
4068
  var HOOK_HARNESSES = {
3774
4069
  "claude-code": {
@@ -3966,17 +4261,29 @@ var HOOK_HARNESSES = {
3966
4261
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3967
4262
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3968
4263
  },
4264
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
4265
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
4266
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
4267
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
3969
4268
  sessionStart: {
3970
4269
  ...standardSessionStart("grok-build"),
3971
4270
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3972
4271
  parse: (ev) => ({
3973
4272
  cwd: ev.cwd,
3974
4273
  sessionId: ev.sessionId
3975
- })
4274
+ }),
4275
+ deferContextToToolHook: true
3976
4276
  },
3977
4277
  prompt: {
3978
4278
  ...claudePrompt,
3979
4279
  harness: "grok-build",
4280
+ toolHook: {
4281
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
4282
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
4283
+ emit: (context) => ({
4284
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
4285
+ })
4286
+ },
3980
4287
  parse: (ev) => ({
3981
4288
  prompt: ev.prompt,
3982
4289
  cwd: ev.cwd,
@@ -4210,6 +4517,48 @@ var HOOK_HARNESSES = {
4210
4517
  },
4211
4518
  readTranscript: readKimiTranscript
4212
4519
  }
4520
+ },
4521
+ /**
4522
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4523
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4524
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4525
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4526
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4527
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4528
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4529
+ * file-backed host rather than the journal ZCode needs.
4530
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4531
+ */
4532
+ workbuddy: {
4533
+ configStyle: "nested",
4534
+ install: {
4535
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4536
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
4537
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
4538
+ },
4539
+ sessionStart: genieSessionStart("workbuddy"),
4540
+ prompt: geniePrompt("workbuddy"),
4541
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
4542
+ },
4543
+ /**
4544
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
4545
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
4546
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
4547
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
4548
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
4549
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
4550
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
4551
+ */
4552
+ codebuddy: {
4553
+ configStyle: "nested",
4554
+ install: {
4555
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
4556
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
4557
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
4558
+ },
4559
+ sessionStart: genieSessionStart("codebuddy"),
4560
+ prompt: geniePrompt("codebuddy"),
4561
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
4213
4562
  }
4214
4563
  };
4215
4564
  var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);