@vectorize-io/hindsight-coding-agents 0.5.4 → 0.6.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 (50) hide show
  1. package/README.md +24 -7
  2. package/dist/antigravity-hook.js +205 -81
  3. package/dist/antigravity-statusline.js +32 -22
  4. package/dist/antigravity-stop-hook.js +216 -79
  5. package/dist/claude-hook.js +205 -81
  6. package/dist/claude-sessionstart-hook.js +167 -105
  7. package/dist/claude-stop-hook.js +216 -79
  8. package/dist/cline.js +279 -86
  9. package/dist/codex-hook.js +205 -81
  10. package/dist/codex-sessionstart-hook.js +167 -105
  11. package/dist/codex-stop-hook.js +216 -79
  12. package/dist/copilot-hook.js +205 -81
  13. package/dist/copilot-sessionstart-hook.js +167 -105
  14. package/dist/copilot-stop-hook.js +216 -79
  15. package/dist/cursor-hook.js +205 -81
  16. package/dist/cursor-sessionstart-hook.js +167 -105
  17. package/dist/cursor-stop-hook.js +216 -79
  18. package/dist/daemon-start.js +28 -18
  19. package/dist/dcode-hook.js +205 -81
  20. package/dist/dcode-sessionstart-hook.js +167 -105
  21. package/dist/dcode-stop-hook.js +216 -79
  22. package/dist/deepen.js +98 -40
  23. package/dist/devin-hook.js +205 -81
  24. package/dist/devin-sessionstart-hook.js +167 -105
  25. package/dist/devin-stop-hook.js +216 -79
  26. package/dist/droid-hook.js +205 -81
  27. package/dist/droid-sessionstart-hook.js +167 -105
  28. package/dist/droid-stop-hook.js +216 -79
  29. package/dist/dsh.js +277 -85
  30. package/dist/grok-hook.js +205 -81
  31. package/dist/grok-sessionstart-hook.js +167 -105
  32. package/dist/grok-stop-hook.js +216 -79
  33. package/dist/hindsight-seed.js +32 -22
  34. package/dist/index.js +280 -88
  35. package/dist/installer.js +308 -214
  36. package/dist/kilo.js +280 -88
  37. package/dist/mcp-server.js +97 -39
  38. package/dist/opencode2.js +279 -87
  39. package/dist/pi.js +279 -87
  40. package/dist/prime-agent.js +279 -87
  41. package/dist/qwen-hook.js +205 -81
  42. package/dist/qwen-sessionstart-hook.js +167 -105
  43. package/dist/qwen-stop-hook.js +216 -79
  44. package/dist/status.js +94 -36
  45. package/dist/zcode-hook.js +205 -81
  46. package/dist/zcode-sessionstart-hook.js +167 -105
  47. package/dist/zcode-stop-hook.js +216 -79
  48. package/package.json +1 -1
  49. package/plugin.json +1 -1
  50. package/skill/SKILL.md +24 -7
package/dist/qwen-hook.js CHANGED
@@ -5,16 +5,28 @@ import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
7
  import { existsSync } from "fs";
8
- import { homedir } from "os";
9
- import { basename, dirname as dirname3, join as join3, normalize, sep } from "path";
8
+ import { homedir as homedir2 } from "os";
9
+ import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
10
10
 
11
11
  // src/core/diag.ts
12
- import { appendFileSync as appendFileSync2 } from "fs";
12
+ import { join as join2 } from "path";
13
13
 
14
14
  // src/core/log.ts
15
- import { appendFileSync, mkdirSync } from "fs";
16
- import { tmpdir } from "os";
15
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
16
+ import { homedir } from "os";
17
17
  import { dirname, join } from "path";
