@vectorize-io/hindsight-coding-agents 0.3.4 → 0.4.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.
package/dist/status.js CHANGED
@@ -38,35 +38,41 @@ function getProjectRootFromGit(directory) {
38
38
  return null;
39
39
  }
40
40
  }
41
- function projectNameOf(directory) {
42
- return gitProjectName(directory, true);
41
+ function projectNameOf(directory, sessionRoot) {
42
+ return gitProjectName(directory, true, sessionRoot);
43
43
  }
44
44
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
45
45
  function nearestExistingDir(directory) {
46
- let current = directory;
47
- while (current) {
48
- if (existsSync(current)) return current;
49
- const parent = dirname(current);
50
- if (parent === current) return "";
51
- current = parent;
46
+ let current2 = directory;
47
+ while (current2) {
48
+ if (existsSync(current2)) return current2;
49
+ const parent = dirname(current2);
50
+ if (parent === current2) return "";
51
+ current2 = parent;
52
52
  }
53
53
  return "";
54
54
  }
55
55
  function dirName(directory) {
56
56
  return directory && basename(directory) || "unknown";
57
57
  }
58
- function gitProjectName(directory, resolveWorktrees) {
58
+ function mainWorktreeRoot(directory, sessionRoot = "") {
59
+ const candidates = [
60
+ nearestExistingDir(directory),
61
+ sessionRoot,
62
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
63
+ ];
64
+ for (const candidate of candidates) {
65
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
66
+ if (root) return root;
67
+ }
68
+ return null;
69
+ }
70
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
59
71
  if (resolveWorktrees) {
60
- const candidates = [
61
- nearestExistingDir(directory),
62
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
63
- ];
64
- for (const candidate of candidates) {
65
- const root = candidate ? getProjectRootFromGit(candidate) : null;
66
- if (root) return basename(root);
67
- }
72
+ const root = mainWorktreeRoot(directory, sessionRoot);
73
+ if (root) return basename(root);
68
74
  }
69
- return dirName(directory);
75
+ return dirName(sessionRoot || directory);
70
76
  }
71
77
  function configuredDir(dir) {
72
78
  const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
@@ -86,23 +92,38 @@ function mapLookup(map, directory) {
86
92
  }
87
93
  return best?.bank;
88
94
  }
95
+ function lookupDirectories(config, directory, sessionRoot = "") {
96
+ const directories = [normalize(directory)];
97
+ if (config.resolveWorktrees ?? true) {
98
+ const root = mainWorktreeRoot(directory, sessionRoot);
99
+ const normalizedRoot = root ? normalize(root) : "";
100
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
101
+ }
102
+ return directories;
103
+ }
89
104
  function isOptedIn(config, directory) {
90
105
  if (!config.optInOnly) return true;
91
106
  if (!directory) return false;
92
- const cwd = normalize(directory);
93
- if ((config.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
107
+ const directories = lookupDirectories(config, directory);
108
+ if (directories.some(
109
+ (candidate) => (config.optInPaths ?? []).some(
110
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
111
+ )
112
+ ))
94
113
  return true;
95
- return Boolean(config.mapPathToBank && mapLookup(config.mapPathToBank, directory));
114
+ const pathMap = config.mapPathToBank;
115
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
96
116
  }
97
- function deriveBankId(config, directory, harness = "coding") {
98
- const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
117
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
118
+ const pathMap = config.mapPathToBank;
119
+ const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
99
120
  if (mapped) return mapped;
100
121
  const dynamic = config.dynamicBankId ?? !config.bankId;
101
122
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
102
123
  const resolvers = {
103
124
  harness: () => harness,
104
125
  project: () => dirName(directory),
105
- gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
126
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
106
127
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
107
128
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
108
129
  };
@@ -112,7 +133,7 @@ function deriveBankId(config, directory, harness = "coding") {
112
133
  // src/core/config.ts
113
134
  import { readFileSync } from "fs";
114
135
  import { homedir as homedir2 } from "os";
115
- import { join as join3 } from "path";
136
+ import { join as join4 } from "path";
116
137
 
117
138
  // src/core/seed.ts
118
139
  import { spawn as realSpawn } from "child_process";
@@ -120,196 +141,35 @@ import { dirname as dirname2, join as join2 } from "path";
120
141
  import { fileURLToPath } from "url";
121
142
  var DEFAULT_SEED_LIMIT = 300;
122
143
 
123
- // src/core/config.ts
124
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
125
- var DEFAULT_DAEMON_PORT = 9077;
126
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
127
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
128
- function resolveConfig(raw = {}) {
129
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
130
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
131
- return {
132
- serverMode,
133
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
134
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
135
- // daemon needs no plumbing through eight separate constructors.
136
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
137
- apiToken: raw.apiToken || void 0,
138
- apiPort,
139
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
140
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
141
- embedVersion: raw.embedVersion || void 0,
142
- embedPackagePath: raw.embedPackagePath || void 0,
143
- bankId: raw.bankId,
144
- dynamicBankId: raw.dynamicBankId,
145
- bankIdTemplate: raw.bankIdTemplate,
146
- mapPathToBank: raw.mapPathToBank,
147
- resolveWorktrees: raw.resolveWorktrees,
148
- optInOnly: raw.optInOnly ?? false,
149
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
150
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
151
- harness: raw.harness ?? "opencode",
152
- disabled: raw.disabled ?? false,
153
- retainSessions: raw.retainSessions ?? true,
154
- // opencode: write back by default (parity with hook-harness Stop)
155
- maxParallelRetains: raw.maxParallelRetains || 10,
156
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
157
- autoReflect: raw.autoReflect ?? true,
158
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
159
- autoSeed: raw.autoSeed ?? true,
160
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
161
- codebaseSurvey: raw.codebaseSurvey ?? true,
162
- surveyModel: raw.surveyModel || "haiku",
163
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
164
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
165
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
166
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
167
- // nested object cannot reach the API as a tag and fail the whole retain.
168
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
169
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
170
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
171
- ) : {},
172
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
173
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
174
- };
144
+ // src/core/log.ts
145
+ import { appendFileSync, mkdirSync } from "fs";
146
+ import { tmpdir } from "os";
147
+ import { dirname as dirname3, join as join3 } from "path";
148
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
149
+ var current = ["debug", "info", "warn", "error"].find(
150
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
151
+ ) ?? "info";
152
+ function logFilePath() {
153
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
175
154
  }
176
- function readRaw(path) {
155
+ function write(level, scope, msg, extra) {
156
+ if (WEIGHT[level] < WEIGHT[current]) return;
177
157
  try {
178
- return JSON.parse(readFileSync(path, "utf8"));
179
- } catch (e) {
180
- if (e?.code !== "ENOENT") {
181
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
182
- }
183
- return {};
158
+ const file = logFilePath();
159
+ mkdirSync(dirname3(file), { recursive: true });
160
+ appendFileSync(
161
+ file,
162
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
163
+ );
164
+ } catch {
184
165
  }
185
166
  }
186
- function mergeRaw(a, b) {
187
- const { harnesses: _drop, ...flat } = b;
188
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
189
- }
190
- function applyLayer(raw, layer, harness) {
191
- let out = mergeRaw(raw, layer);
192
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
193
- if (perHarness) out = mergeRaw(out, perHarness);
194
- return out;
195
- }
196
- var ENV_KEYS = {
197
- serverMode: "HINDSIGHT_SERVER_MODE",
198
- apiUrl: "HINDSIGHT_API_URL",
199
- apiToken: "HINDSIGHT_API_TOKEN",
200
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
201
- // it can carry their existing environment over unchanged.
202
- apiPort: "HINDSIGHT_API_PORT",
203
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
204
- embedVersion: "HINDSIGHT_EMBED_VERSION",
205
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
206
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
207
- bankId: "HINDSIGHT_BANK_ID",
208
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
209
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
210
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
211
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
212
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
213
- harness: "HINDSIGHT_HARNESS",
214
- disabled: "HINDSIGHT_DISABLED",
215
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
216
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
217
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
218
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
219
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
220
- autoSeed: "HINDSIGHT_AUTO_SEED",
221
- seedLimit: "HINDSIGHT_SEED_LIMIT",
222
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
223
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
224
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
225
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
226
- logLevel: "HINDSIGHT_LOG_LEVEL",
227
- gitIngest: "HINDSIGHT_GIT_INGEST",
228
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
229
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
230
- retainTags: "HINDSIGHT_RETAIN_TAGS"
167
+ var log = {
168
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
169
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
170
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
171
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
231
172
  };
232
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
233
- "dynamicBankId",
234
- "resolveWorktrees",
235
- "optInOnly",
236
- "disabled",
237
- "retainSessions",
238
- "autoReflect",
239
- "autoSeed",
240
- "codebaseSurvey"
241
- ]);
242
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
243
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
244
- "apiPort",
245
- "daemonIdleTimeout",
246
- "maxParallelRetains",
247
- "reflectTimeoutMs",
248
- "pageRefreshEveryTurns",
249
- "seedLimit",
250
- "surveyBudgetUsd",
251
- "surveyRefreshCommits"
252
- ]);
253
- function readEnvConfig(env = process.env) {
254
- const out = {};
255
- for (const [key, name] of Object.entries(ENV_KEYS)) {
256
- const value = env[name];
257
- if (value === void 0 || value.trim() === "") continue;
258
- if (ENV_BOOLEANS.has(key)) {
259
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
260
- } else if (ENV_LISTS.has(key)) {
261
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
262
- if (items.length) out[key] = items;
263
- } else if (ENV_NUMBERS.has(key)) {
264
- const n = Number(value);
265
- if (Number.isFinite(n)) out[key] = n;
266
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
267
- } else {
268
- out[key] = value;
269
- }
270
- }
271
- return out;
272
- }
273
- function loadConfig(opts = {}) {
274
- const o = typeof opts === "string" ? { path: opts } : opts;
275
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
276
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
277
- if (!raw.harness && o.harness) raw.harness = o.harness;
278
- return resolveConfig(raw);
279
- }
280
- var BANK_OVERRIDE_EXCLUDED = [
281
- "bankId",
282
- "bankIdTemplate",
283
- "mapPathToBank",
284
- "dynamicBankId",
285
- "resolveWorktrees",
286
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
287
- // only ever arrive too late to matter — strip them rather than let them read as effective.
288
- "optInOnly",
289
- "optInPaths",
290
- "harness"
291
- ];
292
- function applyBankConfig(cfg2, resolvedId, directory) {
293
- if (directory !== void 0 && !isOptedIn(cfg2, directory))
294
- return { cfg: { ...cfg2, disabled: true }, bankId: resolvedId };
295
- const section = cfg2.banks[resolvedId];
296
- if (!section) return { cfg: cfg2, bankId: resolvedId };
297
- const safe = { ...section };
298
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
299
- delete safe.banks;
300
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
301
- delete safe.bank;
302
- return { cfg: { ...cfg2, ...resolvePartial(cfg2, safe) }, bankId };
303
- }
304
- function resolvePartial(cfg2, patch) {
305
- const full = resolveConfig(patch);
306
- const out = {};
307
- for (const key of Object.keys(patch)) {
308
- if (key in full)
309
- out[key] = full[key];
310
- }
311
- return out;
312
- }
313
173
 
314
174
  // src/core/missions.ts
315
175
  var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
@@ -386,7 +246,10 @@ var KNOWLEDGE_LABELS = {
386
246
  }
387
247
  ]
388
248
  };
389
- var PAGES = [
249
+ function pageScopeRule(project) {
250
+ return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
251
+ }
252
+ var PAGE_TAXONOMY = [
390
253
  {
391
254
  name: "Component map",
392
255
  source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
@@ -409,15 +272,28 @@ var PAGES = [
409
272
  },
410
273
  {
411
274
  name: "Initiatives and enhancements",
412
- source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
275
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
413
276
  tags: ["knowledge:feature-work"]
414
277
  }
415
278
  ];
279
+ function pagesFor(project) {
280
+ const scope = pageScopeRule(project);
281
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
282
+ }
416
283
  var PAGE_MAX_TOKENS = 4096;
417
- var PAGE_TRIGGER = {
418
- fact_types: ["world", "experience", "observation"],
419
- refresh_after_consolidation: true
420
- };
284
+ var PAGE_TAGS_MATCH = "all";
285
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
286
+ function buildPageTrigger(cfg2 = {}) {
287
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
288
+ switch (cfg2.pageTriggerType) {
289
+ case "cron":
290
+ return { ...base, refresh_cron: cfg2.pageTriggerCron };
291
+ case "manual":
292
+ return { ...base, refresh_after_consolidation: false };
293
+ default:
294
+ return { ...base, refresh_after_consolidation: true };
295
+ }
296
+ }
421
297
  var CODING_BANK_TEMPLATE = {
422
298
  version: "1",
423
299
  bank: {
@@ -472,6 +348,7 @@ async function pool(items, n, fn, onError, onProgress) {
472
348
  }
473
349
 
474
350
  // src/core/hindsight.ts
351
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
475
352
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
476
353
  var RateLimitedError = class extends Error {
477
354
  constructor(retryAfterMs2) {
@@ -504,8 +381,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
504
381
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
505
382
  var HindsightClient = class {
506
383
  apiUrl;
507
- apiToken;
384
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
385
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
386
+ token;
387
+ tokenProvider;
508
388
  bank;
389
+ project;
509
390
  opIds = [];
510
391
  // async operation ids collected by retain(), for drain()
511
392
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -514,34 +395,81 @@ var HindsightClient = class {
514
395
  idempotentRetain;
515
396
  log;
516
397
  maxParallelRetains;
398
+ observationScopes;
517
399
  constructor(o) {
518
400
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
519
- this.apiToken = o.apiToken;
401
+ this.token = o.apiToken;
402
+ this.tokenProvider = o.tokenProvider;
520
403
  this.bank = o.bank;
404
+ this.project = o.project;
521
405
  this.log = o.log ?? (() => {
522
406
  });
523
407
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
408
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
409
+ }
410
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
411
+ get apiToken() {
412
+ return this.token;
524
413
  }
525
414
  headers() {
526
415
  const h = { "Content-Type": "application/json" };
527
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
416
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
528
417
  return h;
529
418
  }
419
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
420
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
421
+ * doubling every failing request. */
422
+ refreshToken() {
423
+ if (!this.tokenProvider) return false;
424
+ let next;
425
+ try {
426
+ next = this.tokenProvider();
427
+ } catch {
428
+ return false;
429
+ }
430
+ if (next === this.token) return false;
431
+ this.token = next;
432
+ return true;
433
+ }
434
+ /**
435
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
436
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
437
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
438
+ * not.
439
+ *
440
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
441
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
442
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
443
+ * bounds the whole call.
444
+ */
445
+ async fetchWithAuth(url, init) {
446
+ const send = () => fetch(url, { ...init, headers: this.headers() });
447
+ const r = await send();
448
+ if (r.status !== 401 || !this.refreshToken()) return r;
449
+ return send();
450
+ }
451
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
452
+ * server answers identically for both — only the client knows which it sent. */
453
+ authHint(status) {
454
+ if (status !== 401) return "";
455
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
456
+ }
530
457
  bankUrl(suffix = "") {
531
458
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
532
459
  }
533
460
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
534
461
  async req(method, url, body, tolerate = []) {
535
- const r = await fetch(url, {
462
+ const r = await this.fetchWithAuth(url, {
536
463
  method,
537
- headers: this.headers(),
538
464
  body: body ? JSON.stringify(body) : void 0,
539
465
  signal: AbortSignal.timeout(15e3)
540
466
  });
541
467
  if (r.status === 429 && !tolerate.includes(429))
542
468
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
543
469
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
544
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
470
+ throw new Error(
471
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
472
+ );
545
473
  return r;
546
474
  }
547
475
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -552,7 +480,11 @@ var HindsightClient = class {
552
480
  context,
553
481
  document_id: documentId,
554
482
  tags,
555
- strategy
483
+ strategy,
484
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
485
+ // observations were built under is a property of the write rather than of whichever server
486
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
487
+ observation_scopes: this.observationScopes
556
488
  };
557
489
  if (opts.timestamp) item.timestamp = opts.timestamp;
558
490
  if (opts.metadata) item.metadata = opts.metadata;
@@ -631,7 +563,7 @@ var HindsightClient = class {
631
563
  this.log(
632
564
  seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
633
565
  );
634
- await this.seedPages();
566
+ await this.seedPages(opts.pageTrigger);
635
567
  }
636
568
  /**
637
569
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -689,7 +621,7 @@ var HindsightClient = class {
689
621
  let backoffMs = POLL_CYCLE_MS;
690
622
  await pool([...pending], this.maxParallelRetains, async (id) => {
691
623
  try {
692
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
624
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
693
625
  if (r.status === 429) {
694
626
  backoffMs = Math.min(
695
627
  RETRY_AFTER_CEILING_MS,
@@ -715,18 +647,23 @@ var HindsightClient = class {
715
647
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
716
648
  );
717
649
  }
718
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
719
- async reflect(query, opts = {}) {
650
+ /**
651
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
652
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
653
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
654
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
655
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
656
+ */
657
+ async reflect(query, opts) {
720
658
  const ctrl = new AbortController();
721
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
659
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
722
660
  try {
723
- const resp = await fetch(this.bankUrl("/reflect"), {
661
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
724
662
  method: "POST",
725
- headers: this.headers(),
726
663
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
727
664
  signal: ctrl.signal
728
665
  });
729
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
666
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
730
667
  const data = await resp.json();
731
668
  return (data.text || "").trim();
732
669
  } finally {
@@ -810,16 +747,18 @@ var HindsightClient = class {
810
747
  }));
811
748
  }
812
749
  /**
813
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
750
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
814
751
  *
815
752
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
816
753
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
817
754
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
818
755
  *
819
756
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
820
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
757
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
758
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
821
759
  */
822
- async seedPages() {
760
+ async seedPages(pageTrigger = buildPageTrigger()) {
761
+ const pages = pagesFor(this.project ?? this.bank);
823
762
  const existing = /* @__PURE__ */ new Map();
824
763
  let roots;
825
764
  try {
@@ -836,14 +775,14 @@ var HindsightClient = class {
836
775
  }
837
776
  let created = 0;
838
777
  let updated = 0;
839
- for (const page of PAGES) {
778
+ for (const page of pages) {
840
779
  const hit = existing.get(page.name.toLowerCase());
841
780
  const body = {
842
781
  name: page.name,
843
782
  source_query: page.source_query,
844
783
  tags: page.tags,
845
784
  max_tokens: PAGE_MAX_TOKENS,
846
- trigger: PAGE_TRIGGER
785
+ trigger: pageTrigger
847
786
  };
848
787
  if (!hit) {
849
788
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -855,11 +794,18 @@ var HindsightClient = class {
855
794
  return;
856
795
  }
857
796
  if (r.status !== 409) created++;
858
- } else if (hit.description !== page.source_query) {
797
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
798
+ const patch = {
799
+ trigger: pageTrigger
800
+ };
801
+ if (hit.description !== page.source_query) {
802
+ patch.source_query = page.source_query;
803
+ patch.tags = page.tags;
804
+ }
859
805
  const r = await this.req(
860
806
  "PATCH",
861
807
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
862
- { source_query: page.source_query, tags: page.tags }
808
+ patch
863
809
  );
864
810
  if ([404, 405, 501].includes(r.status)) {
865
811
  this.knowledgePagesSupported = false;
@@ -872,7 +818,7 @@ var HindsightClient = class {
872
818
  }
873
819
  }
874
820
  this.log(
875
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
821
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
876
822
  );
877
823
  }
878
824
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -880,9 +826,17 @@ var HindsightClient = class {
880
826
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
881
827
  }
882
828
  /**
883
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
884
- * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
885
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
829
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
830
+ * New initiative → creates a page under the Initiatives folder.
831
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
832
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
833
+ *
834
+ * The marker carries its page id in two places, neither of them a tag (#3641):
835
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
836
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
837
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
838
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
839
+ * vocabulary that exists to be matched with exact set-ops.
886
840
  */
887
841
  async captureInitiative(args) {
888
842
  let pageId = args.relatesToPageId;
@@ -893,10 +847,7 @@ var HindsightClient = class {
893
847
  source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
894
848
  parent_id: folderId,
895
849
  tags: ["knowledge:feature-work"],
896
- trigger: {
897
- fact_types: ["world", "experience", "observation"],
898
- refresh_after_consolidation: true
899
- }
850
+ trigger: args.pageTrigger ?? buildPageTrigger()
900
851
  });
901
852
  try {
902
853
  const j = await r.json();
@@ -905,23 +856,14 @@ var HindsightClient = class {
905
856
  }
906
857
  pageId ||= `initiative-${this.slugify(args.title)}`;
907
858
  }
908
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
859
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
909
860
  const content = `${verb}: ${args.title}. ${args.summary}`;
910
861
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
911
- const tags = [
912
- .../* @__PURE__ */ new Set([
913
- ...args.stamp?.tags ?? [],
914
- "knowledge:feature-work",
915
- `relatedPageId:${pageId}`
916
- ])
917
- ];
918
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
919
- await this.retain(content, "initiative marker", markerId, tags, "document", {
920
- metadata: args.stamp?.metadata
921
- });
922
- } else {
923
- await this.retain(content, "initiative marker", markerId, tags, "document");
924
- }
862
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
863
+ const context = `initiative marker for [[page:${pageId}]]`;
864
+ await this.retain(content, context, markerId, tags, "document", {
865
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
866
+ });
925
867
  return { page_id: pageId };
926
868
  }
927
869
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -943,6 +885,244 @@ var HindsightClient = class {
943
885
  }
944
886
  };
945
887
 
888
+ // src/core/config.ts
889
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
890
+ var DEFAULT_DAEMON_PORT = 9077;
891
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
892
+ function resolvePageTriggerType(raw) {
893
+ if (raw.pageTriggerType === "manual") return "manual";
894
+ if (raw.pageTriggerType === "cron") {
895
+ if (raw.pageTriggerCron?.trim()) return "cron";
896
+ log.warn(
897
+ "config",
898
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
899
+ );
900
+ }
901
+ return "auto-refresh";
902
+ }
903
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
904
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
905
+ function resolveReflectBudget(raw) {
906
+ const value = raw.reflectBudget;
907
+ if (value === void 0) return "high";
908
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
909
+ return value;
910
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
911
+ return "high";
912
+ }
913
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
914
+ function resolveObservationScopes(raw) {
915
+ const value = raw;
916
+ if (typeof value === "string")
917
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
918
+ if (Array.isArray(value)) {
919
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
920
+ if (scopes.length) return scopes;
921
+ }
922
+ return DEFAULT_OBSERVATION_SCOPES;
923
+ }
924
+ function resolveConfig(raw = {}) {
925
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
926
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
927
+ return {
928
+ serverMode,
929
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
930
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
931
+ // daemon needs no plumbing through eight separate constructors.
932
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
933
+ apiToken: raw.apiToken || void 0,
934
+ apiPort,
935
+ daemonIdleTimeout: raw.daemonIdleTimeout,
936
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
937
+ embedVersion: raw.embedVersion || void 0,
938
+ embedPackagePath: raw.embedPackagePath || void 0,
939
+ bankId: raw.bankId,
940
+ dynamicBankId: raw.dynamicBankId,
941
+ bankIdTemplate: raw.bankIdTemplate,
942
+ mapPathToBank: raw.mapPathToBank,
943
+ resolveWorktrees: raw.resolveWorktrees,
944
+ optInOnly: raw.optInOnly ?? false,
945
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
946
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
947
+ harness: raw.harness ?? "opencode",
948
+ disabled: raw.disabled ?? false,
949
+ retainSessions: raw.retainSessions ?? true,
950
+ // write sessions back by default, every harness
951
+ maxParallelRetains: raw.maxParallelRetains || 10,
952
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
953
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
954
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
955
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
956
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
957
+ reflectBudget: resolveReflectBudget(raw),
958
+ autoReflect: raw.autoReflect ?? true,
959
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
960
+ pageTriggerType: resolvePageTriggerType(raw),
961
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
962
+ autoSeed: raw.autoSeed ?? true,
963
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
964
+ codebaseSurvey: raw.codebaseSurvey ?? true,
965
+ surveyModel: raw.surveyModel || "haiku",
966
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
967
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
968
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
969
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
970
+ // nested object cannot reach the API as a tag and fail the whole retain.
971
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
972
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
973
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
974
+ ) : {},
975
+ observationScopes: resolveObservationScopes(raw.observationScopes),
976
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
977
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
978
+ };
979
+ }
980
+ function readRaw(path) {
981
+ try {
982
+ return JSON.parse(readFileSync(path, "utf8"));
983
+ } catch (e) {
984
+ if (e?.code !== "ENOENT") {
985
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
986
+ }
987
+ return {};
988
+ }
989
+ }
990
+ function mergeRaw(a, b) {
991
+ const { harnesses: _drop, ...flat } = b;
992
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
993
+ }
994
+ function applyLayer(raw, layer, harness) {
995
+ let out = mergeRaw(raw, layer);
996
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
997
+ if (perHarness) out = mergeRaw(out, perHarness);
998
+ return out;
999
+ }
1000
+ var ENV_KEYS = {
1001
+ serverMode: "HINDSIGHT_SERVER_MODE",
1002
+ apiUrl: "HINDSIGHT_API_URL",
1003
+ apiToken: "HINDSIGHT_API_TOKEN",
1004
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1005
+ // it can carry their existing environment over unchanged.
1006
+ apiPort: "HINDSIGHT_API_PORT",
1007
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1008
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1009
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1010
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1011
+ bankId: "HINDSIGHT_BANK_ID",
1012
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1013
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1014
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1015
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1016
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1017
+ harness: "HINDSIGHT_HARNESS",
1018
+ disabled: "HINDSIGHT_DISABLED",
1019
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1020
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1021
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1022
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1023
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1024
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1025
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1026
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1027
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1028
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1029
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1030
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1031
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1032
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1033
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1034
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1035
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1036
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1037
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1038
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1039
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1040
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1041
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1042
+ };
1043
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1044
+ "dynamicBankId",
1045
+ "resolveWorktrees",
1046
+ "optInOnly",
1047
+ "disabled",
1048
+ "retainSessions",
1049
+ "autoReflect",
1050
+ "autoSeed",
1051
+ "codebaseSurvey"
1052
+ ]);
1053
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1054
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1055
+ "apiPort",
1056
+ "daemonIdleTimeout",
1057
+ "maxParallelRetains",
1058
+ "reflectTimeoutMs",
1059
+ "reflectToolTimeoutMs",
1060
+ "pageRefreshEveryTurns",
1061
+ "seedLimit",
1062
+ "surveyBudgetUsd",
1063
+ "surveyRefreshCommits"
1064
+ ]);
1065
+ function readEnvConfig(env = process.env) {
1066
+ const out = {};
1067
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1068
+ const value = env[name];
1069
+ if (value === void 0 || value.trim() === "") continue;
1070
+ if (ENV_BOOLEANS.has(key)) {
1071
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1072
+ } else if (ENV_LISTS.has(key)) {
1073
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1074
+ if (items.length) out[key] = items;
1075
+ } else if (ENV_NUMBERS.has(key)) {
1076
+ const n = Number(value);
1077
+ if (Number.isFinite(n)) out[key] = n;
1078
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1079
+ } else {
1080
+ out[key] = value;
1081
+ }
1082
+ }
1083
+ return out;
1084
+ }
1085
+ function loadConfig(opts = {}) {
1086
+ const o = typeof opts === "string" ? { path: opts } : opts;
1087
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1088
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1089
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1090
+ return resolveConfig(raw);
1091
+ }
1092
+ var BANK_OVERRIDE_EXCLUDED = [
1093
+ "bankId",
1094
+ "bankIdTemplate",
1095
+ "mapPathToBank",
1096
+ "dynamicBankId",
1097
+ "resolveWorktrees",
1098
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1099
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1100
+ "optInOnly",
1101
+ "optInPaths",
1102
+ "harness"
1103
+ ];
1104
+ function applyBankConfig(cfg2, resolvedId, directory) {
1105
+ if (directory !== void 0 && !isOptedIn(cfg2, directory))
1106
+ return { cfg: { ...cfg2, disabled: true }, bankId: resolvedId };
1107
+ const section = cfg2.banks[resolvedId];
1108
+ if (!section) return { cfg: cfg2, bankId: resolvedId };
1109
+ const safe = { ...section };
1110
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1111
+ delete safe.banks;
1112
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1113
+ delete safe.bank;
1114
+ return { cfg: { ...cfg2, ...resolvePartial(cfg2, safe) }, bankId };
1115
+ }
1116
+ function resolvePartial(cfg2, patch) {
1117
+ const full = resolveConfig(patch);
1118
+ const out = {};
1119
+ for (const key of Object.keys(patch)) {
1120
+ if (key in full)
1121
+ out[key] = full[key];
1122
+ }
1123
+ return out;
1124
+ }
1125
+
946
1126
  // src/core/status.ts
947
1127
  import { execFileSync as execFileSync3 } from "child_process";
948
1128
 
@@ -981,7 +1161,7 @@ function parsePageList(raw) {
981
1161
  import { spawn as realSpawn2 } from "child_process";
982
1162
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
983
1163
  import { homedir as homedir3 } from "os";
984
- import { delimiter, dirname as dirname3, join as join4 } from "path";
1164
+ import { delimiter, dirname as dirname4, join as join5 } from "path";
985
1165
  import { fileURLToPath as fileURLToPath2 } from "url";
986
1166
  var SURVEY_DOC_IDS = [
987
1167
  "repository-component-map",
@@ -1069,7 +1249,8 @@ var client = new HindsightClient({
1069
1249
  apiUrl: arg("api-url") ?? cfg.apiUrl,
1070
1250
  apiToken: arg("api-token") ?? cfg.apiToken,
1071
1251
  bank: FINAL_BANK,
1072
- maxParallelRetains: cfg.maxParallelRetains
1252
+ maxParallelRetains: cfg.maxParallelRetains,
1253
+ observationScopes: cfg.observationScopes
1073
1254
  });
1074
1255
  syncStatus(client, FINAL_BANK, REPO).then((s) => console.log(JSON.stringify(s))).catch((e) => {
1075
1256
  console.error("status failed:", e.message || e);