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

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 +67 -6
  2. package/dist/antigravity-hook.js +441 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +441 -95
  5. package/dist/claude-hook.js +441 -80
  6. package/dist/claude-sessionstart-hook.js +473 -93
  7. package/dist/claude-stop-hook.js +441 -95
  8. package/dist/cline.js +290 -95
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +441 -80
  13. package/dist/codex-sessionstart-hook.js +473 -93
  14. package/dist/codex-stop-hook.js +441 -95
  15. package/dist/copilot-hook.js +441 -80
  16. package/dist/copilot-sessionstart-hook.js +473 -93
  17. package/dist/copilot-stop-hook.js +441 -95
  18. package/dist/cursor-hook.js +441 -80
  19. package/dist/cursor-sessionstart-hook.js +473 -93
  20. package/dist/cursor-stop-hook.js +441 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +441 -80
  23. package/dist/dcode-sessionstart-hook.js +473 -93
  24. package/dist/dcode-stop-hook.js +441 -95
  25. package/dist/deepen.js +140 -49
  26. package/dist/devin-hook.js +441 -80
  27. package/dist/devin-sessionstart-hook.js +473 -93
  28. package/dist/devin-stop-hook.js +441 -95
  29. package/dist/droid-hook.js +441 -80
  30. package/dist/droid-sessionstart-hook.js +473 -93
  31. package/dist/droid-stop-hook.js +441 -95
  32. package/dist/dsh.js +297 -95
  33. package/dist/grok-hook.js +441 -80
  34. package/dist/grok-sessionstart-hook.js +473 -93
  35. package/dist/grok-stop-hook.js +441 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +299 -104
  38. package/dist/installer.js +1043 -647
  39. package/dist/kilo.js +299 -104
  40. package/dist/kimi-hook.js +441 -80
  41. package/dist/kimi-sessionstart-hook.js +473 -93
  42. package/dist/kimi-stop-hook.js +441 -95
  43. package/dist/mcp-server.js +261 -86
  44. package/dist/opencode2.js +296 -101
  45. package/dist/pi.js +352 -107
  46. package/dist/prime-agent.js +352 -107
  47. package/dist/qwen-hook.js +441 -80
  48. package/dist/qwen-sessionstart-hook.js +473 -93
  49. package/dist/qwen-stop-hook.js +441 -95
  50. package/dist/status.js +115 -42
  51. package/dist/traecode-hook.js +441 -80
  52. package/dist/traecode-sessionstart-hook.js +473 -93
  53. package/dist/traecode-stop-hook.js +441 -95
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +441 -80
  58. package/dist/zcode-sessionstart-hook.js +473 -93
  59. package/dist/zcode-stop-hook.js +441 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +4 -4
package/dist/kimi-hook.js CHANGED
@@ -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;
@@ -335,7 +357,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
335
357
  }
336
358
 
337
359
  // src/core/config.ts
338
- import { readFileSync as readFileSync2 } from "fs";
360
+ import { readFileSync as readFileSync3 } from "fs";
339
361
  import { homedir as homedir3 } from "os";
340
362
  import { join as join7 } from "path";
341
363
 
@@ -375,7 +397,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
375
397
  // src/core/missions.ts
376
398
  import { createHash } from "crypto";
377
399
  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.";
