@vectorize-io/hindsight-coding-agents 0.5.2 → 0.5.4

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 (51) hide show
  1. package/README.md +42 -8
  2. package/dist/antigravity-hook.js +335 -91
  3. package/dist/antigravity-statusline.js +17 -10
  4. package/dist/antigravity-stop-hook.js +340 -92
  5. package/dist/claude-hook.js +335 -91
  6. package/dist/claude-sessionstart-hook.js +459 -132
  7. package/dist/claude-stop-hook.js +340 -92
  8. package/dist/cline.js +283 -64
  9. package/dist/codex-hook.js +335 -91
  10. package/dist/codex-sessionstart-hook.js +459 -132
  11. package/dist/codex-stop-hook.js +340 -92
  12. package/dist/copilot-hook.js +335 -91
  13. package/dist/copilot-sessionstart-hook.js +459 -132
  14. package/dist/copilot-stop-hook.js +340 -92
  15. package/dist/cursor-hook.js +335 -91
  16. package/dist/cursor-sessionstart-hook.js +459 -132
  17. package/dist/cursor-stop-hook.js +340 -92
  18. package/dist/daemon-start.js +17 -10
  19. package/dist/dcode-hook.js +335 -91
  20. package/dist/dcode-sessionstart-hook.js +459 -132
  21. package/dist/dcode-stop-hook.js +340 -92
  22. package/dist/deepen.js +113 -32
  23. package/dist/devin-hook.js +335 -91
  24. package/dist/devin-sessionstart-hook.js +459 -132
  25. package/dist/devin-stop-hook.js +340 -92
  26. package/dist/droid-hook.js +335 -91
  27. package/dist/droid-sessionstart-hook.js +459 -132
  28. package/dist/droid-stop-hook.js +340 -92
  29. package/dist/dsh.js +322 -101
  30. package/dist/grok-hook.js +335 -91
  31. package/dist/grok-sessionstart-hook.js +459 -132
  32. package/dist/grok-stop-hook.js +340 -92
  33. package/dist/hindsight-seed.js +17 -10
  34. package/dist/index.js +322 -101
  35. package/dist/installer.js +1252 -325
  36. package/dist/kilo.js +322 -101
  37. package/dist/mcp-server.js +100 -23
  38. package/dist/opencode2.js +322 -101
  39. package/dist/pi.js +321 -100
  40. package/dist/prime-agent.js +321 -100
  41. package/dist/qwen-hook.js +335 -91
  42. package/dist/qwen-sessionstart-hook.js +459 -132
  43. package/dist/qwen-stop-hook.js +340 -92
  44. package/dist/status.js +98 -21
  45. package/dist/survey-supervisor.js +81 -0
  46. package/dist/zcode-hook.js +2954 -0
  47. package/dist/zcode-sessionstart-hook.js +3655 -0
  48. package/dist/zcode-stop-hook.js +3218 -0
  49. package/package.json +7 -3
  50. package/plugin.json +1 -1
  51. package/skill/SKILL.md +17 -7
@@ -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 readFileSync4 } from "fs";
4
+ import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
7
  import { existsSync } from "fs";
