@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/dsh.js CHANGED
@@ -9,8 +9,8 @@ import { randomUUID as randomUUID2 } from "crypto";
9
9
 
10
10
  // src/core/config.ts
11
11
  import { readFileSync as readFileSync2 } from "fs";
12
- import { homedir as homedir2 } from "os";
13
- import { join as join6 } from "path";
12
+ import { homedir as homedir3 } from "os";
13
+ import { join as join7 } from "path";
14
14
 
15
15
  // src/core/seed.ts
16
16
  import { spawn as realSpawn } from "child_process";
@@ -47,16 +47,28 @@ function startBackgroundSeed(repoDir, opts = {}) {
47
47
 
48
48
  // src/core/bank.ts
49
49
  import { existsSync } from "fs";
50
- import { homedir } from "os";
51
- import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
50
+ import { homedir as homedir2 } from "os";
51
+ import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
52
52
 
53
53
  // src/core/diag.ts
54
- import { appendFileSync as appendFileSync2 } from "fs";
54
+ import { join as join3 } from "path";
55
55
 
56
56
  // src/core/log.ts
57
- import { appendFileSync, mkdirSync } from "fs";
58
- import { tmpdir } from "os";
57
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
58
+ import { homedir } from "os";
59
59
  import { dirname as dirname2, join as join2 } from "path";
60
+ function logsDir() {
61
+ return join2(homedir(), ".hindsight", "coding-agents-logs");
62
+ }
63
+ var LOG_MAX_BYTES = 10 * 1024 * 1024;
64
+ function appendLogLine(file2, text) {
65
+ mkdirSync(dirname2(file2), { recursive: true, mode: 448 });
66
+ try {
67
+ if (statSync(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
68
+ } catch {
69
+ }
70
+ appendFileSync(file2, text, { mode: 384 });
71
+ }
60
72
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
61
73
  var current = ["debug", "info", "warn", "error"].find(
62
74
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -65,15 +77,13 @@ function setLogLevel(level) {
65
77
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
66
78
  }
67
79
  function logFilePath() {
68
- return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
80
+ return process.env.HINDSIGHT_LOG_FILE || join2(logsDir(), "plugin.log");
69
81
  }
70
82
  function write(level, scope, msg, extra) {
71
83
  if (WEIGHT[level] < WEIGHT[current]) return;
72
84
  try {
73
- const file2 = logFilePath();
74
- mkdirSync(dirname2(file2), { recursive: true });
75
- appendFileSync(
76
- file2,
85
+ appendLogLine(
86
+ logFilePath(),
77
87
  `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
78
88
  );
79
89
  } catch {
@@ -102,12 +112,12 @@ function describeError(value, maxChars = 200) {
102
112
 
103
113
  // src/core/diag.ts
104
114
  function diagFilePath() {
105
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
115
+ return process.env.HINDSIGHT_DIAG_FILE || join3(logsDir(), "diag.jsonl");
106
116
  }
107
117
  function diag(harness, event, extra = {}) {
108
118
  log.debug(harness, `diag:${event}`, extra);
109
119
  try {
110
- appendFileSync2(
120
+ appendLogLine(
111
121
  diagFilePath(),
112
122
  JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
113
123
  );
@@ -117,7 +127,7 @@ function diag(harness, event, extra = {}) {
117
127
 
118
128
  // src/core/git-layout.ts
119
129
  import { lstatSync, readFileSync, realpathSync } from "fs";
120
- import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
130
+ import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
121
131
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
122
132
  var ATTEMPTS = 3;
123
133
  var BACKOFF_MS = 20;
@@ -153,16 +163,16 @@ function gitDirFromPointer(text, holder) {
153
163
  return isAbsolute(target) ? target : resolve(holder, target);
154
164
  }
155
165
  function commonDirOf(gitDir) {
156
- const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
166
+ const pointer = entryKind(join4(gitDir, "commondir")) === "file" ? readTextOrNull(join4(gitDir, "commondir"))?.trim() : null;
157
167
  if (!pointer) return gitDir;
158
168
  return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
159
169
  }
160
170
  function isBare(commonDir) {
161
- const config2 = readTextOrNull(join3(commonDir, "config"));
171
+ const config2 = readTextOrNull(join4(commonDir, "config"));
162
172
  return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
163
173
  }
164
174
  function looksLikeBareRepository(directory) {
165
- return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
175
+ return entryKind(join4(directory, "HEAD")) === "file" && entryKind(join4(directory, "objects")) === "dir" && entryKind(join4(directory, "refs")) === "dir";
166
176
  }
167
177
  function canonical(path) {
168
178
  try {
@@ -179,7 +189,7 @@ function resolved(commonDir) {
179
189
  function probeOnce(directory) {
180
190
  let current2 = resolve(directory);
181
191
  for (; ; ) {
182
- const dotGit = join3(current2, ".git");
192
+ const dotGit = join4(current2, ".git");
183
193
  const kind = entryKind(dotGit);
184
194
  if (kind === "dir") {
185
195
  const layout = resolved(commonDirOf(dotGit));
@@ -293,7 +303,7 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
293
303
  return dirName(sessionRoot || directory);
294
304
  }
295
305
  function configuredDir(dir) {
296
- const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
306
+ const expanded = dir === "~" || dir.startsWith("~/") ? join5(homedir2(), dir.slice(1)) : dir;
297
307
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
298
308
  }
299
309
  function isWithin(directory, configured) {
@@ -597,7 +607,7 @@ function codingBankManifest(overrides) {
597
607
 
598
608
  // src/core/util.ts
599
609
  import { accessSync, constants } from "fs";
600
- import { delimiter, join as join5 } from "path";
610
+ import { delimiter, join as join6 } from "path";
601
611
  function binOnPath(bin) {
602
612
  try {
603
613
  if (bin.includes("/")) {
@@ -607,7 +617,7 @@ function binOnPath(bin) {
607
617
  for (const dir of (process.env.PATH || "").split(delimiter)) {
608
618
  if (!dir) continue;
609
619
  try {
610
- accessSync(join5(dir, bin), constants.X_OK);
620
+ accessSync(join6(dir, bin), constants.X_OK);
611
621
  return true;
612
622
  } catch {
613
623
  }
@@ -679,6 +689,22 @@ var KnowledgePagesUnavailableError = class extends Error {
679
689
  }
680
690
  };
681
691
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
692
+ var ReflectError = class extends Error {
693
+ constructor(message, status, timedOut, options) {
694
+ super(message, options);
695
+ this.status = status;
696
+ this.timedOut = timedOut;
697
+ this.name = "ReflectError";
698
+ }
699
+ status;
700
+ timedOut;
701
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
702
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
703
+ * every endpoint (auth, missing bank), so it is not. */
704
+ get fallbackEligible() {
705
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
706
+ }
707
+ };
682
708
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
683
709
  var POLL_CYCLE_MS = 5e3;
684
710
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -762,11 +788,11 @@ var HindsightClient = class {
762
788
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
763
789
  }
764
790
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
765
- async req(method, url2, body, tolerate = []) {
791
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
766
792
  const r = await this.fetchWithAuth(url2, {
767
793
  method,
768
794
  body: body ? JSON.stringify(body) : void 0,
769
- signal: AbortSignal.timeout(15e3)
795
+ signal: AbortSignal.timeout(timeoutMs)
770
796
  });
771
797
  if (r.status === 429 && !tolerate.includes(429))
772
798
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -959,7 +985,7 @@ var HindsightClient = class {
959
985
  /**
960
986
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
961
987
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
962
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
988
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
963
989
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
964
990
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
965
991
  */
@@ -973,19 +999,45 @@ var HindsightClient = class {
973
999
  signal: ctrl.signal
974
1000
  });
975
1001
  if (!resp.ok)
976
- throw new Error(
977
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
1002
+ throw new ReflectError(
1003
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
1004
+ resp.status,
1005
+ false
978
1006
  );
979
1007
  const data = await resp.json();
980
1008
  return (data.text || "").trim();
981
1009
  } catch (e) {
982
1010
  if (ctrl.signal.aborted)
983
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
1011
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1012
+ cause: e
1013
+ });
984
1014
  throw e;
985
1015
  } finally {
986
1016
  clearTimeout(timer);
987
1017
  }
988
1018
  }
1019
+ /**
1020
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1021
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1022
+ */
1023
+ async recallObservations(query, opts) {
1024
+ const r = await this.req(
1025
+ "POST",
1026
+ this.bankUrl("/memories/recall"),
1027
+ {
1028
+ query,
1029
+ types: ["observation"],
1030
+ budget: "low",
1031
+ max_tokens: opts.maxTokens,
1032
+ include: { entities: null }
1033
+ },
1034
+ [],
1035
+ opts.timeoutMs
1036
+ );
1037
+ if (r.status === 404) return [];
1038
+ const j = await r.json();
1039
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1040
+ }
989
1041
  /**
990
1042
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
991
1043
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1050,10 +1102,16 @@ var HindsightClient = class {
1050
1102
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1051
1103
  * Returns page-level hits with a relevance snippet — the real search behind
1052
1104
  * hindsight_search_knowledge_pages. */
1053
- async searchKnowledgePages(query, limit = 3) {
1105
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1054
1106
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1055
1107
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1056
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1108
+ const r = await this.req(
1109
+ "GET",
1110
+ this.bankUrl(`/knowledge-base/search${q}`),
1111
+ void 0,
1112
+ [],
1113
+ timeoutMs
1114
+ );
1057
1115
  const j = await r.json();
1058
1116
  return (j.results ?? []).map((x) => ({
1059
1117
  id: x.id,
@@ -1240,7 +1298,7 @@ var HindsightClient = class {
1240
1298
  };
1241
1299
 
1242
1300
  // src/core/config.ts
1243
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1301
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join7(homedir3(), ".hindsight", "coding-agent.json");
1244
1302
  var DEFAULT_DAEMON_PORT = 9077;
1245
1303
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1246
1304
  function resolvePageTrigger(raw) {
@@ -1534,20 +1592,20 @@ import {
1534
1592
  unlinkSync,
1535
1593
  writeFileSync
1536
1594
  } from "fs";
1537
- import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1538
- import { dirname as dirname5, join as join7 } from "path";
1595
+ import { homedir as homedir4, tmpdir } from "os";
1596
+ import { dirname as dirname5, join as join8 } from "path";
1539
1597
  import { fileURLToPath as fileURLToPath2 } from "url";
1540
1598
  var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1541
1599
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1542
1600
  var FETCH_TIMEOUT_MS = 5e3;
1543
1601
  function stateFile(runtimeDir) {
1544
- return join7(runtimeDir, ".update-check.json");
1602
+ return join8(runtimeDir, ".update-check.json");
1545
1603
  }
1546
1604
  function packageRoot() {
1547
- return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
1605
+ return join8(dirname5(fileURLToPath2(import.meta.url)), "..");
1548
1606
  }
1549
1607
  function stagedRuntimeDir() {
1550
- return join7(homedir3(), ".hindsight", "coding-agents");
1608
+ return join8(homedir4(), ".hindsight", "coding-agents");
1551
1609
  }
1552
1610
  function sameDir(a, b) {
1553
1611
  try {
@@ -1558,7 +1616,7 @@ function sameDir(a, b) {
1558
1616
  }
1559
1617
  function stagedVersion(pkgRoot) {
1560
1618
  try {
1561
- const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
1619
+ const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1562
1620
  return typeof pkg.version === "string" ? pkg.version : "";
1563
1621
  } catch {
1564
1622
  return "";
@@ -1592,7 +1650,7 @@ function dueForCheck(file2, now) {
1592
1650
  var ORIGIN_FILE = ".install-origin.json";
1593
1651
  function selfUpdatable(runtimeDir) {
1594
1652
  try {
1595
- const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
1653
+ const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1596
1654
  if (typeof origin.source !== "string" || !origin.source) return false;
1597
1655
  return origin.source.split(/[\\/]/).includes("_npx");
1598
1656
  } catch {
@@ -1601,7 +1659,7 @@ function selfUpdatable(runtimeDir) {
1601
1659
  }
1602
1660
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1603
1661
  function lockFile() {
1604
- return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
1662
+ return join8(tmpdir(), "hindsight-coding-agent", "auto-update.lock");
1605
1663
  }
1606
1664
  function acquireUpdateLock(file2, now) {
1607
1665
  try {
@@ -1718,7 +1776,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
1718
1776
 
1719
1777
  // src/core/daemon.ts
1720
1778
  import { execFileSync, spawn as realSpawn3 } from "child_process";
1721
- import { dirname as dirname6, join as join8 } from "path";
1779
+ import { dirname as dirname6, join as join9 } from "path";
1722
1780
  import { fileURLToPath as fileURLToPath3 } from "url";
1723
1781
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1724
1782
  var DAEMON_WAIT_RETAIN_MS = 4e4;
@@ -1793,7 +1851,7 @@ function onPath(bin) {
1793
1851
  }
1794
1852
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1795
1853
  try {
1796
- const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1854
+ const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1797
1855
  const child = spawnFn("node", [starter, "--harness", harness], {
1798
1856
  detached: true,
1799
1857
  stdio: "ignore",
@@ -16362,8 +16420,8 @@ config(en_default());
16362
16420
 
16363
16421
  // src/core/knowledge-tools.ts
16364
16422
  import { existsSync as existsSync4 } from "fs";
16365
- import { homedir as homedir5 } from "os";
16366
- import { join as join11 } from "path";
16423
+ import { homedir as homedir6 } from "os";
16424
+ import { join as join12 } from "path";
16367
16425
 
16368
16426
  // src/core/status.ts
16369
16427
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16452,8 +16510,8 @@ ${toolGuide(opts)}
16452
16510
  import { spawn as realSpawn5 } from "child_process";
16453
16511
  import { createHash as createHash2 } from "crypto";
16454
16512
  import { existsSync as existsSync3 } from "fs";
16455
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16456
- import { dirname as dirname7, join as join10 } from "path";
16513
+ import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16514
+ import { dirname as dirname7, join as join11 } from "path";
16457
16515
  import { fileURLToPath as fileURLToPath4 } from "url";
16458
16516
 
16459
16517
  // src/core/survey-lease.ts
@@ -16463,20 +16521,20 @@ import {
16463
16521
  mkdirSync as mkdirSync3,
16464
16522
  mkdtempSync,
16465
16523
  readdirSync,
16466
- renameSync,
16524
+ renameSync as renameSync2,
16467
16525
  rmdirSync,
16468
16526
  rmSync,
16469
- statSync,
16527
+ statSync as statSync2,
16470
16528
  unlinkSync as unlinkSync2,
16471
16529
  utimesSync,
16472
16530
  writeFileSync as writeFileSync2
16473
16531
  } from "fs";
16474
- import { join as join9 } from "path";
16532
+ import { join as join10 } from "path";
16475
16533
  var LEASE_STALE_MS = 3e4;
16476
16534
  var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16477
16535
  function tryRename(from, to) {
16478
16536
  try {
16479
- renameSync(from, to);
16537
+ renameSync2(from, to);
16480
16538
  return true;
16481
16539
  } catch {
16482
16540
  return false;
@@ -16484,7 +16542,7 @@ function tryRename(from, to) {
16484
16542
  }
16485
16543
  function releaseLease(lease) {
16486
16544
  try {
16487
- unlinkSync2(join9(lease.directory, lease.owner));
16545
+ unlinkSync2(join10(lease.directory, lease.owner));
16488
16546
  } catch {
16489
16547
  return;
16490
16548
  }
@@ -16503,7 +16561,7 @@ function reclaimIfStale(directory, staleMs) {
16503
16561
  return true;
16504
16562
  }
16505
16563
  if (owners.length !== 1) return false;
16506
- const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16564
+ const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
16507
16565
  if (Math.abs(age) <= staleMs) return false;
16508
16566
  releaseLease({ directory, owner: owners[0] });
16509
16567
  return true;
@@ -16512,10 +16570,10 @@ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16512
16570
  let staging;
16513
16571
  try {
16514
16572
  mkdirSync3(root, { recursive: true, mode: 448 });
16515
- staging = mkdtempSync(join9(root, "claim-"));
16573
+ staging = mkdtempSync(join10(root, "claim-"));
16516
16574
  const owner = randomUUID();
16517
- writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16518
- const directory = join9(root, `survey-${key}.lock`);
16575
+ writeFileSync2(join10(staging, owner), "", { flag: "wx", mode: 384 });
16576
+ const directory = join10(root, `survey-${key}.lock`);
16519
16577
  if (!tryRename(staging, directory)) {
16520
16578
  if (!reclaimIfStale(directory, staleMs)) return void 0;
16521
16579
  if (!tryRename(staging, directory)) return void 0;
@@ -16538,7 +16596,7 @@ var SURVEY_DOC_IDS = [
16538
16596
  function resolveClaudeBin(explicit) {
16539
16597
  if (explicit) return explicit;
16540
16598
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16541
- const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16599
+ const nativeInstallPath = join11(homedir5(), ".claude", "local", "claude");
16542
16600
  try {
16543
16601
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16544
16602
  } catch {
@@ -16656,7 +16714,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16656
16714
  try {
16657
16715
  const spawnFn = opts.spawn ?? realSpawn5;
16658
16716
  const exists = opts.exists ?? binOnPath;
16659
- const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16717
+ const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16660
16718
  const preferred = opts.harness ?? "claude-code";
16661
16719
  const order = [
16662
16720
  preferred,
@@ -16680,7 +16738,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16680
16738
  if (cfg.disabled) return false;
16681
16739
  const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16682
16740
  const lease = acquireLease(
16683
- opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16741
+ opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
16684
16742
  key,
16685
16743
  opts.lease?.staleMs ?? LEASE_STALE_MS
16686
16744
  );
@@ -16691,7 +16749,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16691
16749
  args: plan.args,
16692
16750
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16693
16751
  };
16694
- const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16752
+ const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16695
16753
  return await new Promise((resolve3) => {
16696
16754
  try {
16697
16755
  const child = spawnFn("node", [supervisorPath], {
@@ -16833,7 +16891,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16833
16891
  inputSchema: {},
16834
16892
  annotations: READ_ONLY_ANNOTATIONS,
16835
16893
  handler: async (_args) => {
16836
- const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16894
+ const configPath = process.env.HINDSIGHT_CONFIG || join12(homedir6(), ".hindsight", "coding-agent.json");
16837
16895
  const harness = opts.harness ?? "unknown";
16838
16896
  const cfg = applyBankConfig(
16839
16897
  loadConfig({ harness: opts.harness }),
@@ -16863,7 +16921,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16863
16921
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
16864
16922
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
16865
16923
  log_level: process.env.HINDSIGHT_LOG_LEVEL ?? null,
16866
- diagnostics_file: process.env.HINDSIGHT_DIAG_FILE ?? "/tmp/hindsight-plugin.log",
16924
+ diagnostics_file: diagFilePath(),
16867
16925
  channel_id_configured: Boolean(process.env.HINDSIGHT_CHANNEL_ID),
16868
16926
  user_id_configured: Boolean(process.env.HINDSIGHT_USER_ID)
16869
16927
  }
@@ -17164,6 +17222,64 @@ ${content}`);
17164
17222
  }
17165
17223
  }
17166
17224
 
17225
+ // src/core/usage.ts
17226
+ import { readFileSync as readFileSync4 } from "fs";
17227
+ import { join as join13 } from "path";
17228
+ function usageFilePath() {
17229
+ return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
17230
+ }
17231
+ var HINDSIGHT_TOOL_RE = /hindsight_(?:[a-z]+_)*[a-z]+$/;
17232
+ var CREDIT_RE = /from hindsight memory/i;
17233
+ var ASSISTANT_ROLES = /* @__PURE__ */ new Set(["assistant", "model"]);
17234
+ function summarizeTurns(turns) {
17235
+ const out = [];
17236
+ for (const t of turns) {
17237
+ if (t.role === "user") {
17238
+ out.push({ turn: out.length + 1, calls: [], credited: false });
17239
+ continue;
17240
+ }
17241
+ const current2 = out.at(-1);
17242
+ if (!current2) continue;
17243
+ if (t.role === "action") {
17244
+ const tool = t.content.split(" ", 1)[0].match(HINDSIGHT_TOOL_RE)?.[0];
17245
+ if (tool) current2.calls.push(tool);
17246
+ } else if (ASSISTANT_ROLES.has(t.role) && CREDIT_RE.test(t.content)) {
17247
+ current2.credited = true;
17248
+ }
17249
+ }
17250
+ return out;
17251
+ }
17252
+ function memoryUsageCursorStore() {
17253
+ const recorded = /* @__PURE__ */ new Map();
17254
+ return {
17255
+ read: (sessionId) => recorded.get(sessionId),
17256
+ write: (sessionId, turns) => void recorded.set(sessionId, turns)
17257
+ };
17258
+ }
17259
+ function recordUsage(args) {
17260
+ const summary = summarizeTurns(args.turns);
17261
+ const finished = args.lastTurnComplete ? summary : summary.slice(0, -1);
17262
+ const from = args.cursors.read(args.sessionId) ?? 0;
17263
+ if (finished.length <= from) return;
17264
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
17265
+ const lines = finished.slice(from).map(
17266
+ (u) => JSON.stringify({
17267
+ ts,
17268
+ harness: args.harness,
17269
+ session: args.sessionId,
17270
+ bank: args.bankId,
17271
+ turn: u.turn,
17272
+ calls: u.calls,
17273
+ credited: u.credited
17274
+ }) + "\n"
17275
+ ).join("");
17276
+ try {
17277
+ appendLogLine(usageFilePath(), lines);
17278
+ args.cursors.write(args.sessionId, finished.length);
17279
+ } catch {
17280
+ }
17281
+ }
17282
+
17167
17283
  // src/core/retain-stamp.ts
17168
17284
  import { basename as basename2 } from "path";
17169
17285
  var RESERVED_TAG_PREFIX = /^(source|harness):/;
@@ -17212,12 +17328,12 @@ function buildRetainStamp(cfg, ctx) {
17212
17328
  }
17213
17329
 
17214
17330
  // src/core/session-start.ts
17215
- import { readFileSync as readFileSync7 } from "fs";
17331
+ import { readFileSync as readFileSync8 } from "fs";
17216
17332
 
17217
17333
  // src/core/skill-sync.ts
17218
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17219
- import { homedir as homedir6 } from "os";
17220
- import { dirname as dirname8, join as join12 } from "path";
17334
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17335
+ import { homedir as homedir7 } from "os";
17336
+ import { dirname as dirname8, join as join14 } from "path";
17221
17337
  import { fileURLToPath as fileURLToPath5 } from "url";
17222
17338
 
17223
17339
  // src/core/brand.ts
@@ -17235,15 +17351,15 @@ function brandWord() {
17235
17351
  }
17236
17352
 
17237
17353
  // src/core/legacy.ts
17238
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17239
- import { homedir as homedir7 } from "os";
17240
- import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17354
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17355
+ import { homedir as homedir8 } from "os";
17356
+ import { join as join15, relative, isAbsolute as isAbsolute2 } from "path";
17241
17357
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17242
- function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17243
- const registry2 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17358
+ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")) {
17359
+ const registry2 = readJson(join15(claudeDir, "plugins", "installed_plugins.json"));
17244
17360
  const plugins = registry2?.plugins;
17245
17361
  if (!plugins || typeof plugins !== "object") return void 0;
17246
- const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17362
+ const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
17247
17363
  for (const [key, raw] of Object.entries(plugins)) {
17248
17364
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17249
17365
  if (enabled && enabled[key] === false) continue;
@@ -17260,7 +17376,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")
17260
17376
  }
17261
17377
  function readJson(path) {
17262
17378
  try {
17263
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
17379
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
17264
17380
  return parsed && typeof parsed === "object" ? parsed : void 0;
17265
17381
  } catch {
17266
17382
  return void 0;
@@ -17272,15 +17388,15 @@ function legacyClaudePluginWarning(key) {
17272
17388
  }
17273
17389
 
17274
17390
  // src/core/session-cache.ts
17275
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17276
- import { tmpdir as tmpdir4 } from "os";
17277
- import { dirname as dirname9, join as join14 } from "path";
17391
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17392
+ import { tmpdir as tmpdir3 } from "os";
17393
+ import { dirname as dirname9, join as join16 } from "path";
17278
17394
  function sessionCacheFile(harness, sessionId) {
17279
- return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId}.json`);
17395
+ return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17280
17396
  }
17281
17397
  function readSessionCache(cacheFile) {
17282
17398
  try {
17283
- return JSON.parse(readFileSync6(cacheFile, "utf8"));
17399
+ return JSON.parse(readFileSync7(cacheFile, "utf8"));
17284
17400
  } catch {
17285
17401
  return {};
17286
17402
  }
@@ -17290,7 +17406,7 @@ function writeFileAtomic(path, body) {
17290
17406
  const tmp = `${path}.${process.pid}.tmp`;
17291
17407
  try {
17292
17408
  writeFileSync3(tmp, body);
17293
- renameSync2(tmp, path);
17409
+ renameSync3(tmp, path);
17294
17410
  } catch (e) {
17295
17411
  try {
17296
17412
  rmSync2(tmp, { force: true });
@@ -17466,7 +17582,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17466
17582
  }
17467
17583
 
17468
17584
  // src/core/hook.ts
17469
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17585
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
17470
17586
 
17471
17587
  // src/core/inject.ts
17472
17588
  function buildReflectQuery(prompt) {
@@ -17484,6 +17600,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17484
17600
  - 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.
17485
17601
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17486
17602
  }
17603
+ function formatPageFallback(hits) {
17604
+ 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) => {
17605
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17606
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17607
+ }).join("\n");
17608
+ }
17609
+ function formatObservationFallback(observations) {
17610
+ 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");
17611
+ }
17487
17612
  function buildSystemInjection(memory) {
17488
17613
  return `<hindsight_memory>
17489
17614
  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.
@@ -17498,9 +17623,9 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17498
17623
  }
17499
17624
 
17500
17625
  // src/core/turn-journal.ts
17501
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17502
- import { tmpdir as tmpdir5 } from "os";
17503
- import { dirname as dirname10, join as join15 } from "path";
17626
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
17627
+ import { tmpdir as tmpdir4 } from "os";
17628
+ import { dirname as dirname10, join as join17 } from "path";
17504
17629
 
17505
17630
  // src/core/transcript-util.ts
17506
17631
  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;
@@ -17541,7 +17666,52 @@ function actionLine(tool, input) {
17541
17666
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17542
17667
 
17543
17668
  // src/core/hook.ts
17544
- var HOOK_REFLECT_CAP_MS = 25e3;
17669
+ var HOOK_REFLECT_CAP_MS = 2e4;
17670
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17671
+ var FALLBACK_PAGE_LIMIT = 3;
17672
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17673
+ async function reflectFallback(harness, prompt, client) {
17674
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17675
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17676
+ const query = prompt.slice(0, 500);
17677
+ let t0 = Date.now();
17678
+ try {
17679
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17680
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17681
+ if (hits.length) {
17682
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17683
+ }
17684
+ } catch (e) {
17685
+ diag(harness, "reflect_fallback_pages_failed", {
17686
+ ms: Date.now() - t0,
17687
+ error: describeError(e)
17688
+ });
17689
+ }
17690
+ t0 = Date.now();
17691
+ try {
17692
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17693
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17694
+ timeoutMs: remaining()
17695
+ });
17696
+ diag(harness, "reflect_fallback_observations", {
17697
+ ms: Date.now() - t0,
17698
+ count: observations.length
17699
+ });
17700
+ if (observations.length) {
17701
+ return {
17702
+ memory: formatObservationFallback(observations),
17703
+ source: "observations",
17704
+ count: observations.length
17705
+ };
17706
+ }
17707
+ } catch (e) {
17708
+ diag(harness, "reflect_fallback_observations_failed", {
17709
+ ms: Date.now() - t0,
17710
+ error: describeError(e)
17711
+ });
17712
+ }
17713
+ return void 0;
17714
+ }
17545
17715
  async function buildHookOutput(args) {
17546
17716
  const { harness, prompt, cfg, client, cacheFile } = args;
17547
17717
  const cached2 = readSessionCache(cacheFile);
@@ -17549,6 +17719,7 @@ async function buildHookOutput(args) {
17549
17719
  let reflectAnswer = cached2.reflectAnswer;
17550
17720
  let reflectRanThisTurn = false;
17551
17721
  let reflectFailed = false;
17722
+ let fallback;
17552
17723
  const deferInitialReflect = cached2.deferInitialReflect === true;
17553
17724
  if (deferInitialReflect) {
17554
17725
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17558,7 +17729,7 @@ async function buildHookOutput(args) {
17558
17729
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17559
17730
  try {
17560
17731
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17561
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17732
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17562
17733
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17563
17734
  // tool still get the deeper high-budget path.
17564
17735
  budget: "low",
@@ -17586,6 +17757,10 @@ async function buildHookOutput(args) {
17586
17757
  error: describeError(e, 1500),
17587
17758
  query: prompt.slice(0, 80)
17588
17759
  });
17760
+ if (e instanceof ReflectError && e.fallbackEligible) {
17761
+ fallback = await reflectFallback(harness, prompt, client);
17762
+ if (fallback) reflectAnswer = fallback.memory;
17763
+ }
17589
17764
  }
17590
17765
  }
17591
17766
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17619,7 +17794,10 @@ async function buildHookOutput(args) {
17619
17794
  }
17620
17795
  const kept = blocks.filter(Boolean);
17621
17796
  let notice;
17622
- if (reflectRanThisTurn && reflectAnswer) {
17797
+ if (fallback) {
17798
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17799
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17800
+ } else if (reflectRanThisTurn && reflectAnswer) {
17623
17801
  const q = prompt.replace(/\s+/g, " ").trim();
17624
17802
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17625
17803
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -17655,6 +17833,8 @@ var RuntimeCore = class {
17655
17833
  sessionState = /* @__PURE__ */ new Map();
17656
17834
  /** Live write-back cursors. In memory, unlike the hook harnesses': this host outlives the session. */
17657
17835
  cursors = memoryCursorStore();
17836
+ /** Turns already written to the usage log (core/usage.ts), per session. */
17837
+ usageCursors = memoryUsageCursorStore();
17658
17838
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
17659
17839
  fetchTranscript;
17660
17840
  lastInjection = "";
@@ -17777,9 +17957,10 @@ var RuntimeCore = class {
17777
17957
  * (`engine.retain.fold`), so submitting every turn costs one extraction, not one per turn, and
17778
17958
  * nothing is ever held somewhere it can be lost.
17779
17959
  */
17780
- async onTranscript(sessionId, turns) {
17960
+ async onTranscript(sessionId, turns, lastTurnComplete) {
17781
17961
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17782
17962
  if (!this.writeBackEnabled || !sessionId || !turns.length) return;
17963
+ this.recordUsage(sessionId, turns, lastTurnComplete);
17783
17964
  const st = this.stateFor(sessionId);
17784
17965
  this.retain(sessionId, turns, st.startTs);
17785
17966
  }
@@ -17809,11 +17990,22 @@ var RuntimeCore = class {
17809
17990
  return;
17810
17991
  }
17811
17992
  if (!turns.length) return;
17993
+ this.recordUsage(sessionId, turns, true);
17812
17994
  const st = this.stateFor(sessionId);
17813
17995
  if (turns.length <= st.retainedTurns) return;
17814
17996
  st.retainedTurns = turns.length;
17815
17997
  this.retain(sessionId, turns, st.startTs, "idle");
17816
17998
  }
17999
+ recordUsage(sessionId, turns, lastTurnComplete) {
18000
+ recordUsage({
18001
+ harness: this.harness,
18002
+ sessionId,
18003
+ bankId: this.bankId,
18004
+ turns,
18005
+ cursors: this.usageCursors,
18006
+ lastTurnComplete
18007
+ });
18008
+ }
17817
18009
  stateFor(sessionId) {
17818
18010
  let st = this.sessionState.get(sessionId);
17819
18011
  if (!st) {