@vectorize-io/hindsight-coding-agents 0.2.1 → 0.3.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.
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/hook.ts
4
- import { existsSync, readFileSync as readFileSync3 } from "fs";
4
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
7
  import { execFileSync } from "child_process";
8
+ import { existsSync } from "fs";
8
9
  import { homedir } from "os";
9
10
  import { basename, dirname, join, normalize, sep } from "path";
10
11
 
@@ -43,25 +44,59 @@ function getProjectRootFromGit(directory) {
43
44
  function projectNameOf(directory) {
44
45
  return gitProjectName(directory, true);
45
46
  }
47
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
48
+ function nearestExistingDir(directory) {
49
+ let current2 = directory;
50
+ while (current2) {
51
+ if (existsSync(current2)) return current2;
52
+ const parent = dirname(current2);
53
+ if (parent === current2) return "";
54
+ current2 = parent;
55
+ }
56
+ return "";
57
+ }
58
+ function dirName(directory) {
59
+ return directory && basename(directory) || "unknown";
60
+ }
46
61
  function gitProjectName(directory, resolveWorktrees) {
47
62
  if (resolveWorktrees) {
48
- const root = getProjectRootFromGit(directory);
49
- if (root) return basename(root);
63
+ const candidates = [
64
+ nearestExistingDir(directory),
65
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
66
+ ];
67
+ for (const candidate of candidates) {
68
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
69
+ if (root) return basename(root);
70
+ }
50
71
  }
51
- return directory ? basename(directory) : "unknown";
72
+ return dirName(directory);
73
+ }
74
+ function configuredDir(dir) {
75
+ const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
76
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
77
+ }
78
+ function isWithin(directory, configured) {
79
+ return directory === configured || directory.startsWith(configured + sep);
52
80
  }
53
81
  function mapLookup(map, directory) {
54
82
  const cwd = normalize(directory);
55
83
  let best;
56
84
  for (const [dir, bank] of Object.entries(map)) {
57
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
58
- const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
59
- if (cwd === p || cwd.startsWith(p + sep)) {
85
+ const p = configuredDir(dir);
86
+ if (isWithin(cwd, p)) {
60
87
  if (!best || p.length > best.len) best = { len: p.length, bank };
61
88
  }
62
89
  }
63
90
  return best?.bank;
64
91
  }
92
+ function isOptedIn(config, directory) {
93
+ if (!config.optInOnly) return true;
94
+ if (!directory) return false;
95
+ const cwd = normalize(directory);
96
+ if ((config.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
97
+ return true;
98
+ return Boolean(config.mapPathToBank && mapLookup(config.mapPathToBank, directory));
99
+ }
65
100
  function deriveBankId(config, directory, harness = "coding") {
66
101
  const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
67
102
  if (mapped) return mapped;
@@ -69,7 +104,7 @@ function deriveBankId(config, directory, harness = "coding") {
69
104
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
70
105
  const resolvers = {
71
106
  harness: () => harness,
72
- project: () => directory ? basename(directory) : "unknown",
107
+ project: () => dirName(directory),
73
108
  gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
74
109
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
75
110
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
@@ -113,11 +148,14 @@ function resolveConfig(raw = {}) {
113
148
  bankIdTemplate: raw.bankIdTemplate,
114
149
  mapPathToBank: raw.mapPathToBank,
115
150
  resolveWorktrees: raw.resolveWorktrees,
151
+ optInOnly: raw.optInOnly ?? false,
152
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
153
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
116
154
  harness: raw.harness ?? "opencode",
117
155
  disabled: raw.disabled ?? false,
118
156
  retainSessions: raw.retainSessions ?? true,
119
157
  // opencode: write back by default (parity with hook-harness Stop)
120
- retainEveryTurns: raw.retainEveryTurns || 1,
158
+ maxParallelRetains: raw.maxParallelRetains || 10,
121
159
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
122
160
  autoReflect: raw.autoReflect ?? true,
123
161
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
@@ -173,10 +211,12 @@ var ENV_KEYS = {
173
211
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
174
212
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
175
213
  resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
214
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
215
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
176
216
  harness: "HINDSIGHT_HARNESS",
177
217
  disabled: "HINDSIGHT_DISABLED",
178
218
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
179
- retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
219
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
180
220
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
181
221
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
182
222
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
@@ -195,17 +235,18 @@ var ENV_KEYS = {
195
235
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
196
236
  "dynamicBankId",
197
237
  "resolveWorktrees",
238
+ "optInOnly",
198
239
  "disabled",
199
240
  "retainSessions",
200
241
  "autoReflect",
201
242
  "autoSeed",
202
243
  "codebaseSurvey"
203
244
  ]);
204
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
245
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
205
246
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
206
247
  "apiPort",
207
248
  "daemonIdleTimeout",
208
- "retainEveryTurns",
249
+ "maxParallelRetains",
209
250
  "reflectTimeoutMs",
210
251
  "pageRefreshEveryTurns",
211
252
  "seedLimit",
@@ -245,9 +286,15 @@ var BANK_OVERRIDE_EXCLUDED = [
245
286
  "mapPathToBank",
246
287
  "dynamicBankId",
247
288
  "resolveWorktrees",
289
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
290
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
291
+ "optInOnly",
292
+ "optInPaths",
248
293
  "harness"
249
294
  ];
250
- function applyBankConfig(cfg, resolvedId) {
295
+ function applyBankConfig(cfg, resolvedId, directory) {
296
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
297
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
251
298
  const section = cfg.banks[resolvedId];
252
299
  if (!section) return { cfg, bankId: resolvedId };
253
300
  const safe = { ...section };
@@ -459,9 +506,40 @@ function semverGte(version, min) {
459
506
  }
460
507
  return true;
461
508
  }
509
+ async function pool(items, n, fn, onError, onProgress) {
510
+ let i = 0, done = 0;
511
+ async function worker() {
512
+ while (i < items.length) {
513
+ const idx = i++;
514
+ try {
515
+ await fn(items[idx], idx);
516
+ } catch (e) {
517
+ onError?.(idx, e);
518
+ }
519
+ onProgress?.(++done, items.length);
520
+ }
521
+ }
522
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
523
+ }
462
524
 
463
525
  // src/core/hindsight.ts
464
526
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
527
+ var RateLimitedError = class extends Error {
528
+ constructor(retryAfterMs2) {
529
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
530
+ this.retryAfterMs = retryAfterMs2;
531
+ this.name = "RateLimitedError";
532
+ }
533
+ retryAfterMs;
534
+ code = "rate_limited";
535
+ };
536
+ function retryAfterMs(header) {
537
+ if (!header) return 0;
538
+ const secs = Number(header.trim());
539
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
540
+ const at = Date.parse(header);
541
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
542
+ }
465
543
  var KnowledgePagesUnavailableError = class extends Error {
466
544
  code = "knowledge_pages_unavailable";
467
545
  constructor() {
@@ -470,6 +548,10 @@ var KnowledgePagesUnavailableError = class extends Error {
470
548
  }
471
549
  };
472
550
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
551
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
552
+ var POLL_CYCLE_MS = 5e3;
553
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
554
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
473
555
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
474
556
  var HindsightClient = class {
475
557
  apiUrl;
@@ -482,12 +564,14 @@ var HindsightClient = class {
482
564
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
483
565
  idempotentRetain;
484
566
  log;
567
+ maxParallelRetains;
485
568
  constructor(o) {
486
569
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
487
570
  this.apiToken = o.apiToken;
488
571
  this.bank = o.bank;
489
572
  this.log = o.log ?? (() => {
490
573
  });
574
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
491
575
  }
492
576
  headers() {
493
577
  const h = { "Content-Type": "application/json" };
@@ -505,6 +589,8 @@ var HindsightClient = class {
505
589
  body: body ? JSON.stringify(body) : void 0,
506
590
  signal: AbortSignal.timeout(15e3)
507
591
  });
592
+ if (r.status === 429 && !tolerate.includes(429))
593
+ throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
508
594
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
509
595
  throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
510
596
  return r;
@@ -636,7 +722,14 @@ var HindsightClient = class {
636
722
  return 0;
637
723
  }
638
724
  }
639
- /** Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable. */
725
+ /**
726
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
727
+ *
728
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
729
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
730
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
731
+ * of hammering the next cycle 5s later.
732
+ */
640
733
  async drain(ids, label, maxMs = 60 * 60 * 1e3) {
641
734
  if (!ids.length) return;
642
735
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
@@ -644,23 +737,29 @@ var HindsightClient = class {
644
737
  const pending = new Set(ids);
645
738
  let failed = 0;
646
739
  while (pending.size && Date.now() - start < maxMs) {
647
- await Promise.all(
648
- [...pending].map(async (id) => {
649
- try {
650
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
651
- if (!r.ok) return;
652
- const st = ((await r.json()).status || "").toLowerCase();
653
- if (TERMINAL.has(st)) {
654
- pending.delete(id);
655
- if (st !== "completed") failed++;
656
- }
657
- } catch {
740
+ let backoffMs = POLL_CYCLE_MS;
741
+ await pool([...pending], this.maxParallelRetains, async (id) => {
742
+ try {
743
+ const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
744
+ if (r.status === 429) {
745
+ backoffMs = Math.min(
746
+ RETRY_AFTER_CEILING_MS,
747
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
748
+ );
749
+ return;
658
750
  }
659
- })
660
- );
751
+ if (!r.ok) return;
752
+ const st = ((await r.json()).status || "").toLowerCase();
753
+ if (TERMINAL.has(st)) {
754
+ pending.delete(id);
755
+ if (st !== "completed") failed++;
756
+ }
757
+ } catch {
758
+ }
759
+ });
661
760
  if (pending.size) {
662
761
  this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
663
- await sleep(5e3);
762
+ await sleep(backoffMs);
664
763
  }
665
764
  }
666
765
  this.log(
@@ -860,13 +959,20 @@ var HindsightClient = class {
860
959
  const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
861
960
  const content = `${verb}: ${args.title}. ${args.summary}`;
862
961
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
863
- await this.retain(
864
- content,
865
- "initiative marker",
866
- markerId,
867
- ["knowledge:feature-work", `relatedPageId:${pageId}`],
868
- "document"
869
- );
962
+ const tags = [
963
+ .../* @__PURE__ */ new Set([
964
+ ...args.stamp?.tags ?? [],
965
+ "knowledge:feature-work",
966
+ `relatedPageId:${pageId}`
967
+ ])
968
+ ];
969
+ if (Object.keys(args.stamp?.metadata ?? {}).length) {
970
+ await this.retain(content, "initiative marker", markerId, tags, "document", {
971
+ metadata: args.stamp?.metadata
972
+ });
973
+ } else {
974
+ await this.retain(content, "initiative marker", markerId, tags, "document");
975
+ }
870
976
  return { page_id: pageId };
871
977
  }
872
978
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -889,32 +995,40 @@ var HindsightClient = class {
889
995
  };
890
996
 
891
997
  // src/core/session-cache.ts
892
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
998
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
893
999
  import { tmpdir as tmpdir2 } from "os";
894
1000
  import { dirname as dirname4, join as join5 } from "path";
895
- function sessionCacheFile(harness, sessionId) {
896
- return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
897
- }
898
- function readSessionCache(cacheFile) {
1001
+ function writeFileAtomic(path, body) {
1002
+ mkdirSync2(dirname4(path), { recursive: true });
1003
+ const tmp = `${path}.${process.pid}.tmp`;
899
1004
  try {
900
- return JSON.parse(readFileSync2(cacheFile, "utf8"));
901
- } catch {
902
- return {};
1005
+ writeFileSync(tmp, body);
1006
+ renameSync(tmp, path);
1007
+ } catch (e) {
1008
+ try {
1009
+ rmSync(tmp, { force: true });
1010
+ } catch {
1011
+ }
1012
+ throw e;
903
1013
  }
904
1014
  }
905
- function writeSessionCache(cacheFile, cache) {
906
- try {
907
- mkdirSync2(dirname4(cacheFile), { recursive: true });
908
- writeFileSync(cacheFile, JSON.stringify(cache));
909
- } catch {
910
- }
1015
+ function cursorFile(harness, sessionId) {
1016
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
911
1017
  }
912
1018
  function fileCursorStore(harness) {
913
1019
  return {
914
- read: (sessionId) => readSessionCache(sessionCacheFile(harness, sessionId)).retain,
1020
+ read: (sessionId) => {
1021
+ try {
1022
+ return JSON.parse(readFileSync2(cursorFile(harness, sessionId), "utf8"));
1023
+ } catch {
1024
+ return void 0;
1025
+ }
1026
+ },
915
1027
  write: (sessionId, cursor) => {
916
- const file = sessionCacheFile(harness, sessionId);
917
- writeSessionCache(file, { ...readSessionCache(file), retain: cursor });
1028
+ try {
1029
+ writeFileAtomic(cursorFile(harness, sessionId), JSON.stringify(cursor));
1030
+ } catch {
1031
+ }
918
1032
  }
919
1033
  };
920
1034
  }
@@ -974,6 +1088,23 @@ async function supportsAppend(client) {
974
1088
  return false;
975
1089
  }
976
1090
  }
1091
+ var RETAIN_RETRY_ATTEMPTS = 2;
1092
+ var RETAIN_RETRY_BUDGET_MS = 6e3;
1093
+ async function submitWithRetry(send, isStillNewest) {
1094
+ let spent = 0;
1095
+ for (let attempt = 0; ; attempt++) {
1096
+ try {
1097
+ return await send();
1098
+ } catch (e) {
1099
+ const limited = e instanceof RateLimitedError;
1100
+ if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
1101
+ const wait = e.retryAfterMs || 1e3;
1102
+ if (wait > RETAIN_RETRY_BUDGET_MS - spent) throw e;
1103
+ spent += wait;
1104
+ await sleep(wait);
1105
+ }
1106
+ }
1107
+ }
977
1108
  var writeBacks = /* @__PURE__ */ new WeakMap();
978
1109
  function serialize(cursors, sessionId, write2) {
979
1110
  const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
@@ -1008,37 +1139,46 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
1008
1139
  bank: client.bank
1009
1140
  };
1010
1141
  cursors?.write(sessionId, { ...next, dirty: true });
1011
- await client.retain(
1012
- content,
1013
- "coding agent session",
1014
- refId,
1015
- // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1016
- // the documents list filters and draws its agent logo from, so a template cannot displace them.
1017
- [
1018
- .../* @__PURE__ */ new Set([
1019
- ...stamp?.tags ?? [],
1020
- "source:chat",
1021
- ...harness ? [`harness:${harness}`] : []
1022
- ])
1023
- ],
1024
- "conversation",
1025
- {
1026
- timestamp: startTs,
1027
- updateMode: plan.mode === "append" ? "append" : void 0,
1028
- // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
1029
- // the original operation instead of extracting (or appending) twice.
1030
- operationId: uuidV5(`${client.bank}
1142
+ const claimed = { ...next, dirty: true };
1143
+ await submitWithRetry(
1144
+ () => client.retain(
1145
+ content,
1146
+ "coding agent session",
1147
+ refId,
1148
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1149
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
1150
+ [
1151
+ .../* @__PURE__ */ new Set([
1152
+ ...stamp?.tags ?? [],
1153
+ "source:chat",
1154
+ ...harness ? [`harness:${harness}`] : []
1155
+ ])
1156
+ ],
1157
+ "conversation",
1158
+ {
1159
+ timestamp: startTs,
1160
+ updateMode: plan.mode === "append" ? "append" : void 0,
1161
+ // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
1162
+ // the original operation instead of extracting (or appending) twice.
1163
+ operationId: uuidV5(`${client.bank}
1031
1164
  ${refId}
1032
1165
  ${plan.mode}
1033
1166
  ${content}`),
1034
- metadata: {
1035
- ...stamp?.metadata,
1036
- // configured first: the built-ins below win on any key collision
1037
- source: "chat",
1038
- session_id: sessionId,
1039
- ref_id: refId,
1040
- ...harness ? { harness } : {}
1167
+ metadata: {
1168
+ ...stamp?.metadata,
1169
+ // configured first: the built-ins below win on any key collision
1170
+ source: "chat",
1171
+ session_id: sessionId,
1172
+ ref_id: refId,
1173
+ ...harness ? { harness } : {}
1174
+ }
1041
1175
  }
1176
+ ),
1177
+ // Still ours to retry only while the cursor holds the claim we wrote above.
1178
+ () => {
1179
+ if (!cursors) return true;
1180
+ const now = cursors.read(sessionId);
1181
+ return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
1042
1182
  }
1043
1183
  );
1044
1184
  cursors?.write(sessionId, next);
@@ -1171,7 +1311,7 @@ function resolversFor(ctx) {
1171
1311
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1172
1312
  harness: () => ctx.harness,
1173
1313
  bankId: () => ctx.bankId,
1174
- sessionId: () => ctx.sessionId,
1314
+ sessionId: () => ctx.sessionId ?? "unknown",
1175
1315
  timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
1176
1316
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
1177
1317
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
@@ -1393,12 +1533,17 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
1393
1533
  setLogLevel(cfg.logLevel);
1394
1534
  if (cfg.disabled) return;
1395
1535
  if (!transcriptPath) return;
1396
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness));
1536
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness), cwd);
1397
1537
  cfg = resolved.cfg;
1398
1538
  const bankId = resolved.bankId;
1399
1539
  if (cfg.disabled) return;
1400
1540
  await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
1401
- const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
1541
+ const client = makeClient({
1542
+ apiUrl: cfg.apiUrl,
1543
+ apiToken: cfg.apiToken,
1544
+ bank: bankId,
1545
+ maxParallelRetains: cfg.maxParallelRetains
1546
+ });
1402
1547
  await buildRetain({
1403
1548
  harness: spec.harness,
1404
1549
  sessionId: sessionId || "no-session",
@@ -1426,13 +1571,13 @@ import { execFileSync as execFileSync4 } from "child_process";
1426
1571
 
1427
1572
  // src/core/survey.ts
1428
1573
  import { spawn as realSpawn3 } from "child_process";
1429
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
1574
+ import { accessSync, constants, existsSync as existsSync3 } from "fs";
1430
1575
  import { homedir as homedir3 } from "os";
1431
1576
  import { delimiter, dirname as dirname6, join as join7 } from "path";
1432
1577
  import { fileURLToPath as fileURLToPath3 } from "url";
1433
1578
 
1434
1579
  // src/core/skill-sync.ts
1435
- import { cpSync, existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
1580
+ import { cpSync, existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1436
1581
  import { homedir as homedir4 } from "os";
1437
1582
  import { dirname as dirname7, join as join8 } from "path";
1438
1583
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -1567,14 +1712,14 @@ function readCopilotTranscript(path) {
1567
1712
  }
1568
1713
 
1569
1714
  // src/core/transcript-grok.ts
1570
- import { existsSync as existsSync4, readFileSync as readFileSync7, readdirSync } from "fs";
1715
+ import { existsSync as existsSync5, readFileSync as readFileSync7, readdirSync } from "fs";
1571
1716
  import { homedir as homedir5 } from "os";
1572
1717
  import { join as join9 } from "path";
1573
1718
  var CHAT_HISTORY = "chat_history.jsonl";
1574
1719
  function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1575
1720
  const sessionsDir = join9(grokHome, "sessions");
1576
1721
  const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1577
- if (existsSync4(direct)) return direct;
1722
+ if (existsSync5(direct)) return direct;
1578
1723
  try {
1579
1724
  for (const candidate of readdirSync(sessionsDir)) {
1580
1725
  const directory = join9(sessionsDir, candidate);
@@ -1614,7 +1759,7 @@ function readGrokTranscript(path) {
1614
1759
  }
1615
1760
 
1616
1761
  // src/core/transcript-devin.ts
1617
- import { existsSync as existsSync5 } from "fs";
1762
+ import { existsSync as existsSync6 } from "fs";
1618
1763
  import { createRequire } from "module";
1619
1764
  import { homedir as homedir6 } from "os";
1620
1765
  import { join as join10 } from "path";
@@ -1656,7 +1801,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1656
1801
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1657
1802
  return [];
1658
1803
  }
1659
- if (!existsSync5(dbPath)) {
1804
+ if (!existsSync6(dbPath)) {
1660
1805
  diag("devin-cli", "session_db_missing", { dbPath });
1661
1806
  return [];
1662
1807
  }