@@ -460,6 +460,7 @@ function pagesFor(project) {
460
460
  var PAGE_MAX_TOKENS = 4096;
461
461
  var PAGE_TAGS_MATCH = "all";
462
462
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
463
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
463
464
  var CRON_FIELD_RANGES = [
464
465
  [0, 59],
465
466
  // minute
@@ -513,14 +514,23 @@ function pageTriggerFor(trigger, bank, page) {
513
514
  function buildPageTrigger(cfg = {}) {
514
515
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
515
516
  switch (cfg.pageTriggerType) {
516
- case "cron":
517
- return { ...base, refresh_cron: cfg.pageTriggerCron };
517
+ case "auto-refresh":
518
+ return { ...base, refresh_after_consolidation: true };
518
519
  case "manual":
519
520
  return { ...base, refresh_after_consolidation: false };
521
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
522
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
520
523
  default:
521
- return { ...base, refresh_after_consolidation: true };
524
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
522
525
  }
523
526
  }
527
+ function pageTriggerDrifted(current2, desired) {
528
+ return current2.tags_match !== desired.tags_match || (current2.refresh_cron ?? null) !== (desired.refresh_cron ?? null) || Boolean(current2.refresh_after_consolidation) !== Boolean(desired.refresh_after_consolidation);
529
+ }
530
+ function pageTriggerPatch(desired) {
531
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
532
+ return desired;
533
+ }
524
534
  var CODING_BANK_TEMPLATE = {
525
535
  version: "1",
526
536
  bank: {
@@ -944,9 +954,16 @@ var HindsightClient = class {
944
954
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
945
955
  signal: ctrl.signal
946
956
  });
947
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
957
+ if (!resp.ok)
958
+ throw new Error(
959
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
960
+ );
948
961
  const data = await resp.json();
949
962
  return (data.text || "").trim();
963
+ } catch (e) {
964
+ if (ctrl.signal.aborted)
965
+ throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
966
+ throw e;
950
967
  } finally {
951
968
  clearTimeout(timer);
952
969
  }
@@ -1079,14 +1096,14 @@ var HindsightClient = class {
1079
1096
  if (r.status !== 409) created++;
1080
1097
  } else {
1081
1098
  const sourceDrift = hit.description !== page.source_query;
1082
- const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1099
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1083
1100
  if (!sourceDrift && !triggerDrift) continue;
1084
1101
  const patch = {};
1085
1102
  if (sourceDrift) {
1086
1103
  patch.source_query = page.source_query;
1087
1104
  patch.tags = page.tags;
1088
1105
  }
1089
- if (triggerDrift) patch.trigger = pageTrigger;
1106
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1090
1107
  const r = await this.req(
1091
1108
  "PATCH",
1092
1109
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
@@ -1102,10 +1119,42 @@ var HindsightClient = class {
1102
1119
  updated++;
1103
1120
  }
1104
1121
  }
1122
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1105
1123
  this.log(
1106
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1124
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged` + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1107
1125
  );
1108
1126
  }
1127
+ /**
1128
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1129
+ *
1130
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1131
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1132
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1133
+ * consolidation under the auto-refresh that used to be the default (#3506).
1134
+ *
1135
+ * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1136
+ * initiative's own title, and re-stating either would rebuild a page whose question never
1137
+ * changed. The tree read above is reused rather than re-fetched.
1138
+ */
1139
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1140
+ const folder = roots.find(
1141
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1142
+ );
1143
+ let updated = 0;
1144
+ for (const page of folder?.children ?? []) {
1145
+ if (page.kind !== "page" || page.trigger == null) continue;
1146
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1147
+ if (!pageTriggerDrifted(page.trigger, desired)) continue;
1148
+ const r = await this.req(
1149
+ "PATCH",
1150
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1151
+ { trigger: pageTriggerPatch(desired) }
1152
+ );
1153
+ if ([404, 405, 501].includes(r.status)) break;
1154
+ updated++;
1155
+ }
1156
+ return updated;
1157
+ }
1109
1158
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1110
1159
  slugify(s) {
1111
1160
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
@@ -1127,11 +1176,13 @@ var HindsightClient = class {
1127
1176
  let pageId = args.relatesToPageId;
1128
1177
  if (!pageId) {
1129
1178
  const folderId = await this.ensureFolder("Initiatives");
1179
+ const subject = this.project ?? this.bank;
1130
1180
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1131
1181
  name: args.title,
1132
- 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.`,
1182
+ 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),
1133
1183
  parent_id: folderId,
1134
1184
  tags: ["knowledge:feature-work"],
1185
+ max_tokens: PAGE_MAX_TOKENS,
1135
1186
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1136
1187
  });
1137
1188
  try {
@@ -1174,17 +1225,22 @@ var HindsightClient = class {
1174
1225
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1175
1226
  var DEFAULT_DAEMON_PORT = 9077;
1176
1227
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1177
- function resolvePageTriggerType(raw) {
1178
- if (raw.pageTriggerType === "manual") return "manual";
1179
- if (raw.pageTriggerType === "cron") {
1180
- const cron = raw.pageTriggerCron?.trim();
1181
- if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1228
+ function resolvePageTrigger(raw) {
1229
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1230
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1231
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1182
1232
  log.warn(
1183
1233
  "config",
1184
- cron ? `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
1234
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1185
1235
  );
1186
- }
1187
- return "auto-refresh";
1236
+ const cron = raw.pageTriggerCron?.trim();
1237
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1238
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1239
+ log.warn(
1240
+ "config",
1241
+ `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to ${JSON.stringify(DEFAULT_PAGE_TRIGGER_CRON)}`
1242
+ );
1243
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1188
1244
  }
1189
1245
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1190
1246
  var REFLECT_BUDGETS = ["low", "mid", "high"];
@@ -1216,6 +1272,7 @@ function resolveObservationScopes(raw) {
1216
1272
  function resolveConfig(raw = {}) {
1217
1273
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1218
1274
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1275
+ const pageTrigger = resolvePageTrigger(raw);
1219
1276
  return {
1220
1277
  serverMode,
1221
1278
  // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
@@ -1250,8 +1307,8 @@ function resolveConfig(raw = {}) {
1250
1307
  reflectBudget: resolveReflectBudget(raw),
1251
1308
  autoReflect: raw.autoReflect ?? true,
1252
1309
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1253
- pageTriggerType: resolvePageTriggerType(raw),
1254
- pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1310
+ pageTriggerType: pageTrigger.type,
1311
+ pageTriggerCron: pageTrigger.cron,
1255
1312
  autoSeed: raw.autoSeed ?? true,
1256
1313
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1257
1314
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1516,8 +1573,51 @@ function sessionRootDir(harness, sessionId, cwd) {
1516
1573
  return cwd;
1517
1574
  }
1518
1575
 
1576
+ // src/core/turn-journal.ts
1577
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync } from "fs";
1578
+ import { tmpdir as tmpdir3 } from "os";
1579
+ import { dirname as dirname6, join as join8 } from "path";
1580
+
1581
+ // src/core/transcript-util.ts
1582
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1583
+ function stripInjectedMemory(s) {
1584
+ return s.replace(MEMORY_TAG_RE, "");
1585
+ }
1586
+ var TARGET_KEYS = [
1587
+ "file_path",
1588
+ "path",
1589
+ "notebook_path",
1590
+ "command",
1591
+ "pattern",
1592
+ "query",
1593
+ "url",
1594
+ "name",
1595
+ "id"
1596
+ ];
1597
+ var ACTION_TARGET_CAP = 100;
1598
+ function actionLine(tool, input) {
1599
+ let target = "";
1600
+ if (input && typeof input === "object") {
1601
+ const rec = input;
1602
+ for (const k of TARGET_KEYS) {
1603
+ const v = rec[k];
1604
+ if (typeof v === "string" && v.trim()) {
1605
+ target = v.trim().split("\n")[0];
1606
+ break;
1607
+ }
1608
+ }
1609
+ } else if (typeof input === "string") {
1610
+ target = input.trim().split("\n")[0];
1611
+ }
1612
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1613
+ return target ? `${tool} ${target}` : tool;
1614
+ }
1615
+
1616
+ // src/core/turn-journal.ts
1617
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1618
+
1519
1619
  // src/core/retain-hook.ts
1520
- import { readFileSync as readFileSync5 } from "fs";
1620
+ import { readFileSync as readFileSync6 } from "fs";
1521
1621
 
1522
1622
  // src/core/retain-cursor.ts
1523
1623
  import { createHash as createHash2 } from "crypto";
@@ -1529,7 +1629,7 @@ import { createHash as createHash3 } from "crypto";
1529
1629
 
1530
1630
  // src/core/daemon.ts
1531
1631
  import { execFileSync, spawn as realSpawn2 } from "child_process";
1532
- import { dirname as dirname6, join as join8 } from "path";
1632
+ import { dirname as dirname7, join as join9 } from "path";
1533
1633
  import { fileURLToPath as fileURLToPath2 } from "url";
1534
1634
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1535
1635
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1603,7 +1703,7 @@ function onPath(bin) {
1603
1703
  }
1604
1704
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1605
1705
  try {
1606
- const starter = join8(dirname6(fileURLToPath2(import.meta.url)), "daemon-start.js");
1706
+ const starter = join9(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
1607
1707
  const child = spawnFn("node", [starter, "--harness", harness], {
1608
1708
  detached: true,
1609
1709
  stdio: "ignore",
@@ -1704,7 +1804,7 @@ function buildRetainStamp(cfg, ctx) {
1704
1804
  }
1705
1805
 
1706
1806
  // src/core/jsonl.ts
1707
- import { closeSync, openSync, readSync, statSync } from "fs";
1807
+ import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
1708
1808
  import { StringDecoder } from "string_decoder";
1709
1809
  var CHUNK_BYTES = 64 * 1024;
1710
1810
  var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
@@ -1712,7 +1812,7 @@ function readJsonlTail(path, opts) {
1712
1812
  const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1713
1813
  let size;
1714
1814
  try {
1715
- size = statSync(path).size;
1815
+ size = statSync2(path).size;
1716
1816
  } catch {
1717
1817
  return { lines: emptyLines(), skippedBytes: 0 };
1718
1818
  }
@@ -1764,43 +1864,8 @@ function* streamLines(path, start) {
1764
1864
  }
1765
1865
  }
1766
1866
 
1767
- // src/core/transcript-util.ts
1768
- var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1769
- function stripInjectedMemory(s) {
1770
- return s.replace(MEMORY_TAG_RE, "");
1771
- }
1772
- var TARGET_KEYS = [
1773
- "file_path",
1774
- "path",
1775
- "notebook_path",
1776
- "command",
1777
- "pattern",
1778
- "query",
1779
- "url",
1780
- "name",
1781
- "id"
1782
- ];
1783
- var ACTION_TARGET_CAP = 100;
1784
- function actionLine(tool, input) {
1785
- let target = "";
1786
- if (input && typeof input === "object") {
1787
- const rec = input;
1788
- for (const k of TARGET_KEYS) {
1789
- const v = rec[k];
1790
- if (typeof v === "string" && v.trim()) {
1791
- target = v.trim().split("\n")[0];
1792
- break;
1793
- }
1794
- }
1795
- } else if (typeof input === "string") {
1796
- target = input.trim().split("\n")[0];
1797
- }
1798
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1799
- return target ? `${tool} ${target}` : tool;
1800
- }
1801
-
1802
1867
  // src/core/session-start.ts
1803
- import { readFileSync as readFileSync8 } from "fs";
1868
+ import { readFileSync as readFileSync10 } from "fs";
1804
1869
 
1805
1870
  // src/core/git.ts
1806
1871
  import { execFileSync as execFileSync2 } from "child_process";
@@ -1842,11 +1907,95 @@ function hasGitHistory(dir) {
1842
1907
  import { execFileSync as execFileSync3 } from "child_process";
1843
1908
 
1844
1909
  // src/core/survey.ts
1845
- import { spawn as realSpawn3 } from "child_process";
1910
+ import { spawn as realSpawn4 } from "child_process";
1911
+ import { createHash as createHash4 } from "crypto";
1846
1912
  import { existsSync as existsSync3 } from "fs";
1847
- import { homedir as homedir3 } from "os";
1848
- import { dirname as dirname7, join as join9 } from "path";
1913
+ import { homedir as homedir3, tmpdir as tmpdir4 } from "os";
1914
+ import { dirname as dirname8, join as join11 } from "path";
1849
1915
  import { fileURLToPath as fileURLToPath3 } from "url";
1916
+
1917
+ // src/core/host-client.ts
1918
+ function resolveHostConfig(harness, directory) {
1919
+ const cfg0 = loadConfig({ harness });
1920
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1921
+ const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
1922
+ if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
1923
+ return applyBankConfig(cfg0, bankId, directory);
1924
+ }
1925
+
1926
+ // src/core/survey-lease.ts
1927
+ import { spawn as realSpawn3 } from "child_process";
1928
+ import { randomUUID } from "crypto";
1929
+ import {
1930
+ mkdirSync as mkdirSync4,
1931
+ mkdtempSync,
1932
+ readdirSync,
1933
+ renameSync as renameSync2,
1934
+ rmdirSync,
1935
+ rmSync as rmSync2,
1936
+ statSync as statSync3,
1937
+ unlinkSync,
1938
+ utimesSync,
1939
+ writeFileSync as writeFileSync2
1940
+ } from "fs";
1941
+ import { join as join10 } from "path";
1942
+ var LEASE_STALE_MS = 3e4;
1943
+ var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
1944
+ function tryRename(from, to) {
1945
+ try {
1946
+ renameSync2(from, to);
1947
+ return true;
1948
+ } catch {
1949
+ return false;
1950
+ }
1951
+ }
1952
+ function releaseLease(lease) {
1953
+ try {
1954
+ unlinkSync(join10(lease.directory, lease.owner));
1955
+ } catch {
1956
+ return;
1957
+ }
1958
+ try {
1959
+ rmdirSync(lease.directory);
1960
+ } catch {
1961
+ }
1962
+ }
1963
+ function reclaimIfStale(directory, staleMs) {
1964
+ const owners = readdirSync(directory);
1965
+ if (owners.length === 0) {
1966
+ try {
1967
+ rmdirSync(directory);
1968
+ } catch {
1969
+ }
1970
+ return true;
1971
+ }
1972
+ if (owners.length !== 1) return false;
1973
+ const age = Date.now() - statSync3(join10(directory, owners[0])).mtimeMs;
1974
+ if (Math.abs(age) <= staleMs) return false;
1975
+ releaseLease({ directory, owner: owners[0] });
1976
+ return true;
1977
+ }
1978
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
1979
+ let staging;
1980
+ try {
1981
+ mkdirSync4(root, { recursive: true, mode: 448 });
1982
+ staging = mkdtempSync(join10(root, "claim-"));
1983
+ const owner = randomUUID();
1984
+ writeFileSync2(join10(staging, owner), "", { flag: "wx", mode: 384 });
1985
+ const directory = join10(root, `survey-${key}.lock`);
1986
+ if (!tryRename(staging, directory)) {
1987
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
1988
+ if (!tryRename(staging, directory)) return void 0;
1989
+ }
1990
+ return { directory, owner };
1991
+ } catch {
1992
+ return void 0;
1993
+ } finally {
1994
+ if (staging) rmSync2(staging, { recursive: true, force: true });
1995
+ }
1996
+ }
1997
+
1998
+ // src/core/survey.ts
1850
1999
  var SURVEY_DOC_IDS = [
1851
2000
  "repository-component-map",
1852
2001
  "repository-core-concepts",
@@ -1856,7 +2005,7 @@ var SURVEY_DOC_IDS = [
1856
2005
  function resolveClaudeBin(explicit) {
1857
2006
  if (explicit) return explicit;
1858
2007
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
1859
- const nativeInstallPath = join9(homedir3(), ".claude", "local", "claude");
2008
+ const nativeInstallPath = join11(homedir3(), ".claude", "local", "claude");
1860
2009
  try {
1861
2010
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
1862
2011
  } catch {
@@ -1970,11 +2119,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1970
2119
  }
1971
2120
  }
1972
2121
  }
1973
- function startCodebaseSurvey(repoDir, opts = {}) {
2122
+ async function startCodebaseSurvey(repoDir, opts = {}) {
1974
2123
  try {
1975
- const spawnFn = opts.spawn ?? realSpawn3;
2124
+ const spawnFn = opts.spawn ?? realSpawn4;
1976
2125
  const exists = opts.exists ?? binOnPath;
1977
- const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath3(import.meta.url)), "mcp-server.js");
2126
+ const mcpServerPath = opts.mcpServerPath ?? join11(dirname8(fileURLToPath3(import.meta.url)), "mcp-server.js");
1978
2127
  const preferred = opts.harness ?? "claude-code";
1979
2128
  const order = [
1980
2129
  preferred,
@@ -1994,49 +2143,80 @@ function startCodebaseSurvey(repoDir, opts = {}) {
1994
2143
  budgetUsd: opts.budgetUsd,
1995
2144
  mcpServerPath
1996
2145
  });
1997
- const child = spawnFn(plan.bin, plan.args, {
1998
- cwd: repoDir,
1999
- detached: true,
2000
- stdio: "ignore",
2001
- windowsHide: true,
2002
- env: plan.env
2003
- });
2004
- child.on("error", () => {
2146
+ const { cfg, bankId } = resolveHostConfig(harness, repoDir);
2147
+ if (cfg.disabled) return false;
2148
+ const key = createHash4("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
2149
+ const lease = acquireLease(
2150
+ opts.lease?.dir ?? join11(tmpdir4(), "hindsight-coding-agent", "surveys"),
2151
+ key,
2152
+ opts.lease?.staleMs ?? LEASE_STALE_MS
2153
+ );
2154
+ if (!lease) return false;
2155
+ const spec = {
2156
+ lease,
2157
+ bin: plan.bin,
2158
+ args: plan.args,
2159
+ ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
2160
+ };
2161
+ const supervisorPath = opts.supervisorPath ?? join11(dirname8(fileURLToPath3(import.meta.url)), "survey-supervisor.js");
2162
+ return await new Promise((resolve3) => {
2163
+ try {
2164
+ const child = spawnFn("node", [supervisorPath], {
2165
+ cwd: repoDir,
2166
+ detached: true,
2167
+ stdio: "ignore",
2168
+ windowsHide: true,
2169
+ env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
2170
+ });
2171
+ let spawned = false;
2172
+ child.on("error", () => {
2173
+ if (spawned) return;
2174
+ releaseLease(lease);
2175
+ resolve3(false);
2176
+ });
2177
+ child.once("spawn", () => {
2178
+ spawned = true;
2179
+ child.unref();
2180
+ resolve3(true);
2181
+ });
2182
+ } catch {
2183
+ releaseLease(lease);
2184
+ resolve3(false);
2185
+ }
2005
2186
  });
2006
- child.unref();
2007
- return;
2008
2187
  }
2009
2188
  } catch {
2010
2189
  }
2190
+ return false;
2011
2191
  }
2012
2192
 
2013
2193
  // src/core/status.ts
2014
2194
  var DEEPEN_DIFF_TARGET = 300;
2015
2195
 
2016
2196
  // src/core/auto-update.ts
2017
- import { spawn as realSpawn4 } from "child_process";
2197
+ import { spawn as realSpawn5 } from "child_process";
2018
2198
  import {
2019
2199
  existsSync as existsSync4,
2020
- mkdirSync as mkdirSync3,
2021
- readFileSync as readFileSync6,
2200
+ mkdirSync as mkdirSync5,
2201
+ readFileSync as readFileSync7,
2022
2202
  realpathSync as realpathSync2,
2023
- unlinkSync,
2024
- writeFileSync as writeFileSync2
2203
+ unlinkSync as unlinkSync2,
2204
+ writeFileSync as writeFileSync3
2025
2205
  } from "fs";
2026
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2027
- import { dirname as dirname8, join as join10 } from "path";
2206
+ import { homedir as homedir4, tmpdir as tmpdir5 } from "os";
2207
+ import { dirname as dirname9, join as join12 } from "path";
2028
2208
  import { fileURLToPath as fileURLToPath4 } from "url";
2029
2209
  var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
2030
2210
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2031
2211
  var FETCH_TIMEOUT_MS = 5e3;
2032
2212
  function stateFile(runtimeDir) {
2033
- return join10(runtimeDir, ".update-check.json");
2213
+ return join12(runtimeDir, ".update-check.json");
2034
2214
  }
2035
2215
  function packageRoot() {
2036
- return join10(dirname8(fileURLToPath4(import.meta.url)), "..");
2216
+ return join12(dirname9(fileURLToPath4(import.meta.url)), "..");
2037
2217
  }
2038
2218
  function stagedRuntimeDir() {
2039
- return join10(homedir4(), ".hindsight", "coding-agents");
2219
+ return join12(homedir4(), ".hindsight", "coding-agents");
2040
2220
  }
2041
2221
  function sameDir(a, b) {
2042
2222
  try {
@@ -2047,7 +2227,7 @@ function sameDir(a, b) {
2047
2227
  }
2048
2228
  function stagedVersion(pkgRoot) {
2049
2229
  try {
2050
- const pkg = JSON.parse(readFileSync6(join10(pkgRoot, "package.json"), "utf8"));
2230
+ const pkg = JSON.parse(readFileSync7(join12(pkgRoot, "package.json"), "utf8"));
2051
2231
  return typeof pkg.version === "string" ? pkg.version : "";
2052
2232
  } catch {
2053
2233
  return "";
@@ -2072,7 +2252,7 @@ function isNewer(candidate, current2) {
2072
2252
  }
2073
2253
  function dueForCheck(file, now) {
2074
2254
  try {
2075
- const state = JSON.parse(readFileSync6(file, "utf8"));
2255
+ const state = JSON.parse(readFileSync7(file, "utf8"));
2076
2256
  return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
2077
2257
  } catch {
2078
2258
  return true;
@@ -2081,7 +2261,7 @@ function dueForCheck(file, now) {
2081
2261
  var ORIGIN_FILE = ".install-origin.json";
2082
2262
  function selfUpdatable(runtimeDir) {
2083
2263
  try {
2084
- const origin = JSON.parse(readFileSync6(join10(runtimeDir, ORIGIN_FILE), "utf8"));
2264
+ const origin = JSON.parse(readFileSync7(join12(runtimeDir, ORIGIN_FILE), "utf8"));
2085
2265
  if (typeof origin.source !== "string" || !origin.source) return false;
2086
2266
  return origin.source.split(/[\\/]/).includes("_npx");
2087
2267
  } catch {
@@ -2090,11 +2270,11 @@ function selfUpdatable(runtimeDir) {
2090
2270
  }
2091
2271
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2092
2272
  function lockFile() {
2093
- return join10(tmpdir3(), "hindsight-coding-agent", "auto-update.lock");
2273
+ return join12(tmpdir5(), "hindsight-coding-agent", "auto-update.lock");
2094
2274
  }
2095
2275
  function acquireUpdateLock(file, now) {
2096
2276
  try {
2097
- const held = JSON.parse(readFileSync6(file, "utf8"));
2277
+ const held = JSON.parse(readFileSync7(file, "utf8"));
2098
2278
  if (held.ts && now - held.ts < LOCK_STALE_MS) {
2099
2279
  let holderAlive = false;
2100
2280
  if (held.pid) {
@@ -2109,8 +2289,8 @@ function acquireUpdateLock(file, now) {
2109
2289
  } catch {
2110
2290
  }
2111
2291
  try {
2112
- mkdirSync3(dirname8(file), { recursive: true });
2113
- writeFileSync2(file, JSON.stringify({ pid: process.pid, ts: now }));
2292
+ mkdirSync5(dirname9(file), { recursive: true });
2293
+ writeFileSync3(file, JSON.stringify({ pid: process.pid, ts: now }));
2114
2294
  return true;
2115
2295
  } catch {
2116
2296
  return false;
@@ -2119,19 +2299,19 @@ function acquireUpdateLock(file, now) {
2119
2299
  function holdLockFor(file, pid, now) {
2120
2300
  try {
2121
2301
  if (pid === void 0) return releaseUpdateLock(file);
2122
- writeFileSync2(file, JSON.stringify({ pid, ts: now }));
2302
+ writeFileSync3(file, JSON.stringify({ pid, ts: now }));
2123
2303
  } catch {
2124
2304
  }
2125
2305
  }
2126
2306
  function releaseUpdateLock(file) {
2127
2307
  try {
2128
- unlinkSync(file);
2308
+ unlinkSync2(file);
2129
2309
  } catch {
2130
2310
  }
2131
2311
  }
2132
2312
  function stampCheck(file, now, latest) {
2133
2313
  try {
2134
- writeFileSync2(file, JSON.stringify({ lastCheck: now, latest }));
2314
+ writeFileSync3(file, JSON.stringify({ lastCheck: now, latest }));
2135
2315
  } catch {
2136
2316
  }
2137
2317
  }
@@ -2180,7 +2360,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2180
2360
  return "";
2181
2361
  }
2182
2362
  log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
2183
- const child = (opts.spawn ?? realSpawn4)(
2363
+ const child = (opts.spawn ?? realSpawn5)(
2184
2364
  "npx",
2185
2365
  ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
2186
2366
  {
@@ -2206,9 +2386,9 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2206
2386
  }
2207
2387
 
2208
2388
  // src/core/skill-sync.ts
2209
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
2389
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
2210
2390
  import { homedir as homedir5 } from "os";
2211
- import { dirname as dirname9, join as join11 } from "path";
2391
+ import { dirname as dirname10, join as join13 } from "path";
2212
2392
  import { fileURLToPath as fileURLToPath5 } from "url";
2213
2393
 
2214
2394
  // src/core/skill-dirs.ts
@@ -2226,6 +2406,11 @@ var SKILL_DIRS = {
2226
2406
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2227
2407
  "factory-droid": [".factory", "skills"],
2228
2408
  // Droid's user-level skills root
2409
+ // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
2410
+ // shared agentskills `~/.agents/skills`. Write its OWN, for the same reason the pi family does —
2411
+ // skill removal is by fixed directory name, so installing into the shared root would make
2412
+ // `uninstall zcode` take Codex's and dsh's copy with it.
2413
+ zcode: [".zcode", "skills"],
2229
2414
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2230
2415
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2231
2416
  // and dsh's copy with it.
@@ -2235,25 +2420,62 @@ var SKILL_DIRS = {
2235
2420
 
2236
2421
  // src/core/skill-sync.ts
2237
2422
  function packagedSkillDir() {
2238
- return join11(dirname9(fileURLToPath5(import.meta.url)), "..", "skill");
2423
+ return join13(dirname10(fileURLToPath5(import.meta.url)), "..", "skill");
2239
2424
  }
2240
2425
  function syncCompanionSkill(harness, opts = {}) {
2241
2426
  try {
2242
2427
  const parts = SKILL_DIRS[harness];
2243
2428
  if (!parts) return;
2244
2429
  const src = opts.srcDir ?? packagedSkillDir();
2245
- const srcMd = join11(src, "SKILL.md");
2430
+ const srcMd = join13(src, "SKILL.md");
2246
2431
  if (!existsSync5(srcMd)) return;
2247
- const dst = join11(opts.home ?? homedir5(), ...parts, "hindsight-coding-agent");
2248
- const dstMd = join11(dst, "SKILL.md");
2432
+ const dst = join13(opts.home ?? homedir5(), ...parts, "hindsight-coding-agent");
2433
+ const dstMd = join13(dst, "SKILL.md");
2249
2434
  if (!existsSync5(dstMd)) return;
2250
- if (readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
2435
+ if (readFileSync8(srcMd, "utf8") !== readFileSync8(dstMd, "utf8")) {
2251
2436
  cpSync(src, dst, { recursive: true });
2252
2437
  }
2253
2438
  } catch {
2254
2439
  }
2255
2440
  }
2256
2441
 
2442
+ // src/core/legacy.ts
2443
+ import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2444
+ import { homedir as homedir6 } from "os";
2445
+ import { join as join14, relative, isAbsolute as isAbsolute2 } from "path";
2446
+ var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
2447
+ function detectLegacyClaudePlugin(cwd, claudeDir = join14(homedir6(), ".claude")) {
2448
+ const registry = readJson(join14(claudeDir, "plugins", "installed_plugins.json"));
2449
+ const plugins = registry?.plugins;
2450
+ if (!plugins || typeof plugins !== "object") return void 0;
2451
+ const enabled = readJson(join14(claudeDir, "settings.json"))?.enabledPlugins;
2452
+ for (const [key, raw] of Object.entries(plugins)) {
2453
+ if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
2454
+ if (enabled && enabled[key] === false) continue;
2455
+ const installs = Array.isArray(raw) ? raw : [raw];
2456
+ const active = installs.some((i) => {
2457
+ if (!i || typeof i !== "object") return false;
2458
+ if (typeof i.projectPath !== "string") return true;
2459
+ const rel = relative(i.projectPath, cwd);
2460
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
2461
+ });
2462
+ if (active) return key;
2463
+ }
2464
+ return void 0;
2465
+ }
2466
+ function readJson(path) {
2467
+ try {
2468
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
2469
+ return parsed && typeof parsed === "object" ? parsed : void 0;
2470
+ } catch {
2471
+ return void 0;
2472
+ }
2473
+ }
2474
+ function legacyClaudePluginWarning(key) {
2475
+ return `\u26A0\uFE0F The old Hindsight Claude Code plugin (${key}) is still installed \u2014 it runs alongside this one, so memory is recalled and retained twice.
2476
+ \u21B3 remove it: claude plugin uninstall ${key}`;
2477
+ }
2478
+
2257
2479
  // src/core/session-start.ts
2258
2480
  function buildSeedBanner(bankId, cold = true, gitNote) {
2259
2481
  const headline = cold ? `${brandWord()} is learning this repo \u2014 ingesting its decisions, conventions and history` : `${brandWord()} is tracking the decisions, conventions and history of this repo`;
@@ -2334,13 +2556,13 @@ async function buildSessionStartContext(args) {
2334
2556
  startSeed(cwd, { limit: cfg.seedLimit, harness });
2335
2557
  if (docIds.size === 0) {
2336
2558
  if (cfg.codebaseSurvey !== false) {
2337
- startSurvey(cwd, {
2559
+ const started = await startSurvey(cwd, {
2338
2560
  harness,
2339
2561
  model: cfg.surveyModel,
2340
2562
  budgetUsd: cfg.surveyBudgetUsd
2341
2563
  });
2342
2564
  const sha = resolveHeadSha(cwd);
2343
- if (sha) recordSurveyBaseline(sha);
2565
+ if (started && sha) recordSurveyBaseline(sha);
2344
2566
  }
2345
2567
  diag(harness, "seed_started", { bank: bankId });
2346
2568
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
@@ -2357,17 +2579,19 @@ async function buildSessionStartContext(args) {
2357
2579
  const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
2358
2580
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
2359
2581
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
2360
- startSurvey(cwd, {
2582
+ const started = await startSurvey(cwd, {
2361
2583
  harness,
2362
2584
  model: cfg.surveyModel,
2363
2585
  budgetUsd: cfg.surveyBudgetUsd
2364
2586
  });
2365
- recordSurveyBaseline(sha);
2366
- diag(harness, "survey_refresh", {
2367
- bank: bankId,
2368
- commits: sinceLast,
2369
- retry: findingsAbsent
2370
- });
2587
+ if (started) {
2588
+ recordSurveyBaseline(sha);
2589
+ diag(harness, "survey_refresh", {
2590
+ bank: bankId,
2591
+ commits: sinceLast,
2592
+ retry: findingsAbsent
2593
+ });
2594
+ }
2371
2595
  } else if (sinceLast === null) {
2372
2596
  recordSurveyBaseline(sha);
2373
2597
  }
@@ -2400,6 +2624,13 @@ async function buildSessionStartContext(args) {
2400
2624
  }).catch(() => void 0);
2401
2625
  }
2402
2626
  systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
2627
+ const detectLegacy = args.detectLegacyPlugin ?? (harness === "claude-code" ? detectLegacyClaudePlugin : void 0);
2628
+ const legacyPlugin = detectLegacy?.(cwd);
2629
+ if (legacyPlugin) {
2630
+ systemMessage += `
2631
+ ${legacyClaudePluginWarning(legacyPlugin)}`;
2632
+ diag(harness, "legacy_plugin_active", { plugin: legacyPlugin });
2633
+ }
2403
2634
  diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
2404
2635
  return { systemMessage, additionalContext, deferInitialReflect };
2405
2636
  }
@@ -2408,7 +2639,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2408
2639
  try {
2409
2640
  let ev = {};
2410
2641
  try {
2411
- ev = JSON.parse(readFileSync8(0, "utf8"));
2642
+ ev = JSON.parse(readFileSync10(0, "utf8"));
2412
2643
  } catch {
2413
2644
  return;
2414
2645
  }
@@ -2577,19 +2808,19 @@ function readCopilotTranscript(path) {
2577
2808
  }
2578
2809
 
2579
2810
  // src/core/transcript-grok.ts
2580
- import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2581
- import { homedir as homedir6 } from "os";
2582
- import { join as join12 } from "path";
2811
+ import { existsSync as existsSync7, readFileSync as readFileSync11, readdirSync as readdirSync2 } from "fs";
2812
+ import { homedir as homedir7 } from "os";
2813
+ import { join as join15 } from "path";
2583
2814
  var CHAT_HISTORY = "chat_history.jsonl";
2584
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
2585
- const sessionsDir = join12(grokHome, "sessions");
2586
- const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2587
- if (existsSync6(direct)) return direct;
2815
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join15(homedir7(), ".grok")) {
2816
+ const sessionsDir = join15(grokHome, "sessions");
2817
+ const direct = join15(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2818
+ if (existsSync7(direct)) return direct;
2588
2819
  try {
2589
- for (const candidate of readdirSync(sessionsDir)) {
2590
- const directory = join12(sessionsDir, candidate);
2591
- if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
2592
- return join12(directory, sessionId, CHAT_HISTORY);
2820
+ for (const candidate of readdirSync2(sessionsDir)) {
2821
+ const directory = join15(sessionsDir, candidate);
2822
+ if (readFileSync11(join15(directory, ".cwd"), "utf8").trim() === cwd) {
2823
+ return join15(directory, sessionId, CHAT_HISTORY);
2593
2824
  }
2594
2825
  }
2595
2826
  } catch {
@@ -2624,12 +2855,12 @@ function readGrokTranscript(path) {
2624
2855
  }
2625
2856
 
2626
2857
  // src/core/transcript-devin.ts
2627
- import { existsSync as existsSync7 } from "fs";
2858
+ import { existsSync as existsSync8 } from "fs";
2628
2859
  import { createRequire } from "module";
2629
- import { homedir as homedir7 } from "os";
2630
- import { join as join13 } from "path";
2631
- function devinSessionDb(home = homedir7()) {
2632
- return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2860
+ import { homedir as homedir8 } from "os";
2861
+ import { join as join16 } from "path";
2862
+ function devinSessionDb(home = homedir8()) {
2863
+ return join16(home, ".local", "share", "devin", "cli", "sessions.db");
2633
2864
  }
2634
2865
  function parseDevinMessages(nodes) {
2635
2866
  const messages = /* @__PURE__ */ new Map();
@@ -2666,7 +2897,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2666
2897
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2667
2898
  return [];
2668
2899
  }
2669
- if (!existsSync7(dbPath)) {
2900
+ if (!existsSync8(dbPath)) {
2670
2901
  diag("devin-cli", "session_db_missing", { dbPath });
2671
2902
  return [];
2672
2903
  }
@@ -2938,6 +3169,51 @@ function readDroidTranscript(path) {
2938
3169
  return turns;
2939
3170
  }
2940
3171
 
3172
+ // src/core/transcript-zcode.ts
3173
+ import { readFileSync as readFileSync12 } from "fs";
3174
+ function messageText2(content) {
3175
+ if (typeof content === "string") return content.trim();
3176
+ if (!Array.isArray(content)) return "";
3177
+ return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
3178
+ }
3179
+ function readZcodeTranscript(path) {
3180
+ if (!path) return [];
3181
+ let body;
3182
+ try {
3183
+ body = readFileSync12(path, "utf8");
3184
+ } catch {
3185
+ return [];
3186
+ }
3187
+ const turns = [];
3188
+ for (const line of body.split("\n")) {
3189
+ const trimmed = line.trim();
3190
+ if (!trimmed) continue;
3191
+ let parsed;
3192
+ try {
3193
+ parsed = JSON.parse(trimmed);
3194
+ } catch {
3195
+ continue;
3196
+ }
3197
+ if (typeof parsed !== "object" || parsed === null) continue;
3198
+ const record = parsed;
3199
+ const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
3200
+ const role = typeof message?.role === "string" ? message.role : record.type;
3201
+ if (role !== "user" && role !== "assistant") continue;
3202
+ const content = stripInjectedMemory(messageText2(message?.content)).trim();
3203
+ if (!content) continue;
3204
+ turns.push({
3205
+ role,
3206
+ content,
3207
+ ...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
3208
+ });
3209
+ }
3210
+ return turns;
3211
+ }
3212
+ function zcodeAssistantText(path) {
3213
+ if (!path) return "";
3214
+ return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3215
+ }
3216
+
2941
3217
  // src/harness/hook-lifecycle.ts
2942
3218
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2943
3219
  var claudePrompt = {
@@ -2978,6 +3254,7 @@ var qwenPrompt = {
2978
3254
  sessionId: ev.session_id
2979
3255
  })
2980
3256
  };
3257
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
2981
3258
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2982
3259
  var antigravityPrompt = {
2983
3260
  harness: "antigravity-cli",
@@ -3320,6 +3597,56 @@ var HOOK_HARNESSES = {
3320
3597
  }),
3321
3598
  readTranscript: readDroidTranscript
3322
3599
  }
3600
+ },
3601
+ /**
3602
+ * ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
3603
+ * Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
3604
+ * with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
3605
+ *
3606
+ * What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
3607
+ * keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
3608
+ * assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
3609
+ * So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
3610
+ * the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
3611
+ * everything downstream (cursor, append, stamping) sees the same full conversation as any host
3612
+ * transcript.
3613
+ */
3614
+ zcode: {
3615
+ configStyle: "process",
3616
+ // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
3617
+ // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
3618
+ timeoutUnit: "milliseconds",
3619
+ install: {
3620
+ sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
3621
+ prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
3622
+ stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
3623
+ },
3624
+ sessionStart: {
3625
+ ...standardSessionStart("zcode"),
3626
+ parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
3627
+ },
3628
+ prompt: {
3629
+ ...claudePrompt,
3630
+ harness: "zcode",
3631
+ journalPrompt: true,
3632
+ parse: (ev) => ({
3633
+ prompt: ev.prompt ?? ev.user_prompt,
3634
+ cwd: ev.cwd,
3635
+ sessionId: zcodeSessionId(ev)
3636
+ })
3637
+ },
3638
+ retain: {
3639
+ hostTimeoutSec: 60,
3640
+ harness: "zcode",
3641
+ // No transcriptPath: the journal supplies it (see `journal` below).
3642
+ parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
3643
+ journal: {
3644
+ // `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
3645
+ // transcript is the fallback when it is absent, and `responsePreview` — which is
3646
+ // TRUNCATED — is the last resort, preferred only over losing the turn entirely.
3647
+ assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3648
+ }
3649
+ }
3323
3650
  }
3324
3651
  };
3325
3652
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);