@vectorize-io/hindsight-coding-agents 0.5.5 → 0.6.1

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 +19 -5
  2. package/dist/antigravity-hook.js +87 -83
  3. package/dist/antigravity-statusline.js +32 -22
  4. package/dist/antigravity-stop-hook.js +160 -71
  5. package/dist/claude-hook.js +87 -83
  6. package/dist/claude-sessionstart-hook.js +111 -97
  7. package/dist/claude-stop-hook.js +160 -71
  8. package/dist/cline.js +161 -88
  9. package/dist/codex-hook.js +87 -83
  10. package/dist/codex-sessionstart-hook.js +111 -97
  11. package/dist/codex-stop-hook.js +160 -71
  12. package/dist/copilot-hook.js +87 -83
  13. package/dist/copilot-sessionstart-hook.js +111 -97
  14. package/dist/copilot-stop-hook.js +160 -71
  15. package/dist/cursor-hook.js +87 -83
  16. package/dist/cursor-sessionstart-hook.js +111 -97
  17. package/dist/cursor-stop-hook.js +160 -71
  18. package/dist/daemon-start.js +28 -18
  19. package/dist/dcode-hook.js +87 -83
  20. package/dist/dcode-sessionstart-hook.js +111 -97
  21. package/dist/dcode-stop-hook.js +160 -71
  22. package/dist/deepen.js +42 -32
  23. package/dist/devin-hook.js +87 -83
  24. package/dist/devin-sessionstart-hook.js +111 -97
  25. package/dist/devin-stop-hook.js +160 -71
  26. package/dist/droid-hook.js +87 -83
  27. package/dist/droid-sessionstart-hook.js +111 -97
  28. package/dist/droid-stop-hook.js +160 -71
  29. package/dist/dsh.js +159 -87
  30. package/dist/grok-hook.js +87 -83
  31. package/dist/grok-sessionstart-hook.js +111 -97
  32. package/dist/grok-stop-hook.js +160 -71
  33. package/dist/hindsight-seed.js +32 -22
  34. package/dist/index.js +162 -90
  35. package/dist/installer.js +308 -214
  36. package/dist/kilo.js +162 -90
  37. package/dist/mcp-server.js +41 -31
  38. package/dist/opencode2.js +161 -89
  39. package/dist/pi.js +161 -89
  40. package/dist/prime-agent.js +161 -89
  41. package/dist/qwen-hook.js +87 -83
  42. package/dist/qwen-sessionstart-hook.js +111 -97
  43. package/dist/qwen-stop-hook.js +160 -71
  44. package/dist/status.js +38 -28
  45. package/dist/zcode-hook.js +87 -83
  46. package/dist/zcode-sessionstart-hook.js +111 -97
  47. package/dist/zcode-stop-hook.js +160 -71
  48. package/package.json +1 -1
  49. package/plugin.json +1 -1
  50. package/skill/SKILL.md +19 -5
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
  }
@@ -1288,7 +1298,7 @@ var HindsightClient = class {
1288
1298
  };
1289
1299
 
1290
1300
  // src/core/config.ts
1291
- 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");
1292
1302
  var DEFAULT_DAEMON_PORT = 9077;
