@vectorize-io/hindsight-coding-agents 0.3.0 → 0.3.2

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.
@@ -71,18 +71,32 @@ function gitProjectName(directory, resolveWorktrees) {
71
71
  }
72
72
  return dirName(directory);
73
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);
80
+ }
74
81
  function mapLookup(map, directory) {
75
82
  const cwd = normalize(directory);
76
83
  let best;
77
84
  for (const [dir, bank] of Object.entries(map)) {
78
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
79
- const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
80
- if (cwd === p || cwd.startsWith(p + sep)) {
85
+ const p = configuredDir(dir);
86
+ if (isWithin(cwd, p)) {
81
87
  if (!best || p.length > best.len) best = { len: p.length, bank };
82
88
  }
83
89
  }
84
90
  return best?.bank;
85
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
+ }
86
100
  function deriveBankId(config, directory, harness = "coding") {
87
101
  const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
88
102
  if (mapped) return mapped;
@@ -134,6 +148,9 @@ function resolveConfig(raw = {}) {
134
148
  bankIdTemplate: raw.bankIdTemplate,
135
149
  mapPathToBank: raw.mapPathToBank,
136
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() !== "") : [],
137
154
  harness: raw.harness ?? "opencode",
138
155
  disabled: raw.disabled ?? false,
139
156
  retainSessions: raw.retainSessions ?? true,
@@ -194,6 +211,8 @@ var ENV_KEYS = {
194
211
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
195
212
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
196
213
  resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
214
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
215
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
197
216
  harness: "HINDSIGHT_HARNESS",
198
217
  disabled: "HINDSIGHT_DISABLED",
199
218
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
@@ -216,13 +235,14 @@ var ENV_KEYS = {
216
235
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
217
236
  "dynamicBankId",
218
237
  "resolveWorktrees",
238
+ "optInOnly",
219
239
  "disabled",
220
240
  "retainSessions",
221
241
  "autoReflect",
222
242
  "autoSeed",
223
243
  "codebaseSurvey"
224
244
  ]);
225
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
245
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
226
246
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
227
247
  "apiPort",
228
248
  "daemonIdleTimeout",
@@ -266,9 +286,15 @@ var BANK_OVERRIDE_EXCLUDED = [
266
286
  "mapPathToBank",
267
287
  "dynamicBankId",
268
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",
269
293
  "harness"
270
294
  ];
271
- 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 };
272
298
  const section = cfg.banks[resolvedId];
273
299
  if (!section) return { cfg, bankId: resolvedId };
274
300
  const safe = { ...section };
@@ -1062,10 +1088,10 @@ async function supportsAppend(client) {
1062
1088
  return false;
1063
1089
  }
1064
1090
  }
1091
+ var DEFAULT_RETRY_WINDOW_MS = 6e4;
1065
1092
  var RETAIN_RETRY_ATTEMPTS = 2;
