@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";
@@ -447,6 +447,7 @@ function pagesFor(project) {
447
447
  var PAGE_MAX_TOKENS = 4096;
448
448
  var PAGE_TAGS_MATCH = "all";
449
449
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
450
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
450
451
  var CRON_FIELD_RANGES = [
451
452
  [0, 59],
452
453
  // minute
@@ -500,14 +501,23 @@ function pageTriggerFor(trigger, bank, page) {
500
501
  function buildPageTrigger(cfg = {}) {
501
502
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
502
503
  switch (cfg.pageTriggerType) {
503
- case "cron":
504
- return { ...base, refresh_cron: cfg.pageTriggerCron };
504
+ case "auto-refresh":
505
+ return { ...base, refresh_after_consolidation: true };
505
506
  case "manual":
506
507
  return { ...base, refresh_after_consolidation: false };
508
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
509
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
507
510
  default:
508
- return { ...base, refresh_after_consolidation: true };
511
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
509
512
  }
510
513
  }
514
+ function pageTriggerDrifted(current2, desired) {
515
+ 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);
516
+ }
517
+ function pageTriggerPatch(desired) {
518
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
519
+ return desired;
520
+ }
511
521
  var CODING_BANK_TEMPLATE = {
512
522
  version: "1",
513
523
  bank: {
@@ -912,9 +922,16 @@ var HindsightClient = class {
912
922
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
913
923
  signal: ctrl.signal
914
924
  });
915
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
925
+ if (!resp.ok)
926
+ throw new Error(
927
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
928
+ );
916
929
  const data = await resp.json();
917
930
  return (data.text || "").trim();
931
+ } catch (e) {
932
+ if (ctrl.signal.aborted)
933
+ throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
934
+ throw e;
918
935
  } finally {
919
936
  clearTimeout(timer);
920
937
  }
@@ -1047,14 +1064,14 @@ var HindsightClient = class {
1047
1064
  if (r.status !== 409) created++;
1048
1065
  } else {
1049
1066
  const sourceDrift = hit.description !== page.source_query;
1050
- const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1067
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1051
1068
  if (!sourceDrift && !triggerDrift) continue;
1052
1069
  const patch = {};
1053
1070
  if (sourceDrift) {
1054
1071
  patch.source_query = page.source_query;
1055
1072
  patch.tags = page.tags;
1056
1073
  }
1057
- if (triggerDrift) patch.trigger = pageTrigger;
1074
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1058
1075
  const r = await this.req(
1059
1076
  "PATCH",
1060
1077
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
@@ -1070,9 +1087,41 @@ var HindsightClient = class {
1070
1087
  updated++;
1071
1088
  }
1072
1089
  }
1090
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1073
1091
  this.log(
1074
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1092
+ `[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` : "")
1093
+ );
1094
+ }
1095
+ /**
1096
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1097
+ *
1098
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1099
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1100
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1101
+ * consolidation under the auto-refresh that used to be the default (#3506).
1102
+ *
1103
+ * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1104
+ * initiative's own title, and re-stating either would rebuild a page whose question never
1105
+ * changed. The tree read above is reused rather than re-fetched.
1106
+ */
1107
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1108
+ const folder = roots.find(
1109
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1075
1110
  );
1111
+ let updated = 0;
1112
+ for (const page of folder?.children ?? []) {
1113
+ if (page.kind !== "page" || page.trigger == null) continue;
1114
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1115
+ if (!pageTriggerDrifted(page.trigger, desired)) continue;
1116
+ const r = await this.req(
1117
+ "PATCH",
1118
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1119
+ { trigger: pageTriggerPatch(desired) }
1120
+ );
1121
+ if ([404, 405, 501].includes(r.status)) break;
1122
+ updated++;
1123
+ }
1124
+ return updated;
1076
1125
  }