1293
1303
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1294
1304
  function resolvePageTrigger(raw) {
@@ -1582,20 +1592,20 @@ import {
1582
1592
  unlinkSync,
1583
1593
  writeFileSync
1584
1594
  } from "fs";
1585
- import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1586
- 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";
1587
1597
  import { fileURLToPath as fileURLToPath2 } from "url";
1588
1598
  var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
1589
1599
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1590
1600
  var FETCH_TIMEOUT_MS = 5e3;
1591
1601
  function stateFile(runtimeDir) {
1592
- return join7(runtimeDir, ".update-check.json");
1602
+ return join8(runtimeDir, ".update-check.json");
1593
1603
  }
1594
1604
  function packageRoot() {
1595
- return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
1605
+ return join8(dirname5(fileURLToPath2(import.meta.url)), "..");
1596
1606
  }
1597
1607
  function stagedRuntimeDir() {
1598
- return join7(homedir3(), ".hindsight", "coding-agents");
1608
+ return join8(homedir4(), ".hindsight", "coding-agents");
1599
1609
  }
1600
1610
  function sameDir(a, b) {
1601
1611
  try {
@@ -1606,7 +1616,7 @@ function sameDir(a, b) {
1606
1616
  }
1607
1617
  function stagedVersion(pkgRoot) {
1608
1618
  try {
1609
- const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
1619
+ const pkg = JSON.parse(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
1610
1620
  return typeof pkg.version === "string" ? pkg.version : "";
1611
1621
  } catch {
1612
1622
  return "";
@@ -1640,7 +1650,7 @@ function dueForCheck(file2, now) {
1640
1650
  var ORIGIN_FILE = ".install-origin.json";
1641
1651
  function selfUpdatable(runtimeDir) {
1642
1652
  try {
1643
- const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
1653
+ const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
1644
1654
  if (typeof origin.source !== "string" || !origin.source) return false;
1645
1655
  return origin.source.split(/[\\/]/).includes("_npx");
1646
1656
  } catch {
@@ -1649,7 +1659,7 @@ function selfUpdatable(runtimeDir) {
1649
1659
  }
1650
1660
  var LOCK_STALE_MS = 10 * 60 * 1e3;
1651
1661
  function lockFile() {
1652
- return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
1662
+ return join8(tmpdir(), "hindsight-coding-agent", "auto-update.lock");
1653
1663
  }
1654
1664
  function acquireUpdateLock(file2, now) {
1655
1665
  try {
@@ -1766,7 +1776,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
1766
1776
 
1767
1777
  // src/core/daemon.ts
1768
1778
  import { execFileSync, spawn as realSpawn3 } from "child_process";
1769
- import { dirname as dirname6, join as join8 } from "path";
1779
+ import { dirname as dirname6, join as join9 } from "path";
1770
1780
  import { fileURLToPath as fileURLToPath3 } from "url";
1771
1781
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
1772
1782
  var DAEMON_WAIT_RETAIN_MS = 4e4;
@@ -1841,7 +1851,7 @@ function onPath(bin) {
1841
1851
  }
1842
1852
  function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
1843
1853
  try {
1844
- const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1854
+ const starter = join9(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
1845
1855
  const child = spawnFn("node", [starter, "--harness", harness], {
1846
1856
  detached: true,
1847
1857
  stdio: "ignore",
@@ -16410,8 +16420,8 @@ config(en_default());
16410
16420
 
16411
16421
  // src/core/knowledge-tools.ts
16412
16422
  import { existsSync as existsSync4 } from "fs";
16413
- import { homedir as homedir5 } from "os";
16414
- import { join as join11 } from "path";
16423
+ import { homedir as homedir6 } from "os";
16424
+ import { join as join12 } from "path";
16415
16425
 
16416
16426
  // src/core/status.ts
16417
16427
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16500,8 +16510,8 @@ ${toolGuide(opts)}
16500
16510
  import { spawn as realSpawn5 } from "child_process";
16501
16511
  import { createHash as createHash2 } from "crypto";
16502
16512
  import { existsSync as existsSync3 } from "fs";
16503
- import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16504
- 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";
16505
16515
  import { fileURLToPath as fileURLToPath4 } from "url";
16506
16516
 
16507
16517
  // src/core/survey-lease.ts
@@ -16511,20 +16521,20 @@ import {
16511
16521
  mkdirSync as mkdirSync3,
16512
16522
  mkdtempSync,
16513
16523
  readdirSync,
16514
- renameSync,
16524
+ renameSync as renameSync2,
16515
16525
  rmdirSync,
16516
16526
  rmSync,
16517
- statSync,
16527
+ statSync as statSync2,
16518
16528
  unlinkSync as unlinkSync2,
16519
16529
  utimesSync,
16520
16530
  writeFileSync as writeFileSync2
16521
16531
  } from "fs";
16522
- import { join as join9 } from "path";
16532
+ import { join as join10 } from "path";
16523
16533
  var LEASE_STALE_MS = 3e4;
16524
16534
  var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16525
16535
  function tryRename(from, to) {
16526
16536
  try {
16527
- renameSync(from, to);
16537
+ renameSync2(from, to);
16528
16538
  return true;
16529
16539
  } catch {
16530
16540
  return false;
@@ -16532,7 +16542,7 @@ function tryRename(from, to) {
16532
16542
  }
16533
16543
  function releaseLease(lease) {
16534
16544
  try {
16535
- unlinkSync2(join9(lease.directory, lease.owner));
16545
+ unlinkSync2(join10(lease.directory, lease.owner));
16536
16546
  } catch {
16537
16547
  return;
16538
16548
  }
@@ -16551,7 +16561,7 @@ function reclaimIfStale(directory, staleMs) {
16551
16561
  return true;
16552
16562
  }
16553
16563
  if (owners.length !== 1) return false;
16554
- const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16564
+ const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
16555
16565
  if (Math.abs(age) <= staleMs) return false;
16556
16566
  releaseLease({ directory, owner: owners[0] });
16557
16567
  return true;
@@ -16560,10 +16570,10 @@ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16560
16570
  let staging;
16561
16571
  try {
16562
16572
  mkdirSync3(root, { recursive: true, mode: 448 });
16563
- staging = mkdtempSync(join9(root, "claim-"));
16573
+ staging = mkdtempSync(join10(root, "claim-"));
16564
16574
  const owner = randomUUID();
16565
- writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16566
- const directory = join9(root, `survey-${key}.lock`);
16575
+ writeFileSync2(join10(staging, owner), "", { flag: "wx", mode: 384 });
16576
+ const directory = join10(root, `survey-${key}.lock`);
16567
16577
  if (!tryRename(staging, directory)) {
16568
16578
  if (!reclaimIfStale(directory, staleMs)) return void 0;
16569
16579
  if (!tryRename(staging, directory)) return void 0;
@@ -16586,7 +16596,7 @@ var SURVEY_DOC_IDS = [
16586
16596
  function resolveClaudeBin(explicit) {
16587
16597
  if (explicit) return explicit;
16588
16598
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16589
- const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16599
+ const nativeInstallPath = join11(homedir5(), ".claude", "local", "claude");
16590
16600
  try {
16591
16601
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16592
16602
  } catch {
@@ -16704,7 +16714,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16704
16714
  try {
16705
16715
  const spawnFn = opts.spawn ?? realSpawn5;
16706
16716
  const exists = opts.exists ?? binOnPath;
16707
- 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");
16708
16718
  const preferred = opts.harness ?? "claude-code";
16709
16719
  const order = [
16710
16720
  preferred,
@@ -16728,7 +16738,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16728
16738
  if (cfg.disabled) return false;
16729
16739
  const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16730
16740
  const lease = acquireLease(
16731
- opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16741
+ opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
16732
16742
  key,
16733
16743
  opts.lease?.staleMs ?? LEASE_STALE_MS
16734
16744
  );
@@ -16739,7 +16749,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
16739
16749
  args: plan.args,
16740
16750
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16741
16751
  };
16742
- 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");
16743
16753
  return await new Promise((resolve3) => {
16744
16754
  try {
16745
16755
  const child = spawnFn("node", [supervisorPath], {
@@ -16881,7 +16891,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16881
16891
  inputSchema: {},
16882
16892
  annotations: READ_ONLY_ANNOTATIONS,
16883
16893
  handler: async (_args) => {
16884
- 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");
16885
16895
  const harness = opts.harness ?? "unknown";
16886
16896
  const cfg = applyBankConfig(
16887
16897
  loadConfig({ harness: opts.harness }),
@@ -16911,7 +16921,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16911
16921
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
16912
16922
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
16913
16923
  log_level: process.env.HINDSIGHT_LOG_LEVEL ?? null,
16914
- diagnostics_file: process.env.HINDSIGHT_DIAG_FILE ?? "/tmp/hindsight-plugin.log",
16924
+ diagnostics_file: diagFilePath(),
16915
16925
  channel_id_configured: Boolean(process.env.HINDSIGHT_CHANNEL_ID),
16916
16926
  user_id_configured: Boolean(process.env.HINDSIGHT_USER_ID)
16917
16927
  }
@@ -17212,6 +17222,64 @@ ${content}`);
17212
17222
  }
17213
17223
  }
17214
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
+
17215
17283
  // src/core/retain-stamp.ts
17216
17284
  import { basename as basename2 } from "path";
17217
17285
  var RESERVED_TAG_PREFIX = /^(source|harness):/;
@@ -17260,12 +17328,12 @@ function buildRetainStamp(cfg, ctx) {
17260
17328
  }
17261
17329
 
17262
17330
  // src/core/session-start.ts
17263
- import { readFileSync as readFileSync7 } from "fs";
17331
+ import { readFileSync as readFileSync8 } from "fs";
17264
17332
 
17265
17333
  // src/core/skill-sync.ts
17266
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17267
- import { homedir as homedir6 } from "os";
17268
- 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";
17269
17337
  import { fileURLToPath as fileURLToPath5 } from "url";
17270
17338
 
17271
17339
  // src/core/brand.ts
@@ -17283,15 +17351,15 @@ function brandWord() {
17283
17351
  }
17284
17352
 
17285
17353
  // src/core/legacy.ts
17286
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17287
- import { homedir as homedir7 } from "os";
17288
- 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";
17289
17357
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17290
- function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17291
- 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"));
17292
17360
  const plugins = registry2?.plugins;
17293
17361
  if (!plugins || typeof plugins !== "object") return void 0;
17294
- const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17362
+ const enabled = readJson(join15(claudeDir, "settings.json"))?.enabledPlugins;
17295
17363
  for (const [key, raw] of Object.entries(plugins)) {
17296
17364
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17297
17365
  if (enabled && enabled[key] === false) continue;
@@ -17308,7 +17376,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")
17308
17376
  }
17309
17377
  function readJson(path) {
17310
17378
  try {
17311
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
17379
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
17312
17380
  return parsed && typeof parsed === "object" ? parsed : void 0;
17313
17381
  } catch {
17314
17382
  return void 0;
@@ -17320,15 +17388,15 @@ function legacyClaudePluginWarning(key) {
17320
17388
  }
17321
17389
 
17322
17390
  // src/core/session-cache.ts
17323
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17324
- import { tmpdir as tmpdir4 } from "os";
17325
- 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";
17326
17394
  function sessionCacheFile(harness, sessionId) {
17327
- return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId}.json`);
17395
+ return join16(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17328
17396
  }
17329
17397
  function readSessionCache(cacheFile) {
17330
17398
  try {
17331
- return JSON.parse(readFileSync6(cacheFile, "utf8"));
17399
+ return JSON.parse(readFileSync7(cacheFile, "utf8"));
17332
17400
  } catch {
17333
17401
  return {};
17334
17402
  }
@@ -17338,7 +17406,7 @@ function writeFileAtomic(path, body) {
17338
17406
  const tmp = `${path}.${process.pid}.tmp`;
17339
17407
  try {
17340
17408
  writeFileSync3(tmp, body);
17341
- renameSync2(tmp, path);
17409
+ renameSync3(tmp, path);
17342
17410
  } catch (e) {
17343
17411
  try {
17344
17412
  rmSync2(tmp, { force: true });
@@ -17514,7 +17582,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
17514
17582
  }
17515
17583
 
17516
17584
  // src/core/hook.ts
17517
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17585
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
17518
17586
 
17519
17587
  // src/core/inject.ts
17520
17588
  function buildReflectQuery(prompt) {
@@ -17555,9 +17623,9 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17555
17623
  }
17556
17624
 
17557
17625
  // src/core/turn-journal.ts
17558
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17559
- import { tmpdir as tmpdir5 } from "os";
17560
- 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";
17561
17629
 
17562
17630
  // src/core/transcript-util.ts
17563
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;
@@ -17610,9 +17678,7 @@ async function reflectFallback(harness, prompt, client) {
17610
17678
  try {
17611
17679
  const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17612
17680
  diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17613
- if (hits.length) {
17614
- return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17615
- }
17681
+ if (hits.length) return formatPageFallback(hits);
17616
17682
  } catch (e) {
17617
17683
  diag(harness, "reflect_fallback_pages_failed", {
17618
17684
  ms: Date.now() - t0,
@@ -17629,13 +17695,7 @@ async function reflectFallback(harness, prompt, client) {
17629
17695
  ms: Date.now() - t0,
17630
17696
  count: observations.length
17631
17697
  });
17632
- if (observations.length) {
17633
- return {
17634
- memory: formatObservationFallback(observations),
17635
- source: "observations",
17636
- count: observations.length
17637
- };
17638
- }
17698
+ if (observations.length) return formatObservationFallback(observations);
17639
17699
  } catch (e) {
17640
17700
  diag(harness, "reflect_fallback_observations_failed", {
17641
17701
  ms: Date.now() - t0,
@@ -17691,7 +17751,7 @@ async function buildHookOutput(args) {
17691
17751
  });
17692
17752
  if (e instanceof ReflectError && e.fallbackEligible) {
17693
17753
  fallback = await reflectFallback(harness, prompt, client);
17694
- if (fallback) reflectAnswer = fallback.memory;
17754
+ if (fallback) reflectAnswer = fallback;
17695
17755
  }
17696
17756
  }
17697
17757
  }
@@ -17727,8 +17787,6 @@ async function buildHookOutput(args) {
17727
17787
  const kept = blocks.filter(Boolean);
17728
17788
  let notice;
17729
17789
  if (fallback) {
17730
- const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17731
- notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17732
17790
  } else if (reflectRanThisTurn && reflectAnswer) {
17733
17791
  const q = prompt.replace(/\s+/g, " ").trim();
17734
17792
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
@@ -17765,6 +17823,8 @@ var RuntimeCore = class {
17765
17823
  sessionState = /* @__PURE__ */ new Map();
17766
17824
  /** Live write-back cursors. In memory, unlike the hook harnesses': this host outlives the session. */
17767
17825
  cursors = memoryCursorStore();
17826
+ /** Turns already written to the usage log (core/usage.ts), per session. */
17827
+ usageCursors = memoryUsageCursorStore();
17768
17828
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
17769
17829
  fetchTranscript;
17770
17830
  lastInjection = "";
@@ -17887,9 +17947,10 @@ var RuntimeCore = class {
17887
17947
  * (`engine.retain.fold`), so submitting every turn costs one extraction, not one per turn, and
17888
17948
  * nothing is ever held somewhere it can be lost.
17889
17949
  */
17890
- async onTranscript(sessionId, turns) {
17950
+ async onTranscript(sessionId, turns, lastTurnComplete) {
17891
17951
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17892
17952
  if (!this.writeBackEnabled || !sessionId || !turns.length) return;
17953
+ this.recordUsage(sessionId, turns, lastTurnComplete);
17893
17954
  const st = this.stateFor(sessionId);
17894
17955
  this.retain(sessionId, turns, st.startTs);
17895
17956
  }
@@ -17919,11 +17980,22 @@ var RuntimeCore = class {
17919
17980
  return;
17920
17981
  }
17921
17982
  if (!turns.length) return;
17983
+ this.recordUsage(sessionId, turns, true);
17922
17984
  const st = this.stateFor(sessionId);
17923
17985
  if (turns.length <= st.retainedTurns) return;
17924
17986
  st.retainedTurns = turns.length;
17925
17987
  this.retain(sessionId, turns, st.startTs, "idle");
17926
17988
  }
17989
+ recordUsage(sessionId, turns, lastTurnComplete) {
17990
+ recordUsage({
17991
+ harness: this.harness,
17992
+ sessionId,
17993
+ bankId: this.bankId,
17994
+ turns,
17995
+ cursors: this.usageCursors,
17996
+ lastTurnComplete
17997
+ });
17998
+ }
17927
17999
  stateFor(sessionId) {
17928
18000
  let st = this.sessionState.get(sessionId);
17929
18001
  if (!st) {