1066
- var RETAIN_RETRY_BUDGET_MS = 6e3;
1067
- async function submitWithRetry(send, isStillNewest) {
1068
- let spent = 0;
1093
+ var REQUEST_BUDGET_MS = 15e3;
1094
+ async function submitWithRetry(send, isStillNewest, retryUntil) {
1069
1095
  for (let attempt = 0; ; attempt++) {
1070
1096
  try {
1071
1097
  return await send();
@@ -1073,8 +1099,7 @@ async function submitWithRetry(send, isStillNewest) {
1073
1099
  const limited = e instanceof RateLimitedError;
1074
1100
  if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
1075
1101
  const wait = e.retryAfterMs || 1e3;
1076
- if (wait > RETAIN_RETRY_BUDGET_MS - spent) throw e;
1077
- spent += wait;
1102
+ if (Date.now() + wait + REQUEST_BUDGET_MS > retryUntil) throw e;
1078
1103
  await sleep(wait);
1079
1104
  }
1080
1105
  }
@@ -1094,14 +1119,24 @@ function serialize(cursors, sessionId, write2) {
1094
1119
  }
1095
1120
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
1096
1121
  const cursors = opts.cursors;
1097
- if (!cursors) return writeSession(client, sessionId, turns, startTs, harness, opts.stamp);
1122
+ if (!cursors)
1123
+ return writeSession(
1124
+ client,
1125
+ sessionId,
1126
+ turns,
1127
+ startTs,
1128
+ harness,
1129
+ opts.stamp,
1130
+ void 0,
1131
+ opts.retryUntil
1132
+ );
1098
1133
  return serialize(
1099
1134
  cursors,
1100
1135
  sessionId,
1101
- () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors)
1136
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
1102
1137
  );
1103
1138
  }
1104
- async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors) {
1139
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
1105
1140
  const refId = `conversation:${sessionId}`;
1106
1141
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
1107
1142
  const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
@@ -1153,7 +1188,8 @@ ${content}`),
1153
1188
  if (!cursors) return true;
1154
1189
  const now = cursors.read(sessionId);
1155
1190
  return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
1156
- }
1191
+ },
1192
+ retryUntil
1157
1193
  );
1158
1194
  cursors?.write(sessionId, next);
1159
1195
  }
@@ -1469,6 +1505,7 @@ function readClaudeTranscript(path) {
1469
1505
  }
1470
1506
 
1471
1507
  // src/core/retain-hook.ts
1508
+ var HOST_DEADLINE_MARGIN_MS = 2e3;
1472
1509
  async function buildRetain(args) {
1473
1510
  const { harness, sessionId, transcriptPath, client } = args;
1474
1511
  const readTranscript = args.readTranscript ?? readClaudeTranscript;
@@ -1479,7 +1516,8 @@ async function buildRetain(args) {
1479
1516
  try {
1480
1517
  await retainLiveSession(client, sessionId, turns, startTs, harness, {
1481
1518
  cursors: args.cursors ?? fileCursorStore(harness),
1482
- stamp: args.stamp
1519
+ stamp: args.stamp,
1520
+ retryUntil: args.retryUntil
1483
1521
  });
1484
1522
  diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
1485
1523
  } catch (e) {
@@ -1495,6 +1533,7 @@ async function buildRetain(args) {
1495
1533
  }
1496
1534
  async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
1497
1535
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
1536
+ const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
1498
1537
  let ev = {};
1499
1538
  try {
1500
1539
  ev = JSON.parse(readFileSync4(0, "utf8"));
@@ -1507,7 +1546,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
1507
1546
  setLogLevel(cfg.logLevel);
1508
1547
  if (cfg.disabled) return;
1509
1548
  if (!transcriptPath) return;
1510
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness));
1549
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness), cwd);
1511
1550
  cfg = resolved.cfg;
1512
1551
  const bankId = resolved.bankId;
1513
1552
  if (cfg.disabled) return;
@@ -1524,6 +1563,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
1524
1563
  transcriptPath,
1525
1564
  client,
1526
1565
  readTranscript: spec.readTranscript,
1566
+ retryUntil: hostDeadline,
1527
1567
  stamp: buildRetainStamp(cfg, {
1528
1568
  directory: cwd,
1529
1569
  harness: spec.harness,
@@ -1895,6 +1935,7 @@ var HOOK_HARNESSES = {
1895
1935
  sessionStart: standardSessionStart("claude-code"),
1896
1936
  prompt: claudePrompt,
1897
1937
  retain: {
1938
+ hostTimeoutSec: 60,
1898
1939
  harness: "claude-code",
1899
1940
  parse: (ev) => ({
1900
1941
  sessionId: ev.session_id,
@@ -1913,6 +1954,7 @@ var HOOK_HARNESSES = {
1913
1954
  sessionStart: standardSessionStart("codex"),
1914
1955
  prompt: codexPrompt,
1915
1956
  retain: {
1957
+ hostTimeoutSec: 60,
1916
1958
  harness: "codex",
1917
1959
  parse: (ev) => ({
1918
1960
  sessionId: ev.session_id,
@@ -1941,6 +1983,7 @@ var HOOK_HARNESSES = {
1941
1983
  },
1942
1984
  prompt: antigravityPrompt,
1943
1985
  retain: {
1986
+ hostTimeoutSec: 30,
1944
1987
  harness: "antigravity-cli",
1945
1988
  parse: (ev) => ({
1946
1989
  sessionId: ev.conversationId,
@@ -1969,6 +2012,7 @@ var HOOK_HARNESSES = {
1969
2012
  },
1970
2013
  prompt: cursorPrompt,
1971
2014
  retain: {
2015
+ hostTimeoutSec: 30,
1972
2016
  harness: "cursor-cli",
1973
2017
  parse: (ev) => ({
1974
2018
  sessionId: ev.conversation_id ?? ev.session_id,
@@ -2002,6 +2046,7 @@ var HOOK_HARNESSES = {
2002
2046
  },
2003
2047
  prompt: copilotPrompt,
2004
2048
  retain: {
2049
+ hostTimeoutSec: 60,
2005
2050
  harness: "copilot-cli",
2006
2051
  parse: (ev) => ({
2007
2052
  sessionId: ev.sessionId,
@@ -2030,6 +2075,7 @@ var HOOK_HARNESSES = {
2030
2075
  },
2031
2076
  prompt: devinPrompt,
2032
2077
  retain: {
2078
+ hostTimeoutSec: 60,
2033
2079
  harness: "devin-cli",
2034
2080
  parse: (ev) => {
2035
2081
  const sessionId = ev.session_id;
@@ -2069,6 +2115,7 @@ var HOOK_HARNESSES = {
2069
2115
  })
2070
2116
  },
2071
2117
  retain: {
2118
+ hostTimeoutSec: 60,
2072
2119
  harness: "grok-build",
2073
2120
  parse: (ev) => ({
2074
2121
  sessionId: ev.sessionId,
@@ -2,8 +2,8 @@
2
2
 
3
3
  // src/core/config.ts
4
4
  import { readFileSync } from "fs";
5
- import { homedir } from "os";
6
- import { join as join2 } from "path";
5
+ import { homedir as homedir2 } from "os";
6
+ import { join as join3 } from "path";
7
7
 
8
8
  // src/core/seed.ts
9
9
  import { spawn as realSpawn } from "child_process";
@@ -47,8 +47,106 @@ function seedControl(command2, args) {
47
47
  return { ok: false, message: "usage: hindsight-seed seed --repo <dir>" };
48
48
  }
49
49
 
50
+ // src/core/bank.ts
51
+ import { execFileSync } from "child_process";
52
+ import { existsSync } from "fs";
53
+ import { homedir } from "os";
54
+ import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
55
+
56
+ // src/core/template.ts
57
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
58
+ function applyTemplate(template, resolvers, what) {
59
+ return template.replace(PLACEHOLDER, (_, name) => {
60
+ const resolve = resolvers[name];
61
+ if (!resolve) {
62
+ console.error(
63
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
64
+ );
65
+ return "unknown";
66
+ }
67
+ return resolve();
68
+ });
69
+ }
70
+
71
+ // src/core/bank.ts
72
+ var DEFAULT_BANK_NAME = "coding";
73
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
74
+ function getProjectRootFromGit(directory) {
75
+ if (!directory) return null;
76
+ try {
77
+ const commonDir = execFileSync(
78
+ "git",
79
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
80
+ { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
81
+ ).trim();
82
+ if (!commonDir) return null;
83
+ return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
89
+ function nearestExistingDir(directory) {
90
+ let current = directory;
91
+ while (current) {
92
+ if (existsSync(current)) return current;
93
+ const parent = dirname2(current);
94
+ if (parent === current) return "";
95
+ current = parent;
96
+ }
97
+ return "";
98
+ }
99
+ function dirName(directory) {
100
+ return directory && basename(directory) || "unknown";
101
+ }
102
+ function gitProjectName(directory, resolveWorktrees) {
103
+ if (resolveWorktrees) {
104
+ const candidates = [
105
+ nearestExistingDir(directory),
106
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
107
+ ];
108
+ for (const candidate of candidates) {
109
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
110
+ if (root) return basename(root);
111
+ }
112
+ }
113
+ return dirName(directory);
114
+ }
115
+ function configuredDir(dir) {
116
+ const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
117
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
118
+ }
119
+ function isWithin(directory, configured) {
120
+ return directory === configured || directory.startsWith(configured + sep);
121
+ }
122
+ function mapLookup(map, directory) {
123
+ const cwd = normalize(directory);
124
+ let best;
125
+ for (const [dir, bank] of Object.entries(map)) {
126
+ const p = configuredDir(dir);
127
+ if (isWithin(cwd, p)) {
128
+ if (!best || p.length > best.len) best = { len: p.length, bank };
129
+ }
130
+ }
131
+ return best?.bank;
132
+ }
133
+ function deriveBankId(config, directory, harness = "coding") {
134
+ const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
135
+ if (mapped) return mapped;
136
+ const dynamic = config.dynamicBankId ?? !config.bankId;
137
+ if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
138
+ const resolvers = {
139
+ harness: () => harness,
140
+ project: () => dirName(directory),
141
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
142
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
143
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
144
+ };
145
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
146
+ }
147
+
50
148
  // src/core/config.ts
51
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join2(homedir(), ".hindsight", "coding-agent.json");
149
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
52
150
  var DEFAULT_DAEMON_PORT = 9077;
53
151
  var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
54
152
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
@@ -72,6 +170,9 @@ function resolveConfig(raw = {}) {
72
170
  bankIdTemplate: raw.bankIdTemplate,
73
171
  mapPathToBank: raw.mapPathToBank,
74
172
  resolveWorktrees: raw.resolveWorktrees,
173
+ optInOnly: raw.optInOnly ?? false,
174
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
175
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
75
176
  harness: raw.harness ?? "opencode",
76
177
  disabled: raw.disabled ?? false,
77
178
  retainSessions: raw.retainSessions ?? true,
@@ -132,6 +233,8 @@ var ENV_KEYS = {
132
233
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
133
234
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
134
235
  resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
236
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
237
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
135
238
  harness: "HINDSIGHT_HARNESS",
136
239
  disabled: "HINDSIGHT_DISABLED",
137
240
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
@@ -154,13 +257,14 @@ var ENV_KEYS = {
154
257
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
155
258
  "dynamicBankId",
156
259
  "resolveWorktrees",
260
+ "optInOnly",
157
261
  "disabled",
158
262
  "retainSessions",
159
263
  "autoReflect",
160
264
  "autoSeed",
161
265
  "codebaseSurvey"
162
266
  ]);
163
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
267
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
164
268
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
165
269
  "apiPort",
166
270
  "daemonIdleTimeout",
@@ -199,98 +303,6 @@ function loadConfig(opts = {}) {
199
303
  return resolveConfig(raw);
200
304
  }
201
305
 
202
- // src/core/bank.ts
203
- import { execFileSync } from "child_process";
204
- import { existsSync } from "fs";
205
- import { homedir as homedir2 } from "os";
206
- import { basename, dirname as dirname2, join as join3, normalize, sep } from "path";
207
-
208
- // src/core/template.ts
209
- var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
210
- function applyTemplate(template, resolvers, what) {
211
- return template.replace(PLACEHOLDER, (_, name) => {
212
- const resolve = resolvers[name];
213
- if (!resolve) {
214
- console.error(
215
- `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
216
- );
217
- return "unknown";
218
- }
219
- return resolve();
220
- });
221
- }
222
-
223
- // src/core/bank.ts
224
- var DEFAULT_BANK_NAME = "coding";
225
- var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
226
- function getProjectRootFromGit(directory) {
227
- if (!directory) return null;
228
- try {
229
- const commonDir = execFileSync(
230
- "git",
231
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
232
- { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
233
- ).trim();
234
- if (!commonDir) return null;
235
- return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
236
- } catch {
237
- return null;
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
- }
254
- function gitProjectName(directory, resolveWorktrees) {
255
- if (resolveWorktrees) {
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
- }
264
- }
265
- return dirName(directory);
266
- }
267
- function mapLookup(map, directory) {
268
- const cwd = normalize(directory);
269
- let best;
270
- for (const [dir, bank] of Object.entries(map)) {
271
- const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir2(), dir.slice(1)) : dir;
272
- const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
273
- if (cwd === p || cwd.startsWith(p + sep)) {
274
- if (!best || p.length > best.len) best = { len: p.length, bank };
275
- }
276
- }
277
- return best?.bank;
278
- }
279
- function deriveBankId(config, directory, harness = "coding") {
280
- const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
281
- if (mapped) return mapped;
282
- const dynamic = config.dynamicBankId ?? !config.bankId;
283
- if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
284
- const resolvers = {
285
- harness: () => harness,
286
- project: () => dirName(directory),
287
- gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
288
- channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
289
- user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
290
- };
291
- return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
292
- }
293
-
294
306
  // src/hindsight-seed.ts