1077
1126
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1078
1127
  slugify(s) {
@@ -1095,11 +1144,13 @@ var HindsightClient = class {
1095
1144
  let pageId = args.relatesToPageId;
1096
1145
  if (!pageId) {
1097
1146
  const folderId = await this.ensureFolder("Initiatives");
1147
+ const subject = this.project ?? this.bank;
1098
1148
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1099
1149
  name: args.title,
1100
- 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.`,
1150
+ 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),
1101
1151
  parent_id: folderId,
1102
1152
  tags: ["knowledge:feature-work"],
1153
+ max_tokens: PAGE_MAX_TOKENS,
1103
1154
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1104
1155
  });
1105
1156
  try {
@@ -1142,17 +1193,22 @@ var HindsightClient = class {
1142
1193
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1143
1194
  var DEFAULT_DAEMON_PORT = 9077;
1144
1195
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1145
- function resolvePageTriggerType(raw) {
1146
- if (raw.pageTriggerType === "manual") return "manual";
1147
- if (raw.pageTriggerType === "cron") {
1148
- const cron = raw.pageTriggerCron?.trim();
1149
- if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1196
+ function resolvePageTrigger(raw) {
1197
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1198
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1199
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1150
1200
  log.warn(
1151
1201
  "config",
1152
- 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"'
1202
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1153
1203
  );
1154
- }
1155
- return "auto-refresh";
1204
+ const cron = raw.pageTriggerCron?.trim();
1205
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1206
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1207
+ log.warn(
1208
+ "config",
1209
+ `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)}`
1210
+ );
1211
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1156
1212
  }
1157
1213
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1158
1214
  var REFLECT_BUDGETS = ["low", "mid", "high"];
@@ -1184,6 +1240,7 @@ function resolveObservationScopes(raw) {
1184
1240
  function resolveConfig(raw = {}) {
1185
1241
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1186
1242
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1243
+ const pageTrigger = resolvePageTrigger(raw);
1187
1244
  return {
1188
1245
  serverMode,
1189
1246
  // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
@@ -1218,8 +1275,8 @@ function resolveConfig(raw = {}) {
1218
1275
  reflectBudget: resolveReflectBudget(raw),
1219
1276
  autoReflect: raw.autoReflect ?? true,
1220
1277
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1221
- pageTriggerType: resolvePageTriggerType(raw),
1222
- pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1278
+ pageTriggerType: pageTrigger.type,
1279
+ pageTriggerCron: pageTrigger.cron,
1223
1280
  autoSeed: raw.autoSeed ?? true,
1224
1281
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1225
1282
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1445,8 +1502,104 @@ function fileCursorStore(harness) {
1445
1502
  };
1446
1503
  }
1447
1504
 
1505
+ // src/core/turn-journal.ts
1506
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync } from "fs";
1507
+ import { tmpdir as tmpdir3 } from "os";
1508
+ import { dirname as dirname6, join as join8 } from "path";
1509
+
1510
+ // src/core/transcript-util.ts
1511
+ 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;
1512
+ function stripInjectedMemory(s) {
1513
+ return s.replace(MEMORY_TAG_RE, "");
1514
+ }
1515
+ var TARGET_KEYS = [
1516
+ "file_path",
1517
+ "path",
1518
+ "notebook_path",
1519
+ "command",
1520
+ "pattern",
1521
+ "query",
1522
+ "url",
1523
+ "name",
1524
+ "id"
1525
+ ];
1526
+ var ACTION_TARGET_CAP = 100;
1527
+ function actionLine(tool, input) {
1528
+ let target = "";
1529
+ if (input && typeof input === "object") {
1530
+ const rec = input;
1531
+ for (const k of TARGET_KEYS) {
1532
+ const v = rec[k];
1533
+ if (typeof v === "string" && v.trim()) {
1534
+ target = v.trim().split("\n")[0];
1535
+ break;
1536
+ }
1537
+ }
1538
+ } else if (typeof input === "string") {
1539
+ target = input.trim().split("\n")[0];
1540
+ }
1541
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1542
+ return target ? `${tool} ${target}` : tool;
1543
+ }
1544
+
1545
+ // src/core/turn-journal.ts
1546
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1547
+ function journalPath(harness, sessionId) {
1548
+ return join8(tmpdir3(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1549
+ }
1550
+ function appendJournalTurn(path, turn) {
1551
+ const content = stripInjectedMemory(turn.content ?? "").trim();
1552
+ if (!content) return;
1553
+ try {
1554
+ if (statSync(path).size >= JOURNAL_MAX_BYTES) return;
1555
+ } catch {
1556
+ }
1557
+ const last = readJournalTranscript(path).at(-1);
1558
+ if (last && last.role === turn.role && last.content === content) return;
1559
+ try {
1560
+ mkdirSync3(dirname6(path), { recursive: true });
1561
+ appendFileSync3(
1562
+ path,
1563
+ JSON.stringify({
1564
+ role: turn.role,
1565
+ content,
1566
+ timestamp: turn.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
1567
+ }) + "\n"
1568
+ );
1569
+ } catch {
1570
+ }
1571
+ }
1572
+ function readJournalTranscript(path) {
1573
+ let body;
1574
+ try {
1575
+ body = readFileSync4(path, "utf8");
1576
+ } catch {
1577
+ return [];
1578
+ }
1579
+ const turns = [];
1580
+ for (const line of body.split("\n")) {
1581
+ const trimmed = line.trim();
1582
+ if (!trimmed) continue;
1583
+ let parsed;
1584
+ try {
1585
+ parsed = JSON.parse(trimmed);
1586
+ } catch {
1587
+ continue;
1588
+ }
1589
+ if (typeof parsed !== "object" || parsed === null) continue;
1590
+ const { role, content, timestamp } = parsed;
1591
+ if (typeof role !== "string" || typeof content !== "string" || !content) continue;
1592
+ turns.push({
1593
+ role,
1594
+ content,
1595
+ ...typeof timestamp === "string" ? { timestamp } : {}
1596
+ });
1597
+ }
1598
+ return turns;
1599
+ }
1600
+
1448
1601
  // src/core/retain-hook.ts
1449
- import { readFileSync as readFileSync5 } from "fs";
1602
+ import { readFileSync as readFileSync6 } from "fs";
1450
1603
 
1451
1604
  // src/core/retain-cursor.ts
1452
1605
  import { createHash as createHash2 } from "crypto";
@@ -1639,7 +1792,7 @@ ${content}`);
1639
1792
 
