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

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 (56) hide show
  1. package/README.md +137 -13
  2. package/dist/antigravity-hook.js +711 -55
  3. package/dist/antigravity-statusline.js +68 -7
  4. package/dist/antigravity-stop-hook.js +771 -57
  5. package/dist/claude-hook.js +711 -55
  6. package/dist/claude-sessionstart-hook.js +789 -68
  7. package/dist/claude-stop-hook.js +771 -57
  8. package/dist/cline.js +295 -75
  9. package/dist/codex-hook.js +711 -55
  10. package/dist/codex-sessionstart-hook.js +789 -68
  11. package/dist/codex-stop-hook.js +771 -57
  12. package/dist/copilot-hook.js +711 -55
  13. package/dist/copilot-sessionstart-hook.js +789 -68
  14. package/dist/copilot-stop-hook.js +771 -57
  15. package/dist/cursor-hook.js +711 -55
  16. package/dist/cursor-sessionstart-hook.js +789 -68
  17. package/dist/cursor-stop-hook.js +771 -57
  18. package/dist/daemon-start.js +38 -1
  19. package/dist/dcode-hook.js +711 -55
  20. package/dist/dcode-sessionstart-hook.js +789 -68
  21. package/dist/dcode-stop-hook.js +771 -57
  22. package/dist/deepen.js +236 -61
  23. package/dist/devin-hook.js +711 -55
  24. package/dist/devin-sessionstart-hook.js +789 -68
  25. package/dist/devin-stop-hook.js +771 -57
  26. package/dist/droid-hook.js +711 -55
  27. package/dist/droid-sessionstart-hook.js +789 -68
  28. package/dist/droid-stop-hook.js +771 -57
  29. package/dist/dsh.js +296 -76
  30. package/dist/grok-hook.js +711 -55
  31. package/dist/grok-sessionstart-hook.js +789 -68
  32. package/dist/grok-stop-hook.js +771 -57
  33. package/dist/hindsight-seed.js +41 -4
  34. package/dist/index.js +295 -75
  35. package/dist/installer.js +1148 -303
  36. package/dist/kilo.js +295 -75
  37. package/dist/kimi-hook.js +3909 -0
  38. package/dist/kimi-sessionstart-hook.js +4650 -0
  39. package/dist/kimi-stop-hook.js +4218 -0
  40. package/dist/mcp-server.js +162 -33
  41. package/dist/opencode2.js +298 -76
  42. package/dist/pi.js +299 -75
  43. package/dist/prime-agent.js +299 -75
  44. package/dist/qwen-hook.js +711 -55
  45. package/dist/qwen-sessionstart-hook.js +789 -68
  46. package/dist/qwen-stop-hook.js +771 -57
  47. package/dist/status.js +132 -14
  48. package/dist/traecode-hook.js +3909 -0
  49. package/dist/traecode-sessionstart-hook.js +4650 -0
  50. package/dist/traecode-stop-hook.js +4218 -0
  51. package/dist/zcode-hook.js +711 -55
  52. package/dist/zcode-sessionstart-hook.js +789 -68
  53. package/dist/zcode-stop-hook.js +771 -57
  54. package/package.json +15 -11
  55. package/plugin.json +1 -1
  56. package/skill/SKILL.md +70 -11
package/dist/deepen.js CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  // src/deepen.ts
4
4
  import { execFileSync as execFileSync3 } from "child_process";
5
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
6
5
  import { tmpdir as tmpdir2 } from "os";
7
6
  import { join as join10 } from "path";
8
7
 