295
307
  function arg(name) {
296
308
  const i = process.argv.indexOf(`--${name}`);
package/dist/index.js CHANGED
@@ -75,18 +75,32 @@ function gitProjectName(directory, resolveWorktrees) {
75
75
  }
76
76
  return dirName(directory);
77
77
  }
78
+ function configuredDir(dir) {
79
+ const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
80
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
81
+ }
82
+ function isWithin(directory, configured) {
83
+ return directory === configured || directory.startsWith(configured + sep);
84
+ }
78
85
  function mapLookup(map3, directory) {
79
86
  const cwd = normalize(directory);
80
87
  let best;
81
88
  for (const [dir, bank] of Object.entries(map3)) {
82
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
83
- const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
84
- if (cwd === p || cwd.startsWith(p + sep)) {
89
+ const p = configuredDir(dir);
90
+ if (isWithin(cwd, p)) {
85
91
  if (!best || p.length > best.len) best = { len: p.length, bank };
86
92
  }
87
93
  }
88
94
  return best?.bank;
89
95
  }
96
+ function isOptedIn(config3, directory) {
97
+ if (!config3.optInOnly) return true;
98
+ if (!directory) return false;
99
+ const cwd = normalize(directory);
100
+ if ((config3.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
101
+ return true;
102
+ return Boolean(config3.mapPathToBank && mapLookup(config3.mapPathToBank, directory));
103
+ }
90
104
  function deriveBankId(config3, directory, harness = "coding") {
91
105
  const mapped = directory && config3.mapPathToBank ? mapLookup(config3.mapPathToBank, directory) : void 0;
92
106
  if (mapped) return mapped;
@@ -164,6 +178,9 @@ function resolveConfig(raw = {}) {
164
178
  bankIdTemplate: raw.bankIdTemplate,
165
179
  mapPathToBank: raw.mapPathToBank,
166
180
  resolveWorktrees: raw.resolveWorktrees,
181
+ optInOnly: raw.optInOnly ?? false,
182
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
183
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
167
184
  harness: raw.harness ?? "opencode",
168
185
  disabled: raw.disabled ?? false,
169
186
  retainSessions: raw.retainSessions ?? true,
@@ -224,6 +241,8 @@ var ENV_KEYS = {
224
241
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
225
242
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
226
243
  resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
244
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
245
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
227
246
  harness: "HINDSIGHT_HARNESS",
228
247
  disabled: "HINDSIGHT_DISABLED",
229
248
  retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
@@ -246,13 +265,14 @@ var ENV_KEYS = {
246
265
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
247
266
  "dynamicBankId",
248
267
  "resolveWorktrees",
268
+ "optInOnly",
249
269
  "disabled",
250
270
  "retainSessions",
251
271
  "autoReflect",
252
272
  "autoSeed",
253
273
  "codebaseSurvey"
254
274
  ]);
255
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
275
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
256
276
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
257
277
  "apiPort",
258
278
  "daemonIdleTimeout",
@@ -296,9 +316,15 @@ var BANK_OVERRIDE_EXCLUDED = [
296
316
  "mapPathToBank",
297
317
  "dynamicBankId",
298
318
  "resolveWorktrees",
319
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
320
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
321
+ "optInOnly",
322
+ "optInPaths",
299
323
  "harness"
300
324
  ];
301
- function applyBankConfig(cfg, resolvedId) {
325
+ function applyBankConfig(cfg, resolvedId, directory) {
326
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
327
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
302
328
  const section = cfg.banks[resolvedId];
303
329
  if (!section) return { cfg, bankId: resolvedId };
304
330
  const safe = { ...section };
@@ -16048,10 +16074,10 @@ async function supportsAppend(client) {
16048
16074
  return false;
16049
16075
  }
16050
16076
  }
16077
+ var DEFAULT_RETRY_WINDOW_MS = 6e4;
16051
16078
  var RETAIN_RETRY_ATTEMPTS = 2;
16052
- var RETAIN_RETRY_BUDGET_MS = 6e3;
16053
- async function submitWithRetry(send, isStillNewest) {
16054
- let spent = 0;
16079
+ var REQUEST_BUDGET_MS = 15e3;
16080
+ async function submitWithRetry(send, isStillNewest, retryUntil) {
16055
16081
  for (let attempt = 0; ; attempt++) {
16056
16082
  try {
16057
16083
  return await send();
@@ -16059,8 +16085,7 @@ async function submitWithRetry(send, isStillNewest) {
16059
16085
  const limited = e instanceof RateLimitedError;
16060
16086
  if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
16061
16087
  const wait = e.retryAfterMs || 1e3;
16062
- if (wait > RETAIN_RETRY_BUDGET_MS - spent) throw e;
16063
- spent += wait;
16088
+ if (Date.now() + wait + REQUEST_BUDGET_MS > retryUntil) throw e;
16064
16089
  await sleep(wait);
16065
16090
  }
16066
16091
  }
@@ -16080,14 +16105,24 @@ function serialize(cursors, sessionId, write2) {
16080
16105
  }
16081
16106
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
16082
16107
  const cursors = opts.cursors;
16083
- if (!cursors) return writeSession(client, sessionId, turns, startTs, harness, opts.stamp);
16108
+ if (!cursors)
16109
+ return writeSession(
16110
+ client,
16111
+ sessionId,
16112
+ turns,
16113
+ startTs,
16114
+ harness,
16115
+ opts.stamp,
16116
+ void 0,
16117
+ opts.retryUntil
16118
+ );
16084
16119
  return serialize(
16085
16120
  cursors,
16086
16121
  sessionId,
16087
- () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors)
16122
+ () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
16088
16123
  );
16089
16124
  }
16090
- async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors) {
16125
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
16091
16126
  const refId = `conversation:${sessionId}`;
16092
16127
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
16093
16128
  const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
@@ -16139,7 +16174,8 @@ ${content}`),
16139
16174
  if (!cursors) return true;
16140
16175
  const now = cursors.read(sessionId);
16141
16176
  return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
16142
- }
16177
+ },
16178
+ retryUntil
16143
16179
  );
16144
16180
  cursors?.write(sessionId, next);
16145
16181
  }
@@ -29306,7 +29342,11 @@ function createPluginEntry(harness) {
29306
29342
  const projectDir = resolveProjectDirectory(input);
29307
29343
  let cfg = loadConfig({ harness });
29308
29344
  if (cfg.disabled) return {};
29309
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, projectDir || process.cwd(), harness));
29345
+ const resolved = applyBankConfig(
29346
+ cfg,
29347
+ deriveBankId(cfg, projectDir || process.cwd(), harness),
29348
+ projectDir || process.cwd()
29349
+ );
29310
29350
  cfg = resolved.cfg;
29311
29351
  const bankId = resolved.bankId;
29312
29352
  if (cfg.disabled) return {};