1640
1793
  // src/core/daemon.ts
1641
1794
  import { execFileSync, spawn as realSpawn2 } from "child_process";
1642
- import { dirname as dirname6, join as join8 } from "path";
1795
+ import { dirname as dirname7, join as join9 } from "path";
1643
1796
  import { fileURLToPath as fileURLToPath2 } from "url";
1644
1797
  var DAEMON_WAIT_RETAIN_MS = 4e4;
1645
1798
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -1713,7 +1866,7 @@ function onPath(bin) {
1713
1866
  }
1714
1867
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1715
1868
  try {
1716
- const starter = join8(dirname6(fileURLToPath2(import.meta.url)), "daemon-start.js");
1869
+ const starter = join9(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
1717
1870
  const child = spawnFn("node", [starter, "--harness", harness], {
1718
1871
  detached: true,
1719
1872
  stdio: "ignore",
@@ -1814,7 +1967,7 @@ function buildRetainStamp(cfg, ctx) {
1814
1967
  }
1815
1968
 
1816
1969
  // src/core/jsonl.ts
1817
- import { closeSync, openSync, readSync, statSync } from "fs";
1970
+ import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
1818
1971
  import { StringDecoder } from "string_decoder";
1819
1972
  var CHUNK_BYTES = 64 * 1024;
1820
1973
  var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
@@ -1822,7 +1975,7 @@ function readJsonlTail(path, opts) {
1822
1975
  const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1823
1976
  let size;
1824
1977
  try {
1825
- size = statSync(path).size;
1978
+ size = statSync2(path).size;
1826
1979
  } catch {
1827
1980
  return { lines: emptyLines(), skippedBytes: 0 };
1828
1981
  }
@@ -1874,41 +2027,6 @@ function* streamLines(path, start) {
1874
2027
  }
1875
2028
  }
1876
2029
 
1877
- // src/core/transcript-util.ts
1878
- 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;
1879
- function stripInjectedMemory(s) {
1880
- return s.replace(MEMORY_TAG_RE, "");
1881
- }
1882
- var TARGET_KEYS = [
1883
- "file_path",
1884
- "path",
1885
- "notebook_path",
1886
- "command",
1887
- "pattern",
1888
- "query",
1889
- "url",
1890
- "name",
1891
- "id"
1892
- ];
1893
- var ACTION_TARGET_CAP = 100;
1894
- function actionLine(tool, input) {
1895
- let target = "";
1896
- if (input && typeof input === "object") {
1897
- const rec = input;
1898
- for (const k of TARGET_KEYS) {
1899
- const v = rec[k];
1900
- if (typeof v === "string" && v.trim()) {
1901
- target = v.trim().split("\n")[0];
1902
- break;
1903
- }
1904
- }
1905
- } else if (typeof input === "string") {
1906
- target = input.trim().split("\n")[0];
1907
- }
1908
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1909
- return target ? `${tool} ${target}` : tool;
1910
- }
1911
-
1912
2030
  // src/core/transcript.ts
1913
2031
  function renderLine(content, type) {
1914
2032
  if (typeof content === "string") {
@@ -2001,16 +2119,27 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2001
2119
  const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2002
2120
  let ev = {};
2003
2121
  try {
2004
- ev = JSON.parse(readFileSync5(0, "utf8"));
2122
+ ev = JSON.parse(readFileSync6(0, "utf8"));
2005
2123
  } catch {
2006
2124
  return;
2007
2125
  }
2008
2126
  if (spec.accept && !spec.accept(ev)) return;
2009
- const { sessionId, transcriptPath, cwd: rawCwd, lastAssistantMessage } = spec.parse(ev);
2127
+ const parsed = spec.parse(ev);
2128
+ const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
2010
2129
  const cwd = rawCwd || process.cwd();
2130
+ let transcriptPath = parsed.transcriptPath;
2131
+ let readTranscript = spec.readTranscript;
2011
2132
  let cfg = loadConfig({ harness: spec.harness });
2012
2133
  setLogLevel(cfg.logLevel);
2013
2134
  if (cfg.disabled) return;
2135
+ if (spec.journal) {
2136
+ transcriptPath = journalPath(spec.harness, sessionId);
2137
+ readTranscript = readJournalTranscript;
2138
+ appendJournalTurn(transcriptPath, {
2139
+ role: "assistant",
2140
+ content: spec.journal.assistantText(ev)
2141
+ });
2142
+ }
2014
2143
  if (!transcriptPath) return;
2015
2144
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2016
2145
  const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
@@ -2036,7 +2165,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2036
2165
  sessionId: sessionId || "no-session",
2037
2166
  transcriptPath,
2038
2167
  client,
2039
- readTranscript: spec.readTranscript,
2168
+ readTranscript,
2040
2169
  lastAssistantMessage,
2041
2170
  readLastMessage: spec.readLastMessage,
2042
2171
  retryUntil: hostDeadline,
@@ -2051,7 +2180,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2051
2180
  }
2052
2181
 
2053
2182
  // src/core/session-start.ts
2054
- import { readFileSync as readFileSync8 } from "fs";
2183
+ import { readFileSync as readFileSync10 } from "fs";
2055
2184
 
2056
2185
  // src/core/git.ts
2057
2186
  import { execFileSync as execFileSync2 } from "child_process";
@@ -2061,34 +2190,57 @@ import { resolve as resolve2 } from "path";
2061
2190
  import { execFileSync as execFileSync3 } from "child_process";
2062
2191
 
2063
2192
  // src/core/survey.ts
2064
- import { spawn as realSpawn3 } from "child_process";
2193
+ import { spawn as realSpawn4 } from "child_process";
2194
+ import { createHash as createHash4 } from "crypto";
2065
2195
  import { existsSync as existsSync3 } from "fs";
2066
- import { homedir as homedir3 } from "os";
2067
- import { dirname as dirname7, join as join9 } from "path";
2196
+ import { homedir as homedir3, tmpdir as tmpdir4 } from "os";
2197
+ import { dirname as dirname8, join as join11 } from "path";
2068
2198
  import { fileURLToPath as fileURLToPath3 } from "url";
2069
2199
 
2200
+ // src/core/survey-lease.ts
2201
+ import { spawn as realSpawn3 } from "child_process";
2202
+ import { randomUUID } from "crypto";
2203
+ import {
2204
+ mkdirSync as mkdirSync4,
2205
+ mkdtempSync,
2206
+ readdirSync,
2207
+ renameSync as renameSync2,
2208
+ rmdirSync,
2209
+ rmSync as rmSync2,
2210
+ statSync as statSync3,
2211
+ unlinkSync,
2212
+ utimesSync,
2213
+ writeFileSync as writeFileSync2
2214
+ } from "fs";
2215
+ import { join as join10 } from "path";
2216
+
2070
2217
  // src/core/auto-update.ts
2071
- import { spawn as realSpawn4 } from "child_process";
2218
+ import { spawn as realSpawn5 } from "child_process";
2072
2219
  import {
2073
2220
  existsSync as existsSync4,
2074
- mkdirSync as mkdirSync3,
2075
- readFileSync as readFileSync6,
2221
+ mkdirSync as mkdirSync5,
2222
+ readFileSync as readFileSync7,
2076
2223
  realpathSync as realpathSync2,
2077
- unlinkSync,
2078
- writeFileSync as writeFileSync2
2224
+ unlinkSync as unlinkSync2,
2225
+ writeFileSync as writeFileSync3
2079
2226
  } from "fs";
2080
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2081
- import { dirname as dirname8, join as join10 } from "path";
2227
+ import { homedir as homedir4, tmpdir as tmpdir5 } from "os";
2228
+ import { dirname as dirname9, join as join12 } from "path";
2082
2229
  import { fileURLToPath as fileURLToPath4 } from "url";
2083
2230
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2084
2231
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2085
2232
 
2086
2233
  // src/core/skill-sync.ts
2087
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
2234
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
2088
2235
  import { homedir as homedir5 } from "os";
2089
- import { dirname as dirname9, join as join11 } from "path";
2236
+ import { dirname as dirname10, join as join13 } from "path";
2090
2237
  import { fileURLToPath as fileURLToPath5 } from "url";
2091
2238
 
2239
+ // src/core/legacy.ts
2240
+ import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2241
+ import { homedir as homedir6 } from "os";
2242
+ import { join as join14, relative, isAbsolute as isAbsolute2 } from "path";
2243
+
2092
2244
  // src/core/transcript-codex.ts
2093
2245
  function isSyntheticUserText(text) {
2094
2246
  const s = text.trimStart();
@@ -2219,19 +2371,19 @@ function readCopilotTranscript(path) {
2219
2371
  }
2220
2372
 
2221
2373
  // src/core/transcript-grok.ts
2222
- import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2223
- import { homedir as homedir6 } from "os";
2224
- import { join as join12 } from "path";
2374
+ import { existsSync as existsSync7, readFileSync as readFileSync11, readdirSync as readdirSync2 } from "fs";
2375
+ import { homedir as homedir7 } from "os";
2376
+ import { join as join15 } from "path";
2225
2377
  var CHAT_HISTORY = "chat_history.jsonl";
2226
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
2227
- const sessionsDir = join12(grokHome, "sessions");
2228
- const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2229
- if (existsSync6(direct)) return direct;
2378
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join15(homedir7(), ".grok")) {
2379
+ const sessionsDir = join15(grokHome, "sessions");
2380
+ const direct = join15(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2381
+ if (existsSync7(direct)) return direct;
2230
2382
  try {
2231
- for (const candidate of readdirSync(sessionsDir)) {
2232
- const directory = join12(sessionsDir, candidate);
2233
- if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
2234
- return join12(directory, sessionId, CHAT_HISTORY);
2383
+ for (const candidate of readdirSync2(sessionsDir)) {
2384
+ const directory = join15(sessionsDir, candidate);
2385
+ if (readFileSync11(join15(directory, ".cwd"), "utf8").trim() === cwd) {
2386
+ return join15(directory, sessionId, CHAT_HISTORY);
2235
2387
  }
2236
2388
  }
2237
2389
  } catch {
@@ -2266,12 +2418,12 @@ function readGrokTranscript(path) {
2266
2418
  }
2267
2419
 
2268
2420
  // src/core/transcript-devin.ts
2269
- import { existsSync as existsSync7 } from "fs";
2421
+ import { existsSync as existsSync8 } from "fs";
2270
2422
  import { createRequire } from "module";
2271
- import { homedir as homedir7 } from "os";
2272
- import { join as join13 } from "path";
2273
- function devinSessionDb(home = homedir7()) {
2274
- return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2423
+ import { homedir as homedir8 } from "os";
2424
+ import { join as join16 } from "path";
2425
+ function devinSessionDb(home = homedir8()) {
2426
+ return join16(home, ".local", "share", "devin", "cli", "sessions.db");
2275
2427
  }
2276
2428
  function parseDevinMessages(nodes) {
2277
2429
  const messages = /* @__PURE__ */ new Map();
@@ -2308,7 +2460,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2308
2460
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2309
2461
  return [];
2310
2462
  }
2311
- if (!existsSync7(dbPath)) {
2463
+ if (!existsSync8(dbPath)) {
2312
2464
  diag("devin-cli", "session_db_missing", { dbPath });
2313
2465
  return [];
2314
2466
  }
@@ -2580,6 +2732,51 @@ function readDroidTranscript(path) {
2580
2732
  return turns;
2581
2733
  }
2582
2734
 
2735
+ // src/core/transcript-zcode.ts
2736
+ import { readFileSync as readFileSync12 } from "fs";
2737
+ function messageText2(content) {
2738
+ if (typeof content === "string") return content.trim();
2739
+ if (!Array.isArray(content)) return "";
2740
+ return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
2741
+ }
2742
+ function readZcodeTranscript(path) {
2743
+ if (!path) return [];
2744
+ let body;
2745
+ try {
2746
+ body = readFileSync12(path, "utf8");
2747
+ } catch {
2748
+ return [];
2749
+ }
2750
+ const turns = [];
2751
+ for (const line of body.split("\n")) {
2752
+ const trimmed = line.trim();
2753
+ if (!trimmed) continue;
2754
+ let parsed;
2755
+ try {
2756
+ parsed = JSON.parse(trimmed);
2757
+ } catch {
2758
+ continue;
2759
+ }
2760
+ if (typeof parsed !== "object" || parsed === null) continue;
2761
+ const record = parsed;
2762
+ const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
2763
+ const role = typeof message?.role === "string" ? message.role : record.type;
2764
+ if (role !== "user" && role !== "assistant") continue;
2765
+ const content = stripInjectedMemory(messageText2(message?.content)).trim();
2766
+ if (!content) continue;
2767
+ turns.push({
2768
+ role,
2769
+ content,
2770
+ ...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
2771
+ });
2772
+ }
2773
+ return turns;
2774
+ }
2775
+ function zcodeAssistantText(path) {
2776
+ if (!path) return "";
2777
+ return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
2778
+ }
2779
+
2583
2780
  // src/harness/hook-lifecycle.ts
2584
2781
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2585
2782
  var claudePrompt = {
@@ -2620,6 +2817,7 @@ var qwenPrompt = {
2620
2817
  sessionId: ev.session_id
2621
2818
  })
2622
2819
  };
2820
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
2623
2821
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2624
2822
  var antigravityPrompt = {
2625
2823
  harness: "antigravity-cli",
@@ -2962,6 +3160,56 @@ var HOOK_HARNESSES = {
2962
3160
  }),
2963
3161
  readTranscript: readDroidTranscript
2964
3162
  }
3163
+ },
3164
+ /**
3165
+ * ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
3166
+ * Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
3167
+ * with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
3168
+ *
3169
+ * What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
3170
+ * keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
3171
+ * assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
3172
+ * So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
3173
+ * the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
3174
+ * everything downstream (cursor, append, stamping) sees the same full conversation as any host
3175
+ * transcript.
3176
+ */
3177
+ zcode: {
3178
+ configStyle: "process",
3179
+ // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
3180
+ // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
3181
+ timeoutUnit: "milliseconds",
3182
+ install: {
3183
+ sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
3184
+ prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
3185
+ stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
3186
+ },
3187
+ sessionStart: {
3188
+ ...standardSessionStart("zcode"),
3189
+ parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
3190
+ },
3191
+ prompt: {
3192
+ ...claudePrompt,
3193
+ harness: "zcode",
3194
+ journalPrompt: true,
3195
+ parse: (ev) => ({
3196
+ prompt: ev.prompt ?? ev.user_prompt,
3197
+ cwd: ev.cwd,
3198
+ sessionId: zcodeSessionId(ev)
3199
+ })
3200
+ },
3201
+ retain: {
3202
+ hostTimeoutSec: 60,
3203
+ harness: "zcode",
3204
+ // No transcriptPath: the journal supplies it (see `journal` below).
3205
+ parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
3206
+ journal: {
3207
+ // `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
3208
+ // transcript is the fallback when it is absent, and `responsePreview` — which is
3209
+ // TRUNCATED — is the last resort, preferred only over losing the turn entirely.
3210
+ assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3211
+ }
3212
+ }
2965
3213
  }
2966
3214
  };
2967
3215
  var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);