@vectorize-io/hindsight-coding-agents 0.2.0 → 0.3.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.
@@ -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,12 +44,32 @@ 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);
52
73
  }
53
74
  function mapLookup(map, directory) {
54
75
  const cwd = normalize(directory);
@@ -69,7 +90,7 @@ function deriveBankId(config, directory, harness = "coding") {
69
90
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
70
91
  const resolvers = {
71
92
  harness: () => harness,
72
- project: () => directory ? basename(directory) : "unknown",
93
+ project: () => dirName(directory),
73
94
  gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
74
95
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
75
96
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
@@ -117,7 +138,7 @@ function resolveConfig(raw = {}) {
117
138
  disabled: raw.disabled ?? false,
118
139
  retainSessions: raw.retainSessions ?? true,
119
140
  // opencode: write back by default (parity with hook-harness Stop)
120
- retainEveryTurns: raw.retainEveryTurns || 1,
141
+ maxParallelRetains: raw.maxParallelRetains || 10,
121
142
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
122
143
  autoReflect: raw.autoReflect ?? true,
123
144
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
@@ -176,7 +197,7 @@ var ENV_KEYS = {
176
197
  harness: "HINDSIGHT_HARNESS",
177
198
  disabled: "HINDSIGHT_DISABLED",
178
199
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
179
- retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
200
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
180
201
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
181
202
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
182
203
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
@@ -205,7 +226,7 @@ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
205
226
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
206
227
  "apiPort",
207
228
  "daemonIdleTimeout",
208
- "retainEveryTurns",
229
+ "maxParallelRetains",
209
230
  "reflectTimeoutMs",
210
231
  "pageRefreshEveryTurns",
211
232
  "seedLimit",
@@ -459,9 +480,40 @@ function semverGte(version, min) {
459
480
  }
460
481
  return true;
461
482
  }
483
+ async function pool(items, n, fn, onError, onProgress) {
484
+ let i = 0, done = 0;
485
+ async function worker() {
486
+ while (i < items.length) {
487
+ const idx = i++;
488
+ try {
489
+ await fn(items[idx], idx);
490
+ } catch (e) {
491
+ onError?.(idx, e);
492
+ }
493
+ onProgress?.(++done, items.length);
494
+ }
495
+ }
496
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
497
+ }
462
498
 
463
499
  // src/core/hindsight.ts
464
500
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
501
+ var RateLimitedError = class extends Error {
502
+ constructor(retryAfterMs2) {
503
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
504
+ this.retryAfterMs = retryAfterMs2;
505
+ this.name = "RateLimitedError";
506
+ }
507
+ retryAfterMs;
508
+ code = "rate_limited";
509
+ };
510
+ function retryAfterMs(header) {
511
+ if (!header) return 0;
512
+ const secs = Number(header.trim());
513
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
514
+ const at = Date.parse(header);
515
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
516
+ }
465
517
  var KnowledgePagesUnavailableError = class extends Error {
466
518
  code = "knowledge_pages_unavailable";
467
519
  constructor() {
@@ -470,6 +522,10 @@ var KnowledgePagesUnavailableError = class extends Error {
470
522
  }
471
523
  };
472
524
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
525
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
526
+ var POLL_CYCLE_MS = 5e3;
527
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
528
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
473
529
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
474
530
  var HindsightClient = class {
475
531
  apiUrl;
@@ -482,12 +538,14 @@ var HindsightClient = class {
482
538
  /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
483
539
  idempotentRetain;
484
540
  log;
541
+ maxParallelRetains;
485
542
  constructor(o) {
486
543
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
487
544
  this.apiToken = o.apiToken;
488
545
  this.bank = o.bank;
489
546
  this.log = o.log ?? (() => {
490
547
  });
548
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
491
549
  }
492
550
  headers() {
493
551
  const h = { "Content-Type": "application/json" };
@@ -505,6 +563,8 @@ var HindsightClient = class {
505
563
  body: body ? JSON.stringify(body) : void 0,
506
564
  signal: AbortSignal.timeout(15e3)
507
565
  });
566
+ if (r.status === 429 && !tolerate.includes(429))
567
+ throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
508
568
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
509
569
  throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
510
570
  return r;
@@ -636,7 +696,14 @@ var HindsightClient = class {
636
696
  return 0;
637
697
  }
638
698
  }
639
- /** Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable. */
699
+ /**
700
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
701
+ *
702
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
703
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
704
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
705
+ * of hammering the next cycle 5s later.
706
+ */
640
707
  async drain(ids, label, maxMs = 60 * 60 * 1e3) {
641
708
  if (!ids.length) return;
642
709
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
@@ -644,23 +711,29 @@ var HindsightClient = class {
644
711
  const pending = new Set(ids);
645
712
  let failed = 0;
646
713
  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 {
714
+ let backoffMs = POLL_CYCLE_MS;
715
+ await pool([...pending], this.maxParallelRetains, async (id) => {
716
+ try {
717
+ const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
718
+ if (r.status === 429) {
719
+ backoffMs = Math.min(
720
+ RETRY_AFTER_CEILING_MS,
721
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
722
+ );
723
+ return;
658
724
  }
659
- })
660
- );
725
+ if (!r.ok) return;
726
+ const st = ((await r.json()).status || "").toLowerCase();
727
+ if (TERMINAL.has(st)) {
728
+ pending.delete(id);
729
+ if (st !== "completed") failed++;
730
+ }
731
+ } catch {
732
+ }
733
+ });
661
734
  if (pending.size) {
662
735
  this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
663
- await sleep(5e3);
736
+ await sleep(backoffMs);
664
737
  }
665
738
  }
666
739
  this.log(
@@ -860,13 +933,20 @@ var HindsightClient = class {
860
933
  const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
861
934
  const content = `${verb}: ${args.title}. ${args.summary}`;
862
935
  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
- );
936
+ const tags = [
937
+ .../* @__PURE__ */ new Set([
938
+ ...args.stamp?.tags ?? [],
939
+ "knowledge:feature-work",
940
+ `relatedPageId:${pageId}`
941
+ ])
942
+ ];
943
+ if (Object.keys(args.stamp?.metadata ?? {}).length) {
944
+ await this.retain(content, "initiative marker", markerId, tags, "document", {
945
+ metadata: args.stamp?.metadata
946
+ });
947
+ } else {
948
+ await this.retain(content, "initiative marker", markerId, tags, "document");
949
+ }
870
950
  return { page_id: pageId };
871
951
  }
872
952
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -889,32 +969,40 @@ var HindsightClient = class {
889
969
  };
890
970
 
891
971
  // src/core/session-cache.ts
892
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
972
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
893
973
  import { tmpdir as tmpdir2 } from "os";
894
974
  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) {
975
+ function writeFileAtomic(path, body) {
976
+ mkdirSync2(dirname4(path), { recursive: true });
977
+ const tmp = `${path}.${process.pid}.tmp`;
899
978
  try {
900
- return JSON.parse(readFileSync2(cacheFile, "utf8"));
901
- } catch {
902
- return {};
979
+ writeFileSync(tmp, body);
980
+ renameSync(tmp, path);
981
+ } catch (e) {
982
+ try {
983
+ rmSync(tmp, { force: true });
984
+ } catch {
985
+ }
986
+ throw e;
903
987
  }
904
988
  }
905
- function writeSessionCache(cacheFile, cache) {
906
- try {
907
- mkdirSync2(dirname4(cacheFile), { recursive: true });
908
- writeFileSync(cacheFile, JSON.stringify(cache));
909
- } catch {
910
- }
989
+ function cursorFile(harness, sessionId) {
990
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
911
991
  }
912
992
  function fileCursorStore(harness) {
913
993
  return {
914
- read: (sessionId) => readSessionCache(sessionCacheFile(harness, sessionId)).retain,
994
+ read: (sessionId) => {
995
+ try {
996
+ return JSON.parse(readFileSync2(cursorFile(harness, sessionId), "utf8"));
997
+ } catch {
998
+ return void 0;
999
+ }
1000
+ },
915
1001
  write: (sessionId, cursor) => {
916
- const file = sessionCacheFile(harness, sessionId);
917
- writeSessionCache(file, { ...readSessionCache(file), retain: cursor });
1002
+ try {
1003
+ writeFileAtomic(cursorFile(harness, sessionId), JSON.stringify(cursor));
1004
+ } catch {
1005
+ }
918
1006
  }
919
1007
  };
920
1008
  }
@@ -974,6 +1062,23 @@ async function supportsAppend(client) {
974
1062
  return false;
975
1063
  }
976
1064
  }
1065
+ var RETAIN_RETRY_ATTEMPTS = 2;
1066
+ var RETAIN_RETRY_BUDGET_MS = 6e3;
1067
+ async function submitWithRetry(send, isStillNewest) {
1068
+ let spent = 0;
1069
+ for (let attempt = 0; ; attempt++) {
1070
+ try {
1071
+ return await send();
1072
+ } catch (e) {
1073
+ const limited = e instanceof RateLimitedError;
1074
+ if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
1075
+ const wait = e.retryAfterMs || 1e3;
1076
+ if (wait > RETAIN_RETRY_BUDGET_MS - spent) throw e;
1077
+ spent += wait;
1078
+ await sleep(wait);
1079
+ }
1080
+ }
1081
+ }
977
1082
  var writeBacks = /* @__PURE__ */ new WeakMap();
978
1083
  function serialize(cursors, sessionId, write2) {
979
1084
  const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
@@ -1008,37 +1113,46 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
1008
1113
  bank: client.bank
1009
1114
  };
1010
1115
  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}
1116
+ const claimed = { ...next, dirty: true };
1117
+ await submitWithRetry(
1118
+ () => client.retain(
1119
+ content,
1120
+ "coding agent session",
1121
+ refId,
1122
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1123
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
1124
+ [
1125
+ .../* @__PURE__ */ new Set([
1126
+ ...stamp?.tags ?? [],
1127
+ "source:chat",
1128
+ ...harness ? [`harness:${harness}`] : []
1129
+ ])
1130
+ ],
1131
+ "conversation",
1132
+ {
1133
+ timestamp: startTs,
1134
+ updateMode: plan.mode === "append" ? "append" : void 0,
1135
+ // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
1136
+ // the original operation instead of extracting (or appending) twice.
1137
+ operationId: uuidV5(`${client.bank}
1031
1138
  ${refId}
1032
1139
  ${plan.mode}
1033
1140
  ${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 } : {}
1141
+ metadata: {
1142
+ ...stamp?.metadata,
1143
+ // configured first: the built-ins below win on any key collision
1144
+ source: "chat",
1145
+ session_id: sessionId,
1146
+ ref_id: refId,
1147
+ ...harness ? { harness } : {}
1148
+ }
1041
1149
  }
1150
+ ),
1151
+ // Still ours to retry only while the cursor holds the claim we wrote above.
1152
+ () => {
1153
+ if (!cursors) return true;
1154
+ const now = cursors.read(sessionId);
1155
+ return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
1042
1156
  }
1043
1157
  );
1044
1158
  cursors?.write(sessionId, next);
@@ -1171,7 +1285,7 @@ function resolversFor(ctx) {
1171
1285
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1172
1286
  harness: () => ctx.harness,
1173
1287
  bankId: () => ctx.bankId,
1174
- sessionId: () => ctx.sessionId,
1288
+ sessionId: () => ctx.sessionId ?? "unknown",
1175
1289
  timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
1176
1290
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
1177
1291
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
@@ -1343,6 +1457,7 @@ function readClaudeTranscript(path) {
1343
1457
  if (line.type !== "user" && line.type !== "assistant") continue;
1344
1458
  if (line.isMeta === true) continue;
1345
1459
  if (line.isSidechain === true) continue;
1460
+ if (line.isCompactSummary === true) continue;
1346
1461
  if (typeof line.message !== "object" || line.message === null) continue;
1347
1462
  for (const rendered of renderLine(line.message.content, line.type)) {
1348
1463
  const turn = { role: rendered.role, content: rendered.content };
@@ -1397,7 +1512,12 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
1397
1512
  const bankId = resolved.bankId;
1398
1513
  if (cfg.disabled) return;
1399
1514
  await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
1400
- const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
1515
+ const client = makeClient({
1516
+ apiUrl: cfg.apiUrl,
1517
+ apiToken: cfg.apiToken,
1518
+ bank: bankId,
1519
+ maxParallelRetains: cfg.maxParallelRetains
1520
+ });
1401
1521
  await buildRetain({
1402
1522
  harness: spec.harness,
1403
1523
  sessionId: sessionId || "no-session",
@@ -1425,13 +1545,13 @@ import { execFileSync as execFileSync4 } from "child_process";
1425
1545
 
1426
1546
  // src/core/survey.ts
1427
1547
  import { spawn as realSpawn3 } from "child_process";
1428
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
1548
+ import { accessSync, constants, existsSync as existsSync3 } from "fs";
1429
1549
  import { homedir as homedir3 } from "os";
1430
1550
  import { delimiter, dirname as dirname6, join as join7 } from "path";
1431
1551
  import { fileURLToPath as fileURLToPath3 } from "url";
1432
1552
 
1433
1553
  // src/core/skill-sync.ts
1434
- import { cpSync, existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
1554
+ import { cpSync, existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1435
1555
  import { homedir as homedir4 } from "os";
1436
1556
  import { dirname as dirname7, join as join8 } from "path";
1437
1557
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -1566,14 +1686,14 @@ function readCopilotTranscript(path) {
1566
1686
  }
1567
1687
 
1568
1688
  // src/core/transcript-grok.ts
1569
- import { existsSync as existsSync4, readFileSync as readFileSync7, readdirSync } from "fs";
1689
+ import { existsSync as existsSync5, readFileSync as readFileSync7, readdirSync } from "fs";
1570
1690
  import { homedir as homedir5 } from "os";
1571
1691
  import { join as join9 } from "path";
1572
1692
  var CHAT_HISTORY = "chat_history.jsonl";
1573
1693
  function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1574
1694
  const sessionsDir = join9(grokHome, "sessions");
1575
1695
  const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1576
- if (existsSync4(direct)) return direct;
1696
+ if (existsSync5(direct)) return direct;
1577
1697
  try {
1578
1698
  for (const candidate of readdirSync(sessionsDir)) {
1579
1699
  const directory = join9(sessionsDir, candidate);
@@ -1613,7 +1733,7 @@ function readGrokTranscript(path) {
1613
1733
  }
1614
1734
 
1615
1735
  // src/core/transcript-devin.ts
1616
- import { existsSync as existsSync5 } from "fs";
1736
+ import { existsSync as existsSync6 } from "fs";
1617
1737
  import { createRequire } from "module";
1618
1738
  import { homedir as homedir6 } from "os";
1619
1739
  import { join as join10 } from "path";
@@ -1655,7 +1775,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1655
1775
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1656
1776
  return [];
1657
1777
  }
1658
- if (!existsSync5(dbPath)) {
1778
+ if (!existsSync6(dbPath)) {
1659
1779
  diag("devin-cli", "session_db_missing", { dbPath });
1660
1780
  return [];
1661
1781
  }
@@ -76,7 +76,7 @@ function resolveConfig(raw = {}) {
76
76
  disabled: raw.disabled ?? false,
77
77
  retainSessions: raw.retainSessions ?? true,
78
78
  // opencode: write back by default (parity with hook-harness Stop)
79
- retainEveryTurns: raw.retainEveryTurns || 1,
79
+ maxParallelRetains: raw.maxParallelRetains || 10,
80
80
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
81
81
  autoReflect: raw.autoReflect ?? true,
82
82
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
@@ -135,7 +135,7 @@ var ENV_KEYS = {
135
135
  harness: "HINDSIGHT_HARNESS",
136
136
  disabled: "HINDSIGHT_DISABLED",
137
137
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
138
- retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
138
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
139
139
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
140
140
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
141
141
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
@@ -164,7 +164,7 @@ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
164
164
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
165
165
  "apiPort",
166
166
  "daemonIdleTimeout",
167
- "retainEveryTurns",
167
+ "maxParallelRetains",
168
168
  "reflectTimeoutMs",
169
169
  "pageRefreshEveryTurns",
170
170
  "seedLimit",
@@ -201,6 +201,7 @@ function loadConfig(opts = {}) {
201
201
 
202
202
  // src/core/bank.ts
203
203
  import { execFileSync } from "child_process";
204
+ import { existsSync } from "fs";
204
205
  import { homedir as homedir2 } from "os";
205
206
  import { basename, dirname as dirname2, join as join3, normalize, sep } from "path";
206
207
 
@@ -236,12 +237,32 @@ function getProjectRootFromGit(directory) {
236
237
  return null;
237
238
  }
238
239
  }
240
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
241
+ function nearestExistingDir(directory) {
242
+ let current = directory;
243
+ while (current) {
244
+ if (existsSync(current)) return current;
245
+ const parent = dirname2(current);
246
+ if (parent === current) return "";
247
+ current = parent;
248
+ }
249
+ return "";
250
+ }
251
+ function dirName(directory) {
252
+ return directory && basename(directory) || "unknown";
253
+ }
239
254
  function gitProjectName(directory, resolveWorktrees) {
240
255
  if (resolveWorktrees) {
241
- const root = getProjectRootFromGit(directory);
242
- if (root) return basename(root);
256
+ const candidates = [
257
+ nearestExistingDir(directory),
258
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
259
+ ];
260
+ for (const candidate of candidates) {
261
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
262
+ if (root) return basename(root);
263
+ }
243
264
  }
244
- return directory ? basename(directory) : "unknown";
265
+ return dirName(directory);
245
266
  }
246
267
  function mapLookup(map, directory) {
247
268
  const cwd = normalize(directory);
@@ -262,7 +283,7 @@ function deriveBankId(config, directory, harness = "coding") {
262
283
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
263
284
  const resolvers = {
264
285
  harness: () => harness,
265
- project: () => directory ? basename(directory) : "unknown",
286
+ project: () => dirName(directory),
266
287
  gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
267
288
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
268
289
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"