@vectorize-io/hindsight-coding-agents 0.7.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 +201 -16
  2. package/dist/antigravity-hook.js +1132 -115
  3. package/dist/antigravity-statusline.js +77 -11
  4. package/dist/antigravity-stop-hook.js +1193 -133
  5. package/dist/claude-hook.js +1132 -115
  6. package/dist/claude-sessionstart-hook.js +1241 -140
  7. package/dist/claude-stop-hook.js +1193 -133
  8. package/dist/cline.js +578 -163
  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 +1132 -115
  13. package/dist/codex-sessionstart-hook.js +1241 -140
  14. package/dist/codex-stop-hook.js +1193 -133
  15. package/dist/copilot-hook.js +1132 -115
  16. package/dist/copilot-sessionstart-hook.js +1241 -140
  17. package/dist/copilot-stop-hook.js +1193 -133
  18. package/dist/cursor-hook.js +1132 -115
  19. package/dist/cursor-sessionstart-hook.js +1241 -140
  20. package/dist/cursor-stop-hook.js +1193 -133
  21. package/dist/daemon-start.js +54 -9
  22. package/dist/dcode-hook.js +1132 -115
  23. package/dist/dcode-sessionstart-hook.js +1241 -140
  24. package/dist/dcode-stop-hook.js +1193 -133
  25. package/dist/deepen.js +370 -104
  26. package/dist/devin-hook.js +1132 -115
  27. package/dist/devin-sessionstart-hook.js +1241 -140
  28. package/dist/devin-stop-hook.js +1193 -133
  29. package/dist/droid-hook.js +1132 -115
  30. package/dist/droid-sessionstart-hook.js +1241 -140
  31. package/dist/droid-stop-hook.js +1193 -133
  32. package/dist/dsh.js +586 -164
  33. package/dist/grok-hook.js +1132 -115
  34. package/dist/grok-sessionstart-hook.js +1241 -140
  35. package/dist/grok-stop-hook.js +1193 -133
  36. package/dist/hindsight-seed.js +50 -8
  37. package/dist/index.js +587 -172
  38. package/dist/installer.js +2010 -769
  39. package/dist/kilo.js +587 -172
  40. package/dist/kimi-hook.js +4270 -0
  41. package/dist/kimi-sessionstart-hook.js +5030 -0
  42. package/dist/kimi-stop-hook.js +4564 -0
  43. package/dist/mcp-server.js +419 -115
  44. package/dist/opencode2.js +586 -169
  45. package/dist/pi.js +644 -175
  46. package/dist/prime-agent.js +644 -175
  47. package/dist/qwen-hook.js +1132 -115
  48. package/dist/qwen-sessionstart-hook.js +1241 -140
  49. package/dist/qwen-stop-hook.js +1193 -133
  50. package/dist/status.js +243 -52
  51. package/dist/traecode-hook.js +4270 -0
  52. package/dist/traecode-sessionstart-hook.js +5030 -0
  53. package/dist/traecode-stop-hook.js +4564 -0
  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 +1132 -115
  58. package/dist/zcode-sessionstart-hook.js +1241 -140
  59. package/dist/zcode-stop-hook.js +1193 -133
  60. package/package.json +22 -12
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +73 -14
@@ -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;
@@ -270,13 +292,13 @@ function isWithin(directory, configured) {
270
292
  function mapLookup(map, directory) {
271
293
  const cwd = normalize(directory);
272
294
  let best;
273
- for (const [dir, bank] of Object.entries(map)) {
295
+ for (const [dir, value] of Object.entries(map)) {
274
296
  const p = configuredDir(dir);
275
297
  if (isWithin(cwd, p)) {
276
- if (!best || p.length > best.len) best = { len: p.length, bank };
298
+ if (!best || p.length > best.len) best = { len: p.length, value };
277
299
  }
278
300
  }
279
- return best?.bank;
301
+ return best?.value;
280
302
  }
281
303
  function lookupDirectories(config, directory, sessionRoot = "") {
282
304
  const directories = [normalize(directory)];
@@ -300,6 +322,10 @@ function isOptedIn(config, directory) {
300
322
  const pathMap = config.mapPathToBank;
301
323
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
302
324
  }
325
+ function pathSection(config, paths, directory) {
326
+ if (!directory || !paths) return void 0;
327
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
328
+ }
303
329
  function mappedBank(config, directory, sessionRoot) {
304
330
  const pathMap = config.mapPathToBank;
305
331
  if (!directory || !pathMap) return void 0;
@@ -319,6 +345,19 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
319
345
  };
320
346
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
321
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
+ }
322
361
  function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
323
362
  try {
324
363
  return deriveBankId(config, directory, harness, sessionRoot);
@@ -334,7 +373,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
334
373
  }
335
374
 
336
375
  // src/core/config.ts
337
- import { readFileSync as readFileSync2 } from "fs";
376
+ import { readFileSync as readFileSync3 } from "fs";
338
377
  import { homedir as homedir3 } from "os";
339
378
  import { join as join7 } from "path";
340
379
 
@@ -374,7 +413,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
374
413
  // src/core/missions.ts
375
414
  import { createHash } from "crypto";
376
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.";
377
- 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.";
378
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.`;
379
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.";
380
419
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -450,6 +489,8 @@ var KNOWLEDGE_LABELS = {
450
489
  ]
451
490
  };
452
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.`;
453
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.`;
454
495
  }
455
496
  var PAGE_TAXONOMY = [
@@ -585,12 +626,17 @@ var CODING_BANK_TEMPLATE = {
585
626
  }
586
627
  };
587
628
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
629
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
630
+ "retain_strategies",
631
+ "entity_labels",
632
+ "retain_extraction_mode"
633
+ ];
588
634
  function isSet(v) {
589
635
  if (v === null || v === void 0) return false;
590
636
  if (typeof v === "string") return v.trim() !== "";
591
637
  return true;
592
638
  }
593
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
639
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
594
640
  const current2 = overrides ?? {};
595
641
  const template = CODING_BANK_TEMPLATE.bank;
596
642
  const bank = {};
@@ -619,9 +665,16 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
619
665
  const [knowledgeGroup] = template.entity_labels;
620
666
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
621
667
  bank.entity_labels = [...labels, knowledgeGroup];
668
+ for (const [key, value] of Object.entries(defaults)) {
669
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
670
+ bank[key] = value;
671
+ }
622
672
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
623
673
  }
624
674
 
675
+ // package.json
676
+ var version = "0.8.1";
677
+
625
678
  // src/core/util.ts
626
679
  import { accessSync, constants } from "fs";
627
680
  import { delimiter, join as join6 } from "path";
@@ -645,12 +698,12 @@ function binOnPath(bin) {
645
698
  }
646
699
  }
647
700
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
648
- function semverGte(version, min) {
701
+ function semverGte(version2, min) {
649
702
  const parts = (v) => {
650
703
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
651
704
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
652
705
  };
653
- const a = version ? parts(version) : void 0;
706
+ const a = version2 ? parts(version2) : void 0;
654
707
  const b = parts(min);
655
708
  if (!a || !b) return false;
656
709
  for (let i = 0; i < 3; i++) {
@@ -673,8 +726,18 @@ async function pool(items, n, fn, onError, onProgress) {
673
726
  }
674
727
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
675
728
  }
729
+ function isOurMcpEntry(entry) {
730
+ if (!entry || typeof entry !== "object") return false;
731
+ const candidate = entry;
732
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
733
+ const script = candidate.args[0];
734
+ if (typeof script !== "string") return false;
735
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
736
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
737
+ }
676
738
 
677
739
  // src/core/hindsight.ts
740
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
678
741
  function resolveRetainScopes(tags, configured) {
679
742
  if (configured !== "per_source") return configured;
680
743
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -710,7 +773,7 @@ async function isEndpointMissing(r) {
710
773
  const j = await r.json();
711
774
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
712
775
  } catch {
713
- return true;
776
+ return false;
714
777
  }
715
778
  }
716
779
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -729,6 +792,12 @@ var ReflectError = class extends Error {
729
792
  get fallbackEligible() {
730
793
  return this.timedOut || this.status !== void 0 && this.status >= 500;
731
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
+ }
732
801
  };
733
802
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
734
803
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -739,8 +808,31 @@ var DEFAULT_RECALL_OPTIONS = {
739
808
  include: { entities: null }
740
809
  };
741
810
  var POLL_CYCLE_MS = 5e3;
811
+ var POLL_MAX_SERVER_ERRORS = 12;
742
812
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
743
813
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
814
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
815
+ function shapePage(page) {
816
+ const p = page ?? {};
817
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
818
+ return {
819
+ id: p.id,
820
+ name: p.name,
821
+ ...p.description ? { description: p.description } : {},
822
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
823
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
824
+ body
825
+ };
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
+ }
744
836
  var HindsightClient = class {
745
837
  apiUrl;
746
838
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -760,6 +852,7 @@ var HindsightClient = class {
760
852
  observationScopes;
761
853
  pageSearchLimit;
762
854
  recallOptions;
855
+ rateLimitPatienceMs;
763
856
  constructor(o) {
764
857
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
765
858
  this.token = o.apiToken;
@@ -772,13 +865,18 @@ var HindsightClient = class {
772
865
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
773
866
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
774
867
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
868
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
775
869
  }
776
870
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
777
871
  get apiToken() {
778
872
  return this.token;
779
873
  }
780
874
  headers() {
781
- const h = { "Content-Type": "application/json" };
875
+ const h = {
876
+ "Content-Type": "application/json",
877
+ "Accept-Encoding": "identity",
878
+ "User-Agent": USER_AGENT
879
+ };
782
880
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
783
881
  return h;
784
882
  }
@@ -809,7 +907,8 @@ var HindsightClient = class {
809
907
  * bounds the whole call.
810
908
  */
811
909
  async fetchWithAuth(url, init) {
812
- 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 } : {} });
813
912
  const r = await send();
814
913
  if (r.status !== 401 || !this.refreshToken()) return r;
815
914
  return send();
@@ -825,13 +924,22 @@ var HindsightClient = class {
825
924
  }
826
925
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
827
926
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
828
- const r = await this.fetchWithAuth(url, {
829
- method,
830
- body: body ? JSON.stringify(body) : void 0,
831
- signal: AbortSignal.timeout(timeoutMs)
832
- });
833
- if (r.status === 429 && !tolerate.includes(429))
834
- 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
+ }
835
943
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
836
944
  throw new Error(
837
945
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -866,7 +974,7 @@ var HindsightClient = class {
866
974
  }
867
975
  /**
868
976
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
869
- * 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
870
978
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
871
979
  */
872
980
  async supportsIdempotentRetain() {
@@ -876,14 +984,37 @@ var HindsightClient = class {
876
984
  }
877
985
  return this.idempotentRetain;
878
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. */
879
991
  async probeIdempotentRetain() {
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
+ }
1000
+ }
1001
+ return false;
1002
+ }
1003
+ /**
1004
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
1005
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
1006
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
1007
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
1008
+ */
1009
+ async supportsAppendRetain() {
1010
+ if (!await this.supportsIdempotentRetain()) return false;
880
1011
  try {
881
- const r = await this.req("GET", `${this.apiUrl}/version`);
882
- if (!r.ok) return false;
1012
+ const r = await this.req("GET", this.bankUrl("/config"));
1013
+ if (!r.ok) return true;
883
1014
  const j = await r.json();
884
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
1015
+ return j.config?.store_document_text !== false;
885
1016
  } catch {
886
- return false;
1017
+ return true;
887
1018
  }
888
1019
  }
889
1020
  /**
@@ -911,6 +1042,32 @@ var HindsightClient = class {
911
1042
  }
912
1043
  return ids;
913
1044
  }
1045
+ /**
1046
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
1047
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
1048
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
1049
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
1050
+ */
1051
+ async documentTags(documentId) {
1052
+ const limit = 100;
1053
+ for (let offset = 0; ; offset += limit) {
1054
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
1055
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
1056
+ const j = await r.json();
1057
+ const items = j.items ?? [];
1058
+ const hit = items.find((it) => it.id === documentId);
1059
+ if (hit) return hit.tags ?? [];
1060
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
1061
+ }
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
+ }
914
1071
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
915
1072
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
916
1073
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -932,7 +1089,8 @@ var HindsightClient = class {
932
1089
  } else {
933
1090
  const manifest = codingBankManifest(
934
1091
  opts.reset ? void 0 : await this.readBankOverrides(),
935
- opts.extractionMode
1092
+ opts.extractionMode,
1093
+ opts.defaults
936
1094
  );
937
1095
  if (!manifest) {
938
1096
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -991,7 +1149,13 @@ var HindsightClient = class {
991
1149
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
992
1150
  const start = Date.now();
993
1151
  const pending = new Set(ids);
1152
+ const serverErrors = /* @__PURE__ */ new Map();
994
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
+ };
995
1159
  while (pending.size && Date.now() - start < maxMs) {
996
1160
  let backoffMs = POLL_CYCLE_MS;
997
1161
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -1004,7 +1168,14 @@ var HindsightClient = class {
1004
1168
  );
1005
1169
  return;
1006
1170
  }
1007
- 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);
1008
1179
  const st = ((await r.json()).status || "").toLowerCase();
1009
1180
  if (TERMINAL.has(st)) {
1010
1181
  pending.delete(id);
@@ -1138,8 +1309,8 @@ var HindsightClient = class {
1138
1309
  return { items };
1139
1310
  }
1140
1311
  /**
1141
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1142
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1312
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1313
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1143
1314
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1144
1315
  * token cap.
1145
1316
  */
@@ -1150,7 +1321,7 @@ var HindsightClient = class {
1150
1321
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1151
1322
  );
1152
1323
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1153
- return await r.json();
1324
+ return shapePage(await r.json());
1154
1325
  }
1155
1326
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1156
1327
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1171,6 +1342,7 @@ var HindsightClient = class {
1171
1342
  return (j.results ?? []).map((x) => ({
1172
1343
  id: x.id,
1173
1344
  name: x.name,
1345
+ ...x.source_query ? { source_query: x.source_query } : {},
1174
1346
  snippet: x.snippet ?? "",
1175
1347
  score: x.score ?? 0
1176
1348
  }));
@@ -1187,7 +1359,7 @@ var HindsightClient = class {
1187
1359
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1188
1360
  */
1189
1361
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1190
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1362
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1191
1363
  const existing = /* @__PURE__ */ new Map();
1192
1364
  let roots;
1193
1365
  try {
@@ -1262,7 +1434,7 @@ var HindsightClient = class {
1262
1434
  }
1263
1435
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1264
1436
  this.log(
1265
- `[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` : "")
1266
1438
  );
1267
1439
  }
1268
1440
  /**
@@ -1273,23 +1445,33 @@ var HindsightClient = class {
1273
1445
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1274
1446
  * consolidation under the auto-refresh that used to be the default (#3506).
1275
1447
  *
1276
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1277
- * initiative's own title, and re-stating either would rebuild a page whose question never
1278
- * 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.
1279
1454
  */
1280
1455
  async resyncInitiativeTriggers(roots, pageTrigger) {
1281
1456
  const folder = roots.find(
1282
1457
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1283
1458
  );
1459
+ const bankScope = pageScopeRule(this.bank);
1284
1460
  let updated = 0;
1285
1461
  for (const page of folder?.children ?? []) {
1286
- if (page.kind !== "page" || page.trigger == null) continue;
1287
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1288
- 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;
1289
1471
  const r = await this.req(
1290
1472
  "PATCH",
1291
1473
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1292
- { trigger: pageTriggerPatch(desired) }
1474
+ patch
1293
1475
  );
1294
1476
  if (r.status === 404) continue;
1295
1477
  updated++;
@@ -1317,10 +1499,9 @@ var HindsightClient = class {
1317
1499
  let pageId = args.relatesToPageId;
1318
1500
  if (!pageId) {
1319
1501
  const folderId = await this.ensureFolder("Initiatives");
1320
- const subject = this.project ?? this.bank;
1321
1502
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1322
1503
  name: args.title,
1323
- 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),
1324
1505
  parent_id: folderId,
1325
1506
  tags: ["knowledge:feature-work"],
1326
1507
  max_tokens: PAGE_MAX_TOKENS,
@@ -1335,7 +1516,7 @@ var HindsightClient = class {
1335
1516
  }
1336
1517
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1337
1518
  const content = `${verb}: ${args.title}. ${args.summary}`;
1338
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1519
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1339
1520
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1340
1521
  const context = `initiative marker for [[page:${pageId}]]`;
1341
1522
  await this.retain(content, context, markerId, tags, "document", {
@@ -1441,6 +1622,7 @@ function resolveCustomPages(raw) {
1441
1622
  }
1442
1623
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1443
1624
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1625
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1444
1626
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1445
1627
  function resolveReflectBudget(raw) {
1446
1628
  const value = raw.reflectBudget;
@@ -1467,6 +1649,22 @@ function resolveObservationScopes(raw) {
1467
1649
  }
1468
1650
  return DEFAULT_OBSERVATION_SCOPES;
1469
1651
  }
1652
+ function resolveDefaultBankConfig(raw) {
1653
+ const value = raw;
1654
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1655
+ const out = {};
1656
+ for (const [key, v] of Object.entries(value)) {
1657
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1658
+ log.warn(
1659
+ "config",
1660
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1661
+ );
1662
+ continue;
1663
+ }
1664
+ out[key] = v;
1665
+ }
1666
+ return out;
1667
+ }
1470
1668
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1471
1669
  function resolveAutoInject(raw) {
1472
1670
  if (raw.autoReflect !== void 0) {
@@ -1506,18 +1704,21 @@ function resolveConfig(raw = {}) {
1506
1704
  // write sessions back by default, every harness
1507
1705
  manageBankConfig: raw.manageBankConfig ?? true,
1508
1706
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1707
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1509
1708
  maxParallelRetains: raw.maxParallelRetains || 10,
1510
1709
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1511
1710
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1512
1711
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1513
1712
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1514
1713
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1714
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1515
1715
  reflectBudget: resolveReflectBudget(raw),
1516
1716
  autoInject: resolveAutoInject(raw),
1517
1717
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1518
1718
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1519
1719
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1520
1720
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1721
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1521
1722
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1522
1723
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1523
1724
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1537,18 +1738,22 @@ function resolveConfig(raw = {}) {
1537
1738
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1538
1739
  // nested object cannot reach the API as a tag and fail the whole retain.
1539
1740
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1741
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1742
+ // the built-in default) from a configured value, and an empty context would strip the default.
1743
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1540
1744
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1541
1745
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1542
1746
  ) : {},
1543
1747
  observationScopes: resolveObservationScopes(raw.observationScopes),
1544
1748
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1749
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1545
1750
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1546
1751
  autoUpdate: raw.autoUpdate ?? true
1547
1752
  };
1548
1753
  }
1549
1754
  function readRaw(path) {
1550
1755
  try {
1551
- return JSON.parse(readFileSync2(path, "utf8"));
1756
+ return JSON.parse(readFileSync3(path, "utf8"));
1552
1757
  } catch (e) {
1553
1758
  if (e?.code !== "ENOENT") {
1554
1759
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1558,7 +1763,12 @@ function readRaw(path) {
1558
1763
  }
1559
1764
  function mergeRaw(a, b) {
1560
1765
  const { harnesses: _drop, ...flat } = b;
1561
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1766
+ return {
1767
+ ...a,
1768
+ ...flat,
1769
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1770
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1771
+ };
1562
1772
  }
1563
1773
  function applyLayer(raw, layer, harness) {
1564
1774
  let out = mergeRaw(raw, layer);
@@ -1589,9 +1799,11 @@ var ENV_KEYS = {
1589
1799
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1590
1800
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1591
1801
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1802
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1592
1803
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1593
1804
  autoInject: "HINDSIGHT_AUTO_INJECT",
1594
1805
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1806
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1595
1807
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1596
1808
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1597
1809
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1633,6 +1845,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1633
1845
  "maxParallelRetains",
1634
1846
  "reflectTimeoutMs",
1635
1847
  "reflectToolTimeoutMs",
1848
+ "injectTimeoutMs",
1636
1849
  "pageSearchLimit",
1637
1850
  "pageRefreshEveryTurns",
1638
1851
  "seedLimit",
@@ -1681,15 +1894,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1681
1894
  function applyBankConfig(cfg, resolvedId, directory) {
1682
1895
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1683
1896
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1897
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1898
+ if (byPath) {
1899
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1900
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1901
+ }
1684
1902
  const section = cfg.banks[resolvedId];
1685
1903
  if (!section) return { cfg, bankId: resolvedId };
1686
- const safe = { ...section };
1687
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1688
- delete safe.banks;
1904
+ const safe = overrideFields(section);
1689
1905
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1690
1906
  delete safe.bank;
1691
1907
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1692
1908
  }
1909
+ function overrideFields(section) {
1910
+ const safe = { ...section };
1911
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1912
+ delete safe.banks;
1913
+ delete safe.paths;
1914
+ return safe;
1915
+ }
1693
1916
  function resolvePartial(cfg, patch) {
1694
1917
  const full = resolveConfig(patch);
1695
1918
  const out = {};
@@ -1698,6 +1921,16 @@ function resolvePartial(cfg, patch) {
1698
1921
  out[key] = full[key];
1699
1922
  }
1700
1923
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1924
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1925
+ const conn = resolveConfig({
1926
+ serverMode: patch.serverMode ?? cfg.serverMode,
1927
+ apiPort: patch.apiPort ?? cfg.apiPort,
1928
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1929
+ });
1930
+ out.serverMode = conn.serverMode;
1931
+ out.apiUrl = conn.apiUrl;
1932
+ out.apiPort = conn.apiPort;
1933
+ }
1701
1934
  return out;
1702
1935
  }
1703
1936
 
@@ -1732,13 +1965,13 @@ function indexLine(pages) {
1732
1965
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1733
1966
  return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
1734
1967
  }
1735
- var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today, never what was decided or why, so work built from code alone quietly re-litigates settled questions. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
1736
- \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, is usually already decided);
1968
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
1969
+ \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
1737
1970
  \u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
1738
1971
  \u2022 you are implementing something new, or two parts have to fit together;
1739
1972
  \u2022 the user asks why something is the way it is, or what is left to do;
1740
1973
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1741
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
1974
+ It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
1742
1975
  CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
1743
1976
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
1744
1977
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
@@ -1746,7 +1979,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
1746
1979
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
1747
1980
  var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
1748
1981
  function toolGuide(opts) {
1749
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
1982
+ const extra = opts?.extra?.trim();
1983
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1984
+ ${extra}` : "");
1750
1985
  }
1751
1986
  function buildKnowledgePreamble(pages, opts) {
1752
1987
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
@@ -1760,7 +1995,7 @@ This tool guide and the page list are re-injected for you periodically as things
1760
1995
  }
1761
1996
 
1762
1997
  // src/core/session-cache.ts
1763
- 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";
1764
1999
  import { tmpdir } from "os";
1765
2000
  import { dirname as dirname5, join as join8 } from "path";
1766
2001
  function sessionCacheFile(harness, sessionId) {
@@ -1786,6 +2021,24 @@ function writeSessionCache(cacheFile, cache) {
1786
2021
  } catch {
1787
2022
  }
1788
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
+ }
1789
2042
  function sessionRootFile(harness, sessionId) {
1790
2043
  return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1791
2044
  }
@@ -1793,7 +2046,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1793
2046
  if (!sessionId || !cwd) return cwd;
1794
2047
  const file = sessionRootFile(harness, sessionId);
1795
2048
  try {
1796
- const recorded = readFileSync3(file, "utf8").trim();
2049
+ const recorded = readFileSync4(file, "utf8").trim();
1797
2050
  if (recorded) return recorded;
1798
2051
  } catch {
1799
2052
  }
@@ -1805,7 +2058,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1805
2058
  }
