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

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 (50) hide show
  1. package/README.md +42 -8
  2. package/dist/antigravity-hook.js +286 -76
  3. package/dist/antigravity-statusline.js +17 -10
  4. package/dist/antigravity-stop-hook.js +297 -79
  5. package/dist/claude-hook.js +286 -76
  6. package/dist/claude-sessionstart-hook.js +252 -93
  7. package/dist/claude-stop-hook.js +297 -79
  8. package/dist/cline.js +74 -18
  9. package/dist/codex-hook.js +286 -76
  10. package/dist/codex-sessionstart-hook.js +252 -93
  11. package/dist/codex-stop-hook.js +297 -79
  12. package/dist/copilot-hook.js +286 -76
  13. package/dist/copilot-sessionstart-hook.js +252 -93
  14. package/dist/copilot-stop-hook.js +297 -79
  15. package/dist/cursor-hook.js +286 -76
  16. package/dist/cursor-sessionstart-hook.js +252 -93
  17. package/dist/cursor-stop-hook.js +297 -79
  18. package/dist/daemon-start.js +17 -10
  19. package/dist/dcode-hook.js +286 -76
  20. package/dist/dcode-sessionstart-hook.js +252 -93
  21. package/dist/dcode-stop-hook.js +297 -79
  22. package/dist/deepen.js +73 -19
  23. package/dist/devin-hook.js +286 -76
  24. package/dist/devin-sessionstart-hook.js +252 -93
  25. package/dist/devin-stop-hook.js +297 -79
  26. package/dist/droid-hook.js +286 -76
  27. package/dist/droid-sessionstart-hook.js +252 -93
  28. package/dist/droid-stop-hook.js +297 -79
  29. package/dist/dsh.js +111 -53
  30. package/dist/grok-hook.js +286 -76
  31. package/dist/grok-sessionstart-hook.js +252 -93
  32. package/dist/grok-stop-hook.js +297 -79
  33. package/dist/hindsight-seed.js +17 -10
  34. package/dist/index.js +113 -55
  35. package/dist/installer.js +383 -218
  36. package/dist/kilo.js +113 -55
  37. package/dist/mcp-server.js +67 -17
  38. package/dist/opencode2.js +113 -55
  39. package/dist/pi.js +112 -54
  40. package/dist/prime-agent.js +112 -54
  41. package/dist/qwen-hook.js +286 -76
  42. package/dist/qwen-sessionstart-hook.js +252 -93
  43. package/dist/qwen-stop-hook.js +297 -79
  44. package/dist/status.js +67 -17
  45. package/dist/zcode-hook.js +2920 -0
  46. package/dist/zcode-sessionstart-hook.js +3487 -0
  47. package/dist/zcode-stop-hook.js +3188 -0
  48. package/package.json +6 -3
  49. package/plugin.json +1 -1
  50. package/skill/SKILL.md +17 -7
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Long-term project memory for **coding agents**, backed by [Hindsight](https://vectorize.io/hindsight).
4
4
  One package, several agents: a shared reflect-and-inject core with a thin entry point per agent
5
- (**Claude Code**, **Codex CLI**, **DeepAgents Dcode**, **opencode**, **opencode 2**, **Kilo CLI**, **Cursor CLI**, **GitHub Copilot CLI**, **Grok Build**, **Qwen Code**, **Factory Droid**, **Antigravity CLI**, **Devin CLI**, **Cline CLI**, **pi**, **Prime Agent**, **DeepSeek Harness**). Ingestion is fully
5
+ (**Claude Code**, **Codex CLI**, **DeepAgents Dcode**, **opencode**, **opencode 2**, **Kilo CLI**, **Cursor CLI**, **GitHub Copilot CLI**, **Grok Build**, **Qwen Code**, **Factory Droid**, **ZCode**, **Antigravity CLI**, **Devin CLI**, **Cline CLI**, **pi**, **Prime Agent**, **DeepSeek Harness**). Ingestion is fully
6
6
  automatic — there is no setup command: a repo's git history and conversations flow into its memory
7
7
  bank in the background as you work.
8
8
 
@@ -169,6 +169,30 @@ user-managed MCP server already named `hindsight`. Droid's hook protocol matches
169
169
  injection use the same protocol; write-back also handles Droid's cancellation notification because
170
170
  Droid does not emit `Stop` after a cancelled turn.
171
171
 
172
+ #### <img src="https://hindsight.vectorize.io/img/harness/zcode.svg" alt="" width="20" height="20" /> ZCode
173
+
174
+ ```bash
175
+ npx @vectorize-io/hindsight-coding-agents install zcode
176
+ ```
177
+
178
+ Three hook registrations plus a stdio MCP server under `mcp.servers.hindsight`, both in ZCode's own
179
+ CLI config `~/.zcode/cli/config.json` - never your real Claude Code settings, even though ZCode
180
+ embeds the Claude Code agent runtime and speaks its hook protocol. The companion skill goes to
181
+ `~/.zcode/skills`. Config hooks ship **disabled**, so the installer also sets `hooks.enabled` to
182
+ `true`; `uninstall` removes the whole block again when nothing else is registered there, and
183
+ refuses to touch an MCP server named `hindsight` that it did not write.
184
+
185
+ > ZCode's hook `timeoutMs` is in **milliseconds** (installed values `30000/30000/60000`), and
186
+ > `hooks.maxOutputBytes` caps what a hook may print - anything larger is dropped, injection and
187
+ > all. The installer seeds it at `32768` only when your config does not already set one.
188
+ >
189
+ > ZCode keeps no durable session transcript: `Stop` carries the reply plus a temp, assistant-only
190
+ > file it deletes as soon as the hook returns, and no user prompt at all. So this is the one agent
191
+ > whose conversation the plugin journals itself - the prompt hook records what you asked, the
192
+ > `Stop` hook records the reply - and the write-back then behaves like every other agent's,
193
+ > appending each new turn to the same session document. `--import-conversations` is therefore not
194
+ > available for ZCode: there is no past history on disk to backfill from.
195
+
172
196
  #### <img src="https://hindsight.vectorize.io/img/harness/antigravity-cli.png" alt="" width="20" height="20" /> Antigravity CLI
173
197
 
174
198
  ```bash
@@ -503,8 +527,8 @@ hook by Codex...), so one shared config serves several agents side by side:
503
527
  | `reflectBudget` | `"high"` | reflect budget for the `hindsight_reflect` tool: `"low"`, `"mid"` or `"high"`. Drop it on a large bank where high-budget synthesis exceeds the server's wall timeout. The automatic session-start reflect always uses `"low"` to fit its hook window and is unaffected |
504
528
  | `autoReflect` | `true` | inject a one-time reflect synthesis on the session's **first prompt**. `false` = tool-only reflect: nothing is injected; the agent searches knowledge pages first and reflects only when they are too shallow |
505
529
  | `pageRefreshEveryTurns` | `10` | refetch the knowledge pages and re-inject the page roster + tool guide every N user turns |
506
- | `pageTriggerType` | `"auto-refresh"` | when NEW knowledge pages refresh, i.e. what keeping them current costs — `"auto-refresh"` after every consolidation that produced new material, `"cron"` on `pageTriggerCron` only, `"manual"` never on their own. Auto-refresh is the most current and the most expensive: one synthesis per page per consolidation. Maps to the page's `trigger.refresh_after_consolidation` in the Hindsight API (`true` for auto-refresh, `false` for manual) |
507
- | `pageTriggerCron` | — | schedule for `pageTriggerType: "cron"` — UTC, standard 5-field cron, e.g. `"0 3 * * *"`. Sets the page's `trigger.refresh_cron`, which the API treats as mutually exclusive with `refresh_after_consolidation`; a scheduled refresh is skipped when nothing changed. Write a field as `H` to give each page its own value there — see **Spreading refreshes with `H`** below |
530
+ | `pageTriggerType` | `"cron"` | when NEW knowledge pages refresh, i.e. what keeping them current costs — `"cron"` (default) on `pageTriggerCron` only and only when actually stale, `"auto-refresh"` after every consolidation that produced new material, `"manual"` never on their own. Auto-refresh is the most current and by far the most expensive: one synthesis per page per consolidation. Maps to the page's `trigger.refresh_cron`, or `trigger.refresh_after_consolidation` in the Hindsight API (`true` for auto-refresh, `false` for manual) |
531
+ | `pageTriggerCron` | `"H * * * *"` | schedule for `pageTriggerType: "cron"` — UTC, standard 5-field cron, e.g. `"0 3 * * *"`. The default is hourly, each page on its own hashed minute. Sets the page's `trigger.refresh_cron`, which the API treats as mutually exclusive with `refresh_after_consolidation`; a scheduled refresh is skipped when nothing changed. Write a field as `H` to give each page its own value there — see **Spreading refreshes with `H`** below |
508
532
  | `autoSeed` | `true` | SessionStart: auto-seed a cold repo's bank from git history |
509
533
  | `seedLimit` | `300` | auto-seed: most-recent-N-commits cap |
510
534
  | `codebaseSurvey` | `true` | SessionStart: headless survey of a cold repo's structure, run under the current harness's own CLI (claude/codex/antigravity/opencode), falling back to any available agent |
@@ -519,6 +543,12 @@ hook by Codex...), so one shared config serves several agents side by side:
519
543
  | `harnesses.<name>` | — | per-harness override of any field above |
520
544
  | `harness` | `opencode` | **deepen engine only**: which session format `--conversations` is read as |
521
545
 
546
+ By default a page refreshes **hourly, staggered**: `pageTriggerCron` is `"H * * * *"`, so every
547
+ page gets its own minute of the hour (see below) and a tick with nothing new to fold in is skipped
548
+ server-side. That keeps pages within an hour of the repo without paying auto-refresh's price — one
549
+ LLM synthesis per page per consolidation, on a repo that consolidates all day. Set
550
+ `pageTriggerType: "auto-refresh"` to go back to refreshing on every consolidation.
551
+
522
552
  `pageTriggerType`/`pageTriggerCron` decide only **when** a page refreshes. **How** it refreshes
523
553
  belongs to the server: Hindsight creates a knowledge page with a delta refresh (each pass edits the
524
554
  page instead of rebuilding it) that doesn't reflect over sibling pages, and these settings merge
@@ -548,11 +578,15 @@ problem. It never reaches the API: the plugin resolves it to an ordinary cron ex
548
578
  one you can edit. Hashing spreads pages out, it does not partition them — two pages can still land
549
579
  on the same minute, just not all of them.
550
580
 
551
- **These settings apply to pages created from here on.** Changing them does not migrate the pages a
552
- repo already has: a page keeps the trigger it was created with, so a bank seeded before you set
553
- `"manual"` keeps refreshing on every consolidation. To move an existing page, change its trigger
554
- through the API (`PATCH /knowledge-base/nodes/{id}`), an SDK, or the control plane — or delete it
555
- and let the next session seed it again.
581
+ **These settings apply to the pages a repo already has, too.** Every session compares each page
582
+ this plugin created — the seeded taxonomy and every captured initiative — against the config and
583
+ re-syncs the ones that differ, so a bank seeded before this default changed moves onto the hourly
584
+ schedule by itself, and a page you retriggered by hand in the control plane is put back on the
585
+ configured policy the next time an agent runs. The config
586
+ file is the source of truth for these pages: to give one a different schedule, change
587
+ `pageTriggerType`/`pageTriggerCron` (per bank, if it is only that repo) rather than editing the
588
+ page. Only the fields this plugin states are touched — a page's `mode`, its excluded siblings and
589
+ its minimum refresh interval are left exactly as they are.
556
590
 
557
591
  ### A bank you shape yourself — `manageBankConfig`
558
592
 
@@ -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";
@@ -471,6 +471,7 @@ function pagesFor(project) {
471
471
  var PAGE_MAX_TOKENS = 4096;
472
472
  var PAGE_TAGS_MATCH = "all";
473
473
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
474
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
474
475
  var CRON_FIELD_RANGES = [
475
476
  [0, 59],
476
477
  // minute
@@ -524,14 +525,23 @@ function pageTriggerFor(trigger, bank, page) {
524
525
  function buildPageTrigger(cfg = {}) {
525
526
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
526
527
  switch (cfg.pageTriggerType) {
527
- case "cron":
528
- return { ...base, refresh_cron: cfg.pageTriggerCron };
528
+ case "auto-refresh":
529
+ return { ...base, refresh_after_consolidation: true };
529
530
  case "manual":
530
531
  return { ...base, refresh_after_consolidation: false };
532
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
533
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
531
534
  default:
532
- return { ...base, refresh_after_consolidation: true };
535
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
533
536
  }
534
537
  }
538
+ function pageTriggerDrifted(current2, desired) {
539
+ 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);
540
+ }
541
+ function pageTriggerPatch(desired) {
542
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
543
+ return desired;
544
+ }
535
545
  var CODING_BANK_TEMPLATE = {
536
546
  version: "1",
537
547
  bank: {
@@ -1071,14 +1081,14 @@ var HindsightClient = class {
1071
1081
  if (r.status !== 409) created++;
1072
1082
  } else {
1073
1083
  const sourceDrift = hit.description !== page.source_query;
1074
- const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1084
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1075
1085
  if (!sourceDrift && !triggerDrift) continue;
1076
1086
  const patch = {};
1077
1087
  if (sourceDrift) {
1078
1088
  patch.source_query = page.source_query;
1079
1089
  patch.tags = page.tags;
1080
1090
  }
1081
- if (triggerDrift) patch.trigger = pageTrigger;
1091
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1082
1092
  const r = await this.req(
1083
1093
  "PATCH",
1084
1094
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
@@ -1094,10 +1104,42 @@ var HindsightClient = class {
1094
1104
  updated++;
1095
1105
  }
1096
1106
  }
1107
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1097
1108
  this.log(
1098
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1109
+ `[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` : "")
1099
1110
  );
1100
1111
  }
1112
+ /**
1113
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1114
+ *
1115
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1116
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1117
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1118
+ * consolidation under the auto-refresh that used to be the default (#3506).
1119
+ *
1120
+ * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1121
+ * initiative's own title, and re-stating either would rebuild a page whose question never
1122
+ * changed. The tree read above is reused rather than re-fetched.
1123
+ */
1124
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1125
+ const folder = roots.find(
1126
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1127
+ );
1128
+ let updated = 0;
1129
+ for (const page of folder?.children ?? []) {
1130
+ if (page.kind !== "page" || page.trigger == null) continue;
1131
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1132
+ if (!pageTriggerDrifted(page.trigger, desired)) continue;
1133
+ const r = await this.req(
1134
+ "PATCH",
1135
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1136
+ { trigger: pageTriggerPatch(desired) }
1137
+ );
1138
+ if ([404, 405, 501].includes(r.status)) break;
1139
+ updated++;
1140
+ }
1141
+ return updated;
1142
+ }
1101
1143
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1102
1144
  slugify(s) {
1103
1145
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
@@ -1119,11 +1161,13 @@ var HindsightClient = class {
1119
1161
  let pageId = args.relatesToPageId;
1120
1162
  if (!pageId) {
1121
1163
  const folderId = await this.ensureFolder("Initiatives");
1164
+ const subject = this.project ?? this.bank;
1122
1165
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1123
1166
  name: args.title,
1124
- 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.`,
1167
+ 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),
1125
1168
  parent_id: folderId,
1126
1169
  tags: ["knowledge:feature-work"],
1170
+ max_tokens: PAGE_MAX_TOKENS,
1127
1171
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1128
1172
  });