378
- 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.";
400
+ 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.";
379
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.`;
380
402
  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.";
381
403
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -451,6 +473,8 @@ var KNOWLEDGE_LABELS = {
451
473
  ]
452
474
  };
453
475
  function pageScopeRule(project) {
476
+ if (project === void 0)
477
+ 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.`;
454
478
  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.`;
455
479
  }
456
480
  var PAGE_TAXONOMY = [
@@ -632,16 +656,19 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
632
656
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
633
657
  }
634
658
 
659
+ // package.json
660
+ var version = "0.8.1";
661
+
635
662
  // src/core/util.ts
636
663
  import { accessSync, constants } from "fs";
637
664
  import { delimiter, join as join6 } from "path";
638
665
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
639
- function semverGte(version, min) {
666
+ function semverGte(version2, min) {
640
667
  const parts = (v) => {
641
668
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
642
669
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
643
670
  };
644
- const a = version ? parts(version) : void 0;
671
+ const a = version2 ? parts(version2) : void 0;
645
672
  const b = parts(min);
646
673
  if (!a || !b) return false;
647
674
  for (let i = 0; i < 3; i++) {
@@ -675,6 +702,7 @@ function isOurMcpEntry(entry) {
675
702
  }
676
703
 
677
704
  // src/core/hindsight.ts
705
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
678
706
  function resolveRetainScopes(tags, configured) {
679
707
  if (configured !== "per_source") return configured;
680
708
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -710,7 +738,7 @@ async function isEndpointMissing(r) {
710
738
  const j = await r.json();
711
739
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
712
740
  } catch {
713
- return true;
741
+ return false;
714
742
  }
715
743
  }
716
744
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -729,6 +757,12 @@ var ReflectError = class extends Error {
729
757
  get fallbackEligible() {
730
758
  return this.timedOut || this.status !== void 0 && this.status >= 500;
731
759
  }
760
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
761
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
762
+ get permanent() {
763
+ const s = this.status;
764
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
765
+ }
732
766
  };
733
767
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
734
768
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -739,8 +773,10 @@ var DEFAULT_RECALL_OPTIONS = {
739
773
  include: { entities: null }
740
774
  };
741
775
  var POLL_CYCLE_MS = 5e3;
776
+ var POLL_MAX_SERVER_ERRORS = 12;
742
777
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
743
778
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
779
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
744
780
  function shapePage(page) {
745
781
  const p = page ?? {};
746
782
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -753,6 +789,15 @@ function shapePage(page) {
753
789
  body
754
790
  };
755
791
  }
792
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
793
+ function signalOnlyDispatcher() {
794
+ void globalThis.Headers;
795
+ const d = globalThis[GLOBAL_DISPATCHER];
796
+ if (typeof d?.compose !== "function") return void 0;
797
+ return d.compose(
798
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
799
+ );
800
+ }
756
801
  var HindsightClient = class {
757
802
  apiUrl;
758
803
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -772,6 +817,7 @@ var HindsightClient = class {
772
817
  observationScopes;
773
818
  pageSearchLimit;
774
819
  recallOptions;
820
+ rateLimitPatienceMs;
775
821
  constructor(o) {
776
822
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
777
823
  this.token = o.apiToken;
@@ -784,6 +830,7 @@ var HindsightClient = class {
784
830
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
785
831
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
786
832
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
833
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
787
834
  }
788
835
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
789
836
  get apiToken() {
@@ -792,7 +839,8 @@ var HindsightClient = class {
792
839
  headers() {
793
840
  const h = {
794
841
  "Content-Type": "application/json",
795
- "Accept-Encoding": "identity"
842
+ "Accept-Encoding": "identity",
843
+ "User-Agent": USER_AGENT
796
844
  };
797
845
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
798
846
  return h;
@@ -824,7 +872,8 @@ var HindsightClient = class {
824
872
  * bounds the whole call.
825
873
  */
826
874
  async fetchWithAuth(url, init) {
827
- const send = () => fetch(url, { ...init, headers: this.headers() });
875
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
876
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
828
877
  const r = await send();
829
878
  if (r.status !== 401 || !this.refreshToken()) return r;
830
879
  return send();
@@ -840,13 +889,22 @@ var HindsightClient = class {
840
889
  }
841
890
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
842
891
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
843
- const r = await this.fetchWithAuth(url, {
844
- method,
845
- body: body ? JSON.stringify(body) : void 0,
846
- signal: AbortSignal.timeout(timeoutMs)
847
- });
848
- if (r.status === 429 && !tolerate.includes(429))
849
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
892
+ const payload = body ? JSON.stringify(body) : void 0;
893
+ let r;
894
+ for (let attempt = 0, waited = 0; ; attempt++) {
895
+ r = await this.fetchWithAuth(url, {
896
+ method,
897
+ body: payload,
898
+ signal: AbortSignal.timeout(timeoutMs)
899
+ });
900
+ if (r.status !== 429 || tolerate.includes(429)) break;
901
+ const asked = retryAfterMs(r.headers.get("retry-after"));
902
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
903
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
904
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
905
+ await sleep(wait);
906
+ waited += wait;
907
+ }
850
908
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
851
909
  throw new Error(
852
910
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -881,7 +939,7 @@ var HindsightClient = class {
881
939
  }
882
940
  /**
883
941
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
884
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
942
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
885
943
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
886
944
  */
887
945
  async supportsIdempotentRetain() {
@@ -891,15 +949,21 @@ var HindsightClient = class {
891
949
  }
892
950
  return this.idempotentRetain;
893
951
  }
952
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
953
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
954
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
955
+ * `/version`, so that stays as the fallback. */
894
956
  async probeIdempotentRetain() {
895
- try {
896
- const r = await this.req("GET", `${this.apiUrl}/version`);
897
- if (!r.ok) return false;
898
- const j = await r.json();
899
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
900
- } catch {
901
- return false;
957
+ for (const path of ["/v1/version", "/version"]) {
958
+ try {
959
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
960
+ if (!r.ok) continue;
961
+ const j = await r.json();
962
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
963
+ } catch {
964
+ }
902
965
  }
966
+ return false;
903
967
  }
904
968
  /**
905
969
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -961,6 +1025,14 @@ var HindsightClient = class {
961
1025
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
962
1026
  }
963
1027
  }
1028
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1029
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1030
+ async hasDocuments() {
1031
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1032
+ if (r.status === 404) return false;
1033
+ const j = await r.json();
1034
+ return (j.total ?? j.items?.length ?? 0) > 0;
1035
+ }
964
1036
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
965
1037
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
966
1038
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1042,7 +1114,13 @@ var HindsightClient = class {
1042
1114
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1043
1115
  const start = Date.now();
1044
1116
  const pending = new Set(ids);
1117
+ const serverErrors = /* @__PURE__ */ new Map();
1045
1118
  let failed = 0;
1119
+ const giveUp = (id, status) => {
1120
+ pending.delete(id);
1121
+ failed++;
1122
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1123
+ };
1046
1124
  while (pending.size && Date.now() - start < maxMs) {
1047
1125
  let backoffMs = POLL_CYCLE_MS;
1048
1126
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1055,7 +1133,14 @@ var HindsightClient = class {
1055
1133
  );
1056
1134
  return;
1057
1135
  }
1058
- if (!r.ok) return;
1136
+ if (r.status >= 500) {
1137
+ const n = (serverErrors.get(id) ?? 0) + 1;
1138
+ serverErrors.set(id, n);
1139
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1140
+ return;
1141
+ }
1142
+ if (!r.ok) return giveUp(id, r.status);
1143
+ serverErrors.delete(id);
1059
1144
  const st = ((await r.json()).status || "").toLowerCase();
1060
1145
  if (TERMINAL.has(st)) {
1061
1146
  pending.delete(id);
@@ -1239,7 +1324,7 @@ var HindsightClient = class {
1239
1324
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1240
1325
  */
1241
1326
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1242
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1327
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1243
1328
  const existing = /* @__PURE__ */ new Map();
1244
1329
  let roots;
1245
1330
  try {
@@ -1314,7 +1399,7 @@ var HindsightClient = class {
1314
1399
  }
1315
1400
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1316
1401
  this.log(
1317
- `[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` : "")
1402
+ `[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` : "")
1318
1403
  );
1319
1404
  }
1320
1405
  /**
@@ -1325,23 +1410,33 @@ var HindsightClient = class {
1325
1410
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1326
1411
  * consolidation under the auto-refresh that used to be the default (#3506).
1327
1412
  *
1328
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1329
- * initiative's own title, and re-stating either would rebuild a page whose question never
1330
- * changed. The tree read above is reused rather than re-fetched.
1413
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1414
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1415
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1416
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1417
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1418
+ * reused rather than re-fetched.
1331
1419
  */
1332
1420
  async resyncInitiativeTriggers(roots, pageTrigger) {
1333
1421
  const folder = roots.find(
1334
1422
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1335
1423
  );
1424
+ const bankScope = pageScopeRule(this.bank);
1336
1425
  let updated = 0;
1337
1426
  for (const page of folder?.children ?? []) {
1338
- if (page.kind !== "page" || page.trigger == null) continue;
1339
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1340
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1427
+ if (page.kind !== "page") continue;
1428
+ const patch = {};
1429
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1430
+ if (query !== page.description) patch.source_query = query;
1431
+ if (page.trigger != null) {
1432
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1433
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1434
+ }
1435
+ if (!patch.trigger && !patch.source_query) continue;
1341
1436
  const r = await this.req(
1342
1437
  "PATCH",
1343
1438
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1344
- { trigger: pageTriggerPatch(desired) }
1439
+ patch
1345
1440
  );
1346
1441
  if (r.status === 404) continue;
1347
1442
  updated++;
@@ -1369,10 +1464,9 @@ var HindsightClient = class {
1369
1464
  let pageId = args.relatesToPageId;
1370
1465
  if (!pageId) {
1371
1466
  const folderId = await this.ensureFolder("Initiatives");
1372
- const subject = this.project ?? this.bank;
1373
1467
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1374
1468
  name: args.title,
1375
- 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),
1469
+ 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),
1376
1470
  parent_id: folderId,
1377
1471
  tags: ["knowledge:feature-work"],
1378
1472
  max_tokens: PAGE_MAX_TOKENS,
@@ -1387,7 +1481,7 @@ var HindsightClient = class {
1387
1481
  }
1388
1482
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1389
1483
  const content = `${verb}: ${args.title}. ${args.summary}`;
1390
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1484
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1391
1485
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1392
1486
  const context = `initiative marker for [[page:${pageId}]]`;
1393
1487
  await this.retain(content, context, markerId, tags, "document", {
@@ -1624,7 +1718,7 @@ function resolveConfig(raw = {}) {
1624
1718
  }
1625
1719
  function readRaw(path) {
1626
1720
  try {
1627
- return JSON.parse(readFileSync2(path, "utf8"));
1721
+ return JSON.parse(readFileSync3(path, "utf8"));
1628
1722
  } catch (e) {
1629
1723
  if (e?.code !== "ENOENT") {
1630
1724
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1906,7 +2000,7 @@ ${toolGuide(opts)}
1906
2000
  }
1907
2001
 
1908
2002
  // src/core/session-cache.ts
1909
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
2003
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1910
2004
  import { tmpdir } from "os";
1911
2005
  import { dirname as dirname5, join as join8 } from "path";
1912
2006
  function sessionCacheFile(harness, sessionId) {
@@ -1914,7 +2008,7 @@ function sessionCacheFile(harness, sessionId) {
1914
2008
  }
1915
2009
  function readSessionCache(cacheFile) {
1916
2010
  try {
1917
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
2011
+ return JSON.parse(readFileSync4(cacheFile, "utf8"));
1918
2012
  } catch {
1919
2013
  return {};
1920
2014
  }
@@ -1939,6 +2033,36 @@ function writeSessionCache(cacheFile, cache) {
1939
2033
  } catch {
1940
2034
  }
1941
2035
  }
2036
+ function pendingContextFile(harness, sessionId) {
2037
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.pending`);
2038
+ }
2039
+ function stashPendingContext(harness, sessionId, context) {
2040
+ const path = pendingContextFile(harness, sessionId);
2041
+ let existing = "";
2042
+ try {
2043
+ existing = readFileSync4(path, "utf8");
2044
+ } catch {
2045
+ }
2046
+ if (existing.includes(context)) return;
2047
+ try {
2048
+ writeFileAtomic(path, existing ? `${existing}
2049
+
2050
+ ${context}` : context);
2051
+ } catch {
2052
+ }
2053
+ }
2054
+ function takePendingContext(harness, sessionId) {
2055
+ const path = pendingContextFile(harness, sessionId);
2056
+ const claimed = `${path}.${process.pid}.claim`;
2057
+ try {
2058
+ renameSync2(path, claimed);
2059
+ return readFileSync4(claimed, "utf8") || void 0;
2060
+ } catch {
2061
+ return void 0;
2062
+ } finally {
2063
+ rmSync(claimed, { force: true });
2064
+ }
2065
+ }
1942
2066
  function sessionRootFile(harness, sessionId) {
1943
2067
  return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1944
2068
  }