1806
2059
 
1807
2060
  // src/core/turn-journal.ts
1808
- 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";
1809
2062
  import { tmpdir as tmpdir2 } from "os";
1810
2063
  import { dirname as dirname6, join as join9 } from "path";
1811
2064
 
@@ -1847,9 +2100,6 @@ function actionLine(tool, input) {
1847
2100
  // src/core/turn-journal.ts
1848
2101
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1849
2102
 
1850
- // src/core/retain-hook.ts
1851
- import { readFileSync as readFileSync7 } from "fs";
1852
-
1853
2103
  // src/core/retain-cursor.ts
1854
2104
  import { createHash as createHash2 } from "crypto";
1855
2105
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
@@ -1865,7 +2115,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
1865
2115
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1866
2116
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1867
2117
  try {
1868
- 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
+ });
1869
2122
  return res.ok;
1870
2123
  } catch {
1871
2124
  return false;
@@ -1947,12 +2200,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1947
2200
  } catch {
1948
2201
  }
1949
2202
  }
2203
+ var coldStarts = /* @__PURE__ */ new Map();
2204
+ async function waitBounded(p, ms) {
2205
+ let timer;
2206
+ try {
2207
+ await Promise.race([
2208
+ p,
2209
+ new Promise((resolve3) => {
2210
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2211
+ })
2212
+ ]);
2213
+ } finally {
2214
+ clearTimeout(timer);
2215
+ }
2216
+ }
1950
2217
  async function ensureDaemon(cfg, harness, opts = {}) {
1951
2218
  if (cfg.serverMode !== "daemon") return;
1952
2219
  if (await isServerHealthy(cfg.apiUrl)) return;
1953
2220
  if (!preflightDaemon(cfg, harness)) return;
1954
- startDaemonDetached(cfg, harness, opts.spawnFn);
1955
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2221
+ const waitMs = opts.waitMs ?? 0;
2222
+ const running = coldStarts.get(cfg.apiUrl);
2223
+ if (running) {
2224
+ const startedAt = Date.now();
2225
+ await waitBounded(
2226
+ running.catch(() => void 0),
2227
+ waitMs
2228
+ );
2229
+ const remaining = waitMs - (Date.now() - startedAt);
2230
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2231
+ return;
2232
+ }
2233
+ const attempt = (async () => {
2234
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2235
+ await waitForHealth(cfg.apiUrl, waitMs);
2236
+ })();
2237
+ coldStarts.set(cfg.apiUrl, attempt);
2238
+ try {
2239
+ await attempt;
2240
+ } finally {
2241
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2242
+ }
1956
2243
  }
