@vectorize-io/hindsight-coding-agents 0.5.1 → 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 +84 -9
  2. package/dist/antigravity-hook.js +424 -81
  3. package/dist/antigravity-statusline.js +56 -11
  4. package/dist/antigravity-stop-hook.js +515 -134
  5. package/dist/claude-hook.js +424 -81
  6. package/dist/claude-sessionstart-hook.js +392 -98
  7. package/dist/claude-stop-hook.js +515 -134
  8. package/dist/cline.js +218 -73
  9. package/dist/codex-hook.js +424 -81
  10. package/dist/codex-sessionstart-hook.js +392 -98
  11. package/dist/codex-stop-hook.js +515 -134
  12. package/dist/copilot-hook.js +424 -81
  13. package/dist/copilot-sessionstart-hook.js +392 -98
  14. package/dist/copilot-stop-hook.js +515 -134
  15. package/dist/cursor-hook.js +424 -81
  16. package/dist/cursor-sessionstart-hook.js +392 -98
  17. package/dist/cursor-stop-hook.js +515 -134
  18. package/dist/daemon-start.js +50 -9
  19. package/dist/dcode-hook.js +424 -81
  20. package/dist/dcode-sessionstart-hook.js +392 -98
  21. package/dist/dcode-stop-hook.js +515 -134
  22. package/dist/deepen.js +164 -27
  23. package/dist/devin-hook.js +424 -81
  24. package/dist/devin-sessionstart-hook.js +392 -98
  25. package/dist/devin-stop-hook.js +515 -134
  26. package/dist/droid-hook.js +2920 -0
  27. package/dist/droid-sessionstart-hook.js +3487 -0
  28. package/dist/droid-stop-hook.js +3188 -0
  29. package/dist/dsh.js +260 -109
  30. package/dist/grok-hook.js +424 -81
  31. package/dist/grok-sessionstart-hook.js +392 -98
  32. package/dist/grok-stop-hook.js +515 -134
  33. package/dist/hindsight-seed.js +56 -11
  34. package/dist/index.js +257 -110
  35. package/dist/installer.js +530 -223
  36. package/dist/kilo.js +257 -110
  37. package/dist/mcp-server.js +537 -146
  38. package/dist/opencode2.js +257 -110
  39. package/dist/pi.js +256 -109
  40. package/dist/prime-agent.js +256 -109
  41. package/dist/qwen-hook.js +424 -81
  42. package/dist/qwen-sessionstart-hook.js +392 -98
  43. package/dist/qwen-stop-hook.js +515 -134
  44. package/dist/status.js +128 -20
  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 +11 -5
  49. package/plugin.json +1 -1
  50. package/skill/SKILL.md +42 -8
package/dist/qwen-hook.js CHANGED
@@ -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";
@@ -287,9 +287,13 @@ function isOptedIn(config, directory) {
287
287
  const pathMap = config.mapPathToBank;
288
288
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
289
289
  }
290
- function deriveBankId(config, directory, harness = "coding", sessionRoot) {
290
+ function mappedBank(config, directory, sessionRoot) {
291
291
  const pathMap = config.mapPathToBank;
292
- const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
292
+ if (!directory || !pathMap) return void 0;
293
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
294
+ }
295
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
296
+ const mapped = mappedBank(config, directory, sessionRoot);
293
297
  if (mapped) return mapped;
294
298
  const dynamic = config.dynamicBankId ?? !config.bankId;
295
299
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
@@ -355,6 +359,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
355
359
  }
356
360
 
357
361
  // src/core/missions.ts
362
+ import { createHash } from "crypto";
358
363
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
359
364
  var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
360
365
  var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