@@ -1946,7 +2070,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1946
2070
  if (!sessionId || !cwd) return cwd;
1947
2071
  const file = sessionRootFile(harness, sessionId);
1948
2072
  try {
1949
- const recorded = readFileSync3(file, "utf8").trim();
2073
+ const recorded = readFileSync4(file, "utf8").trim();
1950
2074
  if (recorded) return recorded;
1951
2075
  } catch {
1952
2076
  }
@@ -1958,7 +2082,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1958
2082
  }
1959
2083
 
1960
2084
  // src/core/turn-journal.ts
1961
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2085
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1962
2086
  import { tmpdir as tmpdir2 } from "os";
1963
2087
  import { dirname as dirname6, join as join9 } from "path";
1964
2088
 
@@ -2027,7 +2151,7 @@ function appendJournalTurn(path, turn) {
2027
2151
  function readJournalTranscript(path) {
2028
2152
  let body;
2029
2153
  try {
2030
- body = readFileSync4(path, "utf8");
2154
+ body = readFileSync5(path, "utf8");
2031
2155
  } catch {
2032
2156
  return [];
2033
2157
  }
@@ -2055,9 +2179,23 @@ function readJournalTranscript(path) {
2055
2179
 
2056
2180
  // src/core/hook.ts
2057
2181
  var HOOK_INJECT_ATTEMPTS = 2;
2182
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
2058
2183
  function resolveInjection(got, attempts) {
2059
2184
  if (got != null) return got;
2060
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
2185
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
2186
+ return attempts >= budget ? "" : void 0;
2187
+ }
2188
+ var RECALL_QUERY_MAX_TOKENS = 500;
2189
+ function boundRecallQuery(prompt) {
2190
+ let cost = 0;
2191
+ let end = 0;
2192
+ for (const ch of prompt) {
2193
+ const cp = ch.codePointAt(0);
2194
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
2195
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
2196
+ end += ch.length;
2197
+ }
2198
+ return prompt.slice(0, end);
2061
2199
  }
2062
2200
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
2063
2201
  const t0 = Date.now();
@@ -2073,7 +2211,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
2073
2211
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
2074
2212
  const t0 = Date.now();
2075
2213
  try {
2076
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
2214
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
2077
2215
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
2078
2216
  return observations.length ? formatRecallFallback(observations, lead) : null;
2079
2217
  } catch (e) {
@@ -2148,7 +2286,7 @@ async function buildHookOutput(args) {
2148
2286
  answer: reflectAnswer.slice(0, 8e3)
2149
2287
  });
2150
2288
  } catch (e) {
2151
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
2289
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
2152
2290
  reflectFailed = true;
2153
2291
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
2154
2292
  error: describeError(e)
@@ -2219,14 +2357,15 @@ async function buildHookOutput(args) {
2219
2357
  }
2220
2358
  async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2221
2359
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2222
- let ev = {};
2223
- try {
2224
- ev = JSON.parse(readFileSync5(0, "utf8"));
2225
- } catch {
2226
- return;
2227
- }
2360
+ const ev = readHookEvent(spec.harness);
2361
+ if (!ev) return;
2228
2362
  if (spec.accept && !spec.accept(ev)) return;
2229
2363
  const { prompt: rawPrompt, cwd: rawCwd, sessionId } = spec.parse(ev);
2364
+ if (spec.toolHook?.accept(ev)) {
2365
+ const pending = sessionId ? takePendingContext(spec.harness, sessionId) : void 0;
2366
+ if (pending) process.stdout.write(JSON.stringify(spec.toolHook.emit(pending)));
2367
+ return;
2368
+ }
2230
2369
  if (spec.requireCwd && !rawCwd) return;
2231
2370
  const cwd = rawCwd || process.cwd();
2232
2371
  const prompt = (rawPrompt || "").trim();
@@ -2240,7 +2379,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2240
2379
  if (spec.journalPrompt) {
2241
2380
  appendJournalTurn(journalPath(spec.harness, sessionId), { role: "user", content: prompt });
2242
2381
  }
2243
- const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
2382
+ const out = (context2, notice) => process.stdout.write(JSON.stringify(spec.emit(context2 ?? "", notice, ev)));
2244
2383
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2245
2384
  const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
2246
2385
  if (derived === null) return;
@@ -2268,12 +2407,14 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2268
2407
  if (cfg.autoSeed !== false && client.knowledgePagesSupported !== false && output.pages.length === 0) {
2269
2408
  startBackgroundSeed(cwd, { limit: cfg.seedLimit, harness: spec.harness });
2270
2409
  }
2271
- if (output.context || output.notice) out(output.context, output.notice);
2410
+ let context = output.context;
2411
+ if (context && spec.toolHook && sessionId) {
2412
+ stashPendingContext(spec.harness, sessionId, context);
2413
+ context = void 0;
2414
+ }
2415
+ if (context || output.notice) out(context, output.notice);
2272
2416
  }
2273
2417
 
2274
- // src/core/retain-hook.ts
2275
- import { readFileSync as readFileSync7 } from "fs";
2276
-
2277
2418
  // src/core/retain-cursor.ts
2278
2419
  import { createHash as createHash2 } from "crypto";
2279
2420
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
@@ -2328,18 +2469,15 @@ function* readJsonl(path) {
2328
2469
  import { readFileSync as readFileSync6 } from "fs";
2329
2470
  import { join as join11 } from "path";
2330
2471
 
2331
- // src/core/session-start.ts
2332
- import { readFileSync as readFileSync11 } from "fs";
2333
-
2334
2472
  // src/core/git.ts
2335
2473
  import { execFileSync as execFileSync2 } from "child_process";
2336
2474
  import { resolve as resolve2 } from "path";
2337
2475
 
2338
2476
  // src/core/status.ts
2339
- import { execFileSync as execFileSync3 } from "child_process";
2477
+ import { execFileSync as execFileSync4 } from "child_process";
2340
2478
 
2341
2479
  // src/core/survey.ts
2342
- import { spawn as realSpawn4 } from "child_process";
2480
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2343
2481
  import { createHash as createHash4 } from "crypto";
2344
2482
  import { existsSync as existsSync3 } from "fs";
2345
2483
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2368,7 +2506,7 @@ import { spawn as realSpawn5 } from "child_process";
2368
2506
  import {
2369
2507
  existsSync as existsSync4,
2370
2508
  mkdirSync as mkdirSync5,
2371
- readFileSync as readFileSync8,
2509
+ readFileSync as readFileSync7,
2372
2510
  realpathSync as realpathSync2,
2373
2511
  unlinkSync as unlinkSync2,
2374
2512
  writeFileSync as writeFileSync3
@@ -2382,7 +2520,7 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2382
2520
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2383
2521
 
2384
2522
  // src/core/skill-sync.ts
2385
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2523
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2386
2524
  import { homedir as homedir6 } from "os";
2387
2525
  import { dirname as dirname10, join as join16 } from "path";
2388
2526
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -2392,13 +2530,13 @@ import { existsSync as existsSync5 } from "fs";
2392
2530
  import { join as join15 } from "path";
2393
2531
 
2394
2532
  // src/core/legacy.ts
2395
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2533
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2396
2534
  import { homedir as homedir7 } from "os";
2397
2535
  import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2398
2536
 
2399
2537
  // src/core/traecode-mcp.ts
2400
- import { execFileSync as execFileSync4 } from "child_process";
2401
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2538
+ import { execFileSync as execFileSync5 } from "child_process";
2539
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2402
2540
  import { homedir as homedir8 } from "os";
2403
2541
  import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2404
2542
  import { fileURLToPath as fileURLToPath6 } from "url";
@@ -2435,7 +2573,7 @@ function gateStateFile() {
2435
2573
  }
2436
2574
  function readGateState(opts = {}) {
2437
2575
  try {
2438
- return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2576
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
2439
2577
  } catch {
2440
2578
  return {};
2441
2579
  }
@@ -2443,7 +2581,7 @@ function readGateState(opts = {}) {
2443
2581
  function workspaceMcpGateState(settingsPath) {
2444
2582
  let raw;
2445
2583
  try {
2446
- raw = readFileSync12(settingsPath, "utf8");
2584
+ raw = readFileSync10(settingsPath, "utf8");
2447
2585
  } catch {
2448
2586
  return "unknown";
2449
2587
  }
@@ -2483,7 +2621,7 @@ function gitignoreCovers(lines) {
2483
2621
  function ensureGitignored(repo) {
2484
2622
  const gitignore = join18(repo, ".gitignore");
2485
2623
  if (!existsSync8(gitignore)) return;
2486
- const current2 = readFileSync12(gitignore, "utf8");
2624
+ const current2 = readFileSync10(gitignore, "utf8");
2487
2625
  if (gitignoreCovers(current2.split("\n"))) return;
2488
2626
  const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2489
2627
  writeFileSync4(gitignore, current2 + addition);
@@ -2504,7 +2642,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2504
2642
  let doc = {};
2505
2643
  let exists = false;
2506
2644
  try {
2507
- doc = JSON.parse(readFileSync12(file, "utf8"));
2645
+ doc = JSON.parse(readFileSync10(file, "utf8"));
2508
2646
  exists = true;
2509
2647
  } catch {
2510
2648
  if (existsSync8(file)) return "skipped";
@@ -2560,7 +2698,7 @@ function findWorkspaceStorageDir(storage, repo) {
2560
2698
  }
2561
2699
  for (const name of entries) {
2562
2700
  try {
2563
- const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2701
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
2564
2702
  if (typeof doc.folder !== "string") continue;
2565
2703
  let folder;
2566
2704
  try {
@@ -2583,7 +2721,7 @@ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2583
2721
  if (!dir) return "failed";
2584
2722
  const db = join18(dir, "state.vscdb");
2585
2723
  if (!existsSync8(db)) return "failed";
2586
- const sqlite = opts.sqlite ?? execFileSync4;
2724
+ const sqlite = opts.sqlite ?? execFileSync5;
2587
2725
  const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2588
2726
  encoding: "utf8",
2589
2727
  timeout: SQLITE_TIMEOUT_MS,
@@ -2631,6 +2769,14 @@ function isSyntheticUserText(text) {
2631
2769
  const s = text.trimStart();
2632
2770
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2633
2771
  }
2772
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
2773
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
2774
+ function isStartupItem(text) {
2775
+ const s = text.trim();
2776
+ if (AGENTS_BLOCK_HEADER.test(s))
2777
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
2778
+ return STARTUP_TAG_BLOCK.test(s);
2779
+ }
2634
2780
  function contentText(content) {
2635
2781
  return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2636
2782
  }
@@ -2647,7 +2793,10 @@ function fallbackUserText(payload) {
2647
2793
  if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2648
2794
  return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2649
2795
  }
2650
- const text = contentText(content);
2796
+ const items = (Array.isArray(content) ? content : []).filter(
2797
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
2798
+ );
2799
+ const text = contentText(items);
2651
2800
  return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2652
2801
  }
2653
2802
  function isUserMessageEvent(line) {
@@ -2824,7 +2973,7 @@ function readCopilotTranscript(path) {
2824
2973
  }
2825
2974
 
2826
2975
  // src/core/transcript-grok.ts
2827
- import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
2976
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
2828
2977
  import { homedir as homedir9 } from "os";
2829
2978
  import { join as join19 } from "path";
2830
2979
  var CHAT_HISTORY = "chat_history.jsonl";
@@ -2835,7 +2984,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
2835
2984
  try {
2836
2985
  for (const candidate of readdirSync3(sessionsDir)) {
2837
2986
  const directory = join19(sessionsDir, candidate);
2838
- if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
2987
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
2839
2988
  return join19(directory, sessionId, CHAT_HISTORY);
2840
2989
  }
2841
2990
  }
@@ -3186,7 +3335,7 @@ function readDroidTranscript(path) {
3186
3335
  }
3187
3336
 
3188
3337
  // src/core/transcript-zcode.ts
3189
- import { readFileSync as readFileSync14 } from "fs";
3338
+ import { readFileSync as readFileSync12 } from "fs";
3190
3339
  function messageText(content) {
3191
3340
  if (typeof content === "string") return content.trim();
3192
3341
  if (!Array.isArray(content)) return "";
@@ -3196,7 +3345,7 @@ function readZcodeTranscript(path) {
3196
3345
  if (!path) return [];
3197
3346
  let body;
3198
3347
  try {
3199
- body = readFileSync14(path, "utf8");
3348
+ body = readFileSync12(path, "utf8");
3200
3349
  } catch {
3201
3350
  return [];
3202
3351
  }
@@ -3355,6 +3504,135 @@ function readKimiTranscript(path) {
3355
3504
  return turns;
3356
3505
  }
3357
3506
 
3507
+ // src/core/transcript-workbuddy.ts
3508
+ function messageText2(content) {
3509
+ if (typeof content === "string") return content;
3510
+ if (!Array.isArray(content)) return "";
3511
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
3512
+ }
3513
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
3514
+ function unwrapUserQuery(text) {
3515
+ const match = USER_QUERY_RE.exec(text);
3516
+ return (match ? match[1] : text).trim();
3517
+ }
3518
+ function isSyntheticUserText2(text) {
3519
+ const s = text.trimStart();
3520
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
3521
+ }
3522
+ function parseArgs2(raw) {
3523
+ if (!raw) return void 0;
3524
+ try {
3525
+ return JSON.parse(raw);
3526
+ } catch {
3527
+ return raw;
3528
+ }
3529
+ }
3530
+ function stampOf3(line) {
3531
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
3532
+ }
3533
+ function readWorkbuddyTranscript(path) {
3534
+ const turns = [];
3535
+ for (const rawLine of readJsonl(path)) {
3536
+ const trimmed = rawLine.trim();
3537
+ if (!trimmed) continue;
3538
+ let parsed;
3539
+ try {
3540
+ parsed = JSON.parse(trimmed);
3541
+ } catch {
3542
+ continue;
3543
+ }
3544
+ if (typeof parsed !== "object" || parsed === null) continue;
3545
+ const line = parsed;
3546
+ const stamp = stampOf3(line);
3547
+ if (line.type === "message") {
3548
+ if (line.role !== "user" && line.role !== "assistant") continue;
3549
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
3550
+ if (!text) continue;
3551
+ if (line.role === "user") {
3552
+ if (isSyntheticUserText2(text)) continue;
3553
+ text = unwrapUserQuery(text);
3554
+ if (!text) continue;
3555
+ }
3556
+ turns.push({ role: line.role, content: text, ...stamp });
3557
+ } else if (line.type === "function_call" && typeof line.name === "string") {
3558
+ turns.push({
3559
+ role: "action",
3560
+ content: actionLine(line.name, parseArgs2(line.arguments)),
3561
+ ...stamp
3562
+ });
3563
+ }
3564
+ }
3565
+ return turns;
3566
+ }
3567
+
3568
+ // src/core/transcript-codebuddy-ide.ts
3569
+ import { readFileSync as readFileSync13 } from "fs";
3570
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
3571
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
3572
+ function readJson(path) {
3573
+ try {
3574
+ return JSON.parse(readFileSync13(path, "utf8"));
3575
+ } catch {
3576
+ return void 0;
3577
+ }
3578
+ }
3579
+ function ideUserText(raw) {
3580
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
3581
+ if (!text || isSyntheticUserText2(text)) return "";
3582
+ return unwrapUserQuery(text).trim();
3583
+ }
3584
+ function readCodebuddyIdeTranscript(indexPath) {
3585
+ const index = readJson(indexPath);
3586
+ const entries = index?.messages;
3587
+ if (!Array.isArray(entries)) return [];
3588
+ const messagesDir = join22(dirname12(indexPath), "messages");
3589
+ const turns = [];
3590
+ for (const entry of entries) {
3591
+ const id = entry?.id;
3592
+ if (typeof id !== "string") continue;
3593
+ const file = readJson(join22(messagesDir, `${id}.json`));
3594
+ const encoded = file?.message;
3595
+ if (typeof encoded !== "string") continue;
3596
+ let inner;
3597
+ try {
3598
+ inner = JSON.parse(encoded);
3599
+ } catch {
3600
+ continue;
3601
+ }
3602
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
3603
+ const isUser = role === "user";
3604
+ const isAssistant = role === "assistant";
3605
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
3606
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
3607
+ const texts = [];
3608
+ const calls = [];
3609
+ for (const block of blocks) {
3610
+ if (!block || typeof block !== "object") continue;
3611
+ const { type, text, toolName, args } = block;
3612
+ if (type === "text" && typeof text === "string") texts.push(text);
3613
+ else if (type === "tool-call" && typeof toolName === "string")
3614
+ calls.push({ name: toolName, args });
3615
+ }
3616
+ if (texts.length) {
3617
+ const raw = texts.join("\n");
3618
+ if (isUser) {
3619
+ const text = ideUserText(raw);
3620
+ if (text) turns.push({ role: "user", content: text, ...stamp });
3621
+ } else if (isAssistant) {
3622
+ const text = stripInjectedMemory(raw).trim();
3623
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
3624
+ }
3625
+ }
3626
+ for (const call of calls) {
3627
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
3628
+ }
3629
+ }
3630
+ return turns;
3631
+ }
3632
+ function readCodebuddyTranscript(path) {
3633
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
3634
+ }
3635
+
3358
3636
  // src/harness/hook-lifecycle.ts
3359
3637
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3360
3638
  var claudePrompt = {
@@ -3460,6 +3738,35 @@ var standardSessionStart = (harness) => ({
3460
3738
  }
3461
3739
  })
3462
3740
  });
3741
+ var genieSessionStart = (harness) => {
3742
+ const base = standardSessionStart(harness);
3743
+ return {
3744
+ ...base,
3745
+ parse: (ev) => ({
3746
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
3747
+ sessionId: ev.session_id
3748
+ }),
3749
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
3750
+ };
3751
+ };
3752
+ var geniePrompt = (harness) => ({
3753
+ ...claudePrompt,
3754
+ harness,
3755
+ emit: (context, notice, ev) => ({
3756
+ ...claudePrompt.emit(context, notice, ev),
3757
+ suppressOutput: true
3758
+ })
3759
+ });
3760
+ var genieRetain = (harness, readTranscript) => ({
3761
+ hostTimeoutSec: 60,
3762
+ harness,
3763
+ parse: (ev) => ({
3764
+ sessionId: ev.session_id,
3765
+ transcriptPath: ev.transcript_path,
3766
+ cwd: ev.cwd
3767
+ }),
3768
+ readTranscript
3769
+ });
3463
3770
  var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3464
3771
  var HOOK_HARNESSES = {
3465
3772
  "claude-code": {
@@ -3657,17 +3964,29 @@ var HOOK_HARNESSES = {
3657
3964
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3658
3965
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3659
3966
  },
3967
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
3968
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
3969
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
3970
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
3660
3971
  sessionStart: {
3661
3972
  ...standardSessionStart("grok-build"),
3662
3973
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3663
3974
  parse: (ev) => ({
3664
3975
  cwd: ev.cwd,
3665
3976
  sessionId: ev.sessionId
3666
- })
3977
+ }),
3978
+ deferContextToToolHook: true
3667
3979
  },
3668
3980
  prompt: {
3669
3981
  ...claudePrompt,
3670
3982
  harness: "grok-build",
3983
+ toolHook: {
3984
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
3985
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
3986
+ emit: (context) => ({
3987
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
3988
+ })
3989
+ },
3671
3990
  parse: (ev) => ({
3672
3991
  prompt: ev.prompt,
3673
3992
  cwd: ev.cwd,
@@ -3901,6 +4220,48 @@ var HOOK_HARNESSES = {
3901
4220
  },
3902
4221
  readTranscript: readKimiTranscript
3903
4222
  }
4223
+ },
4224
+ /**
4225
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4226
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4227
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4228
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4229
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4230
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4231
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4232
+ * file-backed host rather than the journal ZCode needs.
4233
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4234
+ */
4235
+ workbuddy: {
4236
+ configStyle: "nested",
4237
+ install: {
4238
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4239
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
4240
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
4241
+ },
4242
+ sessionStart: genieSessionStart("workbuddy"),
4243
+ prompt: geniePrompt("workbuddy"),
4244
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
4245
+ },
4246
+ /**
4247
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
4248
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
4249
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
4250
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
4251
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
4252
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
4253
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
4254
+ */
4255
+ codebuddy: {
4256
+ configStyle: "nested",
4257
+ install: {
4258
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
4259
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
4260
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
4261
+ },
4262
+ sessionStart: genieSessionStart("codebuddy"),
4263
+ prompt: geniePrompt("codebuddy"),
4264
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
3904
4265
  }
3905
4266
  };
3906
4267
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);