18
+ function logsDir() {
19
+ return join(homedir(), ".hindsight", "coding-agents-logs");
20
+ }
21
+ var LOG_MAX_BYTES = 10 * 1024 * 1024;
22
+ function appendLogLine(file, text) {
23
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
24
+ try {
25
+ if (statSync(file).size >= LOG_MAX_BYTES) renameSync(file, `${file}.1`);
26
+ } catch {
27
+ }
28
+ appendFileSync(file, text, { mode: 384 });
29
+ }
18
30
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
19
31
  var current = ["debug", "info", "warn", "error"].find(
20
32
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -23,15 +35,13 @@ function setLogLevel(level) {
23
35
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
24
36
  }
25
37
  function logFilePath() {
26
- return process.env.HINDSIGHT_LOG_FILE || join(tmpdir(), "hindsight-coding-agent", "plugin.log");
38
+ return process.env.HINDSIGHT_LOG_FILE || join(logsDir(), "plugin.log");
27
39
  }
28
40
  function write(level, scope, msg, extra) {
29
41
  if (WEIGHT[level] < WEIGHT[current]) return;
30
42
  try {
31
- const file = logFilePath();
32
- mkdirSync(dirname(file), { recursive: true });
33
- appendFileSync(
34
- file,
43
+ appendLogLine(
44
+ logFilePath(),
35
45
  `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
36
46
  );
37
47
  } catch {
@@ -60,12 +70,12 @@ function describeError(value, maxChars = 200) {
60
70
 
61
71
  // src/core/diag.ts
62
72
  function diagFilePath() {
63
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
73
+ return process.env.HINDSIGHT_DIAG_FILE || join2(logsDir(), "diag.jsonl");
64
74
  }
65
75
  function diag(harness, event, extra = {}) {
66
76
  log.debug(harness, `diag:${event}`, extra);
67
77
  try {
68
- appendFileSync2(
78
+ appendLogLine(
69
79
  diagFilePath(),
70
80
  JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
71
81
  );
@@ -75,7 +85,7 @@ function diag(harness, event, extra = {}) {
75
85
 
76
86
  // src/core/git-layout.ts
77
87
  import { lstatSync, readFileSync, realpathSync } from "fs";
78
- import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
88
+ import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
79
89
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
80
90
  var ATTEMPTS = 3;
81
91
  var BACKOFF_MS = 20;
@@ -111,16 +121,16 @@ function gitDirFromPointer(text, holder) {
111
121
  return isAbsolute(target) ? target : resolve(holder, target);
112
122
  }
113
123
  function commonDirOf(gitDir) {
114
- const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
124
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
115
125
  if (!pointer) return gitDir;
116
126
  return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
117
127
  }
118
128
  function isBare(commonDir) {
119
- const config = readTextOrNull(join2(commonDir, "config"));
129
+ const config = readTextOrNull(join3(commonDir, "config"));
120
130
  return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
121
131
  }
122
132
  function looksLikeBareRepository(directory) {
123
- return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
133
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
124
134
  }
125
135
  function canonical(path) {
126
136
  try {
@@ -137,7 +147,7 @@ function resolved(commonDir) {
137
147
  function probeOnce(directory) {
138
148
  let current2 = resolve(directory);
139
149
  for (; ; ) {
140
- const dotGit = join2(current2, ".git");
150
+ const dotGit = join3(current2, ".git");
141
151
  const kind = entryKind(dotGit);
142
152
  if (kind === "dir") {
143
153
  const layout = resolved(commonDirOf(dotGit));
@@ -248,7 +258,7 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
248
258
  return dirName(sessionRoot || directory);
249
259
  }
250
260
  function configuredDir(dir) {
251
- const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
261
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir2(), dir.slice(1)) : dir;
252
262
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
253
263
  }
254
264
  function isWithin(directory, configured) {
@@ -322,18 +332,18 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
322
332
 
323
333
  // src/core/config.ts
324
334
  import { readFileSync as readFileSync2 } from "fs";
325
- import { homedir as homedir2 } from "os";
326
- import { join as join6 } from "path";
335
+ import { homedir as homedir3 } from "os";
336
+ import { join as join7 } from "path";
327
337
 
328
338
  // src/core/seed.ts
329
339
  import { spawn as realSpawn } from "child_process";
330
- import { dirname as dirname4, join as join4 } from "path";
340
+ import { dirname as dirname4, join as join5 } from "path";
331
341
  import { fileURLToPath } from "url";
332
342
  var DEFAULT_SEED_LIMIT = 300;
333
343
  function startBackgroundSeed(repoDir, opts = {}) {
334
344
  try {
335
345
  const spawnFn = opts.spawn ?? realSpawn;
336
- const enginePath = opts.enginePath ?? join4(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
346
+ const enginePath = opts.enginePath ?? join5(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
337
347
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
338
348
  const child = spawnFn(
339
349
  "node",
@@ -590,7 +600,7 @@ function codingBankManifest(overrides) {
590
600
 
591
601
  // src/core/util.ts
592
602
  import { accessSync, constants } from "fs";
593
- import { delimiter, join as join5 } from "path";
603
+ import { delimiter, join as join6 } from "path";
594
604
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
595
605
  function semverGte(version, min) {
596
606
  const parts = (v) => {
@@ -653,6 +663,22 @@ var KnowledgePagesUnavailableError = class extends Error {
653
663
  }
654
664
  };
655
665
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
666
+ var ReflectError = class extends Error {
667
+ constructor(message, status, timedOut, options) {
668
+ super(message, options);
669
+ this.status = status;
670
+ this.timedOut = timedOut;
671
+ this.name = "ReflectError";
672
+ }
673
+ status;
674
+ timedOut;
675
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
676
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
677
+ * every endpoint (auth, missing bank), so it is not. */
678
+ get fallbackEligible() {
679
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
680
+ }
681
+ };
656
682
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
657
683
  var POLL_CYCLE_MS = 5e3;
658
684
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -736,11 +762,11 @@ var HindsightClient = class {
736
762
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
737
763
  }
738
764
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
739
- async req(method, url, body, tolerate = []) {
765
+ async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
740
766
  const r = await this.fetchWithAuth(url, {
741
767
  method,
742
768
  body: body ? JSON.stringify(body) : void 0,
743
- signal: AbortSignal.timeout(15e3)
769
+ signal: AbortSignal.timeout(timeoutMs)
744
770
  });
745
771
  if (r.status === 429 && !tolerate.includes(429))
746
772
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -933,7 +959,7 @@ var HindsightClient = class {
933
959
  /**
934
960
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
935
961
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
936
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
962
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
937
963
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
938
964
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
939
965
  */
@@ -947,19 +973,45 @@ var HindsightClient = class {
947
973
  signal: ctrl.signal
948
974
  });
949
975
  if (!resp.ok)
950
- throw new Error(
951
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
976
+ throw new ReflectError(
977
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
978
+ resp.status,
979
+ false
952
980
  );
953
981
  const data = await resp.json();
954
982
  return (data.text || "").trim();
955
983
  } catch (e) {
956
984
  if (ctrl.signal.aborted)
957
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
985
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
986
+ cause: e
987
+ });
958
988
  throw e;
959
989
  } finally {
960
990
  clearTimeout(timer);
961
991
  }
962
992
  }
993
+ /**
994
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
995
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
996
+ */
997
+ async recallObservations(query, opts) {
998
+ const r = await this.req(
999
+ "POST",
1000
+ this.bankUrl("/memories/recall"),
1001
+ {
1002
+ query,
1003
+ types: ["observation"],
1004
+ budget: "low",
1005
+ max_tokens: opts.maxTokens,
1006
+ include: { entities: null }
1007
+ },
1008
+ [],
1009
+ opts.timeoutMs
1010
+ );
1011
+ if (r.status === 404) return [];
1012
+ const j = await r.json();
1013
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1014
+ }
963
1015
  /**
964
1016
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
965
1017
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1024,10 +1076,16 @@ var HindsightClient = class {
1024
1076
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1025
1077
  * Returns page-level hits with a relevance snippet — the real search behind
1026
1078
  * hindsight_search_knowledge_pages. */
1027
- async searchKnowledgePages(query, limit = 3) {
1079
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1028
1080
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1029
1081
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1030
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1082
+ const r = await this.req(
1083
+ "GET",
1084
+ this.bankUrl(`/knowledge-base/search${q}`),
1085
+ void 0,
1086
+ [],
1087
+ timeoutMs
1088
+ );
1031
1089
  const j = await r.json();
1032
1090
  return (j.results ?? []).map((x) => ({
1033
1091
  id: x.id,
@@ -1214,7 +1272,7 @@ var HindsightClient = class {
1214
1272
  };
1215
1273
 
1216
1274
  // src/core/config.ts
1217
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1275
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join7(homedir3(), ".hindsight", "coding-agent.json");
1218
1276
  var DEFAULT_DAEMON_PORT = 9077;
1219
1277
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1220
1278
  function resolvePageTrigger(raw) {
@@ -1500,6 +1558,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
1500
1558
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
1501
1559
  - If the bank holds nothing that bears on the goal, say so in one line.`;
1502
1560
  }
1561
+ function formatPageFallback(hits) {
1562
+ return "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)\n" + hits.map((h) => {
1563
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
1564
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
1565
+ }).join("\n");
1566
+ }
1567
+ function formatObservationFallback(observations) {
1568
+ return "(Hindsight's synthesis was unavailable this turn; these consolidated observations were recalled from the bank for the goal, unsynthesized.)\n" + observations.map((o) => `- ${o.replace(/\s+/g, " ").trim()}`).join("\n");
1569
+ }
1503
1570
  function buildSystemInjection(memory) {
1504
1571
  return `<hindsight_memory>
1505
1572
  Automatically retrieved by Hindsight from THIS repository's own history (git rationale and past developer sessions) \u2014 real memory, but retrieval is heuristic: it may or may not bear on the current task.
@@ -1547,11 +1614,11 @@ ${toolGuide(opts)}
1547
1614
  }
1548
1615
 
1549
1616
  // src/core/session-cache.ts
1550
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
1551
- import { tmpdir as tmpdir2 } from "os";
1552
- import { dirname as dirname5, join as join7 } from "path";
1617
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1618
+ import { tmpdir } from "os";
1619
+ import { dirname as dirname5, join as join8 } from "path";
1553
1620
  function sessionCacheFile(harness, sessionId) {
1554
- return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
1621
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.json`);
1555
1622
  }
1556
1623
  function readSessionCache(cacheFile) {
1557
1624
  try {
@@ -1565,7 +1632,7 @@ function writeFileAtomic(path, body) {
1565
1632
  const tmp = `${path}.${process.pid}.tmp`;
1566
1633
  try {
1567
1634
  writeFileSync(tmp, body);
1568
- renameSync(tmp, path);
1635
+ renameSync2(tmp, path);
1569
1636
  } catch (e) {
1570
1637
  try {
1571
1638
  rmSync(tmp, { force: true });
@@ -1581,7 +1648,7 @@ function writeSessionCache(cacheFile, cache) {
1581
1648
  }
1582
1649
  }
1583
1650
  function sessionRootFile(harness, sessionId) {
1584
- return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1651
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1585
1652
  }
1586
1653
  function sessionRootDir(harness, sessionId, cwd) {
1587
1654
  if (!sessionId || !cwd) return cwd;
@@ -1599,9 +1666,9 @@ function sessionRootDir(harness, sessionId, cwd) {
1599
1666
  }
1600
1667
 
1601
1668
  // src/core/turn-journal.ts
1602
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync } from "fs";
1603
- import { tmpdir as tmpdir3 } from "os";
1604
- import { dirname as dirname6, join as join8 } from "path";
1669
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1670
+ import { tmpdir as tmpdir2 } from "os";
1671
+ import { dirname as dirname6, join as join9 } from "path";
1605
1672
 
1606
1673
  // src/core/transcript-util.ts
1607
1674
  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;
@@ -1641,20 +1708,20 @@ function actionLine(tool, input) {
1641
1708
  // src/core/turn-journal.ts
1642
1709
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1643
1710
  function journalPath(harness, sessionId) {
1644
- return join8(tmpdir3(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1711
+ return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1645
1712
  }
1646
1713
  function appendJournalTurn(path, turn) {
1647
1714
  const content = stripInjectedMemory(turn.content ?? "").trim();
1648
1715
  if (!content) return;
1649
1716
  try {
1650
- if (statSync(path).size >= JOURNAL_MAX_BYTES) return;
1717
+ if (statSync2(path).size >= JOURNAL_MAX_BYTES) return;
1651
1718
  } catch {
1652
1719
  }
1653
1720
  const last = readJournalTranscript(path).at(-1);
1654
1721
  if (last && last.role === turn.role && last.content === content) return;
1655
1722
  try {
1656
1723
  mkdirSync3(dirname6(path), { recursive: true });
1657
- appendFileSync3(
1724
+ appendFileSync2(
1658
1725
  path,
1659
1726
  JSON.stringify({
1660
1727
  role: turn.role,
@@ -1695,7 +1762,52 @@ function readJournalTranscript(path) {
1695
1762
  }
1696
1763
 
1697
1764
  // src/core/hook.ts
1698
- var HOOK_REFLECT_CAP_MS = 25e3;
1765
+ var HOOK_REFLECT_CAP_MS = 2e4;
1766
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
1767
+ var FALLBACK_PAGE_LIMIT = 3;
1768
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
1769
+ async function reflectFallback(harness, prompt, client) {
1770
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
1771
+ const remaining = () => Math.max(deadline - Date.now(), 1);
1772
+ const query = prompt.slice(0, 500);
1773
+ let t0 = Date.now();
1774
+ try {
1775
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
1776
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
1777
+ if (hits.length) {
1778
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
1779
+ }
1780
+ } catch (e) {
1781
+ diag(harness, "reflect_fallback_pages_failed", {
1782
+ ms: Date.now() - t0,
1783
+ error: describeError(e)
1784
+ });
1785
+ }
1786
+ t0 = Date.now();
1787
+ try {
1788
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
1789
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
1790
+ timeoutMs: remaining()
1791
+ });
1792
+ diag(harness, "reflect_fallback_observations", {
1793
+ ms: Date.now() - t0,
1794
+ count: observations.length
1795
+ });
1796
+ if (observations.length) {
1797
+ return {
1798
+ memory: formatObservationFallback(observations),
1799
+ source: "observations",
1800
+ count: observations.length
1801
+ };
1802
+ }
1803
+ } catch (e) {
1804
+ diag(harness, "reflect_fallback_observations_failed", {
1805
+ ms: Date.now() - t0,
1806
+ error: describeError(e)
1807
+ });
1808
+ }
1809
+ return void 0;
1810
+ }
1699
1811
  async function buildHookOutput(args) {
1700
1812
  const { harness, prompt, cfg, client, cacheFile } = args;
1701
1813
  const cached = readSessionCache(cacheFile);
@@ -1703,6 +1815,7 @@ async function buildHookOutput(args) {
1703
1815
  let reflectAnswer = cached.reflectAnswer;
1704
1816
  let reflectRanThisTurn = false;
1705
1817
  let reflectFailed = false;
1818
+ let fallback;
1706
1819
  const deferInitialReflect = cached.deferInitialReflect === true;
1707
1820
  if (deferInitialReflect) {
1708
1821
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -1712,7 +1825,7 @@ async function buildHookOutput(args) {
1712
1825
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
1713
1826
  try {
1714
1827
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
1715
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
1828
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
1716
1829
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
1717
1830
  // tool still get the deeper high-budget path.
1718
1831
  budget: "low",
@@ -1740,6 +1853,10 @@ async function buildHookOutput(args) {
1740
1853
  error: describeError(e, 1500),
1741
1854
  query: prompt.slice(0, 80)
1742
1855
  });
1856
+ if (e instanceof ReflectError && e.fallbackEligible) {
1857
+ fallback = await reflectFallback(harness, prompt, client);
1858
+ if (fallback) reflectAnswer = fallback.memory;
1859
+ }
1743
1860
  }
1744
1861
  }
1745
1862
  const cadence = cfg.pageRefreshEveryTurns;
@@ -1773,7 +1890,10 @@ async function buildHookOutput(args) {
1773
1890
  }
1774
1891
  const kept = blocks.filter(Boolean);
1775
1892
  let notice;
1776
- if (reflectRanThisTurn && reflectAnswer) {
1893
+ if (fallback) {
1894
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
1895
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
1896
+ } else if (reflectRanThisTurn && reflectAnswer) {
1777
1897
  const q = prompt.replace(/\s+/g, " ").trim();
1778
1898
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
1779
1899
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -1836,7 +1956,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1836
1956
  }
1837
1957
 
1838
1958
  // src/core/retain-hook.ts
1839
- import { readFileSync as readFileSync6 } from "fs";
1959
+ import { readFileSync as readFileSync7 } from "fs";
1840
1960
 
1841
1961
  // src/core/retain-cursor.ts
1842
1962
  import { createHash as createHash2 } from "crypto";
@@ -1848,14 +1968,14 @@ import { createHash as createHash3 } from "crypto";
1848
1968
 
1849
1969
  // src/core/daemon.ts
1850
1970
  import { execFileSync, spawn as realSpawn2 } from "child_process";
1851
- import { dirname as dirname7, join as join9 } from "path";
1971
+ import { dirname as dirname7, join as join10 } from "path";
1852
1972
  import { fileURLToPath as fileURLToPath2 } from "url";
1853
1973
 
1854
1974
  // src/core/retain-stamp.ts
1855
1975
  import { basename as basename2 } from "path";
1856
1976
 
1857
1977
  // src/core/jsonl.ts
1858
- import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
1978
+ import { closeSync, openSync, readSync, statSync as statSync3 } from "fs";
1859
1979
  import { StringDecoder } from "string_decoder";
1860
1980
  var CHUNK_BYTES = 64 * 1024;
1861
1981
  var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
@@ -1863,7 +1983,7 @@ function readJsonlTail(path, opts) {
1863
1983
  const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1864
1984
  let size;
1865
1985
  try {
1866
- size = statSync2(path).size;
1986
+ size = statSync3(path).size;
1867
1987
  } catch {
1868
1988
  return { lines: emptyLines(), skippedBytes: 0 };
1869
1989
  }
@@ -1915,8 +2035,12 @@ function* streamLines(path, start) {
1915
2035
  }
1916
2036
  }
1917
2037
 
2038
+ // src/core/usage.ts
2039
+ import { readFileSync as readFileSync6 } from "fs";
2040
+ import { join as join11 } from "path";
2041
+
1918
2042
  // src/core/session-start.ts
1919
- import { readFileSync as readFileSync10 } from "fs";
2043
+ import { readFileSync as readFileSync11 } from "fs";
1920
2044
 
1921
2045
  // src/core/git.ts
1922
2046
  import { execFileSync as execFileSync2 } from "child_process";
@@ -1929,8 +2053,8 @@ import { execFileSync as execFileSync3 } from "child_process";
1929
2053
  import { spawn as realSpawn4 } from "child_process";
1930
2054
  import { createHash as createHash4 } from "crypto";
1931
2055
  import { existsSync as existsSync3 } from "fs";
1932
- import { homedir as homedir3, tmpdir as tmpdir4 } from "os";
1933
- import { dirname as dirname8, join as join11 } from "path";
2056
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2057
+ import { dirname as dirname8, join as join13 } from "path";
1934
2058
  import { fileURLToPath as fileURLToPath3 } from "url";
1935
2059
 
1936
2060
  // src/core/survey-lease.ts
@@ -1940,42 +2064,42 @@ import {
1940
2064
  mkdirSync as mkdirSync4,
1941
2065
  mkdtempSync,
1942
2066
  readdirSync,
1943
- renameSync as renameSync2,
2067
+ renameSync as renameSync3,
1944
2068
  rmdirSync,
1945
2069
  rmSync as rmSync2,
1946
- statSync as statSync3,
2070
+ statSync as statSync4,
1947
2071
  unlinkSync,
1948
2072
  utimesSync,
1949
2073
  writeFileSync as writeFileSync2
1950
2074
  } from "fs";
1951
- import { join as join10 } from "path";
2075
+ import { join as join12 } from "path";
1952
2076
 
1953
2077
  // src/core/auto-update.ts
1954
2078
  import { spawn as realSpawn5 } from "child_process";
1955
2079
  import {
1956
2080
  existsSync as existsSync4,
1957
2081
  mkdirSync as mkdirSync5,
1958
- readFileSync as readFileSync7,
2082
+ readFileSync as readFileSync8,
1959
2083
  realpathSync as realpathSync2,
1960
2084
  unlinkSync as unlinkSync2,
1961
2085
  writeFileSync as writeFileSync3
1962
2086
  } from "fs";
1963
- import { homedir as homedir4, tmpdir as tmpdir5 } from "os";
1964
- import { dirname as dirname9, join as join12 } from "path";
2087
+ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2088
+ import { dirname as dirname9, join as join14 } from "path";
1965
2089
  import { fileURLToPath as fileURLToPath4 } from "url";
1966
2090
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1967
2091
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1968
2092
 
1969
2093
  // src/core/skill-sync.ts
1970
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
1971
- import { homedir as homedir5 } from "os";
1972
- import { dirname as dirname10, join as join13 } from "path";
2094
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2095
+ import { homedir as homedir6 } from "os";
2096
+ import { dirname as dirname10, join as join15 } from "path";
1973
2097
  import { fileURLToPath as fileURLToPath5 } from "url";
1974
2098
 
1975
2099
  // src/core/legacy.ts
1976
- import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
1977
- import { homedir as homedir6 } from "os";
1978
- import { join as join14, relative, isAbsolute as isAbsolute2 } from "path";
2100
+ import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2101
+ import { homedir as homedir7 } from "os";
2102
+ import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
1979
2103
 
1980
2104
  // src/core/transcript-codex.ts
1981
2105
  function isSyntheticUserText(text) {
@@ -2107,19 +2231,19 @@ function readCopilotTranscript(path) {
2107
2231
  }
2108
2232
 
2109
2233
  // src/core/transcript-grok.ts
2110
- import { existsSync as existsSync7, readFileSync as readFileSync11, readdirSync as readdirSync2 } from "fs";
2111
- import { homedir as homedir7 } from "os";
2112
- import { join as join15 } from "path";
2234
+ import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2235
+ import { homedir as homedir8 } from "os";
2236
+ import { join as join17 } from "path";
2113
2237
  var CHAT_HISTORY = "chat_history.jsonl";
2114
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join15(homedir7(), ".grok")) {
2115
- const sessionsDir = join15(grokHome, "sessions");
2116
- const direct = join15(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2238
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2239
+ const sessionsDir = join17(grokHome, "sessions");
2240
+ const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2117
2241
  if (existsSync7(direct)) return direct;
2118
2242
  try {
2119
2243
  for (const candidate of readdirSync2(sessionsDir)) {
2120
- const directory = join15(sessionsDir, candidate);
2121
- if (readFileSync11(join15(directory, ".cwd"), "utf8").trim() === cwd) {
2122
- return join15(directory, sessionId, CHAT_HISTORY);
2244
+ const directory = join17(sessionsDir, candidate);
2245
+ if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2246
+ return join17(directory, sessionId, CHAT_HISTORY);
2123
2247
  }
2124
2248
  }
2125
2249
  } catch {
@@ -2156,10 +2280,10 @@ function readGrokTranscript(path) {
2156
2280
  // src/core/transcript-devin.ts
2157
2281
  import { existsSync as existsSync8 } from "fs";
2158
2282
  import { createRequire } from "module";
2159
- import { homedir as homedir8 } from "os";
2160
- import { join as join16 } from "path";
2161
- function devinSessionDb(home = homedir8()) {
2162
- return join16(home, ".local", "share", "devin", "cli", "sessions.db");
2283
+ import { homedir as homedir9 } from "os";
2284
+ import { join as join18 } from "path";
2285
+ function devinSessionDb(home = homedir9()) {
2286
+ return join18(home, ".local", "share", "devin", "cli", "sessions.db");
2163
2287
  }
2164
2288
  function parseDevinMessages(nodes) {
2165
2289
  const messages = /* @__PURE__ */ new Map();
@@ -2469,7 +2593,7 @@ function readDroidTranscript(path) {
2469
2593
  }
2470
2594
 
2471
2595
  // src/core/transcript-zcode.ts
2472
- import { readFileSync as readFileSync12 } from "fs";
2596
+ import { readFileSync as readFileSync13 } from "fs";
2473
2597
  function messageText2(content) {
2474
2598
  if (typeof content === "string") return content.trim();
2475
2599
  if (!Array.isArray(content)) return "";
@@ -2479,7 +2603,7 @@ function readZcodeTranscript(path) {
2479
2603
  if (!path) return [];
2480
2604
  let body;
2481
2605
  try {
2482
- body = readFileSync12(path, "utf8");
2606
+ body = readFileSync13(path, "utf8");
2483
2607
  } catch {
2484
2608
  return [];
2485
2609
  }