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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +201 -16
  2. package/dist/antigravity-hook.js +1132 -115
  3. package/dist/antigravity-statusline.js +77 -11
  4. package/dist/antigravity-stop-hook.js +1193 -133
  5. package/dist/claude-hook.js +1132 -115
  6. package/dist/claude-sessionstart-hook.js +1241 -140
  7. package/dist/claude-stop-hook.js +1193 -133
  8. package/dist/cline.js +578 -163
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +1132 -115
  13. package/dist/codex-sessionstart-hook.js +1241 -140
  14. package/dist/codex-stop-hook.js +1193 -133
  15. package/dist/copilot-hook.js +1132 -115
  16. package/dist/copilot-sessionstart-hook.js +1241 -140
  17. package/dist/copilot-stop-hook.js +1193 -133
  18. package/dist/cursor-hook.js +1132 -115
  19. package/dist/cursor-sessionstart-hook.js +1241 -140
  20. package/dist/cursor-stop-hook.js +1193 -133
  21. package/dist/daemon-start.js +54 -9
  22. package/dist/dcode-hook.js +1132 -115
  23. package/dist/dcode-sessionstart-hook.js +1241 -140
  24. package/dist/dcode-stop-hook.js +1193 -133
  25. package/dist/deepen.js +370 -104
  26. package/dist/devin-hook.js +1132 -115
  27. package/dist/devin-sessionstart-hook.js +1241 -140
  28. package/dist/devin-stop-hook.js +1193 -133
  29. package/dist/droid-hook.js +1132 -115
  30. package/dist/droid-sessionstart-hook.js +1241 -140
  31. package/dist/droid-stop-hook.js +1193 -133
  32. package/dist/dsh.js +586 -164
  33. package/dist/grok-hook.js +1132 -115
  34. package/dist/grok-sessionstart-hook.js +1241 -140
  35. package/dist/grok-stop-hook.js +1193 -133
  36. package/dist/hindsight-seed.js +50 -8
  37. package/dist/index.js +587 -172
  38. package/dist/installer.js +2010 -769
  39. package/dist/kilo.js +587 -172
  40. package/dist/kimi-hook.js +4270 -0
  41. package/dist/kimi-sessionstart-hook.js +5030 -0
  42. package/dist/kimi-stop-hook.js +4564 -0
  43. package/dist/mcp-server.js +419 -115
  44. package/dist/opencode2.js +586 -169
  45. package/dist/pi.js +644 -175
  46. package/dist/prime-agent.js +644 -175
  47. package/dist/qwen-hook.js +1132 -115
  48. package/dist/qwen-sessionstart-hook.js +1241 -140
  49. package/dist/qwen-stop-hook.js +1193 -133
  50. package/dist/status.js +243 -52
  51. package/dist/traecode-hook.js +4270 -0
  52. package/dist/traecode-sessionstart-hook.js +5030 -0
  53. package/dist/traecode-stop-hook.js +4564 -0
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +1132 -115
  58. package/dist/zcode-sessionstart-hook.js +1241 -140
  59. package/dist/zcode-stop-hook.js +1193 -133
  60. package/package.json +22 -12
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +73 -14
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/hook.ts
4
- import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
4
+ import { existsSync as existsSync2 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
7
  import { existsSync } from "fs";
@@ -9,6 +9,7 @@ import { homedir as homedir2 } from "os";
9
9
  import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
10
10
 
11
11
  // src/core/diag.ts
12
+ import { readFileSync } from "fs";
12
13
  import { join as join2 } from "path";
13
14
 
14
15
  // src/core/log.ts
@@ -82,9 +83,30 @@ function diag(harness, event, extra = {}) {
82
83
  } catch {
83
84
  }
84
85
  }
86
+ function parseHookEvent(harness, raw) {
87
+ const text = raw.replace(/^(?:|)+/, "");
88
+ if (!text.trim()) return null;
89
+ try {
90
+ const ev = JSON.parse(text);
91
+ if (ev && typeof ev === "object" && !Array.isArray(ev)) return ev;
92
+ diag(harness, "hook_input_invalid", { error: "not a JSON object" });
93
+ } catch (e) {
94
+ diag(harness, "hook_input_invalid", { error: e.message });
95
+ }
96
+ return null;
97
+ }
98
+ function readHookEvent(harness) {
99
+ let raw;
100
+ try {
101
+ raw = readFileSync(0, "utf8");
102
+ } catch {
103
+ return null;
104
+ }
105
+ return parseHookEvent(harness, raw);
106
+ }
85
107
 
86
108
  // src/core/git-layout.ts
87
- import { lstatSync, readFileSync, realpathSync } from "fs";
109
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
88
110
  import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
89
111
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
90
112
  var ATTEMPTS = 3;
@@ -108,7 +130,7 @@ function entryKind(path) {
108
130
  }