@@ -273,13 +272,13 @@ function isWithin(directory, configured) {
273
272
  function mapLookup(map, directory) {
274
273
  const cwd = normalize(directory);
275
274
  let best;
276
- for (const [dir, bank] of Object.entries(map)) {
275
+ for (const [dir, value] of Object.entries(map)) {
277
276
  const p = configuredDir(dir);
278
277
  if (isWithin(cwd, p)) {
279
- if (!best || p.length > best.len) best = { len: p.length, bank };
278
+ if (!best || p.length > best.len) best = { len: p.length, value };
280
279
  }
281
280
  }
282
- return best?.bank;
281
+ return best?.value;
283
282
  }
284
283
  function lookupDirectories(config, directory, sessionRoot = "") {
285
284
  const directories = [normalize(directory)];
@@ -303,6 +302,10 @@ function isOptedIn(config, directory) {
303
302
  const pathMap = config.mapPathToBank;
304
303
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
305
304
  }
305
+ function pathSection(config, paths, directory) {
306
+ if (!directory || !paths) return void 0;
307
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
308
+ }
306
309
  function mappedBank(config, directory, sessionRoot) {
307
310
  const pathMap = config.mapPathToBank;
308
311
  if (!directory || !pathMap) return void 0;
@@ -563,12 +566,17 @@ var CODING_BANK_TEMPLATE = {
563
566
  }
564
567
  };
565
568
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
569
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
570
+ "retain_strategies",
571
+ "entity_labels",
572
+ "retain_extraction_mode"
573
+ ];
566
574
  function isSet(v) {
567
575
  if (v === null || v === void 0) return false;
568
576
  if (typeof v === "string") return v.trim() !== "";
569
577
  return true;
570
578
  }
571
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
579
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
572
580
  const current2 = overrides ?? {};
573
581
  const template = CODING_BANK_TEMPLATE.bank;
574
582
  const bank = {};
@@ -597,6 +605,10 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
597
605
  const [knowledgeGroup] = template.entity_labels;
598
606
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
599
607
  bank.entity_labels = [...labels, knowledgeGroup];
608
+ for (const [key, value] of Object.entries(defaults)) {
609
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
610
+ bank[key] = value;
611
+ }
600
612
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
601
613
  }
602
614
 
@@ -700,6 +712,18 @@ var DEFAULT_RECALL_OPTIONS = {
700
712
  var POLL_CYCLE_MS = 5e3;
701
713
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
702
714
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
715
+ function shapePage(page) {
716
+ const p = page ?? {};
717
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
718
+ return {
719
+ id: p.id,
720
+ name: p.name,
721
+ ...p.description ? { description: p.description } : {},
722
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
723
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
724
+ body
725
+ };
726
+ }
703
727
  var HindsightClient = class {
704
728
  apiUrl;
705
729
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -737,7 +761,10 @@ var HindsightClient = class {
737
761
  return this.token;
738
762
  }
739
763
  headers() {
740
- const h = { "Content-Type": "application/json" };
764
+ const h = {
765
+ "Content-Type": "application/json",
766
+ "Accept-Encoding": "identity"
767
+ };
741
768
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
742
769
  return h;
743
770
  }
@@ -845,6 +872,23 @@ var HindsightClient = class {
845
872
  return false;
846
873
  }
847
874
  }
875
+ /**
876
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
877
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
878
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
879
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
880
+ */
881
+ async supportsAppendRetain() {
882
+ if (!await this.supportsIdempotentRetain()) return false;
883
+ try {
884
+ const r = await this.req("GET", this.bankUrl("/config"));
885
+ if (!r.ok) return true;
886
+ const j = await r.json();
887
+ return j.config?.store_document_text !== false;
888
+ } catch {
889
+ return true;
890
+ }
891
+ }
848
892
  /**
849
893
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
850
894
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -870,6 +914,24 @@ var HindsightClient = class {
870
914
  }
871
915
  return ids;
872
916
  }
917
+ /**
918
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
919
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
920
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
921
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
922
+ */
923
+ async documentTags(documentId) {
924
+ const limit = 100;
925
+ for (let offset = 0; ; offset += limit) {
926
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
927
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
928
+ const j = await r.json();
929
+ const items = j.items ?? [];
930
+ const hit = items.find((it) => it.id === documentId);
931
+ if (hit) return hit.tags ?? [];
932
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
933
+ }
934
+ }
873
935
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
874
936
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
875
937
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -891,7 +953,8 @@ var HindsightClient = class {
891
953
  } else {
892
954
  const manifest = codingBankManifest(
893
955
  opts.reset ? void 0 : await this.readBankOverrides(),
894
- opts.extractionMode
956
+ opts.extractionMode,
957
+ opts.defaults
895
958
  );
896
959
  if (!manifest) {
897
960
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -1097,8 +1160,8 @@ var HindsightClient = class {
1097
1160
  return { items };
1098
1161
  }
1099
1162
  /**
1100
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1101
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1163
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1164
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1102
1165
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1103
1166
  * token cap.
1104
1167
  */
@@ -1109,7 +1172,7 @@ var HindsightClient = class {
1109
1172
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1110
1173
  );
1111
1174
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1112
- return await r.json();
1175
+ return shapePage(await r.json());
1113
1176
  }
1114
1177
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1115
1178
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1130,6 +1193,7 @@ var HindsightClient = class {
1130
1193
  return (j.results ?? []).map((x) => ({
1131
1194
  id: x.id,
1132
1195
  name: x.name,
1196
+ ...x.source_query ? { source_query: x.source_query } : {},
1133
1197
  snippet: x.snippet ?? "",
1134
1198
  score: x.score ?? 0
1135
1199
  }));
@@ -1350,13 +1414,15 @@ async function ingestChats(client, sessions, opts = {}) {
1350
1414
  const id = s.id || `s${i}`;
1351
1415
  const stamp = opts.stampFor?.(id);
1352
1416
  const sessBase = NOW - (sessions.length - 1 - i) * 36e5;
1353
- const baseIso = new Date(sessBase).toISOString();
1417
+ const sourceTs = (s.turns || []).map((t) => t.timestamp).find((v) => typeof v === "string" && !Number.isNaN(Date.parse(v)));
1418
+ const anchorMs = sourceTs ? Date.parse(sourceTs) : sessBase;
1419
+ const baseIso = sourceTs ?? new Date(sessBase).toISOString();
1354
1420
  const turns = withRefId(
1355
1421
  `chat:${id}`,
1356
1422
  (s.turns || []).map((t, j) => ({
1357
1423
  role: t.role,
1358
1424
  content: t.text,
1359
- timestamp: t.timestamp || new Date(sessBase + (j + 1) * 6e4).toISOString()
1425
+ timestamp: t.timestamp || new Date(anchorMs + (j + 1) * 6e4).toISOString()
1360
1426
  })),
1361
1427
  baseIso
1362
1428
  );
@@ -1476,6 +1542,7 @@ function resolveCustomPages(raw) {
1476
1542
  }
1477
1543
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1478
1544
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1545
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1479
1546
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1480
1547
  function resolveReflectBudget(raw) {
1481
1548
  const value = raw.reflectBudget;
@@ -1502,6 +1569,22 @@ function resolveObservationScopes(raw) {
1502
1569
  }
1503
1570
  return DEFAULT_OBSERVATION_SCOPES;
1504
1571
  }
1572
+ function resolveDefaultBankConfig(raw) {
1573
+ const value = raw;
1574
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1575
+ const out = {};
1576
+ for (const [key, v] of Object.entries(value)) {
1577
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1578
+ log.warn(
1579
+ "config",
1580
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1581
+ );
1582
+ continue;
1583
+ }
1584
+ out[key] = v;
1585
+ }
1586
+ return out;
1587
+ }
1505
1588
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1506
1589
  function resolveAutoInject(raw) {
1507
1590
  if (raw.autoReflect !== void 0) {
@@ -1541,18 +1624,21 @@ function resolveConfig(raw = {}) {
1541
1624
  // write sessions back by default, every harness
1542
1625
  manageBankConfig: raw.manageBankConfig ?? true,
1543
1626
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1627
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1544
1628
  maxParallelRetains: raw.maxParallelRetains || 10,
1545
1629
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1546
1630
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1547
1631
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1548
1632
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1549
1633
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1634
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1550
1635
  reflectBudget: resolveReflectBudget(raw),
1551
1636
  autoInject: resolveAutoInject(raw),
1552
1637
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1553
1638
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1554
1639
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1555
1640
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1641
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1556
1642
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1557
1643
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1558
1644
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1572,11 +1658,15 @@ function resolveConfig(raw = {}) {
1572
1658
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1573
1659
  // nested object cannot reach the API as a tag and fail the whole retain.
1574
1660
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1661
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1662
+ // the built-in default) from a configured value, and an empty context would strip the default.
1663
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1575
1664
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1576
1665
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1577
1666
  ) : {},
1578
1667
  observationScopes: resolveObservationScopes(raw.observationScopes),
1579
1668
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1669
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1580
1670
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1581
1671
  autoUpdate: raw.autoUpdate ?? true
1582
1672
  };
@@ -1593,7 +1683,12 @@ function readRaw(path) {
1593
1683
  }
1594
1684
  function mergeRaw(a, b) {
1595
1685
  const { harnesses: _drop, ...flat } = b;
1596
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1686
+ return {
1687
+ ...a,
1688
+ ...flat,
1689
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1690
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1691
+ };
1597
1692
  }
1598
1693
  function applyLayer(raw, layer, harness) {
1599
1694
  let out = mergeRaw(raw, layer);
@@ -1624,9 +1719,11 @@ var ENV_KEYS = {
1624
1719
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1625
1720
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1626
1721
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1722
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1627
1723
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1628
1724
  autoInject: "HINDSIGHT_AUTO_INJECT",
1629
1725
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1726
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1630
1727
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1631
1728
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1632
1729
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1668,6 +1765,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1668
1765
  "maxParallelRetains",
1669
1766
  "reflectTimeoutMs",
1670
1767
  "reflectToolTimeoutMs",
1768
+ "injectTimeoutMs",
1671
1769
  "pageSearchLimit",
1672
1770
  "pageRefreshEveryTurns",
1673
1771
  "seedLimit",
@@ -1716,15 +1814,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1716
1814
  function applyBankConfig(cfg2, resolvedId, directory) {
1717
1815
  if (directory !== void 0 && !isOptedIn(cfg2, directory))
1718
1816
  return { cfg: { ...cfg2, disabled: true }, bankId: resolvedId };
1817
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg2, cfg2.paths, directory);
1818
+ if (byPath) {
1819
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1820
+ cfg2 = { ...cfg2, ...resolvePartial(cfg2, rest) };
1821
+ }
1719
1822
  const section = cfg2.banks[resolvedId];
1720
1823
  if (!section) return { cfg: cfg2, bankId: resolvedId };
1721
- const safe = { ...section };
1722
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1723
- delete safe.banks;
1824
+ const safe = overrideFields(section);
1724
1825
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1725
1826
  delete safe.bank;
1726
1827
  return { cfg: { ...cfg2, ...resolvePartial(cfg2, safe) }, bankId };
1727
1828
  }
1829
+ function overrideFields(section) {
1830
+ const safe = { ...section };
1831
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1832
+ delete safe.banks;
1833
+ delete safe.paths;
1834
+ return safe;
1835
+ }
1728
1836
  function resolvePartial(cfg2, patch) {
1729
1837
  const full = resolveConfig(patch);
1730
1838
  const out = {};
@@ -1733,6 +1841,16 @@ function resolvePartial(cfg2, patch) {
1733
1841
  out[key] = full[key];
1734
1842
  }
1735
1843
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1844
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1845
+ const conn = resolveConfig({
1846
+ serverMode: patch.serverMode ?? cfg2.serverMode,
1847
+ apiPort: patch.apiPort ?? cfg2.apiPort,
1848
+ apiUrl: patch.apiUrl ?? (cfg2.serverMode === "daemon" ? void 0 : cfg2.apiUrl)
1849
+ });
1850
+ out.serverMode = conn.serverMode;
1851
+ out.apiUrl = conn.apiUrl;
1852
+ out.apiPort = conn.apiPort;
1853
+ }
1736
1854
  return out;
1737
1855
  }
1738
1856
 
@@ -1741,6 +1859,7 @@ import { execFileSync } from "child_process";
1741
1859
  import { resolve as resolve2 } from "path";
1742
1860
  var US = "";
1743
1861
  var RS = "";
1862
+ var GITLOG_HEAD = "gitlog-head:";
1744
1863
  function git(repo, ...args) {
1745
1864
  return execFileSync("git", ["-C", repo, ...args], {
1746
1865
  encoding: "utf8",
@@ -1762,6 +1881,7 @@ function gitHeadSha(dir) {
1762
1881
  }
1763
1882
  }
1764
1883
  function commitsSince(dir, sinceSha) {
1884
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
1765
1885
  try {
1766
1886
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
1767
1887
  return Number.isFinite(n) ? n : null;
@@ -1860,7 +1980,7 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1860
1980
  ...stamp?.tags ?? [],
1861
1981
  "source:git",
1862
1982
  "source:git-log",
1863
- ...head ? [`gitlog-head:${head}`] : []
1983
+ ...head ? [`${GITLOG_HEAD}${head}`] : []
1864
1984
  ])
1865
1985
  ];
1866
1986
  await client.retain(
@@ -1886,12 +2006,20 @@ async function ingestGitLog(client, repo, opts = { limit: 300 }) {
1886
2006
  return 1;
1887
2007
  }
1888
2008
  }
2009
+ async function gitLogIsCurrent(client, repo, head) {
2010
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
2011
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
2012
+ return true;
2013
+ const tags = await client.documentTags?.(canonical2) ?? [];
2014
+ return tags.some(
2015
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
2016
+ );
2017
+ }
1889
2018
  async function syncGitLog(client, repo, opts) {
1890
2019
  const log3 = opts.log ?? (() => {
1891
2020
  });
1892
2021
  const head = gitHeadSha(repo);
1893
- const canonical2 = `gitlog:${repoNameOf(repo)}`;
1894
- const current2 = head !== null && (await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").catch(() => /* @__PURE__ */ new Set())).has(canonical2);
2022
+ const current2 = head !== null && await gitLogIsCurrent(client, repo, head).catch(() => false);
1895
2023
  if (current2) {
1896
2024
  log3("[gitlog] current with HEAD \u2014 skipping");
1897
2025
  return 0;
@@ -1923,6 +2051,70 @@ import {
1923
2051
  writeFileSync
1924
2052
  } from "fs";
1925
2053
  import { join as join8 } from "path";
2054
+ var LEASE_HEARTBEAT_MS = 5e3;
2055
+ var LEASE_STALE_MS = 3e4;
2056
+ function tryRename(from, to) {
2057
+ try {
2058
+ renameSync2(from, to);
2059
+ return true;
2060
+ } catch {
2061
+ return false;
2062
+ }
2063
+ }
2064
+ function releaseLease(lease2) {
2065
+ try {
2066
+ unlinkSync(join8(lease2.directory, lease2.owner));
2067
+ } catch {
2068
+ return;
2069
+ }
2070
+ try {
2071
+ rmdirSync(lease2.directory);
2072
+ } catch {
2073
+ }
2074
+ }
2075
+ function heartbeatLease(lease2) {
2076
+ try {
2077
+ const now = /* @__PURE__ */ new Date();
2078
+ utimesSync(join8(lease2.directory, lease2.owner), now, now);
2079
+ return true;
2080
+ } catch (error) {
2081
+ return error.code !== "ENOENT";
2082
+ }
2083
+ }
2084
+ function reclaimIfStale(directory, staleMs) {
2085
+ const owners = readdirSync(directory);
2086
+ if (owners.length === 0) {
2087
+ try {
2088
+ rmdirSync(directory);
2089
+ } catch {
2090
+ }
2091
+ return true;
2092
+ }
2093
+ if (owners.length !== 1) return false;
2094
+ const age = Date.now() - statSync2(join8(directory, owners[0])).mtimeMs;
2095
+ if (Math.abs(age) <= staleMs) return false;
2096
+ releaseLease({ directory, owner: owners[0] });
2097
+ return true;
2098
+ }
2099
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
2100
+ let staging;
2101
+ try {
2102
+ mkdirSync2(root, { recursive: true, mode: 448 });
2103
+ staging = mkdtempSync(join8(root, "claim-"));
2104
+ const owner = randomUUID();
2105
+ writeFileSync(join8(staging, owner), "", { flag: "wx", mode: 384 });
2106
+ const directory = join8(root, `survey-${key}.lock`);
2107
+ if (!tryRename(staging, directory)) {
2108
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
2109
+ if (!tryRename(staging, directory)) return void 0;
2110
+ }
2111
+ return { directory, owner };
2112
+ } catch {
2113
+ return void 0;
2114
+ } finally {
2115
+ if (staging) rmSync(staging, { recursive: true, force: true });
2116
+ }
2117
+ }
1926
2118
 
1927
2119
  // src/core/survey.ts
1928
2120
  var SURVEY_DOC_IDS = [
@@ -1983,7 +2175,10 @@ var HARNESS_NAMES = [
1983
2175
  "factory-droid",
1984
2176
  // ZCode is a per-prompt HOOK host too, registered in its own CLI config
1985
2177
  // (~/.zcode/cli/config.json) under `hooks.events` — never the user's real Claude Code settings.
1986
- "zcode"
2178
+ "zcode",
2179
+ // TraeCode is a per-prompt HOOK host registered in ~/.trae-cn/hooks.json (see src/installer.ts).
2180
+ "traecode",
2181
+ "kimi-code"
1987
2182
  ];
1988
2183
  var HOOK_BINS = {
1989
2184
  "claude-code": "hindsight-claude-hook",
@@ -1996,7 +2191,9 @@ var HOOK_BINS = {
1996
2191
  "grok-build": "hindsight-grok-hook",
1997
2192
  "qwen-code": "hindsight-qwen-hook",
1998
2193
  "factory-droid": "hindsight-droid-hook",
1999
- zcode: "hindsight-zcode-hook"
2194
+ zcode: "hindsight-zcode-hook",
2195
+ traecode: "hindsight-traecode-hook",
2196
+ "kimi-code": "hindsight-kimi-hook"
2000
2197
  // more hook harnesses: add a HookSpec entry point (see src/cursor-hook.ts) + a registration here.
2001
2198
  };
2002
2199
  var PLUGIN_ENTRYPOINTS = {
@@ -2046,7 +2243,8 @@ function resolversFor(ctx) {
2046
2243
  function buildRetainStamp(cfg2, ctx) {
2047
2244
  const hasTags = Boolean(cfg2.retainTags?.length);
2048
2245
  const hasMetadata = Boolean(cfg2.retainMetadata && Object.keys(cfg2.retainMetadata).length);
2049
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2246
+ const hasContext = Boolean(cfg2.retainContext?.trim());
2247
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2050
2248
  const base = resolversFor(ctx);
2051
2249
  const cache = /* @__PURE__ */ new Map();
2052
2250
  const resolvers = Object.fromEntries(
@@ -2070,12 +2268,12 @@ function buildRetainStamp(cfg2, ctx) {
2070
2268
  for (const [key, value] of Object.entries(cfg2.retainMetadata ?? {})) {
2071
2269
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2072
2270
  }
2073
- return { tags, metadata };
2271
+ const context = hasContext ? applyTemplate(cfg2.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2272
+ return { tags, metadata, context };
2074
2273
  }
2075
2274
 
2076
2275
  // src/deepen.ts
2077
2276
  var DIFF_BATCH = 50;
2078
- var LOCK_STALE_MS = 30 * 60 * 1e3;
2079
2277
  function arg(name, def) {
2080
2278
  const i = process.argv.indexOf(`--${name}`);
2081
2279
  if (i >= 0 && i + 1 < process.argv.length) return process.argv[i + 1];
@@ -2110,35 +2308,16 @@ var log2 = (m) => {
2110
2308
  console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${m}`);
2111
2309
  log.info("deepen", m);
2112
2310
  };
2113
- var LOCK_DIR = join10(tmpdir2(), "hindsight-coding-agent");
2114
- var LOCK = join10(LOCK_DIR, `deepen-${encodeURIComponent(FINAL_BANK ?? "")}.lock`);
2115
- function acquireLock() {
2116
- try {
2117
- const held = JSON.parse(readFileSync4(LOCK, "utf8"));
2118
- if (held.ts && Date.now() - held.ts < LOCK_STALE_MS) {
2119
- let holderAlive = false;
2120
- if (held.pid) {
2121
- try {
2122
- process.kill(held.pid, 0);
2123
- holderAlive = true;
2124
- } catch {
2125
- }
2126
- }
2127
- if (holderAlive) return false;
2128
- }
2129
- } catch {
2130
- }
2131
- try {
2132
- mkdirSync3(LOCK_DIR, { recursive: true });
2133
- writeFileSync2(LOCK, JSON.stringify({ pid: process.pid, ts: Date.now() }));
2134
- return true;
2135
- } catch {
2136
- return false;
2137
- }
2311
+ var LEASE_ROOT = join10(tmpdir2(), "hindsight-coding-agent", "deepen");
2312
+ var lease = acquireLease(LEASE_ROOT, encodeURIComponent(FINAL_BANK ?? ""));
2313
+ if (lease) {
2314
+ setInterval(() => {
2315
+ if (!heartbeatLease(lease)) process.exit(0);
2316
+ }, LEASE_HEARTBEAT_MS).unref();
2138
2317
  }
2139
2318
  async function main() {
2140
- if (!acquireLock()) {
2141
- log2(`deepen: another run holds the lock for ${FINAL_BANK} \u2014 nothing to do`);
2319
+ if (!lease) {
2320
+ log2(`deepen: another run holds the lease for ${FINAL_BANK} \u2014 nothing to do`);
2142
2321
  return;
2143
2322
  }
2144
2323
  const t0 = Date.now();
@@ -2174,7 +2353,8 @@ async function main() {
2174
2353
  pages: cfg.pages,
2175
2354
  customPages: cfg.customPages,
2176
2355
  manage: cfg.manageBankConfig,
2177
- extractionMode: cfg.retainExtractionMode
2356
+ extractionMode: cfg.retainExtractionMode,
2357
+ defaults: cfg.defaultBankConfig
2178
2358
  });
2179
2359
  if (client.knowledgePagesSupported === false) {
2180
2360
  diag(harness.name, "knowledge_pages_unavailable", {
@@ -2210,7 +2390,8 @@ async function main() {
2210
2390
  const shas = execFileSync3(
2211
2391
  "git",
2212
2392
  ["-C", REPO, "rev-list", `-n`, String(DEEPEN_DIFF_TARGET), "HEAD"],
2213
- { encoding: "utf8", windowsHide: true }
2393
+ // `install` runs this with inherited stdio: an empty repo's HEAD error must not print.
2394
+ { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }
2214
2395
  ).trim().split("\n").filter(Boolean).filter((sha) => !gitIds.has(`git:${sha}`)).slice(0, DIFF_BATCH);
2215
2396
  if (shas.length) {
2216
2397
  const repoName = repoNameOf(REPO);
@@ -2287,10 +2468,7 @@ async function main() {
2287
2468
  \u2705 deepen complete in ${((Date.now() - t0) / 1e3).toFixed(1)}s${failures ? ` (${failures} items failed to enqueue)` : ""}.`
2288
2469
  );
2289
2470
  } finally {
2290
- try {
2291
- unlinkSync2(LOCK);
2292
- } catch {
2293
- }
2471
+ releaseLease(lease);
2294
2472
  }
2295
2473
  }
2296
2474
  main().catch((e) => {
@@ -2299,9 +2477,6 @@ main().catch((e) => {
2299
2477
  error: describeError(e)
2300
2478
  });
2301
2479
  console.error("deepen failed:", e.message || e);
2302
- try {
2303
- unlinkSync2(LOCK);
2304
- } catch {
2305
- }
2480
+ if (lease) releaseLease(lease);
2306
2481
  process.exit(1);
2307
2482
  });