1129
1173
  try {
@@ -1166,17 +1210,22 @@ var HindsightClient = class {
1166
1210
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1167
1211
  var DEFAULT_DAEMON_PORT = 9077;
1168
1212
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1169
- function resolvePageTriggerType(raw) {
1170
- if (raw.pageTriggerType === "manual") return "manual";
1171
- if (raw.pageTriggerType === "cron") {
1172
- const cron = raw.pageTriggerCron?.trim();
1173
- if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1213
+ function resolvePageTrigger(raw) {
1214
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1215
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1216
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1174
1217
  log.warn(
1175
1218
  "config",
1176
- 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"'
1219
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1177
1220
  );
1178
- }
1179
- return "auto-refresh";
1221
+ const cron = raw.pageTriggerCron?.trim();
1222
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1223
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1224
+ log.warn(
1225
+ "config",
1226
+ `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)}`
1227
+ );
1228
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1180
1229
  }
1181
1230
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1182
1231
  var REFLECT_BUDGETS = ["low", "mid", "high"];
@@ -1208,6 +1257,7 @@ function resolveObservationScopes(raw) {
1208
1257
  function resolveConfig(raw = {}) {
1209
1258
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1210
1259
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1260
+ const pageTrigger = resolvePageTrigger(raw);
1211
1261
  return {
1212
1262
  serverMode,
1213
1263
  // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
@@ -1242,8 +1292,8 @@ function resolveConfig(raw = {}) {
1242
1292
  reflectBudget: resolveReflectBudget(raw),
1243
1293
  autoReflect: raw.autoReflect ?? true,
1244
1294
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1245
- pageTriggerType: resolvePageTriggerType(raw),
1246
- pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1295
+ pageTriggerType: pageTrigger.type,
1296
+ pageTriggerCron: pageTrigger.cron,
1247
1297
  autoSeed: raw.autoSeed ?? true,
1248
1298
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1249
1299
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1541,6 +1591,102 @@ function sessionRootDir(harness, sessionId, cwd) {
1541
1591
  return cwd;
1542
1592
  }
1543
1593
 
1594
+ // src/core/turn-journal.ts
1595
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync } from "fs";
1596
+ import { tmpdir as tmpdir3 } from "os";
1597
+ import { dirname as dirname6, join as join8 } from "path";
1598
+
1599
+ // src/core/transcript-util.ts
1600
+ 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;
1601
+ function stripInjectedMemory(s) {
1602
+ return s.replace(MEMORY_TAG_RE, "");
1603
+ }
1604
+ var TARGET_KEYS = [
1605
+ "file_path",
1606
+ "path",
1607
+ "notebook_path",
1608
+ "command",
1609
+ "pattern",
1610
+ "query",
1611
+ "url",
1612
+ "name",
1613
+ "id"
1614
+ ];
1615
+ var ACTION_TARGET_CAP = 100;
1616
+ function actionLine(tool, input) {
1617
+ let target = "";
1618
+ if (input && typeof input === "object") {
1619
+ const rec = input;
1620
+ for (const k of TARGET_KEYS) {
1621
+ const v = rec[k];
1622
+ if (typeof v === "string" && v.trim()) {
1623
+ target = v.trim().split("\n")[0];
1624
+ break;
1625
+ }
1626
+ }
1627
+ } else if (typeof input === "string") {
1628
+ target = input.trim().split("\n")[0];
1629
+ }
1630
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1631
+ return target ? `${tool} ${target}` : tool;
1632
+ }
1633
+
1634
+ // src/core/turn-journal.ts
1635
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1636
+ function journalPath(harness, sessionId) {
1637
+ return join8(tmpdir3(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1638
+ }
1639
+ function appendJournalTurn(path, turn) {
1640
+ const content = stripInjectedMemory(turn.content ?? "").trim();
1641
+ if (!content) return;
1642
+ try {
1643
+ if (statSync(path).size >= JOURNAL_MAX_BYTES) return;
1644
+ } catch {
1645
+ }
1646
+ const last = readJournalTranscript(path).at(-1);
1647
+ if (last && last.role === turn.role && last.content === content) return;
1648
+ try {
1649
+ mkdirSync3(dirname6(path), { recursive: true });
1650
+ appendFileSync3(
1651
+ path,
1652
+ JSON.stringify({
1653
+ role: turn.role,
1654
+ content,
1655
+ timestamp: turn.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
1656
+ }) + "\n"
1657
+ );
1658
+ } catch {
1659
+ }
1660
+ }
1661
+ function readJournalTranscript(path) {
1662
+ let body;
1663
+ try {
1664
+ body = readFileSync4(path, "utf8");
1665
+ } catch {
1666
+ return [];
1667
+ }
1668
+ const turns = [];
1669
+ for (const line of body.split("\n")) {
1670
+ const trimmed = line.trim();
1671
+ if (!trimmed) continue;
1672
+ let parsed;
1673
+ try {
1674
+ parsed = JSON.parse(trimmed);
1675
+ } catch {
1676
+ continue;
1677
+ }
1678
+ if (typeof parsed !== "object" || parsed === null) continue;
1679
+ const { role, content, timestamp } = parsed;
1680
+ if (typeof role !== "string" || typeof content !== "string" || !content) continue;
1681
+ turns.push({
1682
+ role,
1683
+ content,
1684
+ ...typeof timestamp === "string" ? { timestamp } : {}
1685
+ });
1686
+ }
1687
+ return turns;
1688
+ }
1689
+
1544
1690
  // src/core/hook.ts
1545
1691
  var HOOK_REFLECT_CAP_MS = 25e3;
1546
1692
  async function buildHookOutput(args) {
@@ -1631,7 +1777,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1631
1777
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
1632
1778
  let ev = {};
1633
1779
  try {
1634
- ev = JSON.parse(readFileSync4(0, "utf8"));
1780
+ ev = JSON.parse(readFileSync5(0, "utf8"));
1635
1781
  } catch {
1636
1782
  return;
1637
1783
  }
@@ -1646,6 +1792,9 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1646
1792
  log.debug(spec.harness, "hook skipped: disabled");
1647
1793
  return;
1648
1794
  }
1795
+ if (spec.journalPrompt) {
1796
+ appendJournalTurn(journalPath(spec.harness, sessionId), { role: "user", content: prompt });
1797
+ }
1649
1798
  const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
1650
1799
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
1651
1800
  const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
@@ -1676,7 +1825,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1676
1825
  }
1677
1826
 
1678
1827
  // src/core/retain-hook.ts
1679
- import { readFileSync as readFileSync5 } from "fs";
1828
+ import { readFileSync as readFileSync6 } from "fs";
1680
1829
 
1681
1830
  // src/core/retain-cursor.ts
1682
1831
  import { createHash as createHash2 } from "crypto";
@@ -1688,14 +1837,14 @@ import { createHash as createHash3 } from "crypto";
1688
1837
 
1689
1838
  // src/core/daemon.ts
1690
1839
  import { execFileSync, spawn as realSpawn2 } from "child_process";
1691
- import { dirname as dirname6, join as join8 } from "path";
1840
+ import { dirname as dirname7, join as join9 } from "path";
1692
1841
  import { fileURLToPath as fileURLToPath2 } from "url";
1693
1842
 
1694
1843
  // src/core/retain-stamp.ts
1695
1844
  import { basename as basename2 } from "path";
1696
1845
 
1697
1846
  // src/core/jsonl.ts
1698
- import { closeSync, openSync, readSync, statSync } from "fs";
1847
+ import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
1699
1848
  import { StringDecoder } from "string_decoder";
1700
1849
  var CHUNK_BYTES = 64 * 1024;
1701
1850
  var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
@@ -1703,7 +1852,7 @@ function readJsonlTail(path, opts) {
1703
1852
  const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1704
1853
  let size;
1705
1854
  try {
1706
- size = statSync(path).size;
1855
+ size = statSync2(path).size;
1707
1856
  } catch {
1708
1857
  return { lines: emptyLines(), skippedBytes: 0 };
1709
1858
  }
@@ -1755,43 +1904,8 @@ function* streamLines(path, start) {
1755
1904
  }
1756
1905
  }
1757
1906
 
1758
- // src/core/transcript-util.ts
1759
- 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;
1760
- function stripInjectedMemory(s) {
1761
- return s.replace(MEMORY_TAG_RE, "");
1762
- }
1763
- var TARGET_KEYS = [
1764
- "file_path",
1765
- "path",
1766
- "notebook_path",
1767
- "command",
1768
- "pattern",
1769
- "query",
1770
- "url",
1771
- "name",
1772
- "id"
1773
- ];
1774
- var ACTION_TARGET_CAP = 100;
1775
- function actionLine(tool, input) {
1776
- let target = "";
1777
- if (input && typeof input === "object") {
1778
- const rec = input;
1779
- for (const k of TARGET_KEYS) {
1780
- const v = rec[k];
1781
- if (typeof v === "string" && v.trim()) {
1782
- target = v.trim().split("\n")[0];
1783
- break;
1784
- }
1785
- }
1786
- } else if (typeof input === "string") {
1787
- target = input.trim().split("\n")[0];
1788
- }
1789
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1790
- return target ? `${tool} ${target}` : tool;
1791
- }
1792
-
1793
1907
  // src/core/session-start.ts
1794
- import { readFileSync as readFileSync8 } from "fs";
1908
+ import { readFileSync as readFileSync9 } from "fs";
1795
1909
 
1796
1910
  // src/core/git.ts
1797
1911
  import { execFileSync as execFileSync2 } from "child_process";
@@ -1804,29 +1918,29 @@ import { execFileSync as execFileSync3 } from "child_process";
1804
1918
  import { spawn as realSpawn3 } from "child_process";
1805
1919
  import { existsSync as existsSync3 } from "fs";
1806
1920
  import { homedir as homedir3 } from "os";
1807
- import { dirname as dirname7, join as join9 } from "path";
1921
+ import { dirname as dirname8, join as join10 } from "path";
1808
1922
  import { fileURLToPath as fileURLToPath3 } from "url";
1809
1923
 
1810
1924
  // src/core/auto-update.ts
1811
1925
  import { spawn as realSpawn4 } from "child_process";
1812
1926
  import {
1813
1927
  existsSync as existsSync4,
1814
- mkdirSync as mkdirSync3,
1815
- readFileSync as readFileSync6,
1928
+ mkdirSync as mkdirSync4,
1929
+ readFileSync as readFileSync7,
1816
1930
  realpathSync as realpathSync2,
1817
1931
  unlinkSync,
1818
1932
  writeFileSync as writeFileSync2
1819
1933
  } from "fs";
1820
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
1821
- import { dirname as dirname8, join as join10 } from "path";
1934
+ import { homedir as homedir4, tmpdir as tmpdir4 } from "os";
1935
+ import { dirname as dirname9, join as join11 } from "path";
1822
1936
  import { fileURLToPath as fileURLToPath4 } from "url";
1823
1937
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1824
1938
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1825
1939
 
1826
1940
  // src/core/skill-sync.ts
1827
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
1941
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
1828
1942
  import { homedir as homedir5 } from "os";
1829
- import { dirname as dirname9, join as join11 } from "path";
1943
+ import { dirname as dirname10, join as join12 } from "path";
1830
1944
  import { fileURLToPath as fileURLToPath5 } from "url";
1831
1945
 
1832
1946
  // src/core/transcript-codex.ts
@@ -1959,19 +2073,19 @@ function readCopilotTranscript(path) {
1959
2073
  }
1960
2074
 
1961
2075
  // src/core/transcript-grok.ts
1962
- import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2076
+ import { existsSync as existsSync6, readFileSync as readFileSync10, readdirSync } from "fs";
1963
2077
  import { homedir as homedir6 } from "os";
1964
- import { join as join12 } from "path";
2078
+ import { join as join13 } from "path";
1965
2079
  var CHAT_HISTORY = "chat_history.jsonl";
1966
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
1967
- const sessionsDir = join12(grokHome, "sessions");
1968
- const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2080
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join13(homedir6(), ".grok")) {
2081
+ const sessionsDir = join13(grokHome, "sessions");
2082
+ const direct = join13(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1969
2083
  if (existsSync6(direct)) return direct;
1970
2084
  try {
1971
2085
  for (const candidate of readdirSync(sessionsDir)) {
1972
- const directory = join12(sessionsDir, candidate);
1973
- if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
1974
- return join12(directory, sessionId, CHAT_HISTORY);
2086
+ const directory = join13(sessionsDir, candidate);
2087
+ if (readFileSync10(join13(directory, ".cwd"), "utf8").trim() === cwd) {
2088
+ return join13(directory, sessionId, CHAT_HISTORY);
1975
2089
  }
1976
2090
  }
1977
2091
  } catch {
@@ -2009,9 +2123,9 @@ function readGrokTranscript(path) {
2009
2123
  import { existsSync as existsSync7 } from "fs";
2010
2124
  import { createRequire } from "module";
2011
2125
  import { homedir as homedir7 } from "os";
2012
- import { join as join13 } from "path";
2126
+ import { join as join14 } from "path";
2013
2127
  function devinSessionDb(home = homedir7()) {
2014
- return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2128
+ return join14(home, ".local", "share", "devin", "cli", "sessions.db");
2015
2129
  }
2016
2130
  function parseDevinMessages(nodes) {
2017
2131
  const messages = /* @__PURE__ */ new Map();
@@ -2320,6 +2434,51 @@ function readDroidTranscript(path) {
2320
2434
  return turns;
2321
2435
  }
2322
2436
 
2437
+ // src/core/transcript-zcode.ts
2438
+ import { readFileSync as readFileSync11 } from "fs";
2439
+ function messageText2(content) {
2440
+ if (typeof content === "string") return content.trim();
2441
+ if (!Array.isArray(content)) return "";
2442
+ return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
2443
+ }
2444
+ function readZcodeTranscript(path) {
2445
+ if (!path) return [];
2446
+ let body;
2447
+ try {
2448
+ body = readFileSync11(path, "utf8");
2449
+ } catch {
2450
+ return [];
2451
+ }
2452
+ const turns = [];
2453
+ for (const line of body.split("\n")) {
2454
+ const trimmed = line.trim();
2455
+ if (!trimmed) continue;
2456
+ let parsed;
2457
+ try {
2458
+ parsed = JSON.parse(trimmed);
2459
+ } catch {
2460
+ continue;
2461
+ }
2462
+ if (typeof parsed !== "object" || parsed === null) continue;
2463
+ const record = parsed;
2464
+ const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
2465
+ const role = typeof message?.role === "string" ? message.role : record.type;
2466
+ if (role !== "user" && role !== "assistant") continue;
2467
+ const content = stripInjectedMemory(messageText2(message?.content)).trim();
2468
+ if (!content) continue;
2469
+ turns.push({
2470
+ role,
2471
+ content,
2472
+ ...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
2473
+ });
2474
+ }
2475
+ return turns;
2476
+ }
2477
+ function zcodeAssistantText(path) {
2478
+ if (!path) return "";
2479
+ return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
2480
+ }
2481
+
2323
2482
  // src/harness/hook-lifecycle.ts
2324
2483
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2325
2484
  var claudePrompt = {
@@ -2360,6 +2519,7 @@ var qwenPrompt = {
2360
2519
  sessionId: ev.session_id
2361
2520
  })
2362
2521
  };
2522
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
2363
2523
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2364
2524
  var antigravityPrompt = {
2365
2525
  harness: "antigravity-cli",
@@ -2702,6 +2862,56 @@ var HOOK_HARNESSES = {
2702
2862
  }),
2703
2863
  readTranscript: readDroidTranscript
2704
2864
  }
2865
+ },
2866
+ /**
2867
+ * ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
2868
+ * Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
2869
+ * with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
2870
+ *
2871
+ * What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
2872
+ * keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
2873
+ * assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
2874
+ * So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
2875
+ * the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
2876
+ * everything downstream (cursor, append, stamping) sees the same full conversation as any host
2877
+ * transcript.
2878
+ */
2879
+ zcode: {
2880
+ configStyle: "process",
2881
+ // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
2882
+ // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
2883
+ timeoutUnit: "milliseconds",
2884
+ install: {
2885
+ sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
2886
+ prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
2887
+ stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
2888
+ },
2889
+ sessionStart: {
2890
+ ...standardSessionStart("zcode"),
2891
+ parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
2892
+ },
2893
+ prompt: {
2894
+ ...claudePrompt,
2895
+ harness: "zcode",
2896
+ journalPrompt: true,
2897
+ parse: (ev) => ({
2898
+ prompt: ev.prompt ?? ev.user_prompt,
2899
+ cwd: ev.cwd,
2900
+ sessionId: zcodeSessionId(ev)
2901
+ })
2902
+ },
2903
+ retain: {
2904
+ hostTimeoutSec: 60,
2905
+ harness: "zcode",
2906
+ // No transcriptPath: the journal supplies it (see `journal` below).
2907
+ parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
2908
+ journal: {
2909
+ // `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
2910
+ // transcript is the fallback when it is absent, and `responsePreview` — which is
2911
+ // TRUNCATED — is the last resort, preferred only over losing the turn entirely.
2912
+ assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
2913
+ }
2914
+ }
2705
2915
  }
2706
2916
  };
2707
2917
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);