@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;
@@ -267,13 +289,13 @@ function isWithin(directory, configured) {
267
289
  function mapLookup(map, directory) {
268
290
  const cwd = normalize(directory);
269
291
  let best;
270
- for (const [dir, bank] of Object.entries(map)) {
292
+ for (const [dir, value] of Object.entries(map)) {
271
293
  const p = configuredDir(dir);
272
294
  if (isWithin(cwd, p)) {
273
- if (!best || p.length > best.len) best = { len: p.length, bank };
295
+ if (!best || p.length > best.len) best = { len: p.length, value };
274
296
  }
275
297
  }
276
- return best?.bank;
298
+ return best?.value;
277
299
  }
278
300
  function lookupDirectories(config, directory, sessionRoot = "") {
279
301
  const directories = [normalize(directory)];
@@ -297,6 +319,10 @@ function isOptedIn(config, directory) {
297
319
  const pathMap = config.mapPathToBank;
298
320
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
299
321
  }
322
+ function pathSection(config, paths, directory) {
323
+ if (!directory || !paths) return void 0;
324
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
325
+ }
300
326
  function mappedBank(config, directory, sessionRoot) {
301
327
  const pathMap = config.mapPathToBank;
302
328
  if (!directory || !pathMap) return void 0;
@@ -331,7 +357,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
331
357
  }
332
358
 
333
359
  // src/core/config.ts
334
- import { readFileSync as readFileSync2 } from "fs";
360
+ import { readFileSync as readFileSync3 } from "fs";
335
361
  import { homedir as homedir3 } from "os";
336
362
  import { join as join7 } from "path";
337
363
 
@@ -371,7 +397,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
371
397
  // src/core/missions.ts
372
398
  import { createHash } from "crypto";
373
399
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
374
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
400
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
375
401
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
376
402
  var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
377
403
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -447,6 +473,8 @@ var KNOWLEDGE_LABELS = {
447
473
  ]
448
474
  };
449
475
  function pageScopeRule(project) {
476
+ if (project === void 0)
477
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
450
478
  return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
451
479
  }
452
480
  var PAGE_TAXONOMY = [
@@ -582,12 +610,17 @@ var CODING_BANK_TEMPLATE = {
582
610
  }
583
611
  };
584
612
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
613
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
614
+ "retain_strategies",
615
+ "entity_labels",
616
+ "retain_extraction_mode"
617
+ ];
585
618
  function isSet(v) {
586
619
  if (v === null || v === void 0) return false;
587
620
  if (typeof v === "string") return v.trim() !== "";
588
621
  return true;
589
622
  }
590
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
623
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
591
624
  const current2 = overrides ?? {};
592
625
  const template = CODING_BANK_TEMPLATE.bank;
593
626
  const bank = {};
@@ -616,19 +649,26 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
616
649
  const [knowledgeGroup] = template.entity_labels;
617
650
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
618
651
  bank.entity_labels = [...labels, knowledgeGroup];
652
+ for (const [key, value] of Object.entries(defaults)) {
653
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
654
+ bank[key] = value;
655
+ }
619
656
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
620
657
  }
621
658
 
659
+ // package.json
660
+ var version = "0.8.1";
661
+
622
662
  // src/core/util.ts
623
663
  import { accessSync, constants } from "fs";
624
664
  import { delimiter, join as join6 } from "path";
