@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
@@ -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;
@@ -323,6 +345,19 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
323
345
  };
324
346
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
325
347
  }
348
+ function bankProjectName(config, directory, sessionRoot) {
349
+ if (mappedBank(config, directory, sessionRoot)) return void 0;
350
+ const dynamic = config.dynamicBankId ?? !config.bankId;
351
+ if (!dynamic) return void 0;
352
+ const template = config.bankIdTemplate || DEFAULT_TEMPLATE;
353
+ if (!template.includes("{gitProject}")) return void 0;
354
+ try {
355
+ return gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot);
356
+ } catch (error) {
357
+ if (error instanceof BankResolutionError) return void 0;
358
+ throw error;
359
+ }
360
+ }
326
361
  function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
327
362
  try {
328
363
  return deriveBankId(config, directory, harness, sessionRoot);
@@ -338,7 +373,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
338
373
  }
339
374
 
340
375
  // src/core/config.ts
341
- import { readFileSync as readFileSync2 } from "fs";
376
+ import { readFileSync as readFileSync3 } from "fs";
342
377
  import { homedir as homedir3 } from "os";
343
378
  import { join as join7 } from "path";
344
379
 
@@ -378,7 +413,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
378
413
  // src/core/missions.ts
379
414
  import { createHash } from "crypto";
380
415
  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.";
381
- 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.";
416
+ 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.";
382
417
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
383
418
  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.";
384
419
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -454,6 +489,8 @@ var KNOWLEDGE_LABELS = {
454
489
  ]
455
490
  };
456
491
  function pageScopeRule(project) {
492
+ if (project === void 0)
493
+ 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.`;
457
494
  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.`;
458
495
  }
459
496
  var PAGE_TAXONOMY = [
@@ -635,6 +672,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
635
672
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
636
673
  }
637
674
 
675
+ // package.json
676
+ var version = "0.8.1";
677
+
638
678
  // src/core/util.ts
639
679
  import { accessSync, constants } from "fs";
640
680
  import { delimiter, join as join6 } from "path";
@@ -658,12 +698,12 @@ function binOnPath(bin) {
658
698
  }
659
699
  }