109
131
  function readTextOrNull(path) {
110
132
  try {
111
- return readFileSync(path, "utf8");
133
+ return readFileSync2(path, "utf8");
112
134
  } catch (error) {
113
135
  if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
114
136
  return null;
@@ -270,13 +292,13 @@ function isWithin(directory, configured) {
270
292
  function mapLookup(map, directory) {
271
293
  const cwd = normalize(directory);
272
294
  let best;
273
- for (const [dir, bank] of Object.entries(map)) {
295
+ for (const [dir, value] of Object.entries(map)) {
274
296
  const p = configuredDir(dir);
275
297
  if (isWithin(cwd, p)) {
276
- if (!best || p.length > best.len) best = { len: p.length, bank };
298
+ if (!best || p.length > best.len) best = { len: p.length, value };
277
299
  }
278
300
  }
279
- return best?.bank;
301
+ return best?.value;
280
302
  }
281
303
  function lookupDirectories(config, directory, sessionRoot = "") {
282
304
  const directories = [normalize(directory)];
@@ -300,6 +322,10 @@ function isOptedIn(config, directory) {
300
322
  const pathMap = config.mapPathToBank;
301
323
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
302
324
  }
325
+ function pathSection(config, paths, directory) {
326
+ if (!directory || !paths) return void 0;
327
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
328
+ }
303
329
  function mappedBank(config, directory, sessionRoot) {
304
330
  const pathMap = config.mapPathToBank;
305
331
  if (!directory || !pathMap) return void 0;
@@ -334,7 +360,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
334
360
  }
335
361
 
336
362
  // src/core/config.ts
337
- import { readFileSync as readFileSync2 } from "fs";
363
+ import { readFileSync as readFileSync3 } from "fs";
338
364
  import { homedir as homedir3 } from "os";
339
365
  import { join as join7 } from "path";
340
366
 
@@ -347,7 +373,7 @@ var DEFAULT_SEED_LIMIT = 300;
347
373
  // src/core/missions.ts
348
374
  import { createHash } from "crypto";
349
375
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
350
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
376
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
351
377
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
352
378
  var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
353
379
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -423,6 +449,8 @@ var KNOWLEDGE_LABELS = {
423
449
  ]
424
450
  };
425
451
  function pageScopeRule(project) {
452
+ if (project === void 0)
453
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
426
454
  return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
427
455
  }
428
456
  var PAGE_TAXONOMY = [
@@ -558,12 +586,17 @@ var CODING_BANK_TEMPLATE = {
558
586
  }
559
587
  };
560
588
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
589
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
590
+ "retain_strategies",
591
+ "entity_labels",
592
+ "retain_extraction_mode"
593
+ ];
561
594
  function isSet(v) {
562
595
  if (v === null || v === void 0) return false;
563
596
  if (typeof v === "string") return v.trim() !== "";
564
597
  return true;
565
598
  }
566
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
599
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
567
600
  const current2 = overrides ?? {};
568
601
  const template = CODING_BANK_TEMPLATE.bank;
569
602
  const bank = {};
@@ -592,19 +625,26 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
592
625
  const [knowledgeGroup] = template.entity_labels;
593
626
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
594
627
  bank.entity_labels = [...labels, knowledgeGroup];
628
+ for (const [key, value] of Object.entries(defaults)) {
629
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
630
+ bank[key] = value;
631
+ }
595
632
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
596
633
  }
597
634
 
635
+ // package.json
636
+ var version = "0.8.1";
637
+
598
638
  // src/core/util.ts
599
639
  import { accessSync, constants } from "fs";
600
640
  import { delimiter, join as join6 } from "path";
601
641
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
602
- function semverGte(version, min) {
642
+ function semverGte(version2, min) {
603
643
  const parts = (v) => {
604
644
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
605
645
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
606
646
  };
607
- const a = version ? parts(version) : void 0;
647
+ const a = version2 ? parts(version2) : void 0;
608
648
  const b = parts(min);
609
649
  if (!a || !b) return false;
610
650
  for (let i = 0; i < 3; i++) {
@@ -627,8 +667,18 @@ async function pool(items, n, fn, onError, onProgress) {
627
667
  }
628
668
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
629
669
  }
670
+ function isOurMcpEntry(entry) {
671
+ if (!entry || typeof entry !== "object") return false;
672
+ const candidate = entry;
673
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
674
+ const script = candidate.args[0];
675
+ if (typeof script !== "string") return false;
676
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
677
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
678
+ }
630
679
 
631
680
  // src/core/hindsight.ts
681
+ var USER_AGENT = `hindsight-coding-agents/${version}`;
632
682
  function resolveRetainScopes(tags, configured) {
633
683
  if (configured !== "per_source") return configured;
634
684
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -664,7 +714,7 @@ async function isEndpointMissing(r) {
664
714
  const j = await r.json();
665
715
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
666
716
  } catch {
667
- return true;
717
+ return false;
668
718
  }
669
719
  }
670
720
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -683,6 +733,12 @@ var ReflectError = class extends Error {
683
733
  get fallbackEligible() {
684
734
  return this.timedOut || this.status !== void 0 && this.status >= 500;
685
735
  }
736
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
737
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
738
+ get permanent() {
739
+ const s = this.status;
740
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
741
+ }
686
742
  };
687
743
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
688
744
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -693,8 +749,31 @@ var DEFAULT_RECALL_OPTIONS = {
693
749
  include: { entities: null }
694
750
  };
695
751
  var POLL_CYCLE_MS = 5e3;
752
+ var POLL_MAX_SERVER_ERRORS = 12;
696
753
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
697
754
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
755
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
756
+ function shapePage(page) {
757
+ const p = page ?? {};
758
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
759
+ return {
760
+ id: p.id,
761
+ name: p.name,
762
+ ...p.description ? { description: p.description } : {},
763
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
764
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
765
+ body
766
+ };
767
+ }
768
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
769
+ function signalOnlyDispatcher() {
770
+ void globalThis.Headers;
771
+ const d = globalThis[GLOBAL_DISPATCHER];
772
+ if (typeof d?.compose !== "function") return void 0;
773
+ return d.compose(
774
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
775
+ );
776
+ }
698
777
  var HindsightClient = class {
699
778
  apiUrl;
700
779
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -714,6 +793,7 @@ var HindsightClient = class {
714
793
  observationScopes;
715
794
  pageSearchLimit;
716
795
  recallOptions;
796
+ rateLimitPatienceMs;
717
797
  constructor(o) {
718
798
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
719
799
  this.token = o.apiToken;
@@ -726,13 +806,18 @@ var HindsightClient = class {
726
806
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
727
807
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
728
808
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
809
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
729
810
  }
730
811
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
731
812
  get apiToken() {
732
813
  return this.token;
733
814
  }
734
815
  headers() {
735
- const h = { "Content-Type": "application/json" };
816
+ const h = {
817
+ "Content-Type": "application/json",
818
+ "Accept-Encoding": "identity",
819
+ "User-Agent": USER_AGENT
820
+ };
736
821
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
737
822
  return h;
738
823
  }
@@ -763,7 +848,8 @@ var HindsightClient = class {
763
848
  * bounds the whole call.
764
849
  */
765
850
  async fetchWithAuth(url, init) {
766
- const send = () => fetch(url, { ...init, headers: this.headers() });
851
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
852
+ const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
767
853
  const r = await send();
768
854
  if (r.status !== 401 || !this.refreshToken()) return r;
769
855
  return send();
@@ -779,13 +865,22 @@ var HindsightClient = class {
779
865
  }
780
866
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
781
867
  async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
782
- const r = await this.fetchWithAuth(url, {
783
- method,
784
- body: body ? JSON.stringify(body) : void 0,
785
- signal: AbortSignal.timeout(timeoutMs)
786
- });
787
- if (r.status === 429 && !tolerate.includes(429))
788
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
868
+ const payload = body ? JSON.stringify(body) : void 0;
869
+ let r;
870
+ for (let attempt = 0, waited = 0; ; attempt++) {
871
+ r = await this.fetchWithAuth(url, {
872
+ method,
873
+ body: payload,
874
+ signal: AbortSignal.timeout(timeoutMs)
875
+ });
876
+ if (r.status !== 429 || tolerate.includes(429)) break;
877
+ const asked = retryAfterMs(r.headers.get("retry-after"));
878
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
879
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
880
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
881
+ await sleep(wait);
882
+ waited += wait;
883
+ }
789
884
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
790
885
  throw new Error(
791
886
  `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -820,7 +915,7 @@ var HindsightClient = class {
820
915
  }
821
916
  /**
822
917
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
823
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
918
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
824
919
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
825
920
  */
826
921
  async supportsIdempotentRetain() {
@@ -830,14 +925,37 @@ var HindsightClient = class {
830
925
  }
831
926
  return this.idempotentRetain;
832
927
  }
928
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
929
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
930
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
931
+ * `/version`, so that stays as the fallback. */
833
932
  async probeIdempotentRetain() {
933
+ for (const path of ["/v1/version", "/version"]) {
934
+ try {
935
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
936
+ if (!r.ok) continue;
937
+ const j = await r.json();
938
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
939
+ } catch {
940
+ }
941
+ }
942
+ return false;
943
+ }
944
+ /**
945
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
946
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
947
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
948
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
949
+ */
950
+ async supportsAppendRetain() {
951
+ if (!await this.supportsIdempotentRetain()) return false;
834
952
  try {
835
- const r = await this.req("GET", `${this.apiUrl}/version`);
836
- if (!r.ok) return false;
953
+ const r = await this.req("GET", this.bankUrl("/config"));
954
+ if (!r.ok) return true;
837
955
  const j = await r.json();
838
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
956
+ return j.config?.store_document_text !== false;
839
957
  } catch {
840
- return false;
958
+ return true;
841
959
  }
842
960
  }
843
961
  /**
@@ -865,6 +983,32 @@ var HindsightClient = class {
865
983
  }
866
984
  return ids;
867
985
  }
986
+ /**
987
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
988
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
989
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
990
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
991
+ */
992
+ async documentTags(documentId) {
993
+ const limit = 100;
994
+ for (let offset = 0; ; offset += limit) {
995
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
996
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
997
+ const j = await r.json();
998
+ const items = j.items ?? [];
999
+ const hit = items.find((it) => it.id === documentId);
1000
+ if (hit) return hit.tags ?? [];
1001
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
1002
+ }
1003
+ }
1004
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
1005
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
1006
+ async hasDocuments() {
1007
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
1008
+ if (r.status === 404) return false;
1009
+ const j = await r.json();
1010
+ return (j.total ?? j.items?.length ?? 0) > 0;
1011
+ }
868
1012
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
869
1013
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
870
1014
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -886,7 +1030,8 @@ var HindsightClient = class {
886
1030
  } else {
887
1031
  const manifest = codingBankManifest(
888
1032
  opts.reset ? void 0 : await this.readBankOverrides(),
889
- opts.extractionMode
1033
+ opts.extractionMode,
1034
+ opts.defaults
890
1035
  );
891
1036
  if (!manifest) {
892
1037
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -945,7 +1090,13 @@ var HindsightClient = class {
945
1090
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
946
1091
  const start = Date.now();
947
1092
  const pending = new Set(ids);
1093
+ const serverErrors = /* @__PURE__ */ new Map();
948
1094
  let failed = 0;
1095
+ const giveUp = (id, status) => {
1096
+ pending.delete(id);
1097
+ failed++;
1098
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
1099
+ };
949
1100
  while (pending.size && Date.now() - start < maxMs) {
950
1101
  let backoffMs = POLL_CYCLE_MS;
951
1102
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -958,7 +1109,14 @@ var HindsightClient = class {
958
1109
  );
959
1110
  return;
960
1111
  }
961
- if (!r.ok) return;
1112
+ if (r.status >= 500) {
1113
+ const n = (serverErrors.get(id) ?? 0) + 1;
1114
+ serverErrors.set(id, n);
1115
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
1116
+ return;
1117
+ }
1118
+ if (!r.ok) return giveUp(id, r.status);
1119
+ serverErrors.delete(id);
962
1120
  const st = ((await r.json()).status || "").toLowerCase();
963
1121
  if (TERMINAL.has(st)) {
964
1122
  pending.delete(id);
@@ -1092,8 +1250,8 @@ var HindsightClient = class {
1092
1250
  return { items };
1093
1251
  }
1094
1252
  /**
1095
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1096
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1253
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1254
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1097
1255
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1098
1256
  * token cap.
1099
1257
  */
@@ -1104,7 +1262,7 @@ var HindsightClient = class {
1104
1262
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1105
1263
  );
1106
1264
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1107
- return await r.json();
1265
+ return shapePage(await r.json());
1108
1266
  }
1109
1267
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1110
1268
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1125,6 +1283,7 @@ var HindsightClient = class {
1125
1283
  return (j.results ?? []).map((x) => ({
1126
1284
  id: x.id,
1127
1285
  name: x.name,
1286
+ ...x.source_query ? { source_query: x.source_query } : {},
1128
1287
  snippet: x.snippet ?? "",
1129
1288
  score: x.score ?? 0
1130
1289
  }));
@@ -1141,7 +1300,7 @@ var HindsightClient = class {
1141
1300
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1142
1301
  */
1143
1302
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1144
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1303
+ const pages = pagesFor(this.project, pagesConfig, customPages);
1145
1304
  const existing = /* @__PURE__ */ new Map();
1146
1305
  let roots;
1147
1306
  try {
@@ -1216,7 +1375,7 @@ var HindsightClient = class {
1216
1375
  }
1217
1376
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1218
1377
  this.log(
1219
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1378
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1220
1379
  );
1221
1380
  }
1222
1381
  /**
@@ -1227,23 +1386,33 @@ var HindsightClient = class {
1227
1386
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1228
1387
  * consolidation under the auto-refresh that used to be the default (#3506).
1229
1388
  *
1230
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1231
- * initiative's own title, and re-stating either would rebuild a page whose question never
1232
- * changed. The tree read above is reused rather than re-fetched.
1389
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
1390
+ * re-stating either would rebuild a page whose question never changed. The one exception is
1391
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
1392
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
1393
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
1394
+ * reused rather than re-fetched.
1233
1395
  */
1234
1396
  async resyncInitiativeTriggers(roots, pageTrigger) {
1235
1397
  const folder = roots.find(
1236
1398
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1237
1399
  );
1400
+ const bankScope = pageScopeRule(this.bank);
1238
1401
  let updated = 0;
1239
1402
  for (const page of folder?.children ?? []) {
1240
- if (page.kind !== "page" || page.trigger == null) continue;
1241
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1242
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
1403
+ if (page.kind !== "page") continue;
1404
+ const patch = {};
1405
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
1406
+ if (query !== page.description) patch.source_query = query;
1407
+ if (page.trigger != null) {
1408
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1409
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
1410
+ }
1411
+ if (!patch.trigger && !patch.source_query) continue;
1243
1412
  const r = await this.req(
1244
1413
  "PATCH",
1245
1414
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1246
- { trigger: pageTriggerPatch(desired) }
1415
+ patch
1247
1416
  );
1248
1417
  if (r.status === 404) continue;
1249
1418
  updated++;
@@ -1271,10 +1440,9 @@ var HindsightClient = class {
1271
1440
  let pageId = args.relatesToPageId;
1272
1441
  if (!pageId) {
1273
1442
  const folderId = await this.ensureFolder("Initiatives");
1274
- const subject = this.project ?? this.bank;
1275
1443
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1276
1444
  name: args.title,
1277
- source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(subject),
1445
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
1278
1446
  parent_id: folderId,
1279
1447
  tags: ["knowledge:feature-work"],
1280
1448
  max_tokens: PAGE_MAX_TOKENS,
@@ -1289,7 +1457,7 @@ var HindsightClient = class {
1289
1457
  }
1290
1458
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1291
1459
  const content = `${verb}: ${args.title}. ${args.summary}`;
1292
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1460
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
1293
1461
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1294
1462
  const context = `initiative marker for [[page:${pageId}]]`;
1295
1463
  await this.retain(content, context, markerId, tags, "document", {
@@ -1395,6 +1563,7 @@ function resolveCustomPages(raw) {
1395
1563
  }
1396
1564
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1397
1565
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1566
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1398
1567
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1399
1568
  function resolveReflectBudget(raw) {
1400
1569
  const value = raw.reflectBudget;
@@ -1421,6 +1590,22 @@ function resolveObservationScopes(raw) {
1421
1590
  }
1422
1591
  return DEFAULT_OBSERVATION_SCOPES;
1423
1592
  }
1593
+ function resolveDefaultBankConfig(raw) {
1594
+ const value = raw;
1595
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1596
+ const out = {};
1597
+ for (const [key, v] of Object.entries(value)) {
1598
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1599
+ log.warn(
1600
+ "config",
1601
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1602
+ );
1603
+ continue;
1604
+ }
1605
+ out[key] = v;
1606
+ }
1607
+ return out;
1608
+ }
1424
1609
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1425
1610
  function resolveAutoInject(raw) {
1426
1611
  if (raw.autoReflect !== void 0) {
@@ -1460,18 +1645,21 @@ function resolveConfig(raw = {}) {
1460
1645
  // write sessions back by default, every harness
1461
1646
  manageBankConfig: raw.manageBankConfig ?? true,
1462
1647
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1648
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1463
1649
  maxParallelRetains: raw.maxParallelRetains || 10,
1464
1650
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1465
1651
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1466
1652
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1467
1653
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1468
1654
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1655
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1469
1656
  reflectBudget: resolveReflectBudget(raw),
1470
1657
  autoInject: resolveAutoInject(raw),
1471
1658
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1472
1659
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1473
1660
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1474
1661
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1662
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1475
1663
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1476
1664
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1477
1665
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1491,18 +1679,22 @@ function resolveConfig(raw = {}) {
1491
1679
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1492
1680
  // nested object cannot reach the API as a tag and fail the whole retain.
1493
1681
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1682
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1683
+ // the built-in default) from a configured value, and an empty context would strip the default.
1684
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1494
1685
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1495
1686
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1496
1687
  ) : {},
1497
1688
  observationScopes: resolveObservationScopes(raw.observationScopes),
1498
1689
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1690
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1499
1691
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1500
1692
  autoUpdate: raw.autoUpdate ?? true
1501
1693
  };
1502
1694
  }
1503
1695
  function readRaw(path) {
1504
1696
  try {
1505
- return JSON.parse(readFileSync2(path, "utf8"));
1697
+ return JSON.parse(readFileSync3(path, "utf8"));
1506
1698
  } catch (e) {
1507
1699
  if (e?.code !== "ENOENT") {
1508
1700
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1512,7 +1704,12 @@ function readRaw(path) {
1512
1704
  }
1513
1705
  function mergeRaw(a, b) {
1514
1706
  const { harnesses: _drop, ...flat } = b;
1515
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1707
+ return {
1708
+ ...a,
1709
+ ...flat,
1710
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1711
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1712
+ };
1516
1713
  }
1517
1714
  function applyLayer(raw, layer, harness) {
1518
1715
  let out = mergeRaw(raw, layer);
@@ -1543,9 +1740,11 @@ var ENV_KEYS = {
1543
1740
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1544
1741
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1545
1742
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1743
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1546
1744
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1547
1745
  autoInject: "HINDSIGHT_AUTO_INJECT",
1548
1746
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1747
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1549
1748
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1550
1749
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1551
1750
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1587,6 +1786,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1587
1786
  "maxParallelRetains",
1588
1787
  "reflectTimeoutMs",
1589
1788
  "reflectToolTimeoutMs",
1789
+ "injectTimeoutMs",
1590
1790
  "pageSearchLimit",
1591
1791
  "pageRefreshEveryTurns",
1592
1792
  "seedLimit",
@@ -1635,15 +1835,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1635
1835
  function applyBankConfig(cfg, resolvedId, directory) {
1636
1836
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1637
1837
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1838
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1839
+ if (byPath) {
1840
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1841
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1842
+ }
1638
1843
  const section = cfg.banks[resolvedId];
1639
1844
  if (!section) return { cfg, bankId: resolvedId };
1640
- const safe = { ...section };
1641
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1642
- delete safe.banks;
1845
+ const safe = overrideFields(section);
1643
1846
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1644
1847
  delete safe.bank;
1645
1848
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1646
1849
  }
1850
+ function overrideFields(section) {
1851
+ const safe = { ...section };
1852
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1853
+ delete safe.banks;
1854
+ delete safe.paths;
1855
+ return safe;
1856
+ }
1647
1857
  function resolvePartial(cfg, patch) {
1648
1858
  const full = resolveConfig(patch);
1649
1859
  const out = {};
@@ -1652,11 +1862,21 @@ function resolvePartial(cfg, patch) {
1652
1862
  out[key] = full[key];
1653
1863
  }
1654
1864
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1865
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1866
+ const conn = resolveConfig({
1867
+ serverMode: patch.serverMode ?? cfg.serverMode,
1868
+ apiPort: patch.apiPort ?? cfg.apiPort,
1869
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1870
+ });
1871
+ out.serverMode = conn.serverMode;
1872
+ out.apiUrl = conn.apiUrl;
1873
+ out.apiPort = conn.apiPort;
1874
+ }
1655
1875
  return out;
1656
1876
  }
1657
1877
 
1658
1878
  // src/core/session-cache.ts
1659
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1879
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1660
1880
  import { tmpdir } from "os";
1661
1881
  import { dirname as dirname5, join as join8 } from "path";
1662
1882
  function writeFileAtomic(path, body) {
@@ -1680,7 +1900,7 @@ function sessionRootDir(harness, sessionId, cwd) {
1680
1900
  if (!sessionId || !cwd) return cwd;
1681
1901
  const file = sessionRootFile(harness, sessionId);
1682
1902
  try {
1683
- const recorded = readFileSync3(file, "utf8").trim();
1903
+ const recorded = readFileSync4(file, "utf8").trim();
1684
1904
  if (recorded) return recorded;
1685
1905
  } catch {
1686
1906
  }
@@ -1695,7 +1915,7 @@ function fileUsageCursorStore(harness) {
1695
1915
  return {
1696
1916
  read: (sessionId) => {
1697
1917
  try {
1698
- const turns = JSON.parse(readFileSync3(file(sessionId), "utf8")).turns;
1918
+ const turns = JSON.parse(readFileSync4(file(sessionId), "utf8")).turns;
1699
1919
  return typeof turns === "number" ? turns : void 0;
1700
1920
  } catch {
1701
1921
  return void 0;
@@ -1716,7 +1936,7 @@ function fileCursorStore(harness) {
1716
1936
  return {
1717
1937
  read: (sessionId) => {
1718
1938
  try {
1719
- return JSON.parse(readFileSync3(cursorFile(harness, sessionId), "utf8"));
1939
+ return JSON.parse(readFileSync4(cursorFile(harness, sessionId), "utf8"));
1720
1940
  } catch {
1721
1941
  return void 0;
1722
1942
  }
@@ -1731,7 +1951,7 @@ function fileCursorStore(harness) {
1731
1951
  }
1732
1952
 
1733
1953
  // src/core/turn-journal.ts
1734
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1954
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1735
1955
  import { tmpdir as tmpdir2 } from "os";
1736
1956
  import { dirname as dirname6, join as join9 } from "path";
1737
1957
 
@@ -1800,7 +2020,7 @@ function appendJournalTurn(path, turn) {
1800
2020
  function readJournalTranscript(path) {
1801
2021
  let body;
1802
2022
  try {
1803
- body = readFileSync4(path, "utf8");
2023
+ body = readFileSync5(path, "utf8");
1804
2024
  } catch {
1805
2025
  return [];
1806
2026
  }
@@ -1826,19 +2046,22 @@ function readJournalTranscript(path) {
1826
2046
  return turns;
1827
2047
  }
1828
2048
 
1829
- // src/core/retain-hook.ts
1830
- import { readFileSync as readFileSync7 } from "fs";
1831
-
1832
2049
  // src/core/retain-cursor.ts
1833
2050
  import { createHash as createHash2 } from "crypto";
1834
2051
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1835
2052
  var PENDING_MAX_BYTES = 256 * 1024;
2053
+ var MAX_CURSOR_PATHS = 16;
2054
+ function advancePaths(seen, path) {
2055
+ if (!path) return seen;
2056
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
2057
+ }
1836
2058
  function pendingReplayable(cursor, now) {
1837
2059
  const pending = cursor.pending ?? [];
1838
2060
  if (!pending.length) return true;
1839
2061
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
1840
2062
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
1841
2063
  }
2064
+ var MAX_CURSOR_OPS = 8;
1842
2065
  function fingerprintTurns(turns, count) {
1843
2066
  const h = createHash2("sha1").update(String(count));
1844
2067
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
@@ -1849,8 +2072,10 @@ function planRetain(turns, cursor, opts) {
1849
2072
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
1850
2073
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
1851
2074
  if (cursor.bank !== opts.bank) return { mode: "replace" };
1852
- if (cursor.turns > turns.length) return { mode: "replace" };
1853
- if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
2075
+ const seen = cursor.paths ?? [];
2076
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
2077
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
2078
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
1854
2079
  if (cursor.turns === turns.length) return { mode: "skip" };
1855
2080
  return { mode: "append", fromTurn: cursor.turns };
1856
2081
  }
@@ -1885,11 +2110,36 @@ function renderSessionJsonl(refId, turns, baseTs) {
1885
2110
  }
1886
2111
  async function supportsAppend(client) {
1887
2112
  try {
1888
- return await client.supportsIdempotentRetain();
2113
+ return await client.supportsAppendRetain();
1889
2114
  } catch {
1890
2115
  return false;
1891
2116
  }
1892
2117
  }
2118
+ var OP_CHECK_TIMEOUT_MS = 5e3;
2119
+ var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
2120
+ async function settleOps(client, cursor) {
2121
+ const ops = cursor.ops ?? [];
2122
+ const statuses = await Promise.all(
2123
+ ops.map(async (id) => {
2124
+ try {
2125
+ const r = await client.req(
2126
+ "GET",
2127
+ client.bankUrl(`/operations/${encodeURIComponent(id)}`),
2128
+ void 0,
2129
+ [],
2130
+ OP_CHECK_TIMEOUT_MS
2131
+ );
2132
+ if (r.status === 404) return "not_found";
2133
+ return String((await r.json()).status ?? "").toLowerCase();
2134
+ } catch {
2135
+ return "";
2136
+ }
2137
+ })
2138
+ );
2139
+ const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
2140
+ const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
2141
+ return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
2142
+ }
1893
2143
  var DEFAULT_RETRY_WINDOW_MS = 6e4;
1894
2144
  var RETAIN_RETRY_ATTEMPTS = 2;
1895
2145
  var REQUEST_BUDGET_MS = 15e3;
@@ -1919,6 +2169,7 @@ function serialize(cursors, sessionId, write2) {
1919
2169
  });
1920
2170
  return next;
1921
2171
  }
2172
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
1922
2173
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
1923
2174
  const cursors = opts.cursors;
1924
2175
  if (!cursors)
@@ -1930,20 +2181,41 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
1930
2181
  harness,
1931
2182
  opts.stamp,
1932
2183
  void 0,
1933
- opts.retryUntil
2184
+ opts.retryUntil,
2185
+ opts.transcriptPath
1934
2186
  );
1935
2187
  return serialize(
1936
2188
  cursors,
1937
2189
  sessionId,
1938
- () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
2190
+ () => writeSession(
2191
+ client,
2192
+ sessionId,
2193
+ turns,
2194
+ startTs,
2195
+ harness,
2196
+ opts.stamp,
2197
+ cursors,
2198
+ opts.retryUntil,
2199
+ opts.transcriptPath
2200
+ )
1939
2201
  );
1940
2202
  }
1941
- async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
2203
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
1942
2204
  if (!turns.length) return;
1943
2205
  const refId = `conversation:${sessionId}`;
1944
- const cursor = cursors?.read(sessionId);
2206
+ let cursor = cursors?.read(sessionId);
2207
+ const probed = Boolean(cursors) && cursor?.appendSupported !== true;
1945
2208
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
1946
- const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
2209
+ let ops = [];
2210
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty)
2211
+ ({ cursor, ops } = await settleOps(client, cursor));
2212
+ const plan = planRetain(turns, cursor, {
2213
+ appendSupported,
2214
+ bank: client.bank,
2215
+ path: transcriptPath
2216
+ });
2217
+ if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
2218
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
1947
2219
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
1948
2220
  if (plan.mode === "skip" && !outbox.length) return;
1949
2221
  const opId = (mode, content) => uuidV5(`${client.bank}
@@ -1952,7 +2224,10 @@ ${mode}
1952
2224
  ${content}`);
1953
2225
  const submit = (content, operationId, append) => client.retain(
1954
2226
  content,
1955
- "coding agent session",
2227
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
2228
+ // default names both speakers: the previous "coding agent session" said nothing about
2229
+ // authorship and let an assistant's proposal be recorded as the user's decision.
2230
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
1956
2231
  refId,
1957
2232
  // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1958
2233
  // the documents list filters and draws its agent logo from, so a template cannot displace them.
@@ -1982,8 +2257,13 @@ ${content}`);
1982
2257
  turns: turns.length,
1983
2258
  fingerprint: fingerprintTurns(turns, turns.length),
1984
2259
  bank: client.bank,
2260
+ ...paths ? { paths } : {},
1985
2261
  ...appendSupported ? { appendSupported: true } : {}
1986
2262
  };
2263
+ const accepted = (id) => {
2264
+ if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
2265
+ return ops.length ? { ...next, ops } : next;
2266
+ };
1987
2267
  const stillOurs = () => {
1988
2268
  if (!cursors) return true;
1989
2269
  const now = cursors.read(sessionId);
@@ -1992,12 +2272,10 @@ ${content}`);
1992
2272
  if (plan.mode === "replace") {
1993
2273
  const content = renderSessionJsonl(refId, turns, startTs);
1994
2274
  cursors?.write(sessionId, { ...next, dirty: true });
1995
- await submitWithRetry(
1996
- () => submit(content, opId("replace", content), false),
1997
- stillOurs,
1998
- retryUntil
1999
- );
2000
- cursors?.write(sessionId, next);
2275
+ const operationId = opId("replace", content);
2276
+ await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
2277
+ ops = [];
2278
+ cursors?.write(sessionId, accepted(operationId));
2001
2279
  return;
2002
2280
  }
2003
2281
  const queue = [...outbox];
@@ -2005,7 +2283,7 @@ ${content}`);
2005
2283
  const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
2006
2284
  queue.push({ content, operationId: opId("append", content), at: Date.now() });
2007
2285
  }
2008
- cursors?.write(sessionId, { ...next, pending: queue });
2286
+ cursors?.write(sessionId, { ...accepted(), pending: queue });
2009
2287
  for (let i = 0; i < queue.length; i++) {
2010
2288
  if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
2011
2289
  const entry = queue[i];
@@ -2015,7 +2293,8 @@ ${content}`);
2015
2293
  retryUntil
2016
2294
  );
2017
2295
  const remaining = queue.slice(i + 1);
2018
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
2296
+ const done = accepted(entry.operationId);
2297
+ cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
2019
2298
  }
2020
2299
  }
2021
2300
 
@@ -2026,7 +2305,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
2026
2305
  var DAEMON_WAIT_RETAIN_MS = 4e4;
2027
2306
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2028
2307
  try {
2029
- const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2308
+ const res = await fetch(`${baseUrl}/health`, {
2309
+ headers: { "User-Agent": USER_AGENT },
2310
+ signal: AbortSignal.timeout(timeoutMs)
2311
+ });
2030
2312
  return res.ok;
2031
2313
  } catch {
2032
2314
  return false;
@@ -2108,12 +2390,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
2108
2390
  } catch {
2109
2391
  }
2110
2392
  }
2393
+ var coldStarts = /* @__PURE__ */ new Map();
2394
+ async function waitBounded(p, ms) {
2395
+ let timer;
2396
+ try {
2397
+ await Promise.race([
2398
+ p,
2399
+ new Promise((resolve3) => {
2400
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2401
+ })
2402
+ ]);
2403
+ } finally {
2404
+ clearTimeout(timer);
2405
+ }
2406
+ }
2111
2407
  async function ensureDaemon(cfg, harness, opts = {}) {
2112
2408
  if (cfg.serverMode !== "daemon") return;
2113
2409
  if (await isServerHealthy(cfg.apiUrl)) return;
2114
2410
  if (!preflightDaemon(cfg, harness)) return;
2115
- startDaemonDetached(cfg, harness, opts.spawnFn);
2116
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2411
+ const waitMs = opts.waitMs ?? 0;
2412
+ const running = coldStarts.get(cfg.apiUrl);
2413
+ if (running) {
2414
+ const startedAt = Date.now();
2415
+ await waitBounded(
2416
+ running.catch(() => void 0),
2417
+ waitMs
2418
+ );
2419
+ const remaining = waitMs - (Date.now() - startedAt);
2420
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2421
+ return;
2422
+ }
2423
+ const attempt = (async () => {
2424
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2425
+ await waitForHealth(cfg.apiUrl, waitMs);
2426
+ })();
2427
+ coldStarts.set(cfg.apiUrl, attempt);
2428
+ try {
2429
+ await attempt;
2430
+ } finally {
2431
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2432
+ }
2117
2433
  }
2118
2434
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
2119
2435
  const deadline = Date.now() + budgetMs;
@@ -2168,7 +2484,8 @@ function resolversFor(ctx) {
2168
2484
  function buildRetainStamp(cfg, ctx) {
2169
2485
  const hasTags = Boolean(cfg.retainTags?.length);
2170
2486
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2171
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2487
+ const hasContext = Boolean(cfg.retainContext?.trim());
2488
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2172
2489
  const base = resolversFor(ctx);
2173
2490
  const cache = /* @__PURE__ */ new Map();
2174
2491
  const resolvers = Object.fromEntries(
@@ -2192,7 +2509,8 @@ function buildRetainStamp(cfg, ctx) {
2192
2509
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2193
2510
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2194
2511
  }
2195
- return { tags, metadata };
2512
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2513
+ return { tags, metadata, context };
2196
2514
  }
2197
2515
 
2198
2516
  // src/core/jsonl.ts
@@ -2360,13 +2678,15 @@ async function buildRetain(args) {
2360
2678
  // Stop, reading a complete transcript, corrects it. See recordUsage.
2361
2679
  reviseLastTurn: true
2362
2680
  });
2681
+ if (!client) return;
2363
2682
  const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
2364
2683
  const t0 = Date.now();
2365
2684
  try {
2366
2685
  await retainLiveSession(client, sessionId, turns, startTs, harness, {
2367
2686
  cursors: args.cursors ?? fileCursorStore(harness),
2368
2687
  stamp: args.stamp,
2369
- retryUntil: args.retryUntil
2688
+ retryUntil: args.retryUntil,
2689
+ transcriptPath
2370
2690
  });
2371
2691
  diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
2372
2692
  } catch (e) {
@@ -2383,12 +2703,8 @@ async function buildRetain(args) {
2383
2703
  async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2384
2704
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2385
2705
  const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2386
- let ev = {};
2387
- try {
2388
- ev = JSON.parse(readFileSync7(0, "utf8"));
2389
- } catch {
2390
- return;
2391
- }
2706
+ const ev = readHookEvent(spec.harness);
2707
+ if (!ev) return;
2392
2708
  if (spec.accept && !spec.accept(ev)) return;
2393
2709
  const parsed = spec.parse(ev);
2394
2710
  const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
@@ -2414,18 +2730,19 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2414
2730
  cfg = resolved2.cfg;
2415
2731
  const bankId = resolved2.bankId;
2416
2732
  if (cfg.disabled) return;
2733
+ let client;
2417
2734
  if (!cfg.retainSessions) {
2418
2735
  diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
2419
- return;
2736
+ } else {
2737
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2738
+ client = makeClient({
2739
+ apiUrl: cfg.apiUrl,
2740
+ apiToken: cfg.apiToken,
2741
+ bank: bankId,
2742
+ maxParallelRetains: cfg.maxParallelRetains,
2743
+ observationScopes: cfg.observationScopes
2744
+ });
2420
2745
  }
2421
- await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2422
- const client = makeClient({
2423
- apiUrl: cfg.apiUrl,
2424
- apiToken: cfg.apiToken,
2425
- bank: bankId,
2426
- maxParallelRetains: cfg.maxParallelRetains,
2427
- observationScopes: cfg.observationScopes
2428
- });
2429
2746
  await buildRetain({
2430
2747
  harness: spec.harness,
2431
2748
  sessionId: sessionId || "no-session",
@@ -2446,18 +2763,15 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2446
2763
  });
2447
2764
  }
2448
2765
 
2449
- // src/core/session-start.ts
2450
- import { readFileSync as readFileSync11 } from "fs";
2451
-
2452
2766
  // src/core/git.ts
2453
2767
  import { execFileSync as execFileSync2 } from "child_process";
2454
2768
  import { resolve as resolve2 } from "path";
2455
2769
 
2456
2770
  // src/core/status.ts
2457
- import { execFileSync as execFileSync3 } from "child_process";
2771
+ import { execFileSync as execFileSync4 } from "child_process";
2458
2772
 
2459
2773
  // src/core/survey.ts
2460
- import { spawn as realSpawn4 } from "child_process";
2774
+ import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
2461
2775
  import { createHash as createHash4 } from "crypto";
2462
2776
  import { existsSync as existsSync3 } from "fs";
2463
2777
  import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
@@ -2486,7 +2800,7 @@ import { spawn as realSpawn5 } from "child_process";
2486
2800
  import {
2487
2801
  existsSync as existsSync4,
2488
2802
  mkdirSync as mkdirSync5,
2489
- readFileSync as readFileSync8,
2803
+ readFileSync as readFileSync7,
2490
2804
  realpathSync as realpathSync2,
2491
2805
  unlinkSync as unlinkSync2,
2492
2806
  writeFileSync as writeFileSync3
@@ -2500,15 +2814,246 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2500
2814
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2501
2815
 
2502
2816
  // src/core/skill-sync.ts
2503
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2817
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
2504
2818
  import { homedir as homedir6 } from "os";
2505
- import { dirname as dirname10, join as join15 } from "path";
2819
+ import { dirname as dirname10, join as join16 } from "path";
2506
2820
  import { fileURLToPath as fileURLToPath5 } from "url";
2507
2821
 
2822
+ // src/core/skill-dirs.ts
2823
+ import { existsSync as existsSync5 } from "fs";
2824
+ import { join as join15 } from "path";
2825
+
2508
2826
  // src/core/legacy.ts
2509
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2827
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
2510
2828
  import { homedir as homedir7 } from "os";
2511
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2829
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2830
+
2831
+ // src/core/traecode-mcp.ts
2832
+ import { execFileSync as execFileSync5 } from "child_process";
2833
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2834
+ import { homedir as homedir8 } from "os";
2835
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2836
+ import { fileURLToPath as fileURLToPath6 } from "url";
2837
+ var MCP_SERVER_NAME = "hindsight";
2838
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2839
+ function bundledDistDir() {
2840
+ const here = dirname11(fileURLToPath6(import.meta.url));
2841
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2842
+ }
2843
+ function canon(value) {
2844
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2845
+ if (value && typeof value === "object") {
2846
+ const entries = Object.entries(value).sort(
2847
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2848
+ );
2849
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2850
+ }
2851
+ return JSON.stringify(value);
2852
+ }
2853
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2854
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2855
+ function traecodeUserDataDir(home) {
2856
+ 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");
2857
+ for (const brand of ["Trae CN", "Trae"]) {
2858
+ const dir = join18(root, brand);
2859
+ if (existsSync8(dir)) return dir;
2860
+ }
2861
+ return join18(root, "Trae CN");
2862
+ }
2863
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2864
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2865
+ function gateStateFile() {
2866
+ return gateStateFileFor(bundledDistDir());
2867
+ }
2868
+ function readGateState(opts = {}) {
2869
+ try {
2870
+ return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
2871
+ } catch {
2872
+ return {};
2873
+ }
2874
+ }
2875
+ function workspaceMcpGateState(settingsPath) {
2876
+ let raw;
2877
+ try {
2878
+ raw = readFileSync10(settingsPath, "utf8");
2879
+ } catch {
2880
+ return "unknown";
2881
+ }
2882
+ try {
2883
+ const doc = JSON.parse(raw);
2884
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2885
+ } catch {
2886
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2887
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2888
+ }
2889
+ }
2890
+ function workspaceMcpHint(opts = {}) {
2891
+ try {
2892
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2893
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2894
+ const now = opts.now ?? Date.now();
2895
+ const state = readGateState(opts);
2896
+ if (state.workspaceMcpEnabled) return void 0;
2897
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2898
+ return void 0;
2899
+ }
2900
+ writeFileSync4(
2901
+ opts.stateFile ?? gateStateFile(),
2902
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2903
+ );
2904
+ 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.';
2905
+ } catch {
2906
+ return void 0;
2907
+ }
2908
+ }
2909
+ function gitignoreCovers(lines) {
2910
+ return lines.some((l) => {
2911
+ const t = l.trim();
2912
+ return t.includes(".trae");
2913
+ });
2914
+ }
2915
+ function ensureGitignored(repo) {
2916
+ const gitignore = join18(repo, ".gitignore");
2917
+ if (!existsSync8(gitignore)) return;
2918
+ const current2 = readFileSync10(gitignore, "utf8");
2919
+ if (gitignoreCovers(current2.split("\n"))) return;
2920
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2921
+ writeFileSync4(gitignore, current2 + addition);
2922
+ }
2923
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2924
+ registerTraecodeWorkspaceMcp(cwd, opts);
2925
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2926
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2927
+ }
2928
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2929
+ try {
2930
+ const home = opts.home ?? homedir8();
2931
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2932
+ const dist = opts.dist ?? bundledDistDir();
2933
+ const script = join18(dist, "mcp-server.js");
2934
+ if (!existsSync8(script)) return "skipped";
2935
+ const file = join18(cwd, MCP_FILE_REL);
2936
+ let doc = {};
2937
+ let exists = false;
2938
+ try {
2939
+ doc = JSON.parse(readFileSync10(file, "utf8"));
2940
+ exists = true;
2941
+ } catch {
2942
+ if (existsSync8(file)) return "skipped";
2943
+ }
2944
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2945
+ const entry = {
2946
+ command: "node",
2947
+ args: [script],
2948
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2949
+ };
2950
+ const existing = servers[MCP_SERVER_NAME];
2951
+ let merged;
2952
+ if (existing === void 0) {
2953
+ merged = entry;
2954
+ } else if (isOurMcpEntry(existing)) {
2955
+ const env = existing.env;
2956
+ merged = {
2957
+ ...existing,
2958
+ command: entry.command,
2959
+ args: entry.args,
2960
+ env: { ...env ?? {}, ...entry.env }
2961
+ };
2962
+ } else {
2963
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2964
+ return "skipped";
2965
+ }
2966
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2967
+ servers[MCP_SERVER_NAME] = merged;
2968
+ mkdirSync6(dirname11(file), { recursive: true });
2969
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2970
+ if (!exists) ensureGitignored(cwd);
2971
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2972
+ return "registered";
2973
+ } catch (e) {
2974
+ diag("traecode", "workspace_mcp_register_failed", {
2975
+ cwd,
2976
+ error: e instanceof Error ? e.message : String(e)
2977
+ });
2978
+ return "failed";
2979
+ }
2980
+ }
2981
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2982
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2983
+ var SQLITE_TIMEOUT_MS = 5e3;
2984
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2985
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2986
+ function findWorkspaceStorageDir(storage, repo) {
2987
+ let entries;
2988
+ try {
2989
+ entries = readdirSync2(storage);
2990
+ } catch {
2991
+ return void 0;
2992
+ }
2993
+ for (const name of entries) {
2994
+ try {
2995
+ const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
2996
+ if (typeof doc.folder !== "string") continue;
2997
+ let folder;
2998
+ try {
2999
+ folder = fileURLToPath6(doc.folder);
3000
+ } catch {
3001
+ folder = doc.folder;
3002
+ }
3003
+ if (folder === repo) return join18(storage, name);
3004
+ } catch {
3005
+ continue;
3006
+ }
3007
+ }
3008
+ return void 0;
3009
+ }
3010
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3011
+ try {
3012
+ const home = opts.home ?? homedir8();
3013
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3014
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3015
+ if (!dir) return "failed";
3016
+ const db = join18(dir, "state.vscdb");
3017
+ if (!existsSync8(db)) return "failed";
3018
+ const sqlite = opts.sqlite ?? execFileSync5;
3019
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3020
+ encoding: "utf8",
3021
+ timeout: SQLITE_TIMEOUT_MS,
3022
+ windowsHide: true,
3023
+ stdio: ["ignore", "pipe", "pipe"]
3024
+ }).trim();
3025
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
3026
+ return "on";
3027
+ }
3028
+ run(
3029
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
3030
+ );
3031
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
3032
+ return "seeded";
3033
+ } catch (e) {
3034
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
3035
+ cwd,
3036
+ error: e instanceof Error ? e.message : String(e)
3037
+ });
3038
+ return "failed";
3039
+ }
3040
+ }
3041
+ function workspaceEnableHint(opts = {}) {
3042
+ try {
3043
+ const now = opts.now ?? Date.now();
3044
+ const state = readGateState(opts);
3045
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3046
+ return void 0;
3047
+ }
3048
+ writeFileSync4(
3049
+ opts.stateFile ?? gateStateFile(),
3050
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3051
+ );
3052
+ 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.";
3053
+ } catch {
3054
+ return void 0;
3055
+ }
3056
+ }
2512
3057
 
2513
3058
  // src/core/transcript-codex.ts
2514
3059
  function stampOf(line) {
@@ -2518,12 +3063,68 @@ function isSyntheticUserText(text) {
2518
3063
  const s = text.trimStart();
2519
3064
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2520
3065
  }
3066
+ var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
3067
+ var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
3068
+ function isStartupItem(text) {
3069
+ const s = text.trim();
3070
+ if (AGENTS_BLOCK_HEADER.test(s))
3071
+ return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
3072
+ return STARTUP_TAG_BLOCK.test(s);
3073
+ }
2521
3074
  function contentText(content) {
2522
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3075
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3076
+ }
3077
+ var startupKinds = /* @__PURE__ */ new Set([
3078
+ "agents_md.instructions",
3079
+ "environments.instructions",
3080
+ "environments.environment_context",
3081
+ "plugins.recommendations",
3082
+ "plugins.usage_instructions"
3083
+ ]);
3084
+ function fallbackUserText(payload) {
3085
+ const content = payload.content;
3086
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
3087
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3088
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3089
+ }
3090
+ const items = (Array.isArray(content) ? content : []).filter(
3091
+ (c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
3092
+ );
3093
+ const text = contentText(items);
3094
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2523
3095
  }
2524
3096
  function isUserMessageEvent(line) {
2525
3097
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2526
3098
  }
3099
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
3100
+ function isToolItemEvent(line) {
3101
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
3102
+ }
3103
+ function parseArgs(raw) {
3104
+ if (typeof raw !== "string") return raw;
3105
+ try {
3106
+ return JSON.parse(raw);
3107
+ } catch {
3108
+ return void 0;
3109
+ }
3110
+ }
3111
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
3112
+ function commandText(command) {
3113
+ if (typeof command === "string") return command;
3114
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
3115
+ const argv = command;
3116
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
3117
+ return argv.join(" ");
3118
+ }
3119
+ function toolItemAction(item) {
3120
+ if (item.type === "McpToolCall") {
3121
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
3122
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
3123
+ return actionLine(name, parseArgs(item.arguments));
3124
+ }
3125
+ const command = commandText(item.command).trim();
3126
+ return command ? actionLine("exec_command", { command }) : void 0;
3127
+ }
2527
3128
  function readCodexTranscript(path) {
2528
3129
  const lines = [];
2529
3130
  for (const rawLine of readJsonl(path)) {
@@ -2537,6 +3138,7 @@ function readCodexTranscript(path) {
2537
3138
  }
2538
3139
  }
2539
3140
  const userFromEvents = lines.some(isUserMessageEvent);
3141
+ const actionsFromEvents = lines.some(isToolItemEvent);
2540
3142
  const turns = [];
2541
3143
  const push = (role, raw, stamp = {}) => {
2542
3144
  const text = stripInjectedMemory(raw).trim();
@@ -2547,16 +3149,24 @@ function readCodexTranscript(path) {
2547
3149
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2548
3150
  continue;
2549
3151
  }
3152
+ if (isToolItemEvent(line)) {
3153
+ const action = toolItemAction(line.payload?.item ?? {});
3154
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3155
+ continue;
3156
+ }
2550
3157
  if (line.type !== "response_item") continue;
2551
3158
  const p = line.payload;
2552
3159
  if (!p || typeof p !== "object") continue;
2553
3160
  if (p.type === "message") {
2554
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2555
- else if (p.role === "user" && !userFromEvents) {
2556
- const text = contentText(p.content);
2557
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
3161
+ if (p.role === "assistant") {
3162
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3163
+ continue;
3164
+ push("assistant", contentText(p.content), stampOf(line));
3165
+ } else if (p.role === "user" && !userFromEvents) {
3166
+ push("user", fallbackUserText(p), stampOf(line));
2558
3167
  }
2559
3168
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3169
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2560
3170
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2561
3171
  let input;
2562
3172
  try {
@@ -2657,19 +3267,19 @@ function readCopilotTranscript(path) {
2657
3267
  }
2658
3268
 
2659
3269
  // src/core/transcript-grok.ts
2660
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2661
- import { homedir as homedir8 } from "os";
2662
- import { join as join17 } from "path";
3270
+ import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3271
+ import { homedir as homedir9 } from "os";
3272
+ import { join as join19 } from "path";
2663
3273
  var CHAT_HISTORY = "chat_history.jsonl";
2664
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2665
- const sessionsDir = join17(grokHome, "sessions");
2666
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2667
- if (existsSync7(direct)) return direct;
3274
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3275
+ const sessionsDir = join19(grokHome, "sessions");
3276
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3277
+ if (existsSync9(direct)) return direct;
2668
3278
  try {
2669
- for (const candidate of readdirSync2(sessionsDir)) {
2670
- const directory = join17(sessionsDir, candidate);
2671
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2672
- return join17(directory, sessionId, CHAT_HISTORY);
3279
+ for (const candidate of readdirSync3(sessionsDir)) {
3280
+ const directory = join19(sessionsDir, candidate);
3281
+ if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3282
+ return join19(directory, sessionId, CHAT_HISTORY);
2673
3283
  }
2674
3284
  }
2675
3285
  } catch {
@@ -2704,12 +3314,12 @@ function readGrokTranscript(path) {
2704
3314
  }
2705
3315
 
2706
3316
  // src/core/transcript-devin.ts
2707
- import { existsSync as existsSync8 } from "fs";
3317
+ import { existsSync as existsSync10 } from "fs";
2708
3318
  import { createRequire } from "module";
2709
- import { homedir as homedir9 } from "os";
2710
- import { join as join18 } from "path";
2711
- function devinSessionDb(home = homedir9()) {
2712
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3319
+ import { homedir as homedir10 } from "os";
3320
+ import { join as join20 } from "path";
3321
+ function devinSessionDb(home = homedir10()) {
3322
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2713
3323
  }
2714
3324
  function parseDevinMessages(nodes) {
2715
3325
  const messages = /* @__PURE__ */ new Map();
@@ -2746,7 +3356,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2746
3356
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2747
3357
  return [];
2748
3358
  }
2749
- if (!existsSync8(dbPath)) {
3359
+ if (!existsSync10(dbPath)) {
2750
3360
  diag("devin-cli", "session_db_missing", { dbPath });
2751
3361
  return [];
2752
3362
  }
@@ -3019,7 +3629,7 @@ function readDroidTranscript(path) {
3019
3629
  }
3020
3630
 
3021
3631
  // src/core/transcript-zcode.ts
3022
- import { readFileSync as readFileSync13 } from "fs";
3632
+ import { readFileSync as readFileSync12 } from "fs";
3023
3633
  function messageText(content) {
3024
3634
  if (typeof content === "string") return content.trim();
3025
3635
  if (!Array.isArray(content)) return "";
@@ -3029,7 +3639,7 @@ function readZcodeTranscript(path) {
3029
3639
  if (!path) return [];
3030
3640
  let body;
3031
3641
  try {
3032
- body = readFileSync13(path, "utf8");
3642
+ body = readFileSync12(path, "utf8");
3033
3643
  } catch {
3034
3644
  return [];
3035
3645
  }
@@ -3063,6 +3673,260 @@ function zcodeAssistantText(path) {
3063
3673
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3064
3674
  }
3065
3675
 
3676
+ // src/core/transcript-kimi.ts
3677
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3678
+ import { homedir as homedir11 } from "os";
3679
+ import { join as join21 } from "path";
3680
+ var HARNESS = "kimi-code";
3681
+ var SESSIONS_DIR = "sessions";
3682
+ var AGENTS_DIR = "agents";
3683
+ var WIRE_LOG = "wire.jsonl";
3684
+ var SESSION_PREFIX = "session_";
3685
+ var MAIN_AGENT = "main";
3686
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3687
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3688
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3689
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3690
+ try {
3691
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3692
+ if (!workspace.isDirectory()) continue;
3693
+ const candidate = join21(sessions, workspace.name, name);
3694
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3695
+ }
3696
+ } catch {
3697
+ }
3698
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3699
+ return void 0;
3700
+ }
3701
+ function stampOf2(event) {
3702
+ if (typeof event.time !== "number") return {};
3703
+ const at = new Date(event.time);
3704
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3705
+ }
3706
+ function kimiPromptText(input) {
3707
+ if (!Array.isArray(input)) return "";
3708
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3709
+ }
3710
+ function readKimiWire(events) {
3711
+ const turns = [];
3712
+ let step;
3713
+ const flushStep = () => {
3714
+ if (!step) return;
3715
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3716
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3717
+ step = void 0;
3718
+ };
3719
+ for (const event of events || []) {
3720
+ if (!event || typeof event !== "object") continue;
3721
+ const stamp = stampOf2(event);
3722
+ if (event.type === "turn.prompt") {
3723
+ flushStep();
3724
+ if (event.origin?.kind !== "user") continue;
3725
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3726
+ if (content) turns.push({ role: "user", content, ...stamp });
3727
+ continue;
3728
+ }
3729
+ if (event.type !== "context.append_loop_event") continue;
3730
+ const loop = event.event;
3731
+ if (!loop || typeof loop !== "object") continue;
3732
+ if (loop.type === "content.part") {
3733
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3734
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3735
+ if (step && step.uuid !== uuid) flushStep();
3736
+ if (!step) step = { uuid, texts: [], stamp };
3737
+ step.texts.push(loop.part.text);
3738
+ } else if (loop.type === "tool.call") {
3739
+ flushStep();
3740
+ if (typeof loop.name !== "string" || !loop.name) continue;
3741
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3742
+ }
3743
+ }
3744
+ flushStep();
3745
+ return turns;
3746
+ }
3747
+ function agentIds(sessionDir) {
3748
+ try {
3749
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3750
+ } catch {
3751
+ return [];
3752
+ }
3753
+ }
3754
+ function byAgentId(a, b) {
3755
+ if (a === b) return 0;
3756
+ if (a === MAIN_AGENT) return -1;
3757
+ if (b === MAIN_AGENT) return 1;
3758
+ const indexA = agentIndex(a);
3759
+ const indexB = agentIndex(b);
3760
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3761
+ }
3762
+ function agentIndex(id) {
3763
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3764
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3765
+ }
3766
+ function parseEvent(rawLine) {
3767
+ const trimmed = rawLine.trim();
3768
+ if (!trimmed) return void 0;
3769
+ let parsed;
3770
+ try {
3771
+ parsed = JSON.parse(trimmed);
3772
+ } catch {
3773
+ return void 0;
3774
+ }
3775
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3776
+ }
3777
+ function readKimiTranscript(path) {
3778
+ const turns = [];
3779
+ let remaining = MAX_SESSION_CHARS;
3780
+ for (const agentId of agentIds(path)) {
3781
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3782
+ const events = [];
3783
+ for (const rawLine of readJsonl(wire)) {
3784
+ remaining -= rawLine.length;
3785
+ if (remaining < 0) break;
3786
+ const event = parseEvent(rawLine);
3787
+ if (event) events.push(event);
3788
+ }
3789
+ for (const turn of readKimiWire(events)) turns.push(turn);
3790
+ if (remaining < 0) {
3791
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3792
+ sessionDir: path,
3793
+ stoppedAt: wire
3794
+ });
3795
+ break;
3796
+ }
3797
+ }
3798
+ return turns;
3799
+ }
3800
+
3801
+ // src/core/transcript-workbuddy.ts
3802
+ function messageText2(content) {
3803
+ if (typeof content === "string") return content;
3804
+ if (!Array.isArray(content)) return "";
3805
+ return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
3806
+ }
3807
+ var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
3808
+ function unwrapUserQuery(text) {
3809
+ const match = USER_QUERY_RE.exec(text);
3810
+ return (match ? match[1] : text).trim();
3811
+ }
3812
+ function isSyntheticUserText2(text) {
3813
+ const s = text.trimStart();
3814
+ return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
3815
+ }
3816
+ function parseArgs2(raw) {
3817
+ if (!raw) return void 0;
3818
+ try {
3819
+ return JSON.parse(raw);
3820
+ } catch {
3821
+ return raw;
3822
+ }
3823
+ }
3824
+ function stampOf3(line) {
3825
+ return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
3826
+ }
3827
+ function readWorkbuddyTranscript(path) {
3828
+ const turns = [];
3829
+ for (const rawLine of readJsonl(path)) {
3830
+ const trimmed = rawLine.trim();
3831
+ if (!trimmed) continue;
3832
+ let parsed;
3833
+ try {
3834
+ parsed = JSON.parse(trimmed);
3835
+ } catch {
3836
+ continue;
3837
+ }
3838
+ if (typeof parsed !== "object" || parsed === null) continue;
3839
+ const line = parsed;
3840
+ const stamp = stampOf3(line);
3841
+ if (line.type === "message") {
3842
+ if (line.role !== "user" && line.role !== "assistant") continue;
3843
+ let text = stripInjectedMemory(messageText2(line.content)).trim();
3844
+ if (!text) continue;
3845
+ if (line.role === "user") {
3846
+ if (isSyntheticUserText2(text)) continue;
3847
+ text = unwrapUserQuery(text);
3848
+ if (!text) continue;
3849
+ }
3850
+ turns.push({ role: line.role, content: text, ...stamp });
3851
+ } else if (line.type === "function_call" && typeof line.name === "string") {
3852
+ turns.push({
3853
+ role: "action",
3854
+ content: actionLine(line.name, parseArgs2(line.arguments)),
3855
+ ...stamp
3856
+ });
3857
+ }
3858
+ }
3859
+ return turns;
3860
+ }
3861
+
3862
+ // src/core/transcript-codebuddy-ide.ts
3863
+ import { readFileSync as readFileSync13 } from "fs";
3864
+ import { basename as basename3, dirname as dirname12, join as join22 } from "path";
3865
+ var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
3866
+ function readJson(path) {
3867
+ try {
3868
+ return JSON.parse(readFileSync13(path, "utf8"));
3869
+ } catch {
3870
+ return void 0;
3871
+ }
3872
+ }
3873
+ function ideUserText(raw) {
3874
+ let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
3875
+ if (!text || isSyntheticUserText2(text)) return "";
3876
+ return unwrapUserQuery(text).trim();
3877
+ }
3878
+ function readCodebuddyIdeTranscript(indexPath) {
3879
+ const index = readJson(indexPath);
3880
+ const entries = index?.messages;
3881
+ if (!Array.isArray(entries)) return [];
3882
+ const messagesDir = join22(dirname12(indexPath), "messages");
3883
+ const turns = [];
3884
+ for (const entry of entries) {
3885
+ const id = entry?.id;
3886
+ if (typeof id !== "string") continue;
3887
+ const file = readJson(join22(messagesDir, `${id}.json`));
3888
+ const encoded = file?.message;
3889
+ if (typeof encoded !== "string") continue;
3890
+ let inner;
3891
+ try {
3892
+ inner = JSON.parse(encoded);
3893
+ } catch {
3894
+ continue;
3895
+ }
3896
+ const role = typeof inner.role === "string" ? inner.role : file?.role;
3897
+ const isUser = role === "user";
3898
+ const isAssistant = role === "assistant";
3899
+ const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
3900
+ const blocks = Array.isArray(inner.content) ? inner.content : [];
3901
+ const texts = [];
3902
+ const calls = [];
3903
+ for (const block of blocks) {
3904
+ if (!block || typeof block !== "object") continue;
3905
+ const { type, text, toolName, args } = block;
3906
+ if (type === "text" && typeof text === "string") texts.push(text);
3907
+ else if (type === "tool-call" && typeof toolName === "string")
3908
+ calls.push({ name: toolName, args });
3909
+ }
3910
+ if (texts.length) {
3911
+ const raw = texts.join("\n");
3912
+ if (isUser) {
3913
+ const text = ideUserText(raw);
3914
+ if (text) turns.push({ role: "user", content: text, ...stamp });
3915
+ } else if (isAssistant) {
3916
+ const text = stripInjectedMemory(raw).trim();
3917
+ if (text) turns.push({ role: "assistant", content: text, ...stamp });
3918
+ }
3919
+ }
3920
+ for (const call of calls) {
3921
+ turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
3922
+ }
3923
+ }
3924
+ return turns;
3925
+ }
3926
+ function readCodebuddyTranscript(path) {
3927
+ return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
3928
+ }
3929
+
3066
3930
  // src/harness/hook-lifecycle.ts
3067
3931
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3068
3932
  var claudePrompt = {
@@ -3141,7 +4005,7 @@ var copilotPrompt = {
3141
4005
  ${context}`.trim()
3142
4006
  })
3143
4007
  };
3144
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
4008
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3145
4009
  var devinPrompt = {
3146
4010
  harness: "devin-cli",
3147
4011
  requireCwd: true,
@@ -3168,6 +4032,36 @@ var standardSessionStart = (harness) => ({
3168
4032
  }
3169
4033
  })
3170
4034
  });
4035
+ var genieSessionStart = (harness) => {
4036
+ const base = standardSessionStart(harness);
4037
+ return {
4038
+ ...base,
4039
+ parse: (ev) => ({
4040
+ cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
4041
+ sessionId: ev.session_id
4042
+ }),
4043
+ emit: (out) => ({ ...base.emit(out), suppressOutput: true })
4044
+ };
4045
+ };
4046
+ var geniePrompt = (harness) => ({
4047
+ ...claudePrompt,
4048
+ harness,
4049
+ emit: (context, notice, ev) => ({
4050
+ ...claudePrompt.emit(context, notice, ev),
4051
+ suppressOutput: true
4052
+ })
4053
+ });
4054
+ var genieRetain = (harness, readTranscript) => ({
4055
+ hostTimeoutSec: 60,
4056
+ harness,
4057
+ parse: (ev) => ({
4058
+ sessionId: ev.session_id,
4059
+ transcriptPath: ev.transcript_path,
4060
+ cwd: ev.cwd
4061
+ }),
4062
+ readTranscript
4063
+ });
4064
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3171
4065
  var HOOK_HARNESSES = {
3172
4066
  "claude-code": {
3173
4067
  configStyle: "nested",
@@ -3176,11 +4070,12 @@ var HOOK_HARNESSES = {
3176
4070
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3177
4071
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3178
4072
  },
3179
- sessionStart: standardSessionStart("claude-code"),
3180
- prompt: claudePrompt,
4073
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
4074
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3181
4075
  retain: {
3182
4076
  hostTimeoutSec: 60,
3183
4077
  harness: "claude-code",
4078
+ accept: notGrokHosted,
3184
4079
  parse: (ev) => ({
3185
4080
  sessionId: ev.session_id,
3186
4081
  transcriptPath: ev.transcript_path,
@@ -3363,17 +4258,29 @@ var HOOK_HARNESSES = {
3363
4258
  prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3364
4259
  stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3365
4260
  },
4261
+ // Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
4262
+ // and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
4263
+ // prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
4264
+ additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
3366
4265
  sessionStart: {
3367
4266
  ...standardSessionStart("grok-build"),
3368
4267
  // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3369
4268
  parse: (ev) => ({
3370
4269
  cwd: ev.cwd,
3371
4270
  sessionId: ev.sessionId
3372
- })
4271
+ }),
4272
+ deferContextToToolHook: true
3373
4273
  },
3374
4274
  prompt: {
3375
4275
  ...claudePrompt,
3376
4276
  harness: "grok-build",
4277
+ toolHook: {
4278
+ // Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
4279
+ accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
4280
+ emit: (context) => ({
4281
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
4282
+ })
4283
+ },
3377
4284
  parse: (ev) => ({
3378
4285
  prompt: ev.prompt,
3379
4286
  cwd: ev.cwd,
@@ -3496,6 +4403,159 @@ var HOOK_HARNESSES = {
3496
4403
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3497
4404
  }
3498
4405
  }
4406
+ },
4407
+ /**
4408
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4409
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4410
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4411
+ * map IS the file) and a `version` field the host writes and expects.
4412
+ *
4413
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4414
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4415
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4416
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4417
+ * plays: `journal.assistantText` closes the turn with it.
4418
+ */
4419
+ traecode: {
4420
+ configStyle: "nested",
4421
+ install: {
4422
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4423
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4424
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4425
+ },
4426
+ sessionStart: {
4427
+ ...standardSessionStart("traecode"),
4428
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4429
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4430
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4431
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4432
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4433
+ // rides the session banner.
4434
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4435
+ },
4436
+ prompt: {
4437
+ ...claudePrompt,
4438
+ harness: "traecode",
4439
+ journalPrompt: true,
4440
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4441
+ parse: (ev) => ({
4442
+ prompt: ev.prompt,
4443
+ cwd: ev.cwd,
4444
+ sessionId: ev.session_id
4445
+ })
4446
+ },
4447
+ retain: {
4448
+ hostTimeoutSec: 60,
4449
+ harness: "traecode",
4450
+ // No transcriptPath: the journal supplies it (see `journal` below).
4451
+ parse: (ev) => ({
4452
+ sessionId: ev.session_id,
4453
+ cwd: ev.cwd
4454
+ }),
4455
+ journal: {
4456
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4457
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4458
+ }
4459
+ }
4460
+ },
4461
+ "kimi-code": {
4462
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4463
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4464
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4465
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4466
+ configStyle: "toml-array",
4467
+ install: {
4468
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4469
+ // supported host, and the opposite of qwen-code's identically named field.
4470
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4471
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4472
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4473
+ },
4474
+ sessionStart: {
4475
+ harness: "kimi-code",
4476
+ parse: (ev) => ({
4477
+ cwd: ev.cwd,
4478
+ sessionId: ev.session_id
4479
+ }),
4480
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4481
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4482
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4483
+ emit: () => ({})
4484
+ },
4485
+ prompt: {
4486
+ harness: "kimi-code",
4487
+ parse: (ev) => ({
4488
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4489
+ prompt: kimiPromptText(ev.prompt),
4490
+ cwd: ev.cwd,
4491
+ sessionId: ev.session_id
4492
+ }),
4493
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4494
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4495
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4496
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4497
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4498
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4499
+ emit: (context, notice) => ({ message: context || notice })
4500
+ },
4501
+ retain: {
4502
+ hostTimeoutSec: 60,
4503
+ harness: "kimi-code",
4504
+ parse: (ev) => {
4505
+ const sessionId = ev.session_id;
4506
+ return {
4507
+ sessionId,
4508
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4509
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4510
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4511
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4512
+ cwd: ev.cwd
4513
+ };
4514
+ },
4515
+ readTranscript: readKimiTranscript
4516
+ }
4517
+ },
4518
+ /**
4519
+ * WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
4520
+ * ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
4521
+ * `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
4522
+ * from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
4523
+ * transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
4524
+ * core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
4525
+ * engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
4526
+ * file-backed host rather than the journal ZCode needs.
4527
+ * CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
4528
+ */
4529
+ workbuddy: {
4530
+ configStyle: "nested",
4531
+ install: {
4532
+ sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
4533
+ prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
4534
+ stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
4535
+ },
4536
+ sessionStart: genieSessionStart("workbuddy"),
4537
+ prompt: geniePrompt("workbuddy"),
4538
+ retain: genieRetain("workbuddy", readWorkbuddyTranscript)
4539
+ },
4540
+ /**
4541
+ * CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
4542
+ * config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
4543
+ * are identical, so this spec differs from `workbuddy` in the files the installer writes, the
4544
+ * harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
4545
+ * transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
4546
+ * IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
4547
+ * a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
4548
+ */
4549
+ codebuddy: {
4550
+ configStyle: "nested",
4551
+ install: {
4552
+ sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
4553
+ prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
4554
+ stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
4555
+ },
4556
+ sessionStart: genieSessionStart("codebuddy"),
4557
+ prompt: geniePrompt("codebuddy"),
4558
+ retain: genieRetain("codebuddy", readCodebuddyTranscript)
3499
4559
  }
3500
4560
  };
3501
4561
  var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);