@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/cline.js CHANGED
@@ -6,8 +6,8 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/core/config.ts
8
8
  import { readFileSync as readFileSync2 } from "fs";
9
- import { homedir as homedir2 } from "os";
10
- import { join as join6 } from "path";
9
+ import { homedir as homedir3 } from "os";
10
+ import { join as join7 } from "path";
11
11
 
12
12
  // src/core/seed.ts
13
13
  import { spawn as realSpawn } from "child_process";
@@ -44,16 +44,28 @@ function startBackgroundSeed(repoDir, opts = {}) {
44
44
 
45
45
  // src/core/bank.ts
46
46
  import { existsSync } from "fs";
47
- import { homedir } from "os";
48
- import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
47
+ import { homedir as homedir2 } from "os";
48
+ import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
49
49
 
50
50
  // src/core/diag.ts
51
- import { appendFileSync as appendFileSync2 } from "fs";
51
+ import { join as join3 } from "path";
52
52
 
53
53
  // src/core/log.ts
54
- import { appendFileSync, mkdirSync } from "fs";
55
- import { tmpdir } from "os";
54
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
55
+ import { homedir } from "os";
56
56
  import { dirname as dirname2, join as join2 } from "path";
57
+ function logsDir() {
58
+ return join2(homedir(), ".hindsight", "coding-agents-logs");
59
+ }
60
+ var LOG_MAX_BYTES = 10 * 1024 * 1024;
61
+ function appendLogLine(file2, text) {
62
+ mkdirSync(dirname2(file2), { recursive: true, mode: 448 });
63
+ try {
64
+ if (statSync(file2).size >= LOG_MAX_BYTES) renameSync(file2, `${file2}.1`);
65
+ } catch {
66
+ }
67
+ appendFileSync(file2, text, { mode: 384 });
68
+ }
57
69
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
58
70
  var current = ["debug", "info", "warn", "error"].find(
59
71
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -62,15 +74,13 @@ function setLogLevel(level) {
62
74
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
63
75
  }
64
76
  function logFilePath() {
65
- return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
77
+ return process.env.HINDSIGHT_LOG_FILE || join2(logsDir(), "plugin.log");
66
78
  }
67
79
  function write(level, scope, msg, extra) {
68
80
  if (WEIGHT[level] < WEIGHT[current]) return;
69
81
  try {
70
- const file2 = logFilePath();
71
- mkdirSync(dirname2(file2), { recursive: true });
72
- appendFileSync(
73
- file2,
82
+ appendLogLine(
83
+ logFilePath(),
74
84
  `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
75
85
  );
76
86
  } catch {
@@ -99,12 +109,12 @@ function describeError(value, maxChars = 200) {
99
109
 
100
110
  // src/core/diag.ts
101
111
  function diagFilePath() {
102
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
112
+ return process.env.HINDSIGHT_DIAG_FILE || join3(logsDir(), "diag.jsonl");
103
113
  }
104
114
  function diag(harness, event, extra = {}) {
105
115
  log.debug(harness, `diag:${event}`, extra);
106
116
  try {
107
- appendFileSync2(
117
+ appendLogLine(
108
118
  diagFilePath(),
109
119
  JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
110
120
  );
@@ -114,7 +124,7 @@ function diag(harness, event, extra = {}) {
114
124
 
115
125
  // src/core/git-layout.ts
116
126
  import { lstatSync, readFileSync, realpathSync } from "fs";
117
- import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
127
+ import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
118
128
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
119
129
  var ATTEMPTS = 3;
120
130
  var BACKOFF_MS = 20;
@@ -150,16 +160,16 @@ function gitDirFromPointer(text, holder) {
150
160
  return isAbsolute(target) ? target : resolve(holder, target);
151
161
  }
152
162
  function commonDirOf(gitDir) {
153
- const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
163
+ const pointer = entryKind(join4(gitDir, "commondir")) === "file" ? readTextOrNull(join4(gitDir, "commondir"))?.trim() : null;
154
164
  if (!pointer) return gitDir;
155
165
  return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
156
166
  }
157
167
  function isBare(commonDir) {
158
- const config2 = readTextOrNull(join3(commonDir, "config"));
168
+ const config2 = readTextOrNull(join4(commonDir, "config"));
159
169
  return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
160
170
  }
161
171
  function looksLikeBareRepository(directory) {
162
- return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
172
+ return entryKind(join4(directory, "HEAD")) === "file" && entryKind(join4(directory, "objects")) === "dir" && entryKind(join4(directory, "refs")) === "dir";
163
173
  }
164
174
  function canonical(path) {
165
175
  try {
@@ -176,7 +186,7 @@ function resolved(commonDir) {
176
186
  function probeOnce(directory) {
177
187
  let current2 = resolve(directory);
178
188
  for (; ; ) {
179
- const dotGit = join3(current2, ".git");
189
+ const dotGit = join4(current2, ".git");
180
190
  const kind = entryKind(dotGit);
181
191
  if (kind === "dir") {
182
192
  const layout = resolved(commonDirOf(dotGit));
@@ -290,7 +300,7 @@ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
290
300
  return dirName(sessionRoot || directory);
291
301
  }
292
302
  function configuredDir(dir) {
293
- const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
303
+ const expanded = dir === "~" || dir.startsWith("~/") ? join5(homedir2(), dir.slice(1)) : dir;
294
304
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
295
305
  }
296
306
  function isWithin(directory, configured) {
@@ -594,7 +604,7 @@ function codingBankManifest(overrides) {
594
604
 
595
605
  // src/core/util.ts
596
606
  import { accessSync, constants } from "fs";
597
- import { delimiter, join as join5 } from "path";
607
+ import { delimiter, join as join6 } from "path";
598
608
  function binOnPath(bin) {
599
609
  try {
600
610
  if (bin.includes("/")) {
@@ -604,7 +614,7 @@ function binOnPath(bin) {
604
614
  for (const dir of (process.env.PATH || "").split(delimiter)) {
605
615
  if (!dir) continue;
606
616
  try {
607
- accessSync(join5(dir, bin), constants.X_OK);
617
+ accessSync(join6(dir, bin), constants.X_OK);
608
618
  return true;
609
619
  } catch {
610
620
  }
@@ -676,6 +686,22 @@ var KnowledgePagesUnavailableError = class extends Error {
676
686
  }
677
687
  };
678
688
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
689
+ var ReflectError = class extends Error {
690
+ constructor(message, status, timedOut, options) {
691
+ super(message, options);
692
+ this.status = status;
693
+ this.timedOut = timedOut;
694
+ this.name = "ReflectError";
695
+ }
696
+ status;
697
+ timedOut;
698
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
699
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
700
+ * every endpoint (auth, missing bank), so it is not. */
701
+ get fallbackEligible() {
702
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
703
+ }
704
+ };
679
705
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
680
706
  var POLL_CYCLE_MS = 5e3;
681
707
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -759,11 +785,11 @@ var HindsightClient = class {
759
785
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
760
786
  }
761
787
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
762
- async req(method, url2, body, tolerate = []) {
788
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
763
789
  const r = await this.fetchWithAuth(url2, {
764
790
  method,
765
791
  body: body ? JSON.stringify(body) : void 0,
766
- signal: AbortSignal.timeout(15e3)
792
+ signal: AbortSignal.timeout(timeoutMs)
767
793
  });
768
794
  if (r.status === 429 && !tolerate.includes(429))
769
795
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -956,7 +982,7 @@ var HindsightClient = class {
956
982
  /**
957
983
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
958
984
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
959
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
985
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
960
986
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
961
987
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
962
988
  */
@@ -970,19 +996,45 @@ var HindsightClient = class {
970
996
  signal: ctrl.signal
971
997
  });
972
998
  if (!resp.ok)
973
- throw new Error(
974
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
999
+ throw new ReflectError(
1000
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
1001
+ resp.status,
1002
+ false
975
1003
  );
976
1004
  const data = await resp.json();
977
1005
  return (data.text || "").trim();
978
1006
  } catch (e) {
979
1007
  if (ctrl.signal.aborted)
980
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
1008
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1009
+ cause: e
1010
+ });
981
1011
  throw e;
982
1012
  } finally {
983
1013
  clearTimeout(timer);
984
1014
  }
985
1015
  }
1016
+ /**
1017
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1018
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1019
+ */
1020
+ async recallObservations(query, opts) {
1021
+ const r = await this.req(
1022
+ "POST",
1023
+ this.bankUrl("/memories/recall"),
1024
+ {
1025
+ query,
1026
+ types: ["observation"],
1027
+ budget: "low",
1028
+ max_tokens: opts.maxTokens,
1029
+ include: { entities: null }
1030
+ },
1031
+ [],
1032
+ opts.timeoutMs
1033
+ );
1034
+ if (r.status === 404) return [];
1035
+ const j = await r.json();
1036
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1037
+ }
986
1038
  /**
987
1039
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
988
1040
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1047,10 +1099,16 @@ var HindsightClient = class {
1047
1099
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1048
1100
  * Returns page-level hits with a relevance snippet — the real search behind
1049
1101
  * hindsight_search_knowledge_pages. */
1050
- async searchKnowledgePages(query, limit = 3) {
1102
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1051
1103
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1052
1104
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1053
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1105
+ const r = await this.req(
1106
+ "GET",
1107
+ this.bankUrl(`/knowledge-base/search${q}`),
1108
+ void 0,
1109
+ [],
1110
+ timeoutMs
1111
+ );
1054
1112
  const j = await r.json();
1055
1113
  return (j.results ?? []).map((x) => ({
1056
1114
  id: x.id,
@@ -1237,7 +1295,7 @@ var HindsightClient = class {
1237
1295
  };
1238
1296
 
1239
1297
  // src/core/config.ts
1240
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1298
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join7(homedir3(), ".hindsight", "coding-agent.json");
1241
1299
  var DEFAULT_DAEMON_PORT = 9077;
1242
1300
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1243
1301
  function resolvePageTrigger(raw) {
@@ -1531,20 +1589,20 @@ import {
1531
1589
  unlinkSync,
1532
1590
  writeFileSync
1533
1591
  } from "fs";
1534
- import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1535
- import { dirname as dirname5, join as join7 } from "path";
1592
+ import { homedir as homedir4, tmpdir } from "os";
1593
+ import { dirname as dirname5, join as join8 } from "path";
1536
1594
  import { fileURLToPath as fileURLToPath2 } from "url";
1537
1595
  var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1538
1596
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1539
1597
  var FETCH_TIMEOUT_MS = 5e3;
1540
1598
  function stateFile(runtimeDir) {
1541
- return join7(runtimeDir, ".update-check.json");
1599
+ return join8(runtimeDir, ".update-check.json");
1542
1600
  }
1543
1601
  function packageRoot() {
1544
- return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
1602
+ return join8(dirname5(fileURLToPath2(import.meta.url)), "..");
1545
1603
  }
1546
1604
  function stagedRuntimeDir() {
1547
- return join7(homedir3(), ".hindsight", "coding-agents");
1605
+ return join8(homedir4(), ".hindsight", "coding-agents");
1548
1606
  }
1549
1607
  function sameDir(a, b) {
1550
1608
  try {
@@ -1555,7 +1613,7 @@ function sameDir(a, b) {
1555
1613
  }
1556
1614
  function stagedVersion(pkgRoot) {
1557
1615
  try {
1558
- const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
1616
+ const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1559
1617
  return typeof pkg.version === "string" ? pkg.version : "";
1560
1618
  } catch {
1561
1619
  return "";
@@ -1589,7 +1647,7 @@ function dueForCheck(file2, now) {
1589
1647
  var ORIGIN_FILE = ".install-origin.json";
1590
1648
  function selfUpdatable(runtimeDir) {
1591
1649
  try {
1592
- const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
1650
+ const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1593
1651
  if (typeof origin.source !== "string" || !origin.source) return false;
1594
1652
  return origin.source.split(/[\\/]/).includes("_npx");
1595
1653
  } catch {
@@ -1598,7 +1656,7 @@ function selfUpdatable(runtimeDir) {
1598
1656
  }
1599
1657
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1600
1658
  function lockFile() {
1601
- return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
1659
+ return join8(tmpdir(), "hindsight-coding-agent", "auto-update.lock");
1602
1660
  }
1603
1661
  function acquireUpdateLock(file2, now) {
1604
1662
  try {
@@ -1715,7 +1773,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
1715
1773
 
1716
1774
  // src/core/daemon.ts
1717
1775
  import { execFileSync, spawn as realSpawn3 } from "child_process";
1718
- import { dirname as dirname6, join as join8 } from "path";
1776
+ import { dirname as dirname6, join as join9 } from "path";
1719
1777
  import { fileURLToPath as fileURLToPath3 } from "url";
1720
1778
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1721
1779
  var DAEMON_WAIT_RETAIN_MS = 4e4;
@@ -1790,7 +1848,7 @@ function onPath(bin) {
1790
1848
  }
1791
1849
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1792
1850
  try {
1793
- const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1851
+ const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1794
1852
  const child = spawnFn("node", [starter, "--harness", harness], {
1795
1853
  detached: true,
1796
1854
  stdio: "ignore",
@@ -16359,8 +16417,8 @@ config(en_default());
16359
16417
 
16360
16418
  // src/core/knowledge-tools.ts
16361
16419
  import { existsSync as existsSync4 } from "fs";
16362
- import { homedir as homedir5 } from "os";
16363
- import { join as join11 } from "path";
16420
+ import { homedir as homedir6 } from "os";
16421
+ import { join as join12 } from "path";
16364
16422
 
16365
16423
  // src/core/status.ts
16366
16424
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16449,8 +16507,8 @@ ${toolGuide(opts)}
16449
16507
  import { spawn as realSpawn5 } from "child_process";
16450
16508
  import { createHash as createHash2 } from "crypto";
16451
16509
  import { existsSync as existsSync3 } from "fs";
16452
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16453
- import { dirname as dirname7, join as join10 } from "path";
16510
+ import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
16511
+ import { dirname as dirname7, join as join11 } from "path";
16454
16512
  import { fileURLToPath as fileURLToPath4 } from "url";
16455
16513
 
16456
16514
  // src/core/survey-lease.ts
@@ -16460,20 +16518,20 @@ import {
16460
16518
  mkdirSync as mkdirSync3,
16461
16519
  mkdtempSync,
16462
16520
  readdirSync,
16463
- renameSync,
16521
+ renameSync as renameSync2,
16464
16522
  rmdirSync,
16465
16523
  rmSync,
16466
- statSync,
16524
+ statSync as statSync2,
16467
16525
  unlinkSync as unlinkSync2,
16468
16526
  utimesSync,
16469
16527
  writeFileSync as writeFileSync2
16470
16528
  } from "fs";
16471
- import { join as join9 } from "path";
16529
+ import { join as join10 } from "path";
16472
16530
  var LEASE_STALE_MS = 3e4;
16473
16531
  var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16474
16532
  function tryRename(from, to) {
16475
16533
  try {
16476
- renameSync(from, to);
16534
+ renameSync2(from, to);
16477
16535
  return true;
16478
16536
  } catch {
16479
16537
  return false;
@@ -16481,7 +16539,7 @@ function tryRename(from, to) {
16481
16539
  }
16482
16540
  function releaseLease(lease) {
16483
16541
  try {
16484
- unlinkSync2(join9(lease.directory, lease.owner));
16542
+ unlinkSync2(join10(lease.directory, lease.owner));
16485
16543
  } catch {
16486
16544
  return;
16487
16545
  }
@@ -16500,7 +16558,7 @@ function reclaimIfStale(directory, staleMs) {
16500
16558
  return true;
16501
16559
  }
16502
16560
  if (owners.length !== 1) return false;
16503
- const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16561
+ const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
16504
16562
  if (Math.abs(age) <= staleMs) return false;
16505
16563
  releaseLease({ directory, owner: owners[0] });
16506
16564
  return true;
@@ -16509,10 +16567,10 @@ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16509
16567
  let staging;
16510
16568
  try {
16511
16569
  mkdirSync3(root, { recursive: true, mode: 448 });
16512
- staging = mkdtempSync(join9(root, "claim-"));
16570
+ staging = mkdtempSync(join10(root, "claim-"));
16513
16571
  const owner = randomUUID();
16514
- writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16515
- const directory = join9(root, `survey-${key}.lock`);
16572
+ writeFileSync2(join10(staging, owner), "", { flag: "wx", mode: 384 });
16573
+ const directory = join10(root, `survey-${key}.lock`);
16516
16574
  if (!tryRename(staging, directory)) {
16517
16575
  if (!reclaimIfStale(directory, staleMs)) return void 0;
16518
16576
  if (!tryRename(staging, directory)) return void 0;
@@ -16535,7 +16593,7 @@ var SURVEY_DOC_IDS = [
16535
16593
  function resolveClaudeBin(explicit) {
16536
16594
  if (explicit) return explicit;
16537
16595
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16538
- const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16596
+ const nativeInstallPath = join11(homedir5(), ".claude", "local", "claude");
16539
16597
  try {
16540
16598
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16541
16599
  } catch {
@@ -16653,7 +16711,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16653
16711
  try {
16654
16712
  const spawnFn = opts.spawn ?? realSpawn5;
16655
16713
  const exists = opts.exists ?? binOnPath;
16656
- const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16714
+ const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16657
16715
  const preferred = opts.harness ?? "claude-code";
16658
16716
  const order = [
16659
16717
  preferred,
@@ -16677,7 +16735,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16677
16735
  if (cfg.disabled) return false;
16678
16736
  const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16679
16737
  const lease = acquireLease(
16680
- opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16738
+ opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
16681
16739
  key,
16682
16740
  opts.lease?.staleMs ?? LEASE_STALE_MS
16683
16741
  );
@@ -16688,7 +16746,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16688
16746
  args: plan.args,
16689
16747
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16690
16748
  };
16691
- const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16749
+ const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16692
16750
  return await new Promise((resolve3) => {
16693
16751
  try {
16694
16752
  const child = spawnFn("node", [supervisorPath], {
@@ -16830,7 +16888,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16830
16888
  inputSchema: {},
16831
16889
  annotations: READ_ONLY_ANNOTATIONS,
16832
16890
  handler: async (_args) => {
16833
- const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16891
+ const configPath = process.env.HINDSIGHT_CONFIG || join12(homedir6(), ".hindsight", "coding-agent.json");
16834
16892
  const harness = opts.harness ?? "unknown";
16835
16893
  const cfg = applyBankConfig(
16836
16894
  loadConfig({ harness: opts.harness }),
@@ -16860,7 +16918,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16860
16918
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
16861
16919
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
16862
16920
  log_level: process.env.HINDSIGHT_LOG_LEVEL ?? null,
16863
- diagnostics_file: process.env.HINDSIGHT_DIAG_FILE ?? "/tmp/hindsight-plugin.log",
16921
+ diagnostics_file: diagFilePath(),
16864
16922
  channel_id_configured: Boolean(process.env.HINDSIGHT_CHANNEL_ID),
16865
16923
  user_id_configured: Boolean(process.env.HINDSIGHT_USER_ID)
16866
16924
  }
@@ -17161,6 +17219,64 @@ ${content}`);
17161
17219
  }
17162
17220
  }
17163
17221
 
17222
+ // src/core/usage.ts
17223
+ import { readFileSync as readFileSync4 } from "fs";
17224
+ import { join as join13 } from "path";
17225
+ function usageFilePath() {
17226
+ return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
17227
+ }
17228
+ var HINDSIGHT_TOOL_RE = /hindsight_(?:[a-z]+_)*[a-z]+$/;
17229
+ var CREDIT_RE = /from hindsight memory/i;
17230
+ var ASSISTANT_ROLES = /* @__PURE__ */ new Set(["assistant", "model"]);
17231
+ function summarizeTurns(turns) {
17232
+ const out = [];
17233
+ for (const t of turns) {
17234
+ if (t.role === "user") {
17235
+ out.push({ turn: out.length + 1, calls: [], credited: false });
17236
+ continue;
17237
+ }
17238
+ const current2 = out.at(-1);
17239
+ if (!current2) continue;
17240
+ if (t.role === "action") {
17241
+ const tool = t.content.split(" ", 1)[0].match(HINDSIGHT_TOOL_RE)?.[0];
17242
+ if (tool) current2.calls.push(tool);
17243
+ } else if (ASSISTANT_ROLES.has(t.role) && CREDIT_RE.test(t.content)) {
17244
+ current2.credited = true;
17245
+ }
17246
+ }
17247
+ return out;
17248
+ }
17249
+ function memoryUsageCursorStore() {
17250
+ const recorded = /* @__PURE__ */ new Map();
17251
+ return {
17252
+ read: (sessionId2) => recorded.get(sessionId2),
17253
+ write: (sessionId2, turns) => void recorded.set(sessionId2, turns)
17254
+ };
17255
+ }
17256
+ function recordUsage(args) {
17257
+ const summary = summarizeTurns(args.turns);
17258
+ const finished = args.lastTurnComplete ? summary : summary.slice(0, -1);
17259
+ const from = args.cursors.read(args.sessionId) ?? 0;
17260
+ if (finished.length <= from) return;
17261
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
17262
+ const lines = finished.slice(from).map(
17263
+ (u) => JSON.stringify({
17264
+ ts,
17265
+ harness: args.harness,
17266
+ session: args.sessionId,
17267
+ bank: args.bankId,
17268
+ turn: u.turn,
17269
+ calls: u.calls,
17270
+ credited: u.credited
17271
+ }) + "\n"
17272
+ ).join("");
17273
+ try {
17274
+ appendLogLine(usageFilePath(), lines);
17275
+ args.cursors.write(args.sessionId, finished.length);
17276
+ } catch {
17277
+ }
17278
+ }
17279
+
17164
17280
  // src/core/retain-stamp.ts
17165
17281
  import { basename as basename2 } from "path";
17166
17282
  var RESERVED_TAG_PREFIX = /^(source|harness):/;
@@ -17209,12 +17325,12 @@ function buildRetainStamp(cfg, ctx) {
17209
17325
  }
17210
17326
 
17211
17327
  // src/core/session-start.ts
17212
- import { readFileSync as readFileSync7 } from "fs";
17328
+ import { readFileSync as readFileSync8 } from "fs";
17213
17329
 
17214
17330
  // src/core/skill-sync.ts
17215
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17216
- import { homedir as homedir6 } from "os";
17217
- import { dirname as dirname8, join as join12 } from "path";
17331
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17332
+ import { homedir as homedir7 } from "os";
17333
+ import { dirname as dirname8, join as join14 } from "path";
17218
17334
  import { fileURLToPath as fileURLToPath5 } from "url";
17219
17335
 
17220
17336
  // src/core/brand.ts
@@ -17232,15 +17348,15 @@ function brandWord() {
17232
17348
  }
17233
17349
 
17234
17350
  // src/core/legacy.ts
17235
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17236
- import { homedir as homedir7 } from "os";
17237
- import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17351
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
17352
+ import { homedir as homedir8 } from "os";
17353
+ import { join as join15, relative, isAbsolute as isAbsolute2 } from "path";
17238
17354
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17239
- function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17240
- const registry2 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17355
+ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")) {
17356
+ const registry2 = readJson(join15(claudeDir, "plugins", "installed_plugins.json"));
17241
17357
  const plugins = registry2?.plugins;
17242
17358
  if (!plugins || typeof plugins !== "object") return void 0;
17243
- const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17359
+ const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
17244
17360
  for (const [key, raw] of Object.entries(plugins)) {
17245
17361
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17246
17362
  if (enabled && enabled[key] === false) continue;
@@ -17257,7 +17373,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")
17257
17373
  }
17258
17374
  function readJson(path) {
17259
17375
  try {
17260
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
17376
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
17261
17377
  return parsed && typeof parsed === "object" ? parsed : void 0;
17262
17378
  } catch {
17263
17379
  return void 0;
@@ -17269,15 +17385,15 @@ function legacyClaudePluginWarning(key) {
17269
17385
  }
17270
17386
 
17271
17387
  // src/core/session-cache.ts
17272
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17273
- import { tmpdir as tmpdir4 } from "os";
17274
- import { dirname as dirname9, join as join14 } from "path";
17388
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17389
+ import { tmpdir as tmpdir3 } from "os";
17390
+ import { dirname as dirname9, join as join16 } from "path";
17275
17391
  function sessionCacheFile(harness, sessionId2) {
17276
- return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId2}.json`);
17392
+ return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
17277
17393
  }
17278
17394
  function readSessionCache(cacheFile) {
17279
17395
  try {
17280
- return JSON.parse(readFileSync6(cacheFile, "utf8"));
17396
+ return JSON.parse(readFileSync7(cacheFile, "utf8"));
17281
17397
  } catch {
17282
17398
  return {};
17283
17399
  }
@@ -17287,7 +17403,7 @@ function writeFileAtomic(path, body) {
17287
17403
  const tmp = `${path}.${process.pid}.tmp`;
17288
17404
  try {
17289
17405
  writeFileSync3(tmp, body);
17290
- renameSync2(tmp, path);
17406
+ renameSync3(tmp, path);
17291
17407
  } catch (e) {
17292
17408
  try {
17293
17409
  rmSync2(tmp, { force: true });
@@ -17463,7 +17579,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17463
17579
  }
17464
17580
 
17465
17581
  // src/core/hook.ts
17466
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17582
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
17467
17583
 
17468
17584
  // src/core/inject.ts
17469
17585
  function buildReflectQuery(prompt) {
@@ -17481,6 +17597,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17481
17597
  - 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.
17482
17598
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17483
17599
  }
17600
+ function formatPageFallback(hits) {
17601
+ 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) => {
17602
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17603
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17604
+ }).join("\n");
17605
+ }
17606
+ function formatObservationFallback(observations) {
17607
+ 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");
17608
+ }
17484
17609
  function buildSystemInjection(memory) {
17485
17610
  return `<hindsight_memory>
17486
17611
  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.
@@ -17495,13 +17620,58 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17495
17620
  }
17496
17621
 
17497
17622
  // src/core/turn-journal.ts
17498
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17499
- import { tmpdir as tmpdir5 } from "os";
17500
- import { dirname as dirname10, join as join15 } from "path";
17623
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
17624
+ import { tmpdir as tmpdir4 } from "os";
17625
+ import { dirname as dirname10, join as join17 } from "path";
17501
17626
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17502
17627
 
17503
17628
  // src/core/hook.ts
17504
- var HOOK_REFLECT_CAP_MS = 25e3;
17629
+ var HOOK_REFLECT_CAP_MS = 2e4;
17630
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17631
+ var FALLBACK_PAGE_LIMIT = 3;
17632
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17633
+ async function reflectFallback(harness, prompt, client) {
17634
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17635
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17636
+ const query = prompt.slice(0, 500);
17637
+ let t0 = Date.now();
17638
+ try {
17639
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17640
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17641
+ if (hits.length) {
17642
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17643
+ }
17644
+ } catch (e) {
17645
+ diag(harness, "reflect_fallback_pages_failed", {
17646
+ ms: Date.now() - t0,
17647
+ error: describeError(e)
17648
+ });
17649
+ }
17650
+ t0 = Date.now();
17651
+ try {
17652
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17653
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17654
+ timeoutMs: remaining()
17655
+ });
17656
+ diag(harness, "reflect_fallback_observations", {
17657
+ ms: Date.now() - t0,
17658
+ count: observations.length
17659
+ });
17660
+ if (observations.length) {
17661
+ return {
17662
+ memory: formatObservationFallback(observations),
17663
+ source: "observations",
17664
+ count: observations.length
17665
+ };
17666
+ }
17667
+ } catch (e) {
17668
+ diag(harness, "reflect_fallback_observations_failed", {
17669
+ ms: Date.now() - t0,
17670
+ error: describeError(e)
17671
+ });
17672
+ }
17673
+ return void 0;
17674
+ }
17505
17675
  async function buildHookOutput(args) {
17506
17676
  const { harness, prompt, cfg, client, cacheFile } = args;
17507
17677
  const cached2 = readSessionCache(cacheFile);
@@ -17509,6 +17679,7 @@ async function buildHookOutput(args) {
17509
17679
  let reflectAnswer = cached2.reflectAnswer;
17510
17680
  let reflectRanThisTurn = false;
17511
17681
  let reflectFailed = false;
17682
+ let fallback;
17512
17683
  const deferInitialReflect = cached2.deferInitialReflect === true;
17513
17684
  if (deferInitialReflect) {
17514
17685
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17518,7 +17689,7 @@ async function buildHookOutput(args) {
17518
17689
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17519
17690
  try {
17520
17691
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17521
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17692
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17522
17693
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17523
17694
  // tool still get the deeper high-budget path.
17524
17695
  budget: "low",
@@ -17546,6 +17717,10 @@ async function buildHookOutput(args) {
17546
17717
  error: describeError(e, 1500),
17547
17718
  query: prompt.slice(0, 80)
17548
17719
  });
17720
+ if (e instanceof ReflectError && e.fallbackEligible) {
17721
+ fallback = await reflectFallback(harness, prompt, client);
17722
+ if (fallback) reflectAnswer = fallback.memory;
17723
+ }
17549
17724
  }
17550
17725
  }
17551
17726
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17579,7 +17754,10 @@ async function buildHookOutput(args) {
17579
17754
  }
17580
17755
  const kept = blocks.filter(Boolean);
17581
17756
  let notice;
17582
- if (reflectRanThisTurn && reflectAnswer) {
17757
+ if (fallback) {
17758
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17759
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17760
+ } else if (reflectRanThisTurn && reflectAnswer) {
17583
17761
  const q = prompt.replace(/\s+/g, " ").trim();
17584
17762
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17585
17763
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -17615,6 +17793,8 @@ var RuntimeCore = class {
17615
17793
  sessionState = /* @__PURE__ */ new Map();
17616
17794
  /** Live write-back cursors. In memory, unlike the hook harnesses': this host outlives the session. */
17617
17795
  cursors = memoryCursorStore();
17796
+ /** Turns already written to the usage log (core/usage.ts), per session. */
17797
+ usageCursors = memoryUsageCursorStore();
17618
17798
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
17619
17799
  fetchTranscript;
17620
17800
  lastInjection = "";
@@ -17737,9 +17917,10 @@ var RuntimeCore = class {
17737
17917
  * (`engine.retain.fold`), so submitting every turn costs one extraction, not one per turn, and
17738
17918
  * nothing is ever held somewhere it can be lost.
17739
17919
  */
17740
- async onTranscript(sessionId2, turns) {
17920
+ async onTranscript(sessionId2, turns, lastTurnComplete) {
17741
17921
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17742
17922
  if (!this.writeBackEnabled || !sessionId2 || !turns.length) return;
17923
+ this.recordUsage(sessionId2, turns, lastTurnComplete);
17743
17924
  const st = this.stateFor(sessionId2);
17744
17925
  this.retain(sessionId2, turns, st.startTs);
17745
17926
  }
@@ -17769,11 +17950,22 @@ var RuntimeCore = class {
17769
17950
  return;
17770
17951
  }
17771
17952
  if (!turns.length) return;
17953
+ this.recordUsage(sessionId2, turns, true);
17772
17954
  const st = this.stateFor(sessionId2);
17773
17955
  if (turns.length <= st.retainedTurns) return;
17774
17956
  st.retainedTurns = turns.length;
17775
17957
  this.retain(sessionId2, turns, st.startTs, "idle");
17776
17958
  }
17959
+ recordUsage(sessionId2, turns, lastTurnComplete) {
17960
+ recordUsage({
17961
+ harness: this.harness,
17962
+ sessionId: sessionId2,
17963
+ bankId: this.bankId,
17964
+ turns,
17965
+ cursors: this.usageCursors,
17966
+ lastTurnComplete
17967
+ });
17968
+ }
17777
17969
  stateFor(sessionId2) {
17778
17970
  let st = this.sessionState.get(sessionId2);
17779
17971
  if (!st) {
@@ -17903,7 +18095,8 @@ function createClineHooks(core, configuredSessionId, sessionStart) {
17903
18095
  },
17904
18096
  async afterRun({ snapshot }) {
17905
18097
  const turns = clineTranscript(snapshot.messages);
17906
- if (turns.length) await core.onTranscript(sessionId(snapshot, configuredSessionId), turns);
18098
+ if (turns.length)
18099
+ await core.onTranscript(sessionId(snapshot, configuredSessionId), turns, true);
17907
18100
  }
17908
18101
  };
17909
18102
  }