625
665
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
626
- function semverGte(version, min) {
666
+ function semverGte(version2, min) {
627
667
  const parts = (v) => {
628
668
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
629
669
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
630
670
  };
631
- const a = version ? parts(version) : void 0;
671
+ const a = version2 ? parts(version2) : void 0;
632
672
  const b = parts(min);
633
673
  if (!a || !b) return false;
634
674
  for (let i = 0; i < 3; i++) {
@@ -651,8 +691,18 @@ async function pool(items, n, fn, onError, onProgress) {
651
691
  }
652
692
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
653
693
  }
694
+ function isOurMcpEntry(entry) {
695
+ if (!entry || typeof entry !== "object") return false;
696
+ const candidate = entry;
697
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
698
+ const script = candidate.args[0];
699
+ if (typeof script !== "string") return false;
700
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
701
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
702
+ }
654
703
 
655
704
  // src/core/hindsight.ts
705
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
656
706
  function resolveRetainScopes(tags, configured) {
657
707
  if (configured !== "per_source") return configured;
658
708
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -688,7 +738,7 @@ async function isEndpointMissing(r) {
688
738
  const j = await r.json();
689
739
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
690
740
  } catch {
691
- return true;
741
+ return false;
692
742
  }
693
743
  }
694
744
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -707,6 +757,12 @@ var ReflectError = class extends Error {
707
757
  get fallbackEligible() {
708
758
  return this.timedOut || this.status !== void 0 && this.status >= 500;
709
759
  }
760
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
761
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
762
+ get permanent() {
763
+ const s = this.status;
764
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
765
+ }
710
766
  };
711
767
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
712
768
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -717,8 +773,31 @@ var DEFAULT_RECALL_OPTIONS = {
717
773
  include: { entities: null }
718
774
  };
719
775
  var POLL_CYCLE_MS = 5e3;
776
+ var POLL_MAX_SERVER_ERRORS = 12;
720
777
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
721
778
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
779
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
780
+ function shapePage(page) {
781
+ const p = page ?? {};
782
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
783
+ return {
784
+ id: p.id,
785
+ name: p.name,
786
+ ...p.description ? { description: p.description } : {},
787
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
788
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
789
+ body
790
+ };
791
+ }
792
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
793
+ function signalOnlyDispatcher() {
794
+ void globalThis.Headers;
795
+ const d = globalThis[GLOBAL_DISPATCHER];
796
+ if (typeof d?.compose !== "function") return void 0;
797
+ return d.compose(
798
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
799
+ );
800
+ }
722
801
  var HindsightClient = class {
723
802
  apiUrl;
724
803
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -738,6 +817,7 @@ var HindsightClient = class {
738
817
  observationScopes;
739
818
  pageSearchLimit;
740
819
  recallOptions;
820
+ rateLimitPatienceMs;
741
821
  constructor(o) {
742
822
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
743
823
  this.token = o.apiToken;
@@ -750,13 +830,18 @@ var HindsightClient = class {
750
830
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
751
831
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
752
832
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
833
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
753
834
  }
754
835
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
755
836
  get apiToken() {
756
837
  return this.token;
757
838
  }
758
839
  headers() {
759
- const h = { "Content-Type": "application/json" };
840
+ const h = {
841
+ "Content-Type": "application/json",
842
+ "Accept-Encoding": "identity",
843
+ "User-Agent": USER_AGENT
844
+ };
760
845
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
761
846
  return h;
762
847
  }
@@ -787,7 +872,8 @@ var HindsightClient = class {
787
872
  * bounds the whole call.
788
873
  */
789
874
  async fetchWithAuth(url, init) {
790
- const send = () => fetch(url, { ...init, headers: this.headers() });
875
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
876
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
791
877
  const r = await send();
792
878
  if (r.status !== 401 || !this.refreshToken()) return r;
793
879
  return send();
@@ -803,13 +889,22 @@ var HindsightClient = class {
803
889
  }
804
890
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
805
891
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
806
- const r = await this.fetchWithAuth(url, {
807
- method,
808
- body: body ? JSON.stringify(body) : void 0,
809
- signal: AbortSignal.timeout(timeoutMs)
810
- });
811
- if (r.status === 429 && !tolerate.includes(429))
812
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
892
+ const payload = body ? JSON.stringify(body) : void 0;
893
+ let r;
894
+ for (let attempt = 0, waited = 0; ; attempt++) {
895
+ r = await this.fetchWithAuth(url, {
896
+ method,
897
+ body: payload,
898
+ signal: AbortSignal.timeout(timeoutMs)
899
+ });
900
+ if (r.status !== 429 || tolerate.includes(429)) break;
901
+ const asked = retryAfterMs(r.headers.get("retry-after"));
902
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
903
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
904
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
905
+ await sleep(wait);
906
+ waited += wait;
907
+ }
813
908
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
814
909
  throw new Error(
815
910
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -844,7 +939,7 @@ var HindsightClient = class {
844
939
  }
845
940
  /**
846
941
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
847
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
942
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
848
943
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
849
944
  */
850
945
  async supportsIdempotentRetain() {
@@ -854,14 +949,37 @@ var HindsightClient = class {
854
949
  }
855
950
  return this.idempotentRetain;
856
951
  }
952
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
953
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
954
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
955
+ * `/version`, so that stays as the fallback. */
857
956
  async probeIdempotentRetain() {
957
+ for (const path of ["/v1/version", "/version"]) {
958
+ try {
959
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
960
+ if (!r.ok) continue;
961
+ const j = await r.json();
962
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
963
+ } catch {
964
+ }
965
+ }
966
+ return false;
967
+ }
968
+ /**
969
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
970
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
971
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
972
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
973
+ */
974
+ async supportsAppendRetain() {
975
+ if (!await this.supportsIdempotentRetain()) return false;
858
976
  try {
859
- const r = await this.req("GET", `${this.apiUrl}/version`);
860
- if (!r.ok) return false;
977
+ const r = await this.req("GET", this.bankUrl("/config"));
978
+ if (!r.ok) return true;
861
979
  const j = await r.json();
862
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
980
+ return j.config?.store_document_text !== false;
863
981
  } catch {
864
- return false;
982
+ return true;
865
983
  }
866
984
  }
867
985
  /**
@@ -889,6 +1007,32 @@ var HindsightClient = class {
889
1007
  }
890
1008
  return ids;
891
1009
  }
1010
+ /**
1011
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
1012
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
1013
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
1014
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
1015
+ */
1016
+ async documentTags(documentId) {
1017
+ const limit = 100;
1018
+ for (let offset = 0; ; offset += limit) {
1019
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
1020
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
1021
+ const j = await r.json();
1022
+ const items = j.items ?? [];
1023
+ const hit = items.find((it) => it.id === documentId);
1024
+ if (hit) return hit.tags ?? [];
1025
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
1026
+ }
1027
+ }
1028
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1029
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1030
+ async hasDocuments() {
1031
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1032
+ if (r.status === 404) return false;
1033
+ const j = await r.json();
1034
+ return (j.total ?? j.items?.length ?? 0) > 0;
1035
+ }
892
1036
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
893
1037
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
894
1038
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -910,7 +1054,8 @@ var HindsightClient = class {
910
1054
  } else {
911
1055
  const manifest = codingBankManifest(
912
1056
  opts.reset ? void 0 : await this.readBankOverrides(),
913
- opts.extractionMode
1057
+ opts.extractionMode,
1058
+ opts.defaults
914
1059
  );
915
1060
  if (!manifest) {
916
1061
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -969,7 +1114,13 @@ var HindsightClient = class {
969
1114
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
970
1115
  const start = Date.now();
971
1116
  const pending = new Set(ids);
1117
+ const serverErrors = /* @__PURE__ */ new Map();
972
1118
  let failed = 0;
1119
+ const giveUp = (id, status) => {
1120
+ pending.delete(id);
1121
+ failed++;
1122
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1123
+ };
973
1124
  while (pending.size && Date.now() - start < maxMs) {
974
1125
  let backoffMs = POLL_CYCLE_MS;
975
1126
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -982,7 +1133,14 @@ var HindsightClient = class {
982
1133
  );
983
1134
  return;
984
1135
  }
985
- if (!r.ok) return;
1136
+ if (r.status >= 500) {
1137
+ const n = (serverErrors.get(id) ?? 0) + 1;
1138
+ serverErrors.set(id, n);
1139
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1140
+ return;
1141
+ }
1142
+ if (!r.ok) return giveUp(id, r.status);
1143
+ serverErrors.delete(id);
986
1144
  const st = ((await r.json()).status || "").toLowerCase();
987
1145
  if (TERMINAL.has(st)) {
988
1146
  pending.delete(id);
@@ -1116,8 +1274,8 @@ var HindsightClient = class {
1116
1274
  return { items };
1117
1275
  }
1118
1276
  /**
1119
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1120
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1277
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1278
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1121
1279
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1122
1280
  * token cap.
1123
1281
  */
@@ -1128,7 +1286,7 @@ var HindsightClient = class {
1128
1286
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1129
1287
  );
1130
1288
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1131
- return await r.json();
1289
+ return shapePage(await r.json());
1132
1290
  }
1133
1291
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1134
1292
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1149,6 +1307,7 @@ var HindsightClient = class {
1149
1307
  return (j.results ?? []).map((x) => ({
1150
1308
  id: x.id,
1151
1309
  name: x.name,
1310
+ ...x.source_query ? { source_query: x.source_query } : {},
1152
1311
  snippet: x.snippet ?? "",
1153
1312
  score: x.score ?? 0
1154
1313
  }));
@@ -1165,7 +1324,7 @@ var HindsightClient = class {
1165
1324
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1166
1325
  */
1167
1326
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1168
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1327
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1169
1328
  const existing = /* @__PURE__ */ new Map();
1170
1329
  let roots;
1171
1330
  try {
@@ -1240,7 +1399,7 @@ var HindsightClient = class {
1240
1399
  }
1241
1400
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1242
1401
  this.log(
1243
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1402
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1244
1403
  );
1245
1404
  }
1246
1405
  /**
@@ -1251,23 +1410,33 @@ var HindsightClient = class {
1251
1410
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1252
1411
  * consolidation under the auto-refresh that used to be the default (#3506).
1253
1412
  *
1254
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1255
- * initiative's own title, and re-stating either would rebuild a page whose question never
1256
- * changed. The tree read above is reused rather than re-fetched.
1413
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1414
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1415
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1416
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1417
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1418
+ * reused rather than re-fetched.
1257
1419
  */
1258
1420
  async resyncInitiativeTriggers(roots, pageTrigger) {
1259
1421
  const folder = roots.find(
1260
1422
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1261
1423
  );
1424
+ const bankScope = pageScopeRule(this.bank);
1262
1425
  let updated = 0;
1263
1426
  for (const page of folder?.children ?? []) {
1264
- if (page.kind !== "page" || page.trigger == null) continue;
1265
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1266
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1427
+ if (page.kind !== "page") continue;
1428
+ const patch = {};
1429
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1430
+ if (query !== page.description) patch.source_query = query;
1431
+ if (page.trigger != null) {
1432
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1433
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1434
+ }
1435
+ if (!patch.trigger && !patch.source_query) continue;
1267
1436
  const r = await this.req(
1268
1437
  "PATCH",
1269
1438
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1270
- { trigger: pageTriggerPatch(desired) }
1439
+ patch
1271
1440
  );
1272
1441
  if (r.status === 404) continue;
1273
1442
  updated++;
@@ -1295,10 +1464,9 @@ var HindsightClient = class {
1295
1464
  let pageId = args.relatesToPageId;
1296
1465
  if (!pageId) {
1297
1466
  const folderId = await this.ensureFolder("Initiatives");
1298
- const subject = this.project ?? this.bank;
1299
1467
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1300
1468
  name: args.title,
1301
- source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(subject),
1469
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
1302
1470
  parent_id: folderId,
1303
1471
  tags: ["knowledge:feature-work"],
1304
1472
  max_tokens: PAGE_MAX_TOKENS,
@@ -1313,7 +1481,7 @@ var HindsightClient = class {
1313
1481
  }
1314
1482
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1315
1483
  const content = `${verb}: ${args.title}. ${args.summary}`;
1316
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1484
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1317
1485
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1318
1486
  const context = `initiative marker for [[page:${pageId}]]`;
1319
1487
  await this.retain(content, context, markerId, tags, "document", {
@@ -1419,6 +1587,7 @@ function resolveCustomPages(raw) {
1419
1587
  }
1420
1588
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1421
1589
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1590
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1422
1591
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1423
1592
  function resolveReflectBudget(raw) {
1424
1593
  const value = raw.reflectBudget;
@@ -1445,6 +1614,22 @@ function resolveObservationScopes(raw) {
1445
1614
  }
1446
1615
  return DEFAULT_OBSERVATION_SCOPES;
1447
1616
  }
1617
+ function resolveDefaultBankConfig(raw) {
1618
+ const value = raw;
1619
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1620
+ const out = {};
1621
+ for (const [key, v] of Object.entries(value)) {
1622
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1623
+ log.warn(
1624
+ "config",
1625
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1626
+ );
1627
+ continue;
1628
+ }
1629
+ out[key] = v;
1630
+ }
1631
+ return out;
1632
+ }
1448
1633
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1449
1634
  function resolveAutoInject(raw) {
1450
1635
  if (raw.autoReflect !== void 0) {
@@ -1484,18 +1669,21 @@ function resolveConfig(raw = {}) {
1484
1669
  // write sessions back by default, every harness
1485
1670
  manageBankConfig: raw.manageBankConfig ?? true,
1486
1671
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1672
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1487
1673
  maxParallelRetains: raw.maxParallelRetains || 10,
1488
1674
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1489
1675
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1490
1676
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1491
1677
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1492
1678
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1679
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1493
1680
  reflectBudget: resolveReflectBudget(raw),
1494
1681
  autoInject: resolveAutoInject(raw),
1495
1682
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1496
1683
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1497
1684
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1498
1685
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1686
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1499
1687
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1500
1688
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1501
1689
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1515,18 +1703,22 @@ function resolveConfig(raw = {}) {
1515
1703
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1516
1704
  // nested object cannot reach the API as a tag and fail the whole retain.
1517
1705
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1706
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1707
+ // the built-in default) from a configured value, and an empty context would strip the default.
1708
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1518
1709
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1519
1710
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1520
1711
  ) : {},
1521
1712
  observationScopes: resolveObservationScopes(raw.observationScopes),
1522
1713
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1714
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1523
1715
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1524
1716
  autoUpdate: raw.autoUpdate ?? true
1525
1717
  };
1526
1718
  }
1527
1719
  function readRaw(path) {
1528
1720
  try {
1529
- return JSON.parse(readFileSync2(path, "utf8"));
1721
+ return JSON.parse(readFileSync3(path, "utf8"));
1530
1722
  } catch (e) {
1531
1723
  if (e?.code !== "ENOENT") {
1532
1724
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1536,7 +1728,12 @@ function readRaw(path) {
1536
1728
  }
1537
1729
  function mergeRaw(a, b) {
1538
1730
  const { harnesses: _drop, ...flat } = b;
1539
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1731
+ return {
1732
+ ...a,
1733
+ ...flat,
1734
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1735
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1736
+ };
1540
1737
  }
1541
1738
  function applyLayer(raw, layer, harness) {
1542
1739
  let out = mergeRaw(raw, layer);
@@ -1567,9 +1764,11 @@ var ENV_KEYS = {
1567
1764
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1568
1765
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1569
1766
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1767
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1570
1768
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1571
1769
  autoInject: "HINDSIGHT_AUTO_INJECT",
1572
1770
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1771
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1573
1772
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1574
1773
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1575
1774
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1611,6 +1810,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1611
1810
  "maxParallelRetains",
1612
1811
  "reflectTimeoutMs",
1613
1812
  "reflectToolTimeoutMs",
1813
+ "injectTimeoutMs",
1614
1814
  "pageSearchLimit",
1615
1815
  "pageRefreshEveryTurns",
1616
1816
  "seedLimit",
@@ -1659,15 +1859,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1659
1859
  function applyBankConfig(cfg, resolvedId, directory) {
1660
1860
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1661
1861
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1862
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1863
+ if (byPath) {
1864
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1865
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1866
+ }
1662
1867
  const section = cfg.banks[resolvedId];
1663
1868
  if (!section) return { cfg, bankId: resolvedId };
1664
- const safe = { ...section };
1665
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1666
- delete safe.banks;
1869
+ const safe = overrideFields(section);
1667
1870
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1668
1871
  delete safe.bank;
1669
1872
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1670
1873
  }
1874
+ function overrideFields(section) {
1875
+ const safe = { ...section };
1876
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1877
+ delete safe.banks;
1878
+ delete safe.paths;
1879
+ return safe;
1880
+ }
1671
1881
  function resolvePartial(cfg, patch) {
1672
1882
  const full = resolveConfig(patch);
1673
1883
  const out = {};
@@ -1676,6 +1886,16 @@ function resolvePartial(cfg, patch) {
1676
1886
  out[key] = full[key];
1677
1887
  }
1678
1888
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1889
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1890
+ const conn = resolveConfig({
1891
+ serverMode: patch.serverMode ?? cfg.serverMode,
1892
+ apiPort: patch.apiPort ?? cfg.apiPort,
1893
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1894
+ });
1895
+ out.serverMode = conn.serverMode;
1896
+ out.apiUrl = conn.apiUrl;
1897
+ out.apiPort = conn.apiPort;
1898
+ }
1679
1899
  return out;
1680
1900
  }
1681
1901
 
@@ -1753,13 +1973,13 @@ function indexLine(pages) {
1753
1973
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1754
1974
  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.`;
1755
1975
  }
1756
- 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:
1757
- \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);
1976
+ 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:
1977
+ \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);
1758
1978
  \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);
1759
1979
  \u2022 you are implementing something new, or two parts have to fit together;
1760
1980
  \u2022 the user asks why something is the way it is, or what is left to do;
1761
1981
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1762
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
1982
+ 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.
1763
1983
  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.
1764
1984
  - 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.
1765
1985
  - 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>").
@@ -1767,7 +1987,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
1767
1987
  - 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).`;
1768
1988
  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";
1769
1989
  function toolGuide(opts) {
1770
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
1990
+ const extra = opts?.extra?.trim();
1991
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1992
+ ${extra}` : "");
1771
1993
  }
1772
1994
  function buildRosterRefresh(pages, opts) {
1773
1995
  const rosterBlock = pages.length ? `${indexLine(pages)}
@@ -1778,7 +2000,7 @@ ${toolGuide(opts)}
1778
2000
  }
1779
2001
 
1780
2002
  // src/core/session-cache.ts
1781
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
2003
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1782
2004
  import { tmpdir } from "os";
1783
2005
  import { dirname as dirname5, join as join8 } from "path";
1784
2006
  function sessionCacheFile(harness, sessionId) {
@@ -1786,7 +2008,7 @@ function sessionCacheFile(harness, sessionId) {
1786
2008
  }
1787
2009
  function readSessionCache(cacheFile) {
1788
2010
  try {
1789
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
2011
+ return JSON.parse(readFileSync4(cacheFile, "utf8"));
1790
2012
  } catch {
1791
2013
  return {};
1792
2014
  }
@@ -1811,6 +2033,36 @@ function writeSessionCache(cacheFile, cache) {
1811
2033
  } catch {
1812
2034
  }
1813
2035
  }
2036
+ function pendingContextFile(harness, sessionId) {
2037
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.pending`);
2038
+ }
2039
+ function stashPendingContext(harness, sessionId, context) {
2040
+ const path = pendingContextFile(harness, sessionId);
2041
+ let existing = "";
2042
+ try {
2043
+ existing = readFileSync4(path, "utf8");
2044
+ } catch {
2045
+ }
2046
+ if (existing.includes(context)) return;
2047
+ try {
2048
+ writeFileAtomic(path, existing ? `${existing}
2049
+
2050
+ ${context}` : context);
2051
+ } catch {
2052
+ }
2053
+ }
2054
+ function takePendingContext(harness, sessionId) {
2055
+ const path = pendingContextFile(harness, sessionId);
2056
+ const claimed = `${path}.${process.pid}.claim`;
2057
+ try {
2058
+ renameSync2(path, claimed);
2059
+ return readFileSync4(claimed, "utf8") || void 0;
2060
+ } catch {
2061
+ return void 0;
2062
+ } finally {
2063
+ rmSync(claimed, { force: true });
2064
+ }
2065
+ }
1814
2066
  function sessionRootFile(harness, sessionId) {
1815
2067
  return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1816
2068
  }
@@ -1818,7 +2070,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1818
2070
  if (!sessionId || !cwd) return cwd;
1819
2071
  const file = sessionRootFile(harness, sessionId);
1820
2072
  try {
1821
- const recorded = readFileSync3(file, "utf8").trim();
2073
+ const recorded = readFileSync4(file, "utf8").trim();
1822
2074
  if (recorded) return recorded;
1823
2075
  } catch {
1824
2076
  }
@@ -1830,7 +2082,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1830
2082
  }
1831
2083
 
1832
2084
  // src/core/turn-journal.ts
1833
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2085
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1834
2086
  import { tmpdir as tmpdir2 } from "os";
1835
2087
  import { dirname as dirname6, join as join9 } from "path";
1836
2088
 
@@ -1899,7 +2151,7 @@ function appendJournalTurn(path, turn) {
1899
2151
  function readJournalTranscript(path) {
1900
2152
  let body;
1901
2153
  try {
1902
- body = readFileSync4(path, "utf8");
2154
+ body = readFileSync5(path, "utf8");
1903
2155
  } catch {
1904
2156
  return [];
1905
2157
  }
@@ -1926,11 +2178,24 @@ function readJournalTranscript(path) {
1926
2178
  }
1927
2179
 
1928
2180
  // src/core/hook.ts
1929
- var HOOK_FALLBACK_BUDGET_MS = 7e3;
1930
2181
  var HOOK_INJECT_ATTEMPTS = 2;
2182
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
1931
2183
  function resolveInjection(got, attempts) {
1932
2184
  if (got != null) return got;
1933
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
2185
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
2186
+ return attempts >= budget ? "" : void 0;
2187
+ }
2188
+ var RECALL_QUERY_MAX_TOKENS = 500;
2189
+ function boundRecallQuery(prompt) {
2190
+ let cost = 0;
2191
+ let end = 0;
2192
+ for (const ch of prompt) {
2193
+ const cp = ch.codePointAt(0);
2194
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
2195
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
2196
+ end += ch.length;
2197
+ }
2198
+ return prompt.slice(0, end);
1934
2199
  }
1935
2200
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
1936
2201
  const t0 = Date.now();
@@ -1946,7 +2211,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
1946
2211
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
1947
2212
  const t0 = Date.now();
1948
2213
  try {
1949
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
2214
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
1950
2215
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
1951
2216
  return observations.length ? formatRecallFallback(observations, lead) : null;
1952
2217
  } catch (e) {
@@ -1954,8 +2219,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
1954
2219
  return void 0;
1955
2220
  }
1956
2221
  }
1957
- async function reflectFallback(harness, prompt, client) {
1958
- const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
2222
+ async function reflectFallback(harness, prompt, client, timeoutMs) {
2223
+ const deadline = Date.now() + timeoutMs;
1959
2224
  const remaining = () => Math.max(deadline - Date.now(), 1);
1960
2225
  return await injectPages(harness, prompt, client, remaining(), "reflect_fallback_pages") ?? // Event name predates the `injectRecall` rename and is kept: it is a logged contract that
1961
2226
  // other tools read, so renaming it would silently break them.
@@ -1980,7 +2245,7 @@ async function buildHookOutput(args) {
1980
2245
  harness,
1981
2246
  prompt,
1982
2247
  client,
1983
- HOOK_FALLBACK_BUDGET_MS,
2248
+ cfg.injectTimeoutMs,
1984
2249
  "inject_pages",
1985
2250
  PAGE_INJECT_LEAD
1986
2251
  );
@@ -1993,7 +2258,7 @@ async function buildHookOutput(args) {
1993
2258
  harness,
1994
2259
  prompt,
1995
2260
  client,
1996
- HOOK_FALLBACK_BUDGET_MS,
2261
+ cfg.injectTimeoutMs,
1997
2262
  "inject_recall",
1998
2263
  RECALL_INJECT_LEAD
1999
2264
  );
@@ -2021,7 +2286,7 @@ async function buildHookOutput(args) {
2021
2286
  answer: reflectAnswer.slice(0, 8e3)
2022
2287
  });
2023
2288
  } catch (e) {
2024
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
2289
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
2025
2290
  reflectFailed = true;
2026
2291
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
2027
2292
  error: describeError(e)
@@ -2035,7 +2300,7 @@ async function buildHookOutput(args) {
2035
2300
  query: prompt.slice(0, 80)
2036
2301
  });
2037
2302
  if (e instanceof ReflectError && e.fallbackEligible) {
2038
- fallback = await reflectFallback(harness, prompt, client);
2303
+ fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
2039
2304
  if (fallback) reflectAnswer = fallback;
2040
2305
  }
2041
2306
  }
@@ -2068,7 +2333,12 @@ async function buildHookOutput(args) {
2068
2333
  const blocks = [];
2069
2334
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
2070
2335
  if (cadence > 0 && turns % cadence === 0) {
2071
- blocks.push(buildRosterRefresh(pages, { reflectOnNewGoals: cfg.autoInject !== "reflect" }));
2336
+ blocks.push(
2337
+ buildRosterRefresh(pages, {
2338
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
2339
+ extra: cfg.toolGuideExtra
2340
+ })
2341
+ );
2072
2342
  }
2073
2343
  const kept = blocks.filter(Boolean);
2074
2344
  let notice;
@@ -2087,13 +2357,15 @@ async function buildHookOutput(args) {
2087
2357
  }
2088
2358
  async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2089
2359
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2090
- let ev = {};
2091
- try {
2092
- ev = JSON.parse(readFileSync5(0, "utf8"));
2093
- } catch {
2360
+ const ev = readHookEvent(spec.harness);
2361
+ if (!ev) return;
2362
+ if (spec.accept && !spec.accept(ev)) return;
2363
+ const { prompt: rawPrompt, cwd: rawCwd, sessionId } = spec.parse(ev);
2364
+ if (spec.toolHook?.accept(ev)) {
2365
+ const pending = sessionId ? takePendingContext(spec.harness, sessionId) : void 0;
2366
+ if (pending) process.stdout.write(JSON.stringify(spec.toolHook.emit(pending)));
2094
2367
  return;
2095
2368
  }
2096
- const { prompt: rawPrompt, cwd: rawCwd, sessionId } = spec.parse(ev);
2097
2369
  if (spec.requireCwd && !rawCwd) return;
2098
2370
  const cwd = rawCwd || process.cwd();
2099
2371
  const prompt = (rawPrompt || "").trim();
@@ -2107,7 +2379,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2107
2379
  if (spec.journalPrompt) {
2108
2380
  appendJournalTurn(journalPath(spec.harness, sessionId), { role: "user", content: prompt });
2109
2381
  }
2110
- const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
2382
+ const out = (context2, notice) => process.stdout.write(JSON.stringify(spec.emit(context2 ?? "", notice, ev)));
2111
2383
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2112
2384
  const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
2113
2385
  if (derived === null) return;
@@ -2135,12 +2407,14 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2135
2407
  if (cfg.autoSeed !== false && client.knowledgePagesSupported !== false && output.pages.length === 0) {
2136
2408
  startBackgroundSeed(cwd, { limit: cfg.seedLimit, harness: spec.harness });
2137
2409
  }
2138
- if (output.context || output.notice) out(output.context, output.notice);
2410
+ let context = output.context;
2411
+ if (context && spec.toolHook && sessionId) {
2412
+ stashPendingContext(spec.harness, sessionId, context);
2413
+ context = void 0;
2414
+ }
2415
+ if (context || output.notice) out(context, output.notice);
2139
2416
  }
2140
2417
 
2141
- // src/core/retain-hook.ts
2142
- import { readFileSync as readFileSync7 } from "fs";
2143
-
2144
2418
  // src/core/retain-cursor.ts
2145
2419
  import { createHash as createHash2 } from "crypto";
2146
2420
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
@@ -2195,18 +2469,15 @@ function* readJsonl(path) {
2195
2469
  import { readFileSync as readFileSync6 } from "fs";
2196
2470
  import { join as join11 } from "path";
2197
2471
 
2198
- // src/core/session-start.ts
2199
- import { readFileSync as readFileSync11 } from "fs";
2200
-
2201
2472
  // src/core/git.ts
2202
2473
  import { execFileSync as execFileSync2 } from "child_process";
2203
2474
  import { resolve as resolve2 } from "path";
2204
2475
 
2205
2476
  // src/core/status.ts
2206
- import { execFileSync as execFileSync3 } from "child_process";
2477
+ import { execFileSync as execFileSync4 } from "child_process";
2207
2478
 
2208
2479
  // src/core/survey.ts
2209
- import { spawn as realSpawn4 } from "child_process";
2480
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2210
2481
  import { createHash as createHash4 } from "crypto";
2211
2482
  import { existsSync as existsSync3 } from "fs";
2212
2483
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2235,7 +2506,7 @@ import { spawn as realSpawn5 } from "child_process";
2235
2506
  import {
2236
2507
  existsSync as existsSync4,
2237
2508
  mkdirSync as mkdirSync5,
2238
- readFileSync as readFileSync8,
2509
+ readFileSync as readFileSync7,
2239
2510
  realpathSync as realpathSync2,
2240
2511
  unlinkSync as unlinkSync2,
2241
2512
  writeFileSync as writeFileSync3
@@ -2249,15 +2520,246 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2249
2520
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2250
2521
 
2251
2522
  // src/core/skill-sync.ts
2252
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2523
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2253
2524
  import { homedir as homedir6 } from "os";
2254
- import { dirname as dirname10, join as join15 } from "path";
2525
+ import { dirname as dirname10, join as join16 } from "path";
2255
2526
  import { fileURLToPath as fileURLToPath5 } from "url";
2256
2527
 
2528
+ // src/core/skill-dirs.ts
2529
+ import { existsSync as existsSync5 } from "fs";
2530
+ import { join as join15 } from "path";
2531
+
2257
2532
  // src/core/legacy.ts
2258
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2533
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2259
2534
  import { homedir as homedir7 } from "os";
2260
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2535
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2536
+
2537
+ // src/core/traecode-mcp.ts
2538
+ import { execFileSync as execFileSync5 } from "child_process";
2539
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2540
+ import { homedir as homedir8 } from "os";
2541
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2542
+ import { fileURLToPath as fileURLToPath6 } from "url";
2543
+ var MCP_SERVER_NAME = "hindsight";
2544
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2545
+ function bundledDistDir() {
2546
+ const here = dirname11(fileURLToPath6(import.meta.url));
2547
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2548
+ }
2549
+ function canon(value) {
2550
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2551
+ if (value && typeof value === "object") {
2552
+ const entries = Object.entries(value).sort(
2553
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2554
+ );
2555
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2556
+ }
2557
+ return JSON.stringify(value);
2558
+ }
2559
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2560
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2561
+ function traecodeUserDataDir(home) {
2562
+ 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");
2563
+ for (const brand of ["Trae CN", "Trae"]) {
2564
+ const dir = join18(root, brand);
2565
+ if (existsSync8(dir)) return dir;
2566
+ }
2567
+ return join18(root, "Trae CN");
2568
+ }
2569
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2570
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2571
+ function gateStateFile() {
2572
+ return gateStateFileFor(bundledDistDir());
2573
+ }
2574
+ function readGateState(opts = {}) {
2575
+ try {
2576
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
2577
+ } catch {
2578
+ return {};
2579
+ }
2580
+ }
2581
+ function workspaceMcpGateState(settingsPath) {
2582
+ let raw;
2583
+ try {
2584
+ raw = readFileSync10(settingsPath, "utf8");
2585
+ } catch {
2586
+ return "unknown";
2587
+ }
2588
+ try {
2589
+ const doc = JSON.parse(raw);
2590
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2591
+ } catch {
2592
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2593
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2594
+ }
2595
+ }
2596
+ function workspaceMcpHint(opts = {}) {
2597
+ try {
2598
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2599
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2600
+ const now = opts.now ?? Date.now();
2601
+ const state = readGateState(opts);
2602
+ if (state.workspaceMcpEnabled) return void 0;
2603
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2604
+ return void 0;
2605
+ }
2606
+ writeFileSync4(
2607
+ opts.stateFile ?? gateStateFile(),
2608
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2609
+ );
2610
+ 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.';
2611
+ } catch {
2612
+ return void 0;
2613
+ }
2614
+ }
2615
+ function gitignoreCovers(lines) {
2616
+ return lines.some((l) => {
2617
+ const t = l.trim();
2618
+ return t.includes(".trae");
2619
+ });
2620
+ }
2621
+ function ensureGitignored(repo) {
2622
+ const gitignore = join18(repo, ".gitignore");
2623
+ if (!existsSync8(gitignore)) return;
2624
+ const current2 = readFileSync10(gitignore, "utf8");
2625
+ if (gitignoreCovers(current2.split("\n"))) return;
2626
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2627
+ writeFileSync4(gitignore, current2 + addition);
2628
+ }
2629
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2630
+ registerTraecodeWorkspaceMcp(cwd, opts);
2631
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2632
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2633
+ }
2634
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2635
+ try {
2636
+ const home = opts.home ?? homedir8();
2637
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2638
+ const dist = opts.dist ?? bundledDistDir();
2639
+ const script = join18(dist, "mcp-server.js");
2640
+ if (!existsSync8(script)) return "skipped";
2641
+ const file = join18(cwd, MCP_FILE_REL);
2642
+ let doc = {};
2643
+ let exists = false;
2644
+ try {
2645
+ doc = JSON.parse(readFileSync10(file, "utf8"));
2646
+ exists = true;
2647
+ } catch {
2648
+ if (existsSync8(file)) return "skipped";
2649
+ }
2650
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2651
+ const entry = {
2652
+ command: "node",
2653
+ args: [script],
2654
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2655
+ };
2656
+ const existing = servers[MCP_SERVER_NAME];
2657
+ let merged;
2658
+ if (existing === void 0) {
2659
+ merged = entry;
2660
+ } else if (isOurMcpEntry(existing)) {
2661
+ const env = existing.env;
2662
+ merged = {
2663
+ ...existing,
2664
+ command: entry.command,
2665
+ args: entry.args,
2666
+ env: { ...env ?? {}, ...entry.env }
2667
+ };
2668
+ } else {
2669
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2670
+ return "skipped";
2671
+ }
2672
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2673
+ servers[MCP_SERVER_NAME] = merged;
2674
+ mkdirSync6(dirname11(file), { recursive: true });
2675
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2676
+ if (!exists) ensureGitignored(cwd);
2677
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2678
+ return "registered";
2679
+ } catch (e) {
2680
+ diag("traecode", "workspace_mcp_register_failed", {
2681
+ cwd,
2682
+ error: e instanceof Error ? e.message : String(e)
2683
+ });
2684
+ return "failed";
2685
+ }
2686
+ }
2687
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2688
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2689
+ var SQLITE_TIMEOUT_MS = 5e3;
2690
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2691
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2692
+ function findWorkspaceStorageDir(storage, repo) {
2693
+ let entries;
2694
+ try {
2695
+ entries = readdirSync2(storage);
2696
+ } catch {
2697
+ return void 0;
2698
+ }
2699
+ for (const name of entries) {
2700
+ try {
2701
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
2702
+ if (typeof doc.folder !== "string") continue;
2703
+ let folder;
2704
+ try {
2705
+ folder = fileURLToPath6(doc.folder);
2706
+ } catch {
2707
+ folder = doc.folder;
2708
+ }
2709
+ if (folder === repo) return join18(storage, name);
2710
+ } catch {
2711
+ continue;
2712
+ }
2713
+ }
2714
+ return void 0;
2715
+ }
2716
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2717
+ try {
2718
+ const home = opts.home ?? homedir8();
2719
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
2720
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
2721
+ if (!dir) return "failed";
2722
+ const db = join18(dir, "state.vscdb");
2723
+ if (!existsSync8(db)) return "failed";
2724
+ const sqlite = opts.sqlite ?? execFileSync5;
2725
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2726
+ encoding: "utf8",
2727
+ timeout: SQLITE_TIMEOUT_MS,
2728
+ windowsHide: true,
2729
+ stdio: ["ignore", "pipe", "pipe"]
2730
+ }).trim();
2731
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
2732
+ return "on";
2733
+ }
2734
+ run(
2735
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
2736
+ );
2737
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
2738
+ return "seeded";
2739
+ } catch (e) {
2740
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
2741
+ cwd,
2742
+ error: e instanceof Error ? e.message : String(e)
2743
+ });
2744
+ return "failed";
2745
+ }
2746
+ }
2747
+ function workspaceEnableHint(opts = {}) {
2748
+ try {
2749
+ const now = opts.now ?? Date.now();
2750
+ const state = readGateState(opts);
2751
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
2752
+ return void 0;
2753
+ }
2754
+ writeFileSync4(
2755
+ opts.stateFile ?? gateStateFile(),
2756
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
2757
+ );
2758
+ 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.";
2759
+ } catch {
2760
+ return void 0;
2761
+ }
2762
+ }
2261
2763
 
2262
2764
  // src/core/transcript-codex.ts
2263
2765
  function stampOf(line) {
@@ -2267,12 +2769,68 @@ function isSyntheticUserText(text) {
2267
2769
  const s = text.trimStart();
2268
2770
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2269
2771
  }
2772
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
2773
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
2774
+ function isStartupItem(text) {
2775
+ const s = text.trim();
2776
+ if (AGENTS_BLOCK_HEADER.test(s))
2777
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
2778
+ return STARTUP_TAG_BLOCK.test(s);
2779
+ }
2270
2780
  function contentText(content) {
2271
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2781
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2782
+ }
2783
+ var startupKinds = /* @__PURE__ */ new Set([
2784
+ "agents_md.instructions",
2785
+ "environments.instructions",
2786
+ "environments.environment_context",
2787
+ "plugins.recommendations",
2788
+ "plugins.usage_instructions"
2789
+ ]);
2790
+ function fallbackUserText(payload) {
2791
+ const content = payload.content;
2792
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2793
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2794
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2795
+ }
2796
+ const items = (Array.isArray(content) ? content : []).filter(
2797
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
2798
+ );
2799
+ const text = contentText(items);
2800
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2272
2801
  }
2273
2802
  function isUserMessageEvent(line) {
2274
2803
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2275
2804
  }
2805
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2806
+ function isToolItemEvent(line) {
2807
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2808
+ }
2809
+ function parseArgs(raw) {
2810
+ if (typeof raw !== "string") return raw;
2811
+ try {
2812
+ return JSON.parse(raw);
2813
+ } catch {
2814
+ return void 0;
2815
+ }
2816
+ }
2817
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2818
+ function commandText(command) {
2819
+ if (typeof command === "string") return command;
2820
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2821
+ const argv = command;
2822
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2823
+ return argv.join(" ");
2824
+ }
2825
+ function toolItemAction(item) {
2826
+ if (item.type === "McpToolCall") {
2827
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2828
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2829
+ return actionLine(name, parseArgs(item.arguments));
2830
+ }
2831
+ const command = commandText(item.command).trim();
2832
+ return command ? actionLine("exec_command", { command }) : void 0;
2833
+ }
2276
2834
  function readCodexTranscript(path) {
2277
2835
  const lines = [];
2278
2836
  for (const rawLine of readJsonl(path)) {
@@ -2286,6 +2844,7 @@ function readCodexTranscript(path) {
2286
2844
  }
2287
2845
  }
2288
2846
  const userFromEvents = lines.some(isUserMessageEvent);
2847
+ const actionsFromEvents = lines.some(isToolItemEvent);
2289
2848
  const turns = [];
2290
2849
  const push = (role, raw, stamp = {}) => {
2291
2850
  const text = stripInjectedMemory(raw).trim();
@@ -2296,16 +2855,24 @@ function readCodexTranscript(path) {
2296
2855
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2297
2856
  continue;
2298
2857
  }
2858
+ if (isToolItemEvent(line)) {
2859
+ const action = toolItemAction(line.payload?.item ?? {});
2860
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
2861
+ continue;
2862
+ }
2299
2863
  if (line.type !== "response_item") continue;
2300
2864
  const p = line.payload;
2301
2865
  if (!p || typeof p !== "object") continue;
2302
2866
  if (p.type === "message") {
2303
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2304
- else if (p.role === "user" && !userFromEvents) {
2305
- const text = contentText(p.content);
2306
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
2867
+ if (p.role === "assistant") {
2868
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
2869
+ continue;
2870
+ push("assistant", contentText(p.content), stampOf(line));
2871
+ } else if (p.role === "user" && !userFromEvents) {
2872
+ push("user", fallbackUserText(p), stampOf(line));
2307
2873
  }
2308
2874
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
2875
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2309
2876
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2310
2877
  let input;
2311
2878
  try {
@@ -2406,19 +2973,19 @@ function readCopilotTranscript(path) {
2406
2973
  }
2407
2974
 
2408
2975
  // src/core/transcript-grok.ts
2409
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2410
- import { homedir as homedir8 } from "os";
2411
- import { join as join17 } from "path";
2976
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
2977
+ import { homedir as homedir9 } from "os";
2978
+ import { join as join19 } from "path";
2412
2979
  var CHAT_HISTORY = "chat_history.jsonl";
2413
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2414
- const sessionsDir = join17(grokHome, "sessions");
2415
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2416
- if (existsSync7(direct)) return direct;
2980
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
2981
+ const sessionsDir = join19(grokHome, "sessions");
2982
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2983
+ if (existsSync9(direct)) return direct;
2417
2984
  try {
2418
- for (const candidate of readdirSync2(sessionsDir)) {
2419
- const directory = join17(sessionsDir, candidate);
2420
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2421
- return join17(directory, sessionId, CHAT_HISTORY);
2985
+ for (const candidate of readdirSync3(sessionsDir)) {
2986
+ const directory = join19(sessionsDir, candidate);
2987
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
2988
+ return join19(directory, sessionId, CHAT_HISTORY);
2422
2989
  }
2423
2990
  }
2424
2991
  } catch {
@@ -2453,12 +3020,12 @@ function readGrokTranscript(path) {
2453
3020
  }
2454
3021
 
2455
3022
  // src/core/transcript-devin.ts
2456
- import { existsSync as existsSync8 } from "fs";
3023
+ import { existsSync as existsSync10 } from "fs";
2457
3024
  import { createRequire } from "module";
2458
- import { homedir as homedir9 } from "os";
2459
- import { join as join18 } from "path";
2460
- function devinSessionDb(home = homedir9()) {
2461
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3025
+ import { homedir as homedir10 } from "os";
3026
+ import { join as join20 } from "path";
3027
+ function devinSessionDb(home = homedir10()) {
3028
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2462
3029
  }
2463
3030
  function parseDevinMessages(nodes) {
2464
3031
  const messages = /* @__PURE__ */ new Map();
@@ -2495,7 +3062,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2495
3062
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2496
3063
  return [];
2497
3064
  }
2498
- if (!existsSync8(dbPath)) {
3065
+ if (!existsSync10(dbPath)) {
2499
3066
  diag("devin-cli", "session_db_missing", { dbPath });
2500
3067
  return [];
2501
3068
  }
@@ -2768,7 +3335,7 @@ function readDroidTranscript(path) {
2768
3335
  }
2769
3336
 
2770
3337
  // src/core/transcript-zcode.ts
2771
- import { readFileSync as readFileSync13 } from "fs";
3338
+ import { readFileSync as readFileSync12 } from "fs";
2772
3339
  function messageText(content) {
2773
3340
  if (typeof content === "string") return content.trim();
2774
3341
  if (!Array.isArray(content)) return "";
@@ -2778,7 +3345,7 @@ function readZcodeTranscript(path) {
2778
3345
  if (!path) return [];
2779
3346
  let body;
2780
3347
  try {
2781
- body = readFileSync13(path, "utf8");
3348
+ body = readFileSync12(path, "utf8");
2782
3349
  } catch {
2783
3350
  return [];
2784
3351
  }
@@ -2812,6 +3379,260 @@ function zcodeAssistantText(path) {
2812
3379
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
2813
3380
  }
2814
3381
 
3382
+ // src/core/transcript-kimi.ts
3383
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3384
+ import { homedir as homedir11 } from "os";
3385
+ import { join as join21 } from "path";
3386
+ var HARNESS = "kimi-code";
3387
+ var SESSIONS_DIR = "sessions";
3388
+ var AGENTS_DIR = "agents";
3389
+ var WIRE_LOG = "wire.jsonl";
3390
+ var SESSION_PREFIX = "session_";
3391
+ var MAIN_AGENT = "main";
3392
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3393
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3394
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3395
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3396
+ try {
3397
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3398
+ if (!workspace.isDirectory()) continue;
3399
+ const candidate = join21(sessions, workspace.name, name);
3400
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3401
+ }
3402
+ } catch {
3403
+ }
3404
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3405
+ return void 0;
3406
+ }
3407
+ function stampOf2(event) {
3408
+ if (typeof event.time !== "number") return {};
3409
+ const at = new Date(event.time);
3410
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3411
+ }
3412
+ function kimiPromptText(input) {
3413
+ if (!Array.isArray(input)) return "";
3414
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3415
+ }
3416
+ function readKimiWire(events) {
3417
+ const turns = [];
3418
+ let step;
3419
+ const flushStep = () => {
3420
+ if (!step) return;
3421
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3422
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3423
+ step = void 0;
3424
+ };
3425
+ for (const event of events || []) {
3426
+ if (!event || typeof event !== "object") continue;
3427
+ const stamp = stampOf2(event);
3428
+ if (event.type === "turn.prompt") {
3429
+ flushStep();
3430
+ if (event.origin?.kind !== "user") continue;
3431
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3432
+ if (content) turns.push({ role: "user", content, ...stamp });
3433
+ continue;
3434
+ }
3435
+ if (event.type !== "context.append_loop_event") continue;
3436
+ const loop = event.event;
3437
+ if (!loop || typeof loop !== "object") continue;
3438
+ if (loop.type === "content.part") {
3439
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3440
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3441
+ if (step && step.uuid !== uuid) flushStep();
3442
+ if (!step) step = { uuid, texts: [], stamp };
3443
+ step.texts.push(loop.part.text);
3444
+ } else if (loop.type === "tool.call") {
3445
+ flushStep();
3446
+ if (typeof loop.name !== "string" || !loop.name) continue;
3447
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3448
+ }
3449
+ }
3450
+ flushStep();
3451
+ return turns;
3452
+ }
3453
+ function agentIds(sessionDir) {
3454
+ try {
3455
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3456
+ } catch {
3457
+ return [];
3458
+ }
3459
+ }
3460
+ function byAgentId(a, b) {
3461
+ if (a === b) return 0;
3462
+ if (a === MAIN_AGENT) return -1;
3463
+ if (b === MAIN_AGENT) return 1;
3464
+ const indexA = agentIndex(a);
3465
+ const indexB = agentIndex(b);
3466
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3467
+ }
3468
+ function agentIndex(id) {
3469
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3470
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3471
+ }
3472
+ function parseEvent(rawLine) {
3473
+ const trimmed = rawLine.trim();
3474
+ if (!trimmed) return void 0;
3475
+ let parsed;
3476
+ try {
3477
+ parsed = JSON.parse(trimmed);
3478
+ } catch {
3479
+ return void 0;
3480
+ }
3481
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3482
+ }
3483
+ function readKimiTranscript(path) {
3484
+ const turns = [];
3485
+ let remaining = MAX_SESSION_CHARS;
3486
+ for (const agentId of agentIds(path)) {
3487
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3488
+ const events = [];
3489
+ for (const rawLine of readJsonl(wire)) {
3490
+ remaining -= rawLine.length;
3491
+ if (remaining < 0) break;
3492
+ const event = parseEvent(rawLine);
3493
+ if (event) events.push(event);
3494
+ }
3495
+ for (const turn of readKimiWire(events)) turns.push(turn);
3496
+ if (remaining < 0) {
3497
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3498
+ sessionDir: path,
3499
+ stoppedAt: wire
3500
+ });
3501
+ break;
3502
+ }
3503
+ }
3504
+ return turns;
3505
+ }
3506
+
3507
+ // src/core/transcript-workbuddy.ts
3508
+ function messageText2(content) {
3509
+ if (typeof content === "string") return content;
3510
+ if (!Array.isArray(content)) return "";
3511
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
3512
+ }
3513
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
3514
+ function unwrapUserQuery(text) {
3515
+ const match = USER_QUERY_RE.exec(text);
3516
+ return (match ? match[1] : text).trim();
3517
+ }
3518
+ function isSyntheticUserText2(text) {
3519
+ const s = text.trimStart();
3520
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
3521
+ }
3522
+ function parseArgs2(raw) {
3523
+ if (!raw) return void 0;
3524
+ try {
3525
+ return JSON.parse(raw);
3526
+ } catch {
3527
+ return raw;
3528
+ }
3529
+ }
3530
+ function stampOf3(line) {
3531
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
3532
+ }
3533
+ function readWorkbuddyTranscript(path) {
3534
+ const turns = [];
3535
+ for (const rawLine of readJsonl(path)) {
3536
+ const trimmed = rawLine.trim();
3537
+ if (!trimmed) continue;
3538
+ let parsed;
3539
+ try {
3540
+ parsed = JSON.parse(trimmed);
3541
+ } catch {
3542
+ continue;
3543
+ }
3544
+ if (typeof parsed !== "object" || parsed === null) continue;
3545
+ const line = parsed;
3546
+ const stamp = stampOf3(line);
3547
+ if (line.type === "message") {
3548
+ if (line.role !== "user" && line.role !== "assistant") continue;
3549
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
3550
+ if (!text) continue;
3551
+ if (line.role === "user") {
3552
+ if (isSyntheticUserText2(text)) continue;
3553
+ text = unwrapUserQuery(text);
3554
+ if (!text) continue;
3555
+ }
3556
+ turns.push({ role: line.role, content: text, ...stamp });
3557
+ } else if (line.type === "function_call" && typeof line.name === "string") {
3558
+ turns.push({
3559
+ role: "action",
3560
+ content: actionLine(line.name, parseArgs2(line.arguments)),
3561
+ ...stamp
3562
+ });
3563
+ }
3564
+ }
3565
+ return turns;
3566
+ }
3567
+
3568
+ // src/core/transcript-codebuddy-ide.ts
3569
+ import { readFileSync as readFileSync13 } from "fs";
3570
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
3571
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
3572
+ function readJson(path) {
3573
+ try {
3574
+ return JSON.parse(readFileSync13(path, "utf8"));
3575
+ } catch {
3576
+ return void 0;
3577
+ }
3578
+ }
3579
+ function ideUserText(raw) {
3580
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
3581
+ if (!text || isSyntheticUserText2(text)) return "";
3582
+ return unwrapUserQuery(text).trim();
3583
+ }
3584
+ function readCodebuddyIdeTranscript(indexPath) {
3585
+ const index = readJson(indexPath);
3586
+ const entries = index?.messages;
3587
+ if (!Array.isArray(entries)) return [];
3588
+ const messagesDir = join22(dirname12(indexPath), "messages");
3589
+ const turns = [];
3590
+ for (const entry of entries) {
3591
+ const id = entry?.id;
3592
+ if (typeof id !== "string") continue;
3593
+ const file = readJson(join22(messagesDir, `${id}.json`));
3594
+ const encoded = file?.message;
3595
+ if (typeof encoded !== "string") continue;
3596
+ let inner;
3597
+ try {
3598
+ inner = JSON.parse(encoded);
3599
+ } catch {
3600
+ continue;
3601
+ }
3602
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
3603
+ const isUser = role === "user";
3604
+ const isAssistant = role === "assistant";
3605
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
3606
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
3607
+ const texts = [];
3608
+ const calls = [];
3609
+ for (const block of blocks) {
3610
+ if (!block || typeof block !== "object") continue;
3611
+ const { type, text, toolName, args } = block;
3612
+ if (type === "text" && typeof text === "string") texts.push(text);
3613
+ else if (type === "tool-call" && typeof toolName === "string")
3614
+ calls.push({ name: toolName, args });
3615
+ }
3616
+ if (texts.length) {
3617
+ const raw = texts.join("\n");
3618
+ if (isUser) {
3619
+ const text = ideUserText(raw);
3620
+ if (text) turns.push({ role: "user", content: text, ...stamp });
3621
+ } else if (isAssistant) {
3622
+ const text = stripInjectedMemory(raw).trim();
3623
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
3624
+ }
3625
+ }
3626
+ for (const call of calls) {
3627
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
3628
+ }
3629
+ }
3630
+ return turns;
3631
+ }
3632
+ function readCodebuddyTranscript(path) {
3633
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
3634
+ }
3635
+
2815
3636
  // src/harness/hook-lifecycle.ts
2816
3637
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2817
3638
  var claudePrompt = {
@@ -2890,7 +3711,7 @@ var copilotPrompt = {
2890
3711
  ${context}`.trim()
2891
3712
  })
2892
3713
  };
2893
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
3714
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
2894
3715
  var devinPrompt = {
2895
3716
  harness: "devin-cli",
2896
3717
  requireCwd: true,
@@ -2917,6 +3738,36 @@ var standardSessionStart = (harness) => ({
2917
3738
  }
2918
3739
  })
2919
3740
  });
3741
+ var genieSessionStart = (harness) => {
3742
+ const base = standardSessionStart(harness);
3743
+ return {
3744
+ ...base,
3745
+ parse: (ev) => ({
3746
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
3747
+ sessionId: ev.session_id
3748
+ }),
3749
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
3750
+ };
3751
+ };
3752
+ var geniePrompt = (harness) => ({
3753
+ ...claudePrompt,
3754
+ harness,
3755
+ emit: (context, notice, ev) => ({
3756
+ ...claudePrompt.emit(context, notice, ev),
3757
+ suppressOutput: true
3758
+ })
3759
+ });
3760
+ var genieRetain = (harness, readTranscript) => ({
3761
+ hostTimeoutSec: 60,
3762
+ harness,
3763
+ parse: (ev) => ({
3764
+ sessionId: ev.session_id,
3765
+ transcriptPath: ev.transcript_path,
3766
+ cwd: ev.cwd
3767
+ }),
3768
+ readTranscript
3769
+ });
3770
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
2920
3771
  var HOOK_HARNESSES = {
2921
3772
  "claude-code": {
2922
3773
  configStyle: "nested",
@@ -2925,11 +3776,12 @@ var HOOK_HARNESSES = {
2925
3776
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
2926
3777
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
2927
3778
  },
2928
- sessionStart: standardSessionStart("claude-code"),
2929
- prompt: claudePrompt,
3779
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3780
+ prompt: { ...claudePrompt, accept: notGrokHosted },
2930
3781
  retain: {
2931
3782
  hostTimeoutSec: 60,
2932
3783
  harness: "claude-code",
3784
+ accept: notGrokHosted,
2933
3785
  parse: (ev) => ({
2934
3786
  sessionId: ev.session_id,
2935
3787
  transcriptPath: ev.transcript_path,
@@ -3112,17 +3964,29 @@ var HOOK_HARNESSES = {
3112
3964
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3113
3965
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3114
3966
  },
3967
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
3968
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
3969
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
3970
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
3115
3971
  sessionStart: {
3116
3972
  ...standardSessionStart("grok-build"),
3117
3973
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3118
3974
  parse: (ev) => ({
3119
3975
  cwd: ev.cwd,
3120
3976
  sessionId: ev.sessionId
3121
- })
3977
+ }),
3978
+ deferContextToToolHook: true
3122
3979
  },
3123
3980
  prompt: {
3124
3981
  ...claudePrompt,
3125
3982
  harness: "grok-build",
3983
+ toolHook: {
3984
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
3985
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
3986
+ emit: (context) => ({
3987
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
3988
+ })
3989
+ },
3126
3990
  parse: (ev) => ({
3127
3991
  prompt: ev.prompt,
3128
3992
  cwd: ev.cwd,
@@ -3245,6 +4109,159 @@ var HOOK_HARNESSES = {
3245
4109
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3246
4110
  }
3247
4111
  }
4112
+ },
4113
+ /**
4114
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4115
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4116
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4117
+ * map IS the file) and a `version` field the host writes and expects.
4118
+ *
4119
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4120
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4121
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4122
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4123
+ * plays: `journal.assistantText` closes the turn with it.
4124
+ */
4125
+ traecode: {
4126
+ configStyle: "nested",
4127
+ install: {
4128
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4129
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4130
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4131
+ },
4132
+ sessionStart: {
4133
+ ...standardSessionStart("traecode"),
4134
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4135
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4136
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4137
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4138
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4139
+ // rides the session banner.
4140
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4141
+ },
4142
+ prompt: {
4143
+ ...claudePrompt,
4144
+ harness: "traecode",
4145
+ journalPrompt: true,
4146
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4147
+ parse: (ev) => ({
4148
+ prompt: ev.prompt,
4149
+ cwd: ev.cwd,
4150
+ sessionId: ev.session_id
4151
+ })
4152
+ },
4153
+ retain: {
4154
+ hostTimeoutSec: 60,
4155
+ harness: "traecode",
4156
+ // No transcriptPath: the journal supplies it (see `journal` below).
4157
+ parse: (ev) => ({
4158
+ sessionId: ev.session_id,
4159
+ cwd: ev.cwd
4160
+ }),
4161
+ journal: {
4162
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4163
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4164
+ }
4165
+ }
4166
+ },
4167
+ "kimi-code": {
4168
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4169
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4170
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4171
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4172
+ configStyle: "toml-array",
4173
+ install: {
4174
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4175
+ // supported host, and the opposite of qwen-code's identically named field.
4176
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4177
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4178
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4179
+ },
4180
+ sessionStart: {
4181
+ harness: "kimi-code",
4182
+ parse: (ev) => ({
4183
+ cwd: ev.cwd,
4184
+ sessionId: ev.session_id
4185
+ }),
4186
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4187
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4188
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4189
+ emit: () => ({})
4190
+ },
4191
+ prompt: {
4192
+ harness: "kimi-code",
4193
+ parse: (ev) => ({
4194
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4195
+ prompt: kimiPromptText(ev.prompt),
4196
+ cwd: ev.cwd,
4197
+ sessionId: ev.session_id
4198
+ }),
4199
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4200
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4201
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4202
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4203
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4204
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4205
+ emit: (context, notice) => ({ message: context || notice })
4206
+ },
4207
+ retain: {
4208
+ hostTimeoutSec: 60,
4209
+ harness: "kimi-code",
4210
+ parse: (ev) => {
4211
+ const sessionId = ev.session_id;
4212
+ return {
4213
+ sessionId,
4214
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4215
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4216
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4217
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4218
+ cwd: ev.cwd
4219
+ };
4220
+ },
4221
+ readTranscript: readKimiTranscript
4222
+ }
4223
+ },
4224
+ /**
4225
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4226
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4227
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4228
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4229
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4230
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4231
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4232
+ * file-backed host rather than the journal ZCode needs.
4233
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4234
+ */
4235
+ workbuddy: {
4236
+ configStyle: "nested",
4237
+ install: {
4238
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4239
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
4240
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
4241
+ },
4242
+ sessionStart: genieSessionStart("workbuddy"),
4243
+ prompt: geniePrompt("workbuddy"),
4244
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
4245
+ },
4246
+ /**
4247
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
4248
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
4249
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
4250
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
4251
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
4252
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
4253
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
4254
+ */
4255
+ codebuddy: {
4256
+ configStyle: "nested",
4257
+ install: {
4258
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
4259
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
4260
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
4261
+ },
4262
+ sessionStart: genieSessionStart("codebuddy"),
4263
+ prompt: geniePrompt("codebuddy"),
4264
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
3248
4265
  }
3249
4266
  };
3250
4267
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);