660
700
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
661
- function semverGte(version, min) {
701
+ function semverGte(version2, min) {
662
702
  const parts = (v) => {
663
703
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
664
704
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
665
705
  };
666
- const a = version ? parts(version) : void 0;
706
+ const a = version2 ? parts(version2) : void 0;
667
707
  const b = parts(min);
668
708
  if (!a || !b) return false;
669
709
  for (let i = 0; i < 3; i++) {
@@ -697,6 +737,7 @@ function isOurMcpEntry(entry) {
697
737
  }
698
738
 
699
739
  // src/core/hindsight.ts
740
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
700
741
  function resolveRetainScopes(tags, configured) {
701
742
  if (configured !== "per_source") return configured;
702
743
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -732,7 +773,7 @@ async function isEndpointMissing(r) {
732
773
  const j = await r.json();
733
774
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
734
775
  } catch {
735
- return true;
776
+ return false;
736
777
  }
737
778
  }
738
779
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -751,6 +792,12 @@ var ReflectError = class extends Error {
751
792
  get fallbackEligible() {
752
793
  return this.timedOut || this.status !== void 0 && this.status >= 500;
753
794
  }
795
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
796
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
797
+ get permanent() {
798
+ const s = this.status;
799
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
800
+ }
754
801
  };
755
802
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
756
803
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -761,8 +808,10 @@ var DEFAULT_RECALL_OPTIONS = {
761
808
  include: { entities: null }
762
809
  };
763
810
  var POLL_CYCLE_MS = 5e3;
811
+ var POLL_MAX_SERVER_ERRORS = 12;
764
812
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
765
813
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
814
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
766
815
  function shapePage(page) {
767
816
  const p = page ?? {};
768
817
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -775,6 +824,15 @@ function shapePage(page) {
775
824
  body
776
825
  };
777
826
  }
827
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
828
+ function signalOnlyDispatcher() {
829
+ void globalThis.Headers;
830
+ const d = globalThis[GLOBAL_DISPATCHER];
831
+ if (typeof d?.compose !== "function") return void 0;
832
+ return d.compose(
833
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
834
+ );
835
+ }
778
836
  var HindsightClient = class {
779
837
  apiUrl;
780
838
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -794,6 +852,7 @@ var HindsightClient = class {
794
852
  observationScopes;
795
853
  pageSearchLimit;
796
854
  recallOptions;
855
+ rateLimitPatienceMs;
797
856
  constructor(o) {
798
857
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
799
858
  this.token = o.apiToken;
@@ -806,6 +865,7 @@ var HindsightClient = class {
806
865
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
807
866
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
808
867
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
868
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
809
869
  }
810
870
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
811
871
  get apiToken() {
@@ -814,7 +874,8 @@ var HindsightClient = class {
814
874
  headers() {
815
875
  const h = {
816
876
  "Content-Type": "application/json",
817
- "Accept-Encoding": "identity"
877
+ "Accept-Encoding": "identity",
878
+ "User-Agent": USER_AGENT
818
879
  };
819
880
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
820
881
  return h;
@@ -846,7 +907,8 @@ var HindsightClient = class {
846
907
  * bounds the whole call.
847
908
  */
848
909
  async fetchWithAuth(url, init) {
849
- const send = () => fetch(url, { ...init, headers: this.headers() });
910
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
911
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
850
912
  const r = await send();
851
913
  if (r.status !== 401 || !this.refreshToken()) return r;
852
914
  return send();
@@ -862,13 +924,22 @@ var HindsightClient = class {
862
924
  }
863
925
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
864
926
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
865
- const r = await this.fetchWithAuth(url, {
866
- method,
867
- body: body ? JSON.stringify(body) : void 0,
868
- signal: AbortSignal.timeout(timeoutMs)
869
- });
870
- if (r.status === 429 && !tolerate.includes(429))
871
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
927
+ const payload = body ? JSON.stringify(body) : void 0;
928
+ let r;
929
+ for (let attempt = 0, waited = 0; ; attempt++) {
930
+ r = await this.fetchWithAuth(url, {
931
+ method,
932
+ body: payload,
933
+ signal: AbortSignal.timeout(timeoutMs)
934
+ });
935
+ if (r.status !== 429 || tolerate.includes(429)) break;
936
+ const asked = retryAfterMs(r.headers.get("retry-after"));
937
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
938
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
939
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
940
+ await sleep(wait);
941
+ waited += wait;
942
+ }
872
943
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
873
944
  throw new Error(
874
945
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -903,7 +974,7 @@ var HindsightClient = class {
903
974
  }
904
975
  /**
905
976
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
906
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
977
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
907
978
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
908
979
  */
909
980
  async supportsIdempotentRetain() {
@@ -913,15 +984,21 @@ var HindsightClient = class {
913
984
  }
914
985
  return this.idempotentRetain;
915
986
  }
987
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
988
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
989
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
990
+ * `/version`, so that stays as the fallback. */
916
991
  async probeIdempotentRetain() {
917
- try {
918
- const r = await this.req("GET", `${this.apiUrl}/version`);
919
- if (!r.ok) return false;
920
- const j = await r.json();
921
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
922
- } catch {
923
- return false;
992
+ for (const path of ["/v1/version", "/version"]) {
993
+ try {
994
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
995
+ if (!r.ok) continue;
996
+ const j = await r.json();
997
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
998
+ } catch {
999
+ }
924
1000
  }
1001
+ return false;
925
1002
  }
926
1003
  /**
927
1004
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -983,6 +1060,14 @@ var HindsightClient = class {
983
1060
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
984
1061
  }
985
1062
  }
1063
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1064
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1065
+ async hasDocuments() {
1066
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1067
+ if (r.status === 404) return false;
1068
+ const j = await r.json();
1069
+ return (j.total ?? j.items?.length ?? 0) > 0;
1070
+ }
986
1071
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
987
1072
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
988
1073
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -1064,7 +1149,13 @@ var HindsightClient = class {
1064
1149
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1065
1150
  const start = Date.now();
1066
1151
  const pending = new Set(ids);
1152
+ const serverErrors = /* @__PURE__ */ new Map();
1067
1153
  let failed = 0;
1154
+ const giveUp = (id, status) => {
1155
+ pending.delete(id);
1156
+ failed++;
1157
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1158
+ };
1068
1159
  while (pending.size && Date.now() - start < maxMs) {
1069
1160
  let backoffMs = POLL_CYCLE_MS;
1070
1161
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1077,7 +1168,14 @@ var HindsightClient = class {
1077
1168
  );
1078
1169
  return;
1079
1170
  }
1080
- if (!r.ok) return;
1171
+ if (r.status >= 500) {
1172
+ const n = (serverErrors.get(id) ?? 0) + 1;
1173
+ serverErrors.set(id, n);
1174
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1175
+ return;
1176
+ }
1177
+ if (!r.ok) return giveUp(id, r.status);
1178
+ serverErrors.delete(id);
1081
1179
  const st = ((await r.json()).status || "").toLowerCase();
1082
1180
  if (TERMINAL.has(st)) {
1083
1181
  pending.delete(id);
@@ -1261,7 +1359,7 @@ var HindsightClient = class {
1261
1359
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1262
1360
  */
1263
1361
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1264
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1362
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1265
1363
  const existing = /* @__PURE__ */ new Map();
1266
1364
  let roots;
1267
1365
  try {
@@ -1336,7 +1434,7 @@ var HindsightClient = class {
1336
1434
  }
1337
1435
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1338
1436
  this.log(
1339
- `[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` : "")
1437
+ `[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` : "")
1340
1438
  );
1341
1439
  }
1342
1440
  /**
@@ -1347,23 +1445,33 @@ var HindsightClient = class {
1347
1445
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1348
1446
  * consolidation under the auto-refresh that used to be the default (#3506).
1349
1447
  *
1350
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1351
- * initiative's own title, and re-stating either would rebuild a page whose question never
1352
- * changed. The tree read above is reused rather than re-fetched.
1448
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1449
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1450
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1451
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1452
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1453
+ * reused rather than re-fetched.
1353
1454
  */
1354
1455
  async resyncInitiativeTriggers(roots, pageTrigger) {
1355
1456
  const folder = roots.find(
1356
1457
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1357
1458
  );
1459
+ const bankScope = pageScopeRule(this.bank);
1358
1460
  let updated = 0;
1359
1461
  for (const page of folder?.children ?? []) {
1360
- if (page.kind !== "page" || page.trigger == null) continue;
1361
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1362
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1462
+ if (page.kind !== "page") continue;
1463
+ const patch = {};
1464
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1465
+ if (query !== page.description) patch.source_query = query;
1466
+ if (page.trigger != null) {
1467
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1468
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1469
+ }
1470
+ if (!patch.trigger && !patch.source_query) continue;
1363
1471
  const r = await this.req(
1364
1472
  "PATCH",
1365
1473
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1366
- { trigger: pageTriggerPatch(desired) }
1474
+ patch
1367
1475
  );
1368
1476
  if (r.status === 404) continue;
1369
1477
  updated++;
@@ -1391,10 +1499,9 @@ var HindsightClient = class {
1391
1499
  let pageId = args.relatesToPageId;
1392
1500
  if (!pageId) {
1393
1501
  const folderId = await this.ensureFolder("Initiatives");
1394
- const subject = this.project ?? this.bank;
1395
1502
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1396
1503
  name: args.title,
1397
- 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),
1504
+ 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),
1398
1505
  parent_id: folderId,
1399
1506
  tags: ["knowledge:feature-work"],
1400
1507
  max_tokens: PAGE_MAX_TOKENS,
@@ -1409,7 +1516,7 @@ var HindsightClient = class {
1409
1516
  }
1410
1517
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1411
1518
  const content = `${verb}: ${args.title}. ${args.summary}`;
1412
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1519
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1413
1520
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1414
1521
  const context = `initiative marker for [[page:${pageId}]]`;
1415
1522
  await this.retain(content, context, markerId, tags, "document", {
@@ -1646,7 +1753,7 @@ function resolveConfig(raw = {}) {
1646
1753
  }
1647
1754
  function readRaw(path) {
1648
1755
  try {
1649
- return JSON.parse(readFileSync2(path, "utf8"));
1756
+ return JSON.parse(readFileSync3(path, "utf8"));
1650
1757
  } catch (e) {
1651
1758
  if (e?.code !== "ENOENT") {
1652
1759
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1888,7 +1995,7 @@ This tool guide and the page list are re-injected for you periodically as things
1888
1995
  }
1889
1996
 
1890
1997
  // src/core/session-cache.ts
1891
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1998
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1892
1999
  import { tmpdir } from "os";
1893
2000
  import { dirname as dirname5, join as join8 } from "path";
1894
2001
  function sessionCacheFile(harness, sessionId) {
@@ -1914,6 +2021,24 @@ function writeSessionCache(cacheFile, cache) {
1914
2021
  } catch {
1915
2022
  }
1916
2023
  }
2024
+ function pendingContextFile(harness, sessionId) {
2025
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.pending`);
2026
+ }
2027
+ function stashPendingContext(harness, sessionId, context) {
2028
+ const path = pendingContextFile(harness, sessionId);
2029
+ let existing = "";
2030
+ try {
2031
+ existing = readFileSync4(path, "utf8");
2032
+ } catch {
2033
+ }
2034
+ if (existing.includes(context)) return;
2035
+ try {
2036
+ writeFileAtomic(path, existing ? `${existing}
2037
+
2038
+ ${context}` : context);
2039
+ } catch {
2040
+ }
2041
+ }
1917
2042
  function sessionRootFile(harness, sessionId) {
1918
2043
  return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1919
2044
  }
@@ -1921,7 +2046,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1921
2046
  if (!sessionId || !cwd) return cwd;
1922
2047
  const file = sessionRootFile(harness, sessionId);
1923
2048
  try {
1924
- const recorded = readFileSync3(file, "utf8").trim();
2049
+ const recorded = readFileSync4(file, "utf8").trim();
1925
2050
  if (recorded) return recorded;
1926
2051
  } catch {
1927
2052
  }
@@ -1933,7 +2058,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1933
2058
  }
1934
2059
 
1935
2060
  // src/core/turn-journal.ts
1936
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2061
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1937
2062
  import { tmpdir as tmpdir2 } from "os";
1938
2063
  import { dirname as dirname6, join as join9 } from "path";
1939
2064
 
@@ -1975,9 +2100,6 @@ function actionLine(tool, input) {
1975
2100
  // src/core/turn-journal.ts
1976
2101
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1977
2102
 
1978
- // src/core/retain-hook.ts
1979
- import { readFileSync as readFileSync7 } from "fs";
1980
-
1981
2103
  // src/core/retain-cursor.ts
1982
2104
  import { createHash as createHash2 } from "crypto";
1983
2105
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
@@ -1993,7 +2115,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
1993
2115
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1994
2116
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1995
2117
  try {
1996
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2118
+ const res = await fetch(`${baseUrl}/health`, {
2119
+ headers: { "User-Agent": USER_AGENT },
2120
+ signal: AbortSignal.timeout(timeoutMs)
2121
+ });
1997
2122
  return res.ok;
1998
2123
  } catch {
1999
2124
  return false;
@@ -2236,15 +2361,12 @@ function* readJsonl(path) {
2236
2361
  import { readFileSync as readFileSync6 } from "fs";
2237
2362
  import { join as join11 } from "path";
2238
2363
 
2239
- // src/core/session-start.ts
2240
- import { readFileSync as readFileSync11 } from "fs";
2241
-
2242
2364
  // src/core/git.ts
2243
2365
  import { execFileSync as execFileSync2 } from "child_process";
2244
2366
  import { resolve as resolve2 } from "path";
2245
2367
  var GITLOG_HEAD = "gitlog-head:";
2246
2368
  function git(repo, ...args) {
2247
- return execFileSync2("git", ["-C", repo, ...args], {
2369
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
2248
2370
  encoding: "utf8",
2249
2371
  maxBuffer: 1 << 28,
2250
2372
  windowsHide: true,
@@ -2290,10 +2412,10 @@ async function gitLogIsCurrent(client, repo, head) {
2290
2412
  }
2291
2413
 
2292
2414
  // src/core/status.ts
2293
- import { execFileSync as execFileSync3 } from "child_process";
2415
+ import { execFileSync as execFileSync4 } from "child_process";
2294
2416
 
2295
2417
  // src/core/survey.ts
2296
- import { spawn as realSpawn4 } from "child_process";
2418
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2297
2419
  import { createHash as createHash4 } from "crypto";
2298
2420
  import { existsSync as existsSync3 } from "fs";
2299
2421
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2306,7 +2428,9 @@ function resolveHostConfig(harness, directory) {
2306
2428
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
2307
2429
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
2308
2430
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
2309
- return applyBankConfig(cfg0, bankId, directory);
2431
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
2432
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
2433
+ return { ...resolved2, project };
2310
2434
  }
2311
2435
 
2312
2436
  // src/core/survey-lease.ts
@@ -2411,6 +2535,19 @@ function resolveAgentBin(harness, claudeBin) {
2411
2535
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
2412
2536
  }
2413
2537
  }
2538
+ function opencodeCanDefineSurveyAgent(bin) {
2539
+ try {
2540
+ const out = execFileSync3(bin, ["--version"], {
2541
+ encoding: "utf8",
2542
+ timeout: 5e3,
2543
+ windowsHide: true,
2544
+ stdio: ["ignore", "pipe", "ignore"]
2545
+ });
2546
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
2547
+ } catch {
2548
+ return false;
2549
+ }
2550
+ }
2414
2551
  var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
2415
2552
  var SURVEY_DISALLOWED_TOOLS = [
2416
2553
  "Bash",
@@ -2524,6 +2661,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2524
2661
  seen.add(harness);
2525
2662
  const bin = resolveAgentBin(harness, opts.claudeBin);
2526
2663
  if (!exists(bin)) continue;
2664
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
2665
+ continue;
2527
2666
  const plan = buildSurveyPlan(harness, bin, repoDir, {
2528
2667
  model: opts.model,
2529
2668
  budgetUsd: opts.budgetUsd,
@@ -2584,7 +2723,7 @@ import { spawn as realSpawn5 } from "child_process";
2584
2723
  import {
2585
2724
  existsSync as existsSync4,
2586
2725
  mkdirSync as mkdirSync5,
2587
- readFileSync as readFileSync8,
2726
+ readFileSync as readFileSync7,
2588
2727
  realpathSync as realpathSync2,
2589
2728
  unlinkSync as unlinkSync2,
2590
2729
  writeFileSync as writeFileSync3
@@ -2615,7 +2754,7 @@ function sameDir(a, b) {
2615
2754
  }
2616
2755
  function stagedVersion(pkgRoot) {
2617
2756
  try {
2618
- const pkg = JSON.parse(readFileSync8(join14(pkgRoot, "package.json"), "utf8"));
2757
+ const pkg = JSON.parse(readFileSync7(join14(pkgRoot, "package.json"), "utf8"));
2619
2758
  return typeof pkg.version === "string" ? pkg.version : "";
2620
2759
  } catch {
2621
2760
  return "";
@@ -2640,7 +2779,7 @@ function isNewer(candidate, current2) {
2640
2779
  }
2641
2780
  function dueForCheck(file, now) {
2642
2781
  try {
2643
- const state = JSON.parse(readFileSync8(file, "utf8"));
2782
+ const state = JSON.parse(readFileSync7(file, "utf8"));
2644
2783
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
2645
2784
  } catch {
2646
2785
  return true;
@@ -2649,7 +2788,7 @@ function dueForCheck(file, now) {
2649
2788
  var ORIGIN_FILE = ".install-origin.json";
2650
2789
  function selfUpdatable(runtimeDir) {
2651
2790
  try {
2652
- const origin = JSON.parse(readFileSync8(join14(runtimeDir, ORIGIN_FILE), "utf8"));
2791
+ const origin = JSON.parse(readFileSync7(join14(runtimeDir, ORIGIN_FILE), "utf8"));
2653
2792
  if (typeof origin.source !== "string" || !origin.source) return false;
2654
2793
  return origin.source.split(/[\\/]/).includes("_npx");
2655
2794
  } catch {
@@ -2662,7 +2801,7 @@ function lockFile() {
2662
2801
  }
2663
2802
  function acquireUpdateLock(file, now) {
2664
2803
  try {
2665
- const held = JSON.parse(readFileSync8(file, "utf8"));
2804
+ const held = JSON.parse(readFileSync7(file, "utf8"));
2666
2805
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
2667
2806
  let holderAlive = false;
2668
2807
  if (held.pid) {
@@ -2703,6 +2842,9 @@ function stampCheck(file, now, latest) {
2703
2842
  } catch {
2704
2843
  }
2705
2844
  }
2845
+ function spawnNpm(spawnImpl, bin, args, opts) {
2846
+ return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2847
+ }
2706
2848
  async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2707
2849
  return new Promise((resolve3) => {
2708
2850
  let out = "";
@@ -2716,7 +2858,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2716
2858
  resolve3(v);
2717
2859
  };
2718
2860
  try {
2719
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2861
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
2720
2862
  timeout: NPM_VIEW_TIMEOUT_MS,
2721
2863
  stdio: ["ignore", "pipe", "ignore"],
2722
2864
  windowsHide: true
@@ -2785,7 +2927,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2785
2927
  return "";
2786
2928
  }
2787
2929
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2788
- const child = (opts.spawn ?? realSpawn5)(
2930
+ const child = spawnNpm(
2931
+ opts.spawn ?? realSpawn5,
2789
2932
  "npx",
2790
2933
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2791
2934
  {
@@ -2811,7 +2954,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2811
2954
  }
2812
2955
 
2813
2956
  // src/core/skill-sync.ts
2814
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2957
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2815
2958
  import { homedir as homedir6 } from "os";
2816
2959
  import { dirname as dirname10, join as join16 } from "path";
2817
2960
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -2847,7 +2990,12 @@ var SKILL_DIRS = {
2847
2990
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2848
2991
  // and dsh's copy with it.
2849
2992
  pi: [".pi", "agent", "skills"],
2850
- "prime-agent": [".prime", "agent", "skills"]
2993
+ "prime-agent": [".prime", "agent", "skills"],
2994
+ // WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
2995
+ workbuddy: [".workbuddy", "skills"],
2996
+ // CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
2997
+ // its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
2998
+ codebuddy: [".codebuddy", "skills"]
2851
2999
  };
2852
3000
  var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
2853
3001
  var traecodeDotDirName = (home, exists = existsSync5) => {
@@ -2881,7 +3029,7 @@ function syncCompanionSkill(harness, opts = {}) {
2881
3029
  const dstMd = join16(dst, "SKILL.md");
2882
3030
  const installed = existsSync6(dstMd);
2883
3031
  if (!installed && !opts.install) return;
2884
- if (!installed || readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
3032
+ if (!installed || readFileSync8(srcMd, "utf8") !== readFileSync8(dstMd, "utf8")) {
2885
3033
  cpSync(src, dst, { recursive: true });
2886
3034
  }
2887
3035
  } catch {
@@ -2889,7 +3037,7 @@ function syncCompanionSkill(harness, opts = {}) {
2889
3037
  }
2890
3038
 
2891
3039
  // src/core/legacy.ts
2892
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
3040
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2893
3041
  import { homedir as homedir7 } from "os";
2894
3042
  import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2895
3043
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -2914,7 +3062,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")
2914
3062
  }
2915
3063
  function readJson(path) {
2916
3064
  try {
2917
- const parsed = JSON.parse(readFileSync10(path, "utf8"));
3065
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
2918
3066
  return parsed && typeof parsed === "object" ? parsed : void 0;
2919
3067
  } catch {
2920
3068
  return void 0;
@@ -2943,9 +3091,9 @@ async function gitSyncNote(args) {
2943
3091
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
2944
3092
  let target = DEEPEN_DIFF_TARGET;
2945
3093
  try {
2946
- const { execFileSync: execFileSync5 } = await import("child_process");
3094
+ const { execFileSync: execFileSync6 } = await import("child_process");
2947
3095
  const n = Number(
2948
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
3096
+ execFileSync6("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2949
3097
  encoding: "utf8",
2950
3098
  windowsHide: true,
2951
3099
  stdio: ["ignore", "pipe", "pipe"]
@@ -2962,6 +3110,7 @@ async function buildSessionStartContext(args) {
2962
3110
  const t0 = Date.now();
2963
3111
  let cold;
2964
3112
  let gitDocIds;
3113
+ let bankEmpty = false;
2965
3114
  const harness = args.harness ?? "claude-code";
2966
3115
  const hasGit = args.hasGit ?? hasGitHistory;
2967
3116
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -3001,11 +3150,21 @@ async function buildSessionStartContext(args) {
3001
3150
  } catch {
3002
3151
  docIds = void 0;
3003
3152
  }
3004
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
3153
+ let baselines;
3154
+ if (docIds?.size === 0) {
3155
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
3156
+ }
3157
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
3005
3158
  gitDocIds = docIds;
3159
+ if (cold === true && client.hasDocuments) {
3160
+ bankEmpty = await client.hasDocuments().then(
3161
+ (has) => !has,
3162
+ () => false
3163
+ );
3164
+ }
3006
3165
  if (docIds !== void 0) {
3007
3166
  startSeed(cwd, { limit: cfg.seedLimit, harness });
3008
- if (docIds.size === 0) {
3167
+ if (cold) {
3009
3168
  if (cfg.codebaseSurvey !== false) {
3010
3169
  const started = await startSurvey(cwd, {
3011
3170
  harness,
@@ -3019,7 +3178,7 @@ async function buildSessionStartContext(args) {
3019
3178
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
3020
3179
  const sha = resolveHeadSha(cwd);
3021
3180
  if (sha) {
3022
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
3181
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
3023
3182
  const counts = [];
3024
3183
  for (const id of markers) {
3025
3184
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -3053,10 +3212,8 @@ async function buildSessionStartContext(args) {
3053
3212
  }
3054
3213
  }
3055
3214
  let pages = [];
3056
- let pageListKnown = false;
3057
3215
  try {
3058
3216
  pages = parsePageList(await client.listPages());
3059
- pageListKnown = true;
3060
3217
  } catch {
3061
3218
  if (client.knowledgePagesSupported === false) {
3062
3219
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -3066,7 +3223,7 @@ async function buildSessionStartContext(args) {
3066
3223
  reflectOnNewGoals: cfg.autoInject !== "reflect",
3067
3224
  extra: cfg.toolGuideExtra
3068
3225
  });
3069
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
3226
+ const deferInitialReflect = bankEmpty;
3070
3227
  let gitNote;
3071
3228
  if (gitDocIds) {
3072
3229
  gitNote = await gitSyncNote({
@@ -3091,12 +3248,8 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
3091
3248
  async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient(o)) {
3092
3249
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
3093
3250
  try {
3094
- let ev = {};
3095
- try {
3096
- ev = JSON.parse(readFileSync11(0, "utf8"));
3097
- } catch {
3098
- return;
3099
- }
3251
+ const ev = readHookEvent(spec.harness);
3252
+ if (!ev) return;
3100
3253
  if (spec.accept && !spec.accept(ev)) return;
3101
3254
  const { harness } = spec;
3102
3255
  const { cwd: rawCwd, sessionId } = spec.parse(ev);
@@ -3129,6 +3282,10 @@ ${mcpHint}` : mcpHint;
3129
3282
  if (out.deferInitialReflect && sessionId) {
3130
3283
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
3131
3284
  }
3285
+ if (spec.deferContextToToolHook && out.additionalContext && sessionId) {
3286
+ stashPendingContext(harness, sessionId, out.additionalContext);
3287
+ out.additionalContext = void 0;
3288
+ }
3132
3289
  const payload = spec.emit(out);
3133
3290
  if (out.systemMessage || out.additionalContext) {
3134
3291
  process.stdout.write(JSON.stringify(payload));
@@ -3138,8 +3295,8 @@ ${mcpHint}` : mcpHint;
3138
3295
  }
3139
3296
 
3140
3297
  // src/core/traecode-mcp.ts
3141
- import { execFileSync as execFileSync4 } from "child_process";
3142
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
3298
+ import { execFileSync as execFileSync5 } from "child_process";
3299
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
3143
3300
  import { homedir as homedir8 } from "os";
3144
3301
  import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
3145
3302
  import { fileURLToPath as fileURLToPath6 } from "url";
@@ -3176,7 +3333,7 @@ function gateStateFile() {
3176
3333
  }
3177
3334
  function readGateState(opts = {}) {
3178
3335
  try {
3179
- return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
3336
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
3180
3337
  } catch {
3181
3338
  return {};
3182
3339
  }
@@ -3184,7 +3341,7 @@ function readGateState(opts = {}) {
3184
3341
  function workspaceMcpGateState(settingsPath) {
3185
3342
  let raw;
3186
3343
  try {
3187
- raw = readFileSync12(settingsPath, "utf8");
3344
+ raw = readFileSync10(settingsPath, "utf8");
3188
3345
  } catch {
3189
3346
  return "unknown";
3190
3347
  }
@@ -3224,7 +3381,7 @@ function gitignoreCovers(lines) {
3224
3381
  function ensureGitignored(repo) {
3225
3382
  const gitignore = join18(repo, ".gitignore");
3226
3383
  if (!existsSync8(gitignore)) return;
3227
- const current2 = readFileSync12(gitignore, "utf8");
3384
+ const current2 = readFileSync10(gitignore, "utf8");
3228
3385
  if (gitignoreCovers(current2.split("\n"))) return;
3229
3386
  const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
3230
3387
  writeFileSync4(gitignore, current2 + addition);
@@ -3245,7 +3402,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3245
3402
  let doc = {};
3246
3403
  let exists = false;
3247
3404
  try {
3248
- doc = JSON.parse(readFileSync12(file, "utf8"));
3405
+ doc = JSON.parse(readFileSync10(file, "utf8"));
3249
3406
  exists = true;
3250
3407
  } catch {
3251
3408
  if (existsSync8(file)) return "skipped";
@@ -3301,7 +3458,7 @@ function findWorkspaceStorageDir(storage, repo) {
3301
3458
  }
3302
3459
  for (const name of entries) {
3303
3460
  try {
3304
- const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
3461
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
3305
3462
  if (typeof doc.folder !== "string") continue;
3306
3463
  let folder;
3307
3464
  try {
@@ -3324,7 +3481,7 @@ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3324
3481
  if (!dir) return "failed";
3325
3482
  const db = join18(dir, "state.vscdb");
3326
3483
  if (!existsSync8(db)) return "failed";
3327
- const sqlite = opts.sqlite ?? execFileSync4;
3484
+ const sqlite = opts.sqlite ?? execFileSync5;
3328
3485
  const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3329
3486
  encoding: "utf8",
3330
3487
  timeout: SQLITE_TIMEOUT_MS,
@@ -3372,6 +3529,14 @@ function isSyntheticUserText(text) {
3372
3529
  const s = text.trimStart();
3373
3530
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
3374
3531
  }
3532
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
3533
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
3534
+ function isStartupItem(text) {
3535
+ const s = text.trim();
3536
+ if (AGENTS_BLOCK_HEADER.test(s))
3537
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
3538
+ return STARTUP_TAG_BLOCK.test(s);
3539
+ }
3375
3540
  function contentText(content) {
3376
3541
  return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3377
3542
  }
@@ -3388,7 +3553,10 @@ function fallbackUserText(payload) {
3388
3553
  if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3389
3554
  return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3390
3555
  }
3391
- const text = contentText(content);
3556
+ const items = (Array.isArray(content) ? content : []).filter(
3557
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
3558
+ );
3559
+ const text = contentText(items);
3392
3560
  return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
3393
3561
  }
3394
3562
  function isUserMessageEvent(line) {
@@ -3565,7 +3733,7 @@ function readCopilotTranscript(path) {
3565
3733
  }
3566
3734
 
3567
3735
  // src/core/transcript-grok.ts
3568
- import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3736
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3569
3737
  import { homedir as homedir9 } from "os";
3570
3738
  import { join as join19 } from "path";
3571
3739
  var CHAT_HISTORY = "chat_history.jsonl";
@@ -3576,7 +3744,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
3576
3744
  try {
3577
3745
  for (const candidate of readdirSync3(sessionsDir)) {
3578
3746
  const directory = join19(sessionsDir, candidate);
3579
- if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3747
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3580
3748
  return join19(directory, sessionId, CHAT_HISTORY);
3581
3749
  }
3582
3750
  }
@@ -3927,7 +4095,7 @@ function readDroidTranscript(path) {
3927
4095
  }
3928
4096
 
3929
4097
  // src/core/transcript-zcode.ts
3930
- import { readFileSync as readFileSync14 } from "fs";
4098
+ import { readFileSync as readFileSync12 } from "fs";
3931
4099
  function messageText(content) {
3932
4100
  if (typeof content === "string") return content.trim();
3933
4101
  if (!Array.isArray(content)) return "";
@@ -3937,7 +4105,7 @@ function readZcodeTranscript(path) {
3937
4105
  if (!path) return [];
3938
4106
  let body;
3939
4107
  try {
3940
- body = readFileSync14(path, "utf8");
4108
+ body = readFileSync12(path, "utf8");
3941
4109
  } catch {
3942
4110
  return [];
3943
4111
  }
@@ -4096,6 +4264,135 @@ function readKimiTranscript(path) {
4096
4264
  return turns;
4097
4265
  }
4098
4266
 
4267
+ // src/core/transcript-workbuddy.ts
4268
+ function messageText2(content) {
4269
+ if (typeof content === "string") return content;
4270
+ if (!Array.isArray(content)) return "";
4271
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
4272
+ }
4273
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
4274
+ function unwrapUserQuery(text) {
4275
+ const match = USER_QUERY_RE.exec(text);
4276
+ return (match ? match[1] : text).trim();
4277
+ }
4278
+ function isSyntheticUserText2(text) {
4279
+ const s = text.trimStart();
4280
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
4281
+ }
4282
+ function parseArgs2(raw) {
4283
+ if (!raw) return void 0;
4284
+ try {
4285
+ return JSON.parse(raw);
4286
+ } catch {
4287
+ return raw;
4288
+ }
4289
+ }
4290
+ function stampOf3(line) {
4291
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
4292
+ }
4293
+ function readWorkbuddyTranscript(path) {
4294
+ const turns = [];
4295
+ for (const rawLine of readJsonl(path)) {
4296
+ const trimmed = rawLine.trim();
4297
+ if (!trimmed) continue;
4298
+ let parsed;
4299
+ try {
4300
+ parsed = JSON.parse(trimmed);
4301
+ } catch {
4302
+ continue;
4303
+ }
4304
+ if (typeof parsed !== "object" || parsed === null) continue;
4305
+ const line = parsed;
4306
+ const stamp = stampOf3(line);
4307
+ if (line.type === "message") {
4308
+ if (line.role !== "user" && line.role !== "assistant") continue;
4309
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
4310
+ if (!text) continue;
4311
+ if (line.role === "user") {
4312
+ if (isSyntheticUserText2(text)) continue;
4313
+ text = unwrapUserQuery(text);
4314
+ if (!text) continue;
4315
+ }
4316
+ turns.push({ role: line.role, content: text, ...stamp });
4317
+ } else if (line.type === "function_call" && typeof line.name === "string") {
4318
+ turns.push({
4319
+ role: "action",
4320
+ content: actionLine(line.name, parseArgs2(line.arguments)),
4321
+ ...stamp
4322
+ });
4323
+ }
4324
+ }
4325
+ return turns;
4326
+ }
4327
+
4328
+ // src/core/transcript-codebuddy-ide.ts
4329
+ import { readFileSync as readFileSync13 } from "fs";
4330
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
4331
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
4332
+ function readJson2(path) {
4333
+ try {
4334
+ return JSON.parse(readFileSync13(path, "utf8"));
4335
+ } catch {
4336
+ return void 0;
4337
+ }
4338
+ }
4339
+ function ideUserText(raw) {
4340
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
4341
+ if (!text || isSyntheticUserText2(text)) return "";
4342
+ return unwrapUserQuery(text).trim();
4343
+ }
4344
+ function readCodebuddyIdeTranscript(indexPath) {
4345
+ const index = readJson2(indexPath);
4346
+ const entries = index?.messages;
4347
+ if (!Array.isArray(entries)) return [];
4348
+ const messagesDir = join22(dirname12(indexPath), "messages");
4349
+ const turns = [];
4350
+ for (const entry of entries) {
4351
+ const id = entry?.id;
4352
+ if (typeof id !== "string") continue;
4353
+ const file = readJson2(join22(messagesDir, `${id}.json`));
4354
+ const encoded = file?.message;
4355
+ if (typeof encoded !== "string") continue;
4356
+ let inner;
4357
+ try {
4358
+ inner = JSON.parse(encoded);
4359
+ } catch {
4360
+ continue;
4361
+ }
4362
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
4363
+ const isUser = role === "user";
4364
+ const isAssistant = role === "assistant";
4365
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
4366
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
4367
+ const texts = [];
4368
+ const calls = [];
4369
+ for (const block of blocks) {
4370
+ if (!block || typeof block !== "object") continue;
4371
+ const { type, text, toolName, args } = block;
4372
+ if (type === "text" && typeof text === "string") texts.push(text);
4373
+ else if (type === "tool-call" && typeof toolName === "string")
4374
+ calls.push({ name: toolName, args });
4375
+ }
4376
+ if (texts.length) {
4377
+ const raw = texts.join("\n");
4378
+ if (isUser) {
4379
+ const text = ideUserText(raw);
4380
+ if (text) turns.push({ role: "user", content: text, ...stamp });
4381
+ } else if (isAssistant) {
4382
+ const text = stripInjectedMemory(raw).trim();
4383
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
4384
+ }
4385
+ }
4386
+ for (const call of calls) {
4387
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
4388
+ }
4389
+ }
4390
+ return turns;
4391
+ }
4392
+ function readCodebuddyTranscript(path) {
4393
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
4394
+ }
4395
+
4099
4396
  // src/harness/hook-lifecycle.ts
4100
4397
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
4101
4398
  var claudePrompt = {
@@ -4201,6 +4498,35 @@ var standardSessionStart = (harness) => ({
4201
4498
  }
4202
4499
  })
4203
4500
  });
4501
+ var genieSessionStart = (harness) => {
4502
+ const base = standardSessionStart(harness);
4503
+ return {
4504
+ ...base,
4505
+ parse: (ev) => ({
4506
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
4507
+ sessionId: ev.session_id
4508
+ }),
4509
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
4510
+ };
4511
+ };
4512
+ var geniePrompt = (harness) => ({
4513
+ ...claudePrompt,
4514
+ harness,
4515
+ emit: (context, notice, ev) => ({
4516
+ ...claudePrompt.emit(context, notice, ev),
4517
+ suppressOutput: true
4518
+ })
4519
+ });
4520
+ var genieRetain = (harness, readTranscript) => ({
4521
+ hostTimeoutSec: 60,
4522
+ harness,
4523
+ parse: (ev) => ({
4524
+ sessionId: ev.session_id,
4525
+ transcriptPath: ev.transcript_path,
4526
+ cwd: ev.cwd
4527
+ }),
4528
+ readTranscript
4529
+ });
4204
4530
  var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
4205
4531
  var HOOK_HARNESSES = {
4206
4532
  "claude-code": {
@@ -4398,17 +4724,29 @@ var HOOK_HARNESSES = {
4398
4724
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
4399
4725
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
4400
4726
  },
4727
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
4728
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
4729
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
4730
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
4401
4731
  sessionStart: {
4402
4732
  ...standardSessionStart("grok-build"),
4403
4733
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
4404
4734
  parse: (ev) => ({
4405
4735
  cwd: ev.cwd,
4406
4736
  sessionId: ev.sessionId
4407
- })
4737
+ }),
4738
+ deferContextToToolHook: true
4408
4739
  },
4409
4740
  prompt: {
4410
4741
  ...claudePrompt,
4411
4742
  harness: "grok-build",
4743
+ toolHook: {
4744
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
4745
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
4746
+ emit: (context) => ({
4747
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
4748
+ })
4749
+ },
4412
4750
  parse: (ev) => ({
4413
4751
  prompt: ev.prompt,
4414
4752
  cwd: ev.cwd,
@@ -4642,6 +4980,48 @@ var HOOK_HARNESSES = {
4642
4980
  },
4643
4981
  readTranscript: readKimiTranscript
4644
4982
  }
4983
+ },
4984
+ /**
4985
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4986
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4987
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4988
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4989
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4990
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4991
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4992
+ * file-backed host rather than the journal ZCode needs.
4993
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4994
+ */
4995
+ workbuddy: {
4996
+ configStyle: "nested",
4997
+ install: {
4998
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4999
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
5000
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
5001
+ },
5002
+ sessionStart: genieSessionStart("workbuddy"),
5003
+ prompt: geniePrompt("workbuddy"),
5004
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
5005
+ },
5006
+ /**
5007
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
5008
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
5009
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
5010
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
5011
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
5012
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
5013
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
5014
+ */
5015
+ codebuddy: {
5016
+ configStyle: "nested",
5017
+ install: {
5018
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
5019
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
5020
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
5021
+ },
5022
+ sessionStart: genieSessionStart("codebuddy"),
5023
+ prompt: geniePrompt("codebuddy"),
5024
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
4645
5025
  }
4646
5026
  };
4647
5027
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);