1957
2244
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1958
2245
  const deadline = Date.now() + budgetMs;
@@ -2007,7 +2294,8 @@ function resolversFor(ctx) {
2007
2294
  function buildRetainStamp(cfg, ctx) {
2008
2295
  const hasTags = Boolean(cfg.retainTags?.length);
2009
2296
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2010
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2297
+ const hasContext = Boolean(cfg.retainContext?.trim());
2298
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2011
2299
  const base = resolversFor(ctx);
2012
2300
  const cache = /* @__PURE__ */ new Map();
2013
2301
  const resolvers = Object.fromEntries(
@@ -2031,7 +2319,8 @@ function buildRetainStamp(cfg, ctx) {
2031
2319
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2032
2320
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2033
2321
  }
2034
- return { tags, metadata };
2322
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2323
+ return { tags, metadata, context };
2035
2324
  }
2036
2325
 
2037
2326
  // src/core/jsonl.ts
@@ -2072,14 +2361,12 @@ function* readJsonl(path) {
2072
2361
  import { readFileSync as readFileSync6 } from "fs";
2073
2362
  import { join as join11 } from "path";
2074
2363
 
2075
- // src/core/session-start.ts
2076
- import { readFileSync as readFileSync11 } from "fs";
2077
-
2078
2364
  // src/core/git.ts
2079
2365
  import { execFileSync as execFileSync2 } from "child_process";
2080
2366
  import { resolve as resolve2 } from "path";
2367
+ var GITLOG_HEAD = "gitlog-head:";
2081
2368
  function git(repo, ...args) {
2082
- return execFileSync2("git", ["-C", repo, ...args], {
2369
+ return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
2083
2370
  encoding: "utf8",
2084
2371
  maxBuffer: 1 << 28,
2085
2372
  windowsHide: true,
@@ -2099,6 +2386,7 @@ function gitHeadSha(dir) {
2099
2386
  }
2100
2387
  }
2101
2388
  function commitsSince(dir, sinceSha) {
2389
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
2102
2390
  try {
2103
2391
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
2104
2392
  return Number.isFinite(n) ? n : null;
@@ -2113,12 +2401,21 @@ function hasGitHistory(dir) {
2113
2401
  return false;
2114
2402
  }
2115
2403
  }
2404
+ async function gitLogIsCurrent(client, repo, head) {
2405
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
2406
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
2407
+ return true;
2408
+ const tags = await client.documentTags?.(canonical2) ?? [];
2409
+ return tags.some(
2410
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
2411
+ );
2412
+ }
2116
2413
 
2117
2414
  // src/core/status.ts
2118
- import { execFileSync as execFileSync3 } from "child_process";
2415
+ import { execFileSync as execFileSync4 } from "child_process";
2119
2416
 
2120
2417
  // src/core/survey.ts
2121
- import { spawn as realSpawn4 } from "child_process";
2418
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2122
2419
  import { createHash as createHash4 } from "crypto";
2123
2420
  import { existsSync as existsSync3 } from "fs";
2124
2421
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2131,7 +2428,9 @@ function resolveHostConfig(harness, directory) {
2131
2428
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
2132
2429
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
2133
2430
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
2134
- 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 };
2135
2434
  }
2136
2435
 
2137
2436
  // src/core/survey-lease.ts
@@ -2236,6 +2535,19 @@ function resolveAgentBin(harness, claudeBin) {
2236
2535
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
2237
2536
  }
2238
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
+ }
2239
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.';
2240
2552
  var SURVEY_DISALLOWED_TOOLS = [
2241
2553
  "Bash",
@@ -2349,6 +2661,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
2349
2661
  seen.add(harness);
2350
2662
  const bin = resolveAgentBin(harness, opts.claudeBin);
2351
2663
  if (!exists(bin)) continue;
2664
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
2665
+ continue;
2352
2666
  const plan = buildSurveyPlan(harness, bin, repoDir, {
2353
2667
  model: opts.model,
2354
2668
  budgetUsd: opts.budgetUsd,
@@ -2409,7 +2723,7 @@ import { spawn as realSpawn5 } from "child_process";
2409
2723
  import {
2410
2724
  existsSync as existsSync4,
2411
2725
  mkdirSync as mkdirSync5,
2412
- readFileSync as readFileSync8,
2726
+ readFileSync as readFileSync7,
2413
2727
  realpathSync as realpathSync2,
2414
2728
  unlinkSync as unlinkSync2,
2415
2729
  writeFileSync as writeFileSync3
@@ -2440,7 +2754,7 @@ function sameDir(a, b) {
2440
2754
  }
2441
2755
  function stagedVersion(pkgRoot) {
2442
2756
  try {
2443
- const pkg = JSON.parse(readFileSync8(join14(pkgRoot, "package.json"), "utf8"));
2757
+ const pkg = JSON.parse(readFileSync7(join14(pkgRoot, "package.json"), "utf8"));
2444
2758
  return typeof pkg.version === "string" ? pkg.version : "";
2445
2759
  } catch {
2446
2760
  return "";
@@ -2465,7 +2779,7 @@ function isNewer(candidate, current2) {
2465
2779
  }
2466
2780
  function dueForCheck(file, now) {
2467
2781
  try {
2468
- const state = JSON.parse(readFileSync8(file, "utf8"));
2782
+ const state = JSON.parse(readFileSync7(file, "utf8"));
2469
2783
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
2470
2784
  } catch {
2471
2785
  return true;
@@ -2474,7 +2788,7 @@ function dueForCheck(file, now) {
2474
2788
  var ORIGIN_FILE = ".install-origin.json";
2475
2789
  function selfUpdatable(runtimeDir) {
2476
2790
  try {
2477
- const origin = JSON.parse(readFileSync8(join14(runtimeDir, ORIGIN_FILE), "utf8"));
2791
+ const origin = JSON.parse(readFileSync7(join14(runtimeDir, ORIGIN_FILE), "utf8"));
2478
2792
  if (typeof origin.source !== "string" || !origin.source) return false;
2479
2793
  return origin.source.split(/[\\/]/).includes("_npx");
2480
2794
  } catch {
@@ -2487,7 +2801,7 @@ function lockFile() {
2487
2801
  }
2488
2802
  function acquireUpdateLock(file, now) {
2489
2803
  try {
2490
- const held = JSON.parse(readFileSync8(file, "utf8"));
2804
+ const held = JSON.parse(readFileSync7(file, "utf8"));
2491
2805
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
2492
2806
  let holderAlive = false;
2493
2807
  if (held.pid) {
@@ -2528,6 +2842,9 @@ function stampCheck(file, now, latest) {
2528
2842
  } catch {
2529
2843
  }
2530
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
+ }
2531
2848
  async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2532
2849
  return new Promise((resolve3) => {
2533
2850
  let out = "";
@@ -2541,7 +2858,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2541
2858
  resolve3(v);
2542
2859
  };
2543
2860
  try {
2544
- const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2861
+ const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
2545
2862
  timeout: NPM_VIEW_TIMEOUT_MS,
2546
2863
  stdio: ["ignore", "pipe", "ignore"],
2547
2864
  windowsHide: true
@@ -2610,7 +2927,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2610
2927
  return "";
2611
2928
  }
2612
2929
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2613
- const child = (opts.spawn ?? realSpawn5)(
2930
+ const child = spawnNpm(
2931
+ opts.spawn ?? realSpawn5,
2614
2932
  "npx",
2615
2933
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2616
2934
  {
@@ -2636,12 +2954,14 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2636
2954
  }
2637
2955
 
2638
2956
  // src/core/skill-sync.ts
2639
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2957
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2640
2958
  import { homedir as homedir6 } from "os";
2641
- import { dirname as dirname10, join as join15 } from "path";
2959
+ import { dirname as dirname10, join as join16 } from "path";
2642
2960
  import { fileURLToPath as fileURLToPath5 } from "url";
2643
2961
 
2644
2962
  // src/core/skill-dirs.ts
2963
+ import { existsSync as existsSync5 } from "fs";
2964
+ import { join as join15 } from "path";
2645
2965
  var SKILL_DIRS = {
2646
2966
  "claude-code": [".claude", "skills"],
2647
2967
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -2654,6 +2974,8 @@ var SKILL_DIRS = {
2654
2974
  "cline-cli": [".cline", "data", "settings", "skills"],
2655
2975
  "qwen-code": [".qwen", "skills"],
2656
2976
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2977
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
2978
+ "kimi-code": [".kimi-code", "skills"],
2657
2979
  "factory-droid": [".factory", "skills"],
2658
2980
  // Droid's user-level skills root
2659
2981
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -2661,31 +2983,53 @@ var SKILL_DIRS = {
2661
2983
  // skill removal is by fixed directory name, so installing into the shared root would make
2662
2984
  // `uninstall zcode` take Codex's and dsh's copy with it.
2663
2985
  zcode: [".zcode", "skills"],
2986
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
2987
+ // its own, never the shared agentskills root other hosts install into.
2988
+ traecode: [".trae-cn", "skills"],
2664
2989
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2665
2990
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2666
2991
  // and dsh's copy with it.
2667
2992
  pi: [".pi", "agent", "skills"],
2668
- "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"]
2999
+ };
3000
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
3001
+ var traecodeDotDirName = (home, exists = existsSync5) => {
3002
+ for (const dir of TRAE_DOT_DIRS) {
3003
+ if (exists(join15(home, dir))) return dir;
3004
+ }
3005
+ return ".trae-cn";
3006
+ };
3007
+ var resolveSkillDirs = (harness, home) => {
3008
+ const parts = SKILL_DIRS[harness];
3009
+ if (harness === "traecode" && parts) {
3010
+ return [traecodeDotDirName(home), ...parts.slice(1)];
3011
+ }
3012
+ return parts;
2669
3013
  };
2670
3014
 
2671
3015
  // src/core/skill-sync.ts
2672
3016
  function packagedSkillDir() {
2673
3017
  const here = dirname10(fileURLToPath5(import.meta.url));
2674
- const dist = join15(here, "..", "skill");
2675
- return existsSync5(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
3018
+ const dist = join16(here, "..", "skill");
3019
+ return existsSync6(join16(dist, "SKILL.md")) ? dist : join16(here, "..", "..", "skill");
2676
3020
  }
2677
3021
  function syncCompanionSkill(harness, opts = {}) {
2678
3022
  try {
2679
- const parts = SKILL_DIRS[harness];
3023
+ const parts = resolveSkillDirs(harness, opts.home ?? homedir6());
2680
3024
  if (!parts) return;
2681
3025
  const src = opts.srcDir ?? packagedSkillDir();
2682
- const srcMd = join15(src, "SKILL.md");
2683
- if (!existsSync5(srcMd)) return;
2684
- const dst = join15(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
2685
- const dstMd = join15(dst, "SKILL.md");
2686
- const installed = existsSync5(dstMd);
3026
+ const srcMd = join16(src, "SKILL.md");
3027
+ if (!existsSync6(srcMd)) return;
3028
+ const dst = join16(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
3029
+ const dstMd = join16(dst, "SKILL.md");
3030
+ const installed = existsSync6(dstMd);
2687
3031
  if (!installed && !opts.install) return;
2688
- if (!installed || readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
3032
+ if (!installed || readFileSync8(srcMd, "utf8") !== readFileSync8(dstMd, "utf8")) {
2689
3033
  cpSync(src, dst, { recursive: true });
2690
3034
  }
2691
3035
  } catch {
@@ -2693,15 +3037,15 @@ function syncCompanionSkill(harness, opts = {}) {
2693
3037
  }
2694
3038
 
2695
3039
  // src/core/legacy.ts
2696
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
3040
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2697
3041
  import { homedir as homedir7 } from "os";
2698
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
3042
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2699
3043
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
2700
- function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir7(), ".claude")) {
2701
- const registry = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
3044
+ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")) {
3045
+ const registry = readJson(join17(claudeDir, "plugins", "installed_plugins.json"));
2702
3046
  const plugins = registry?.plugins;
2703
3047
  if (!plugins || typeof plugins !== "object") return void 0;
2704
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
3048
+ const enabled = readJson(join17(claudeDir, "settings.json"))?.enabledPlugins;
2705
3049
  for (const [key, raw] of Object.entries(plugins)) {
2706
3050
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
2707
3051
  if (enabled && enabled[key] === false) continue;
@@ -2718,7 +3062,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir7(), ".claude")
2718
3062
  }
2719
3063
  function readJson(path) {
2720
3064
  try {
2721
- const parsed = JSON.parse(readFileSync10(path, "utf8"));
3065
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
2722
3066
  return parsed && typeof parsed === "object" ? parsed : void 0;
2723
3067
  } catch {
2724
3068
  return void 0;
@@ -2741,15 +3085,15 @@ async function gitSyncNote(args) {
2741
3085
  if (mode === "none" || cold) return void 0;
2742
3086
  const head = gitHeadSha(cwd);
2743
3087
  if (!head) return void 0;
2744
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
3088
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
2745
3089
  if (gitlogCurrent === void 0) return void 0;
2746
3090
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
2747
3091
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
2748
3092
  let target = DEEPEN_DIFF_TARGET;
2749
3093
  try {
2750
- const { execFileSync: execFileSync4 } = await import("child_process");
3094
+ const { execFileSync: execFileSync6 } = await import("child_process");
2751
3095
  const n = Number(
2752
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
3096
+ execFileSync6("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2753
3097
  encoding: "utf8",
2754
3098
  windowsHide: true,
2755
3099
  stdio: ["ignore", "pipe", "pipe"]
@@ -2766,6 +3110,7 @@ async function buildSessionStartContext(args) {
2766
3110
  const t0 = Date.now();
2767
3111
  let cold;
2768
3112
  let gitDocIds;
3113
+ let bankEmpty = false;
2769
3114
  const harness = args.harness ?? "claude-code";
2770
3115
  const hasGit = args.hasGit ?? hasGitHistory;
2771
3116
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -2805,11 +3150,21 @@ async function buildSessionStartContext(args) {
2805
3150
  } catch {
2806
3151
  docIds = void 0;
2807
3152
  }
2808
- 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;
2809
3158
  gitDocIds = docIds;
3159
+ if (cold === true && client.hasDocuments) {
3160
+ bankEmpty = await client.hasDocuments().then(
3161
+ (has) => !has,
3162
+ () => false
3163
+ );
3164
+ }
2810
3165
  if (docIds !== void 0) {
2811
3166
  startSeed(cwd, { limit: cfg.seedLimit, harness });
2812
- if (docIds.size === 0) {
3167
+ if (cold) {
2813
3168
  if (cfg.codebaseSurvey !== false) {
2814
3169
  const started = await startSurvey(cwd, {
2815
3170
  harness,
@@ -2823,7 +3178,7 @@ async function buildSessionStartContext(args) {
2823
3178
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
2824
3179
  const sha = resolveHeadSha(cwd);
2825
3180
  if (sha) {
2826
- 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());
2827
3182
  const counts = [];
2828
3183
  for (const id of markers) {
2829
3184
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -2857,19 +3212,18 @@ async function buildSessionStartContext(args) {
2857
3212
  }
2858
3213
  }
2859
3214
  let pages = [];
2860
- let pageListKnown = false;
2861
3215
  try {
2862
3216
  pages = parsePageList(await client.listPages());
2863
- pageListKnown = true;
2864
3217
  } catch {
2865
3218
  if (client.knowledgePagesSupported === false) {
2866
3219
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
2867
3220
  }
2868
3221
  }
2869
3222
  const additionalContext = buildKnowledgePreamble(pages, {
2870
- reflectOnNewGoals: cfg.autoInject !== "reflect"
3223
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
3224
+ extra: cfg.toolGuideExtra
2871
3225
  });
2872
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
3226
+ const deferInitialReflect = bankEmpty;
2873
3227
  let gitNote;
2874
3228
  if (gitDocIds) {
2875
3229
  gitNote = await gitSyncNote({
@@ -2894,12 +3248,9 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
2894
3248
  async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient(o)) {
2895
3249
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2896
3250
  try {
2897
- let ev = {};
2898
- try {
2899
- ev = JSON.parse(readFileSync11(0, "utf8"));
2900
- } catch {
2901
- return;
2902
- }
3251
+ const ev = readHookEvent(spec.harness);
3252
+ if (!ev) return;
3253
+ if (spec.accept && !spec.accept(ev)) return;
2903
3254
  const { harness } = spec;
2904
3255
  const { cwd: rawCwd, sessionId } = spec.parse(ev);
2905
3256
  const cwd = rawCwd || process.cwd();
@@ -2915,6 +3266,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2915
3266
  cfg = resolved2.cfg;
2916
3267
  const bankId = resolved2.bankId;
2917
3268
  if (cfg.disabled) return;
3269
+ const mcpHint = spec.ensureMcpRegistration?.(cwd);
2918
3270
  await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
2919
3271
  const client = makeClient({
2920
3272
  apiUrl: cfg.apiUrl,
@@ -2924,9 +3276,16 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2924
3276
  observationScopes: cfg.observationScopes
2925
3277
  });
2926
3278
  const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
3279
+ if (mcpHint)
3280
+ out.systemMessage = out.systemMessage ? `${out.systemMessage}
3281
+ ${mcpHint}` : mcpHint;
2927
3282
  if (out.deferInitialReflect && sessionId) {
2928
3283
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
2929
3284
  }
3285
+ if (spec.deferContextToToolHook && out.additionalContext && sessionId) {
3286
+ stashPendingContext(harness, sessionId, out.additionalContext);
3287
+ out.additionalContext = void 0;
3288
+ }
2930
3289
  const payload = spec.emit(out);
2931
3290
  if (out.systemMessage || out.additionalContext) {
2932
3291
  process.stdout.write(JSON.stringify(payload));
@@ -2935,6 +3294,233 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2935
3294
  }
2936
3295
  }
2937
3296
 
3297
+ // src/core/traecode-mcp.ts
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";
3300
+ import { homedir as homedir8 } from "os";
3301
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
3302
+ import { fileURLToPath as fileURLToPath6 } from "url";
3303
+ var MCP_SERVER_NAME = "hindsight";
3304
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
3305
+ function bundledDistDir() {
3306
+ const here = dirname11(fileURLToPath6(import.meta.url));
3307
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
3308
+ }
3309
+ function canon(value) {
3310
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
3311
+ if (value && typeof value === "object") {
3312
+ const entries = Object.entries(value).sort(
3313
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
3314
+ );
3315
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
3316
+ }
3317
+ return JSON.stringify(value);
3318
+ }
3319
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
3320
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3321
+ function traecodeUserDataDir(home) {
3322
+ const root = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA ?? join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME ?? join18(home, ".config");
3323
+ for (const brand of ["Trae CN", "Trae"]) {
3324
+ const dir = join18(root, brand);
3325
+ if (existsSync8(dir)) return dir;
3326
+ }
3327
+ return join18(root, "Trae CN");
3328
+ }
3329
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
3330
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
3331
+ function gateStateFile() {
3332
+ return gateStateFileFor(bundledDistDir());
3333
+ }
3334
+ function readGateState(opts = {}) {
3335
+ try {
3336
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
3337
+ } catch {
3338
+ return {};
3339
+ }
3340
+ }
3341
+ function workspaceMcpGateState(settingsPath) {
3342
+ let raw;
3343
+ try {
3344
+ raw = readFileSync10(settingsPath, "utf8");
3345
+ } catch {
3346
+ return "unknown";
3347
+ }
3348
+ try {
3349
+ const doc = JSON.parse(raw);
3350
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
3351
+ } catch {
3352
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
3353
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
3354
+ }
3355
+ }
3356
+ function workspaceMcpHint(opts = {}) {
3357
+ try {
3358
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
3359
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
3360
+ const now = opts.now ?? Date.now();
3361
+ const state = readGateState(opts);
3362
+ if (state.workspaceMcpEnabled) return void 0;
3363
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
3364
+ return void 0;
3365
+ }
3366
+ writeFileSync4(
3367
+ opts.stateFile ?? gateStateFile(),
3368
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
3369
+ );
3370
+ return 'Hindsight MCP tools are hidden: TraeCode does not read per-repo MCP configs until workspace MCP is enabled. Turn it on once in Trae settings (search "enableWorkspaceMcp") or re-run `hindsight-coding-agents install traecode` \u2014 then reload this window.';
3371
+ } catch {
3372
+ return void 0;
3373
+ }
3374
+ }
3375
+ function gitignoreCovers(lines) {
3376
+ return lines.some((l) => {
3377
+ const t = l.trim();
3378
+ return t.includes(".trae");
3379
+ });
3380
+ }
3381
+ function ensureGitignored(repo) {
3382
+ const gitignore = join18(repo, ".gitignore");
3383
+ if (!existsSync8(gitignore)) return;
3384
+ const current2 = readFileSync10(gitignore, "utf8");
3385
+ if (gitignoreCovers(current2.split("\n"))) return;
3386
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
3387
+ writeFileSync4(gitignore, current2 + addition);
3388
+ }
3389
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
3390
+ registerTraecodeWorkspaceMcp(cwd, opts);
3391
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
3392
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
3393
+ }
3394
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3395
+ try {
3396
+ const home = opts.home ?? homedir8();
3397
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
3398
+ const dist = opts.dist ?? bundledDistDir();
3399
+ const script = join18(dist, "mcp-server.js");
3400
+ if (!existsSync8(script)) return "skipped";
3401
+ const file = join18(cwd, MCP_FILE_REL);
3402
+ let doc = {};
3403
+ let exists = false;
3404
+ try {
3405
+ doc = JSON.parse(readFileSync10(file, "utf8"));
3406
+ exists = true;
3407
+ } catch {
3408
+ if (existsSync8(file)) return "skipped";
3409
+ }
3410
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
3411
+ const entry = {
3412
+ command: "node",
3413
+ args: [script],
3414
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
3415
+ };
3416
+ const existing = servers[MCP_SERVER_NAME];
3417
+ let merged;
3418
+ if (existing === void 0) {
3419
+ merged = entry;
3420
+ } else if (isOurMcpEntry(existing)) {
3421
+ const env = existing.env;
3422
+ merged = {
3423
+ ...existing,
3424
+ command: entry.command,
3425
+ args: entry.args,
3426
+ env: { ...env ?? {}, ...entry.env }
3427
+ };
3428
+ } else {
3429
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
3430
+ return "skipped";
3431
+ }
3432
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
3433
+ servers[MCP_SERVER_NAME] = merged;
3434
+ mkdirSync6(dirname11(file), { recursive: true });
3435
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
3436
+ if (!exists) ensureGitignored(cwd);
3437
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
3438
+ return "registered";
3439
+ } catch (e) {
3440
+ diag("traecode", "workspace_mcp_register_failed", {
3441
+ cwd,
3442
+ error: e instanceof Error ? e.message : String(e)
3443
+ });
3444
+ return "failed";
3445
+ }
3446
+ }
3447
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
3448
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
3449
+ var SQLITE_TIMEOUT_MS = 5e3;
3450
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
3451
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
3452
+ function findWorkspaceStorageDir(storage, repo) {
3453
+ let entries;
3454
+ try {
3455
+ entries = readdirSync2(storage);
3456
+ } catch {
3457
+ return void 0;
3458
+ }
3459
+ for (const name of entries) {
3460
+ try {
3461
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
3462
+ if (typeof doc.folder !== "string") continue;
3463
+ let folder;
3464
+ try {
3465
+ folder = fileURLToPath6(doc.folder);
3466
+ } catch {
3467
+ folder = doc.folder;
3468
+ }
3469
+ if (folder === repo) return join18(storage, name);
3470
+ } catch {
3471
+ continue;
3472
+ }
3473
+ }
3474
+ return void 0;
3475
+ }
3476
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3477
+ try {
3478
+ const home = opts.home ?? homedir8();
3479
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3480
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3481
+ if (!dir) return "failed";
3482
+ const db = join18(dir, "state.vscdb");
3483
+ if (!existsSync8(db)) return "failed";
3484
+ const sqlite = opts.sqlite ?? execFileSync5;
3485
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3486
+ encoding: "utf8",
3487
+ timeout: SQLITE_TIMEOUT_MS,
3488
+ windowsHide: true,
3489
+ stdio: ["ignore", "pipe", "pipe"]
3490
+ }).trim();
3491
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
3492
+ return "on";
3493
+ }
3494
+ run(
3495
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
3496
+ );
3497
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
3498
+ return "seeded";
3499
+ } catch (e) {
3500
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
3501
+ cwd,
3502
+ error: e instanceof Error ? e.message : String(e)
3503
+ });
3504
+ return "failed";
3505
+ }
3506
+ }
3507
+ function workspaceEnableHint(opts = {}) {
3508
+ try {
3509
+ const now = opts.now ?? Date.now();
3510
+ const state = readGateState(opts);
3511
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3512
+ return void 0;
3513
+ }
3514
+ writeFileSync4(
3515
+ opts.stateFile ?? gateStateFile(),
3516
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3517
+ );
3518
+ return "Hindsight's MCP server stays disabled in this window: auto-enabling it failed here. Switch hindsight on for this workspace in Trae's MCP panel, then reload the window.";
3519
+ } catch {
3520
+ return void 0;
3521
+ }
3522
+ }
3523
+
2938
3524
  // src/core/transcript-codex.ts
2939
3525
  function stampOf(line) {
2940
3526
  return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
@@ -2943,12 +3529,68 @@ function isSyntheticUserText(text) {
2943
3529
  const s = text.trimStart();
2944
3530
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2945
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
+ }
2946
3540
  function contentText(content) {
2947
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3541
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3542
+ }
3543
+ var startupKinds = /* @__PURE__ */ new Set([
3544
+ "agents_md.instructions",
3545
+ "environments.instructions",
3546
+ "environments.environment_context",
3547
+ "plugins.recommendations",
3548
+ "plugins.usage_instructions"
3549
+ ]);
3550
+ function fallbackUserText(payload) {
3551
+ const content = payload.content;
3552
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
3553
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3554
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3555
+ }
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);
3560
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2948
3561
  }
2949
3562
  function isUserMessageEvent(line) {
2950
3563
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2951
3564
  }
3565
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
3566
+ function isToolItemEvent(line) {
3567
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
3568
+ }
3569
+ function parseArgs(raw) {
3570
+ if (typeof raw !== "string") return raw;
3571
+ try {
3572
+ return JSON.parse(raw);
3573
+ } catch {
3574
+ return void 0;
3575
+ }
3576
+ }
3577
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
3578
+ function commandText(command) {
3579
+ if (typeof command === "string") return command;
3580
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
3581
+ const argv = command;
3582
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
3583
+ return argv.join(" ");
3584
+ }
3585
+ function toolItemAction(item) {
3586
+ if (item.type === "McpToolCall") {
3587
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
3588
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
3589
+ return actionLine(name, parseArgs(item.arguments));
3590
+ }
3591
+ const command = commandText(item.command).trim();
3592
+ return command ? actionLine("exec_command", { command }) : void 0;
3593
+ }
2952
3594
  function readCodexTranscript(path) {
2953
3595
  const lines = [];
2954
3596
  for (const rawLine of readJsonl(path)) {
@@ -2962,6 +3604,7 @@ function readCodexTranscript(path) {
2962
3604
  }
2963
3605
  }
2964
3606
  const userFromEvents = lines.some(isUserMessageEvent);
3607
+ const actionsFromEvents = lines.some(isToolItemEvent);
2965
3608
  const turns = [];
2966
3609
  const push = (role, raw, stamp = {}) => {
2967
3610
  const text = stripInjectedMemory(raw).trim();
@@ -2972,16 +3615,24 @@ function readCodexTranscript(path) {
2972
3615
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2973
3616
  continue;
2974
3617
  }
3618
+ if (isToolItemEvent(line)) {
3619
+ const action = toolItemAction(line.payload?.item ?? {});
3620
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3621
+ continue;
3622
+ }
2975
3623
  if (line.type !== "response_item") continue;
2976
3624
  const p = line.payload;
2977
3625
  if (!p || typeof p !== "object") continue;
2978
3626
  if (p.type === "message") {
2979
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2980
- else if (p.role === "user" && !userFromEvents) {
2981
- const text = contentText(p.content);
2982
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
3627
+ if (p.role === "assistant") {
3628
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3629
+ continue;
3630
+ push("assistant", contentText(p.content), stampOf(line));
3631
+ } else if (p.role === "user" && !userFromEvents) {
3632
+ push("user", fallbackUserText(p), stampOf(line));
2983
3633
  }
2984
3634
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3635
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2985
3636
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2986
3637
  let input;
2987
3638
  try {
@@ -3082,19 +3733,19 @@ function readCopilotTranscript(path) {
3082
3733
  }
3083
3734
 
3084
3735
  // src/core/transcript-grok.ts
3085
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
3086
- import { homedir as homedir8 } from "os";
3087
- import { join as join17 } from "path";
3736
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3737
+ import { homedir as homedir9 } from "os";
3738
+ import { join as join19 } from "path";
3088
3739
  var CHAT_HISTORY = "chat_history.jsonl";
3089
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
3090
- const sessionsDir = join17(grokHome, "sessions");
3091
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3092
- if (existsSync7(direct)) return direct;
3093
- try {
3094
- for (const candidate of readdirSync2(sessionsDir)) {
3095
- const directory = join17(sessionsDir, candidate);
3096
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
3097
- return join17(directory, sessionId, CHAT_HISTORY);
3740
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3741
+ const sessionsDir = join19(grokHome, "sessions");
3742
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3743
+ if (existsSync9(direct)) return direct;
3744
+ try {
3745
+ for (const candidate of readdirSync3(sessionsDir)) {
3746
+ const directory = join19(sessionsDir, candidate);
3747
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3748
+ return join19(directory, sessionId, CHAT_HISTORY);
3098
3749
  }
3099
3750
  }
3100
3751
  } catch {
@@ -3129,12 +3780,12 @@ function readGrokTranscript(path) {
3129
3780
  }
3130
3781
 
3131
3782
  // src/core/transcript-devin.ts
3132
- import { existsSync as existsSync8 } from "fs";
3783
+ import { existsSync as existsSync10 } from "fs";
3133
3784
  import { createRequire } from "module";
3134
- import { homedir as homedir9 } from "os";
3135
- import { join as join18 } from "path";
3136
- function devinSessionDb(home = homedir9()) {
3137
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3785
+ import { homedir as homedir10 } from "os";
3786
+ import { join as join20 } from "path";
3787
+ function devinSessionDb(home = homedir10()) {
3788
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
3138
3789
  }
3139
3790
  function parseDevinMessages(nodes) {
3140
3791
  const messages = /* @__PURE__ */ new Map();
@@ -3171,7 +3822,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
3171
3822
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
3172
3823
  return [];
3173
3824
  }
3174
- if (!existsSync8(dbPath)) {
3825
+ if (!existsSync10(dbPath)) {
3175
3826
  diag("devin-cli", "session_db_missing", { dbPath });
3176
3827
  return [];
3177
3828
  }
@@ -3444,7 +4095,7 @@ function readDroidTranscript(path) {
3444
4095
  }
3445
4096
 
3446
4097
  // src/core/transcript-zcode.ts
3447
- import { readFileSync as readFileSync13 } from "fs";
4098
+ import { readFileSync as readFileSync12 } from "fs";
3448
4099
  function messageText(content) {
3449
4100
  if (typeof content === "string") return content.trim();
3450
4101
  if (!Array.isArray(content)) return "";
@@ -3454,7 +4105,7 @@ function readZcodeTranscript(path) {
3454
4105
  if (!path) return [];
3455
4106
  let body;
3456
4107
  try {
3457
- body = readFileSync13(path, "utf8");
4108
+ body = readFileSync12(path, "utf8");
3458
4109
  } catch {
3459
4110
  return [];
3460
4111
  }
@@ -3488,6 +4139,260 @@ function zcodeAssistantText(path) {
3488
4139
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3489
4140
  }
3490
4141
 
4142
+ // src/core/transcript-kimi.ts
4143
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
4144
+ import { homedir as homedir11 } from "os";
4145
+ import { join as join21 } from "path";
4146
+ var HARNESS = "kimi-code";
4147
+ var SESSIONS_DIR = "sessions";
4148
+ var AGENTS_DIR = "agents";
4149
+ var WIRE_LOG = "wire.jsonl";
4150
+ var SESSION_PREFIX = "session_";
4151
+ var MAIN_AGENT = "main";
4152
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
4153
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
4154
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
4155
+ const sessions = join21(kimiHome, SESSIONS_DIR);
4156
+ try {
4157
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
4158
+ if (!workspace.isDirectory()) continue;
4159
+ const candidate = join21(sessions, workspace.name, name);
4160
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
4161
+ }
4162
+ } catch {
4163
+ }
4164
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
4165
+ return void 0;
4166
+ }
4167
+ function stampOf2(event) {
4168
+ if (typeof event.time !== "number") return {};
4169
+ const at = new Date(event.time);
4170
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
4171
+ }
4172
+ function kimiPromptText(input) {
4173
+ if (!Array.isArray(input)) return "";
4174
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
4175
+ }
4176
+ function readKimiWire(events) {
4177
+ const turns = [];
4178
+ let step;
4179
+ const flushStep = () => {
4180
+ if (!step) return;
4181
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
4182
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
4183
+ step = void 0;
4184
+ };
4185
+ for (const event of events || []) {
4186
+ if (!event || typeof event !== "object") continue;
4187
+ const stamp = stampOf2(event);
4188
+ if (event.type === "turn.prompt") {
4189
+ flushStep();
4190
+ if (event.origin?.kind !== "user") continue;
4191
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
4192
+ if (content) turns.push({ role: "user", content, ...stamp });
4193
+ continue;
4194
+ }
4195
+ if (event.type !== "context.append_loop_event") continue;
4196
+ const loop = event.event;
4197
+ if (!loop || typeof loop !== "object") continue;
4198
+ if (loop.type === "content.part") {
4199
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
4200
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
4201
+ if (step && step.uuid !== uuid) flushStep();
4202
+ if (!step) step = { uuid, texts: [], stamp };
4203
+ step.texts.push(loop.part.text);
4204
+ } else if (loop.type === "tool.call") {
4205
+ flushStep();
4206
+ if (typeof loop.name !== "string" || !loop.name) continue;
4207
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
4208
+ }
4209
+ }
4210
+ flushStep();
4211
+ return turns;
4212
+ }
4213
+ function agentIds(sessionDir) {
4214
+ try {
4215
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
4216
+ } catch {
4217
+ return [];
4218
+ }
4219
+ }
4220
+ function byAgentId(a, b) {
4221
+ if (a === b) return 0;
4222
+ if (a === MAIN_AGENT) return -1;
4223
+ if (b === MAIN_AGENT) return 1;
4224
+ const indexA = agentIndex(a);
4225
+ const indexB = agentIndex(b);
4226
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
4227
+ }
4228
+ function agentIndex(id) {
4229
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
4230
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
4231
+ }
4232
+ function parseEvent(rawLine) {
4233
+ const trimmed = rawLine.trim();
4234
+ if (!trimmed) return void 0;
4235
+ let parsed;
4236
+ try {
4237
+ parsed = JSON.parse(trimmed);
4238
+ } catch {
4239
+ return void 0;
4240
+ }
4241
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
4242
+ }
4243
+ function readKimiTranscript(path) {
4244
+ const turns = [];
4245
+ let remaining = MAX_SESSION_CHARS;
4246
+ for (const agentId of agentIds(path)) {
4247
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
4248
+ const events = [];
4249
+ for (const rawLine of readJsonl(wire)) {
4250
+ remaining -= rawLine.length;
4251
+ if (remaining < 0) break;
4252
+ const event = parseEvent(rawLine);
4253
+ if (event) events.push(event);
4254
+ }
4255
+ for (const turn of readKimiWire(events)) turns.push(turn);
4256
+ if (remaining < 0) {
4257
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
4258
+ sessionDir: path,
4259
+ stoppedAt: wire
4260
+ });
4261
+ break;
4262
+ }
4263
+ }
4264
+ return turns;
4265
+ }
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
+
3491
4396
  // src/harness/hook-lifecycle.ts
3492
4397
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3493
4398
  var claudePrompt = {
@@ -3566,7 +4471,7 @@ var copilotPrompt = {
3566
4471
  ${context}`.trim()
3567
4472
  })
3568
4473
  };
3569
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
4474
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3570
4475
  var devinPrompt = {
3571
4476
  harness: "devin-cli",
3572
4477
  requireCwd: true,
@@ -3593,6 +4498,36 @@ var standardSessionStart = (harness) => ({
3593
4498
  }
3594
4499
  })
3595
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
+ });
4530
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3596
4531
  var HOOK_HARNESSES = {
3597
4532
  "claude-code": {
3598
4533
  configStyle: "nested",
@@ -3601,11 +4536,12 @@ var HOOK_HARNESSES = {
3601
4536
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3602
4537
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3603
4538
  },
3604
- sessionStart: standardSessionStart("claude-code"),
3605
- prompt: claudePrompt,
4539
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
4540
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3606
4541
  retain: {
3607
4542
  hostTimeoutSec: 60,
3608
4543
  harness: "claude-code",
4544
+ accept: notGrokHosted,
3609
4545
  parse: (ev) => ({
3610
4546
  sessionId: ev.session_id,
3611
4547
  transcriptPath: ev.transcript_path,
@@ -3788,17 +4724,29 @@ var HOOK_HARNESSES = {
3788
4724
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3789
4725
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3790
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 }],
3791
4731
  sessionStart: {
3792
4732
  ...standardSessionStart("grok-build"),
3793
4733
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3794
4734
  parse: (ev) => ({
3795
4735
  cwd: ev.cwd,
3796
4736
  sessionId: ev.sessionId
3797
- })
4737
+ }),
4738
+ deferContextToToolHook: true
3798
4739
  },
3799
4740
  prompt: {
3800
4741
  ...claudePrompt,
3801
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
+ },
3802
4750
  parse: (ev) => ({
3803
4751
  prompt: ev.prompt,
3804
4752
  cwd: ev.cwd,
@@ -3921,6 +4869,159 @@ var HOOK_HARNESSES = {
3921
4869
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3922
4870
  }
3923
4871
  }
4872
+ },
4873
+ /**
4874
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4875
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4876
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4877
+ * map IS the file) and a `version` field the host writes and expects.
4878
+ *
4879
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4880
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4881
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4882
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4883
+ * plays: `journal.assistantText` closes the turn with it.
4884
+ */
4885
+ traecode: {
4886
+ configStyle: "nested",
4887
+ install: {
4888
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4889
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4890
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4891
+ },
4892
+ sessionStart: {
4893
+ ...standardSessionStart("traecode"),
4894
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4895
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4896
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4897
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4898
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4899
+ // rides the session banner.
4900
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4901
+ },
4902
+ prompt: {
4903
+ ...claudePrompt,
4904
+ harness: "traecode",
4905
+ journalPrompt: true,
4906
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4907
+ parse: (ev) => ({
4908
+ prompt: ev.prompt,
4909
+ cwd: ev.cwd,
4910
+ sessionId: ev.session_id
4911
+ })
4912
+ },
4913
+ retain: {
4914
+ hostTimeoutSec: 60,
4915
+ harness: "traecode",
4916
+ // No transcriptPath: the journal supplies it (see `journal` below).
4917
+ parse: (ev) => ({
4918
+ sessionId: ev.session_id,
4919
+ cwd: ev.cwd
4920
+ }),
4921
+ journal: {
4922
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4923
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4924
+ }
4925
+ }
4926
+ },
4927
+ "kimi-code": {
4928
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4929
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4930
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4931
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4932
+ configStyle: "toml-array",
4933
+ install: {
4934
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4935
+ // supported host, and the opposite of qwen-code's identically named field.
4936
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4937
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4938
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4939
+ },
4940
+ sessionStart: {
4941
+ harness: "kimi-code",
4942
+ parse: (ev) => ({
4943
+ cwd: ev.cwd,
4944
+ sessionId: ev.session_id
4945
+ }),
4946
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4947
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4948
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4949
+ emit: () => ({})
4950
+ },
4951
+ prompt: {
4952
+ harness: "kimi-code",
4953
+ parse: (ev) => ({
4954
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4955
+ prompt: kimiPromptText(ev.prompt),
4956
+ cwd: ev.cwd,
4957
+ sessionId: ev.session_id
4958
+ }),
4959
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4960
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4961
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4962
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4963
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4964
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4965
+ emit: (context, notice) => ({ message: context || notice })
4966
+ },
4967
+ retain: {
4968
+ hostTimeoutSec: 60,
4969
+ harness: "kimi-code",
4970
+ parse: (ev) => {
4971
+ const sessionId = ev.session_id;
4972
+ return {
4973
+ sessionId,
4974
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4975
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4976
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4977
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4978
+ cwd: ev.cwd
4979
+ };
4980
+ },
4981
+ readTranscript: readKimiTranscript
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)
3924
5025
  }
3925
5026
  };
3926
5027
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);