@@ -466,17 +471,77 @@ function pagesFor(project) {
466
471
  var PAGE_MAX_TOKENS = 4096;
467
472
  var PAGE_TAGS_MATCH = "all";
468
473
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
474
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
475
+ var CRON_FIELD_RANGES = [
476
+ [0, 59],
477
+ // minute
478
+ [0, 23],
479
+ // hour
480
+ [1, 31],
481
+ // day of month
482
+ [1, 12],
483
+ // month
484
+ [0, 6]
485
+ // day of week
486
+ ];
487
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
488
+ function isHashedCron(cron) {
489
+ return /(^|\s)H/.test(cron);
490
+ }
491
+ function parseHashedCron(cron) {
492
+ const fields = cron.trim().split(/\s+/);
493
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
494
+ for (const [i, field] of fields.entries()) {
495
+ if (!field.startsWith("H")) continue;
496
+ const m = HASHED_FIELD.exec(field);
497
+ if (!m) return void 0;
498
+ if (m[1] === void 0) continue;
499
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
500
+ const [min, max] = CRON_FIELD_RANGES[i];
501
+ if (lo > hi || lo < min || hi > max) return void 0;
502
+ }
503
+ return fields;
504
+ }
505
+ function hashedValue(seed, field, lo, hi) {
506
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
507
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
508
+ }
509
+ function expandCronHash(cron, seed) {
510
+ if (!isHashedCron(cron)) return cron;
511
+ const fields = parseHashedCron(cron);
512
+ if (!fields) return cron;
513
+ return fields.map((field, i) => {
514
+ const m = HASHED_FIELD.exec(field);
515
+ if (!m) return field;
516
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
517
+ return String(hashedValue(seed, i, lo, hi));
518
+ }).join(" ");
519
+ }
520
+ function pageTriggerFor(trigger, bank, page) {
521
+ const cron = trigger.refresh_cron;
522
+ if (!cron || !isHashedCron(cron)) return trigger;
523
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
524
+ }
469
525
  function buildPageTrigger(cfg = {}) {
470
526
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
471
527
  switch (cfg.pageTriggerType) {
472
- case "cron":
473
- return { ...base, refresh_cron: cfg.pageTriggerCron };
528
+ case "auto-refresh":
529
+ return { ...base, refresh_after_consolidation: true };
474
530
  case "manual":
475
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.
476
534
  default:
477
- return { ...base, refresh_after_consolidation: true };
535
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
478
536
  }
479
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
+ }
480
545
  var CODING_BANK_TEMPLATE = {
481
546
  version: "1",
482
547
  bank: {
@@ -1000,7 +1065,9 @@ var HindsightClient = class {
1000
1065
  source_query: page.source_query,
1001
1066
  tags: page.tags,
1002
1067
  max_tokens: PAGE_MAX_TOKENS,
1003
- trigger: pageTrigger
1068
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1069
+ // and one trigger is built per session for all of them.
1070
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1004
1071
  };
1005
1072
  if (!hit) {
1006
1073
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -1014,14 +1081,14 @@ var HindsightClient = class {
1014
1081
  if (r.status !== 409) created++;
1015
1082
  } else {
1016
1083
  const sourceDrift = hit.description !== page.source_query;
1017
- const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1084
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1018
1085
  if (!sourceDrift && !triggerDrift) continue;
1019
1086
  const patch = {};
1020
1087
  if (sourceDrift) {
1021
1088
  patch.source_query = page.source_query;
1022
1089
  patch.tags = page.tags;
1023
1090
  }
1024
- if (triggerDrift) patch.trigger = pageTrigger;
1091
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1025
1092
  const r = await this.req(
1026
1093
  "PATCH",
1027
1094
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
@@ -1037,10 +1104,42 @@ var HindsightClient = class {
1037
1104
  updated++;
1038
1105
  }
1039
1106
  }
1107
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1040
1108
  this.log(
1041
- `[bank] knowledge pages seeded on ${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` : "")
1042
1110
  );
1043
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
+ }
1044
1143
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1045
1144
  slugify(s) {
1046
1145
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
@@ -1062,12 +1161,14 @@ var HindsightClient = class {
1062
1161
  let pageId = args.relatesToPageId;
1063
1162
  if (!pageId) {
1064
1163
  const folderId = await this.ensureFolder("Initiatives");
1164
+ const subject = this.project ?? this.bank;
1065
1165
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1066
1166
  name: args.title,
1067
- 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),
1068
1168
  parent_id: folderId,
1069
1169
  tags: ["knowledge:feature-work"],
1070
- trigger: args.pageTrigger ?? buildPageTrigger()
1170
+ max_tokens: PAGE_MAX_TOKENS,
1171
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1071
1172
  });
1072
1173
  try {
1073
1174
  const j = await r.json();
@@ -1109,16 +1210,22 @@ var HindsightClient = class {
1109
1210
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1110
1211
  var DEFAULT_DAEMON_PORT = 9077;
1111
1212
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1112
- function resolvePageTriggerType(raw) {
1113
- if (raw.pageTriggerType === "manual") return "manual";
1114
- if (raw.pageTriggerType === "cron") {
1115
- if (raw.pageTriggerCron?.trim()) 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")
1116
1217
  log.warn(
1117
1218
  "config",
1118
- 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
1219
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1119
1220
  );
1120
- }
1121
- 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 };
1122
1229
  }
1123
1230
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1124
1231
  var REFLECT_BUDGETS = ["low", "mid", "high"];
@@ -1150,6 +1257,7 @@ function resolveObservationScopes(raw) {
1150
1257
  function resolveConfig(raw = {}) {
1151
1258
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1152
1259
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1260
+ const pageTrigger = resolvePageTrigger(raw);
1153
1261
  return {
1154
1262
  serverMode,
1155
1263
  // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
@@ -1184,8 +1292,8 @@ function resolveConfig(raw = {}) {
1184
1292
  reflectBudget: resolveReflectBudget(raw),
1185
1293
  autoReflect: raw.autoReflect ?? true,
1186
1294
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1187
- pageTriggerType: resolvePageTriggerType(raw),
1188
- pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1295
+ pageTriggerType: pageTrigger.type,
1296
+ pageTriggerCron: pageTrigger.cron,
1189
1297
  autoSeed: raw.autoSeed ?? true,
1190
1298
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1191
1299
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1483,6 +1591,102 @@ function sessionRootDir(harness, sessionId, cwd) {
1483
1591
  return cwd;
1484
1592
  }
1485
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
+
1486
1690
  // src/core/hook.ts
1487
1691
  var HOOK_REFLECT_CAP_MS = 25e3;
1488
1692
  async function buildHookOutput(args) {
@@ -1573,7 +1777,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1573
1777
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
1574
1778
  let ev = {};
1575
1779
  try {
1576
- ev = JSON.parse(readFileSync4(0, "utf8"));
1780
+ ev = JSON.parse(readFileSync5(0, "utf8"));
1577
1781
  } catch {
1578
1782
  return;
1579
1783
  }
@@ -1588,6 +1792,9 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1588
1792
  log.debug(spec.harness, "hook skipped: disabled");
1589
1793
  return;
1590
1794
  }
1795
+ if (spec.journalPrompt) {
1796
+ appendJournalTurn(journalPath(spec.harness, sessionId), { role: "user", content: prompt });
1797
+ }
1591
1798
  const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
1592
1799
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
1593
1800
  const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
@@ -1618,24 +1825,26 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1618
1825
  }
1619
1826
 
1620
1827
  // src/core/retain-hook.ts
1621
- import { readFileSync as readFileSync5 } from "fs";
1828
+ import { readFileSync as readFileSync6 } from "fs";
1622
1829
 
1623
1830
  // src/core/retain-cursor.ts
1624
- import { createHash } from "crypto";
1831
+ import { createHash as createHash2 } from "crypto";
1832
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1833
+ var PENDING_MAX_BYTES = 256 * 1024;
1625
1834
 
1626
1835
  // src/core/uuid.ts
1627
- import { createHash as createHash2 } from "crypto";
1836
+ import { createHash as createHash3 } from "crypto";
1628
1837
 
1629
1838
  // src/core/daemon.ts
1630
1839
  import { execFileSync, spawn as realSpawn2 } from "child_process";
1631
- import { dirname as dirname6, join as join8 } from "path";
1840
+ import { dirname as dirname7, join as join9 } from "path";
1632
1841
  import { fileURLToPath as fileURLToPath2 } from "url";
1633
1842
 
1634
1843
  // src/core/retain-stamp.ts
1635
1844
  import { basename as basename2 } from "path";
1636
1845
 
1637
1846
  // src/core/jsonl.ts
1638
- import { closeSync, openSync, readSync, statSync } from "fs";
1847
+ import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
1639
1848
  import { StringDecoder } from "string_decoder";
1640
1849
  var CHUNK_BYTES = 64 * 1024;
1641
1850
  var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
@@ -1643,7 +1852,7 @@ function readJsonlTail(path, opts) {
1643
1852
  const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1644
1853
  let size;
1645
1854
  try {
1646
- size = statSync(path).size;
1855
+ size = statSync2(path).size;
1647
1856
  } catch {
1648
1857
  return { lines: emptyLines(), skippedBytes: 0 };
1649
1858
  }
@@ -1695,43 +1904,8 @@ function* streamLines(path, start) {
1695
1904
  }
1696
1905
  }
1697
1906
 
1698
- // src/core/transcript-util.ts
1699
- 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;
1700
- function stripInjectedMemory(s) {
1701
- return s.replace(MEMORY_TAG_RE, "");
1702
- }
1703
- var TARGET_KEYS = [
1704
- "file_path",
1705
- "path",
1706
- "notebook_path",
1707
- "command",
1708
- "pattern",
1709
- "query",
1710
- "url",
1711
- "name",
1712
- "id"
1713
- ];
1714
- var ACTION_TARGET_CAP = 100;
1715
- function actionLine(tool, input) {
1716
- let target = "";
1717
- if (input && typeof input === "object") {
1718
- const rec = input;
1719
- for (const k of TARGET_KEYS) {
1720
- const v = rec[k];
1721
- if (typeof v === "string" && v.trim()) {
1722
- target = v.trim().split("\n")[0];
1723
- break;
1724
- }
1725
- }
1726
- } else if (typeof input === "string") {
1727
- target = input.trim().split("\n")[0];
1728
- }
1729
- if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1730
- return target ? `${tool} ${target}` : tool;
1731
- }
1732
-
1733
1907
  // src/core/session-start.ts
1734
- import { readFileSync as readFileSync8 } from "fs";
1908
+ import { readFileSync as readFileSync9 } from "fs";
1735
1909
 
1736
1910
  // src/core/git.ts
1737
1911
  import { execFileSync as execFileSync2 } from "child_process";
@@ -1744,29 +1918,29 @@ import { execFileSync as execFileSync3 } from "child_process";
1744
1918
  import { spawn as realSpawn3 } from "child_process";
1745
1919
  import { existsSync as existsSync3 } from "fs";
1746
1920
  import { homedir as homedir3 } from "os";
1747
- import { dirname as dirname7, join as join9 } from "path";
1921
+ import { dirname as dirname8, join as join10 } from "path";
1748
1922
  import { fileURLToPath as fileURLToPath3 } from "url";
1749
1923
 
1750
1924
  // src/core/auto-update.ts
1751
1925
  import { spawn as realSpawn4 } from "child_process";
1752
1926
  import {
1753
1927
  existsSync as existsSync4,
1754
- mkdirSync as mkdirSync3,
1755
- readFileSync as readFileSync6,
1928
+ mkdirSync as mkdirSync4,
1929
+ readFileSync as readFileSync7,
1756
1930
  realpathSync as realpathSync2,
1757
1931
  unlinkSync,
1758
1932
  writeFileSync as writeFileSync2
1759
1933
  } from "fs";
1760
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
1761
- 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";
1762
1936
  import { fileURLToPath as fileURLToPath4 } from "url";
1763
1937
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1764
1938
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1765
1939
 
1766
1940
  // src/core/skill-sync.ts
1767
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
1941
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
1768
1942
  import { homedir as homedir5 } from "os";
1769
- import { dirname as dirname9, join as join11 } from "path";
1943
+ import { dirname as dirname10, join as join12 } from "path";
1770
1944
  import { fileURLToPath as fileURLToPath5 } from "url";
1771
1945
 
1772
1946
  // src/core/transcript-codex.ts
@@ -1899,19 +2073,19 @@ function readCopilotTranscript(path) {
1899
2073
  }
1900
2074
 
1901
2075
  // src/core/transcript-grok.ts
1902
- import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
2076
+ import { existsSync as existsSync6, readFileSync as readFileSync10, readdirSync } from "fs";
1903
2077
  import { homedir as homedir6 } from "os";
1904
- import { join as join12 } from "path";
2078
+ import { join as join13 } from "path";
1905
2079
  var CHAT_HISTORY = "chat_history.jsonl";
1906
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
1907
- const sessionsDir = join12(grokHome, "sessions");
1908
- 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);
1909
2083
  if (existsSync6(direct)) return direct;
1910
2084
  try {
1911
2085
  for (const candidate of readdirSync(sessionsDir)) {
1912
- const directory = join12(sessionsDir, candidate);
1913
- if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
1914
- 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);
1915
2089
  }
1916
2090
  }
1917
2091
  } catch {
@@ -1949,9 +2123,9 @@ function readGrokTranscript(path) {
1949
2123
  import { existsSync as existsSync7 } from "fs";
1950
2124
  import { createRequire } from "module";
1951
2125
  import { homedir as homedir7 } from "os";
1952
- import { join as join13 } from "path";
2126
+ import { join as join14 } from "path";
1953
2127
  function devinSessionDb(home = homedir7()) {
1954
- return join13(home, ".local", "share", "devin", "cli", "sessions.db");
2128
+ return join14(home, ".local", "share", "devin", "cli", "sessions.db");
1955
2129
  }
1956
2130
  function parseDevinMessages(nodes) {
1957
2131
  const messages = /* @__PURE__ */ new Map();
@@ -2216,6 +2390,95 @@ function collectQwenTurns(path, turns) {
2216
2390
  }
2217
2391
  }
2218
2392
 
2393
+ // src/core/transcript-droid.ts
2394
+ function renderContent(content, role) {
2395
+ if (!Array.isArray(content)) return [];
2396
+ const texts = [];
2397
+ const actions = [];
2398
+ for (const block of content) {
2399
+ if (!block || typeof block !== "object") continue;
2400
+ const b = block;
2401
+ if (b.type === "text" && typeof b.text === "string") {
2402
+ const text = stripInjectedMemory(b.text).trim();
2403
+ if (text) texts.push(text);
2404
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2405
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2406
+ }
2407
+ }
2408
+ const out = [];
2409
+ const joined = texts.join("\n").trim();
2410
+ if (joined) out.push({ role, content: joined });
2411
+ out.push(...actions);
2412
+ return out;
2413
+ }
2414
+ function readDroidTranscript(path) {
2415
+ const turns = [];
2416
+ for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
2417
+ if (!rawLine.trim()) continue;
2418
+ let parsed;
2419
+ try {
2420
+ parsed = JSON.parse(rawLine);
2421
+ } catch {
2422
+ continue;
2423
+ }
2424
+ if (!parsed || typeof parsed !== "object") continue;
2425
+ const line = parsed;
2426
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
2427
+ const message = line.message;
2428
+ const role = message.role;
2429
+ if (role !== "user" && role !== "assistant") continue;
2430
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
2431
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2432
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
2433
+ }
2434
+ return turns;
2435
+ }
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
+
2219
2482
  // src/harness/hook-lifecycle.ts
2220
2483
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2221
2484
  var claudePrompt = {
@@ -2243,6 +2506,10 @@ var dcodePrompt = {
2243
2506
  ...claudePrompt,
2244
2507
  harness: "dcode"
2245
2508
  };
2509
+ var droidPrompt = {
2510
+ ...claudePrompt,
2511
+ harness: "factory-droid"
2512
+ };
2246
2513
  var qwenPrompt = {
2247
2514
  ...claudePrompt,
2248
2515
  harness: "qwen-code",
@@ -2252,6 +2519,7 @@ var qwenPrompt = {
2252
2519
  sessionId: ev.session_id
2253
2520
  })
2254
2521
  };
2522
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
2255
2523
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
2256
2524
  var antigravityPrompt = {
2257
2525
  harness: "antigravity-cli",
@@ -2569,6 +2837,81 @@ var HOOK_HARNESSES = {
2569
2837
  }),
2570
2838
  readTranscript: readQwenTranscript
2571
2839
  }
2840
+ },
2841
+ "factory-droid": {
2842
+ configStyle: "nested",
2843
+ install: {
2844
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
2845
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
2846
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
2847
+ },
2848
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
2849
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
2850
+ // other notification type before config or daemon work begins.
2851
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
2852
+ sessionStart: standardSessionStart("factory-droid"),
2853
+ prompt: droidPrompt,
2854
+ retain: {
2855
+ hostTimeoutSec: 60,
2856
+ harness: "factory-droid",
2857
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
2858
+ parse: (ev) => ({
2859
+ sessionId: ev.session_id,
2860
+ transcriptPath: ev.transcript_path,
2861
+ cwd: ev.cwd
2862
+ }),
2863
+ readTranscript: readDroidTranscript
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
+ }
2572
2915
  }
2573
2916
  };
2574
2917
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);