@vectorize-io/hindsight-coding-agents 0.3.3 → 0.4.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.
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.",
@@ -413,11 +276,23 @@ var PAGES = [
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_FACT_TYPES = ["world", "experience", "observation"];
285
+ function buildPageTrigger(cfg2 = {}) {
286
+ const base = { fact_types: PAGE_FACT_TYPES };
287
+ switch (cfg2.pageTriggerType) {
288
+ case "cron":
289
+ return { ...base, refresh_cron: cfg2.pageTriggerCron };
290
+ case "manual":
291
+ return { ...base, refresh_after_consolidation: false };
292
+ default:
293
+ return { ...base, refresh_after_consolidation: true };
294
+ }
295
+ }
421
296
  var CODING_BANK_TEMPLATE = {
422
297
  version: "1",
423
298
  bank: {
@@ -472,6 +347,7 @@ async function pool(items, n, fn, onError, onProgress) {
472
347
  }
473
348
 
474
349
  // src/core/hindsight.ts
350
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
475
351
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
476
352
  var RateLimitedError = class extends Error {
477
353
  constructor(retryAfterMs2) {
@@ -504,8 +380,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
504
380
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
505
381
  var HindsightClient = class {
506
382
  apiUrl;
507
- apiToken;
383
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
384
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
385
+ token;
386
+ tokenProvider;
508
387
  bank;
388
+ project;
509
389
  opIds = [];
510
390
  // async operation ids collected by retain(), for drain()
511
391
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -514,34 +394,81 @@ var HindsightClient = class {
514
394
  idempotentRetain;
515
395
  log;
516
396
  maxParallelRetains;
397
+ observationScopes;
517
398
  constructor(o) {
518
399
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
519
- this.apiToken = o.apiToken;
400
+ this.token = o.apiToken;
401
+ this.tokenProvider = o.tokenProvider;
520
402
  this.bank = o.bank;
403
+ this.project = o.project;
521
404
  this.log = o.log ?? (() => {
522
405
  });
523
406
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
407
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
408
+ }
409
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
410
+ get apiToken() {
411
+ return this.token;
524
412
  }
525
413
  headers() {
526
414
  const h = { "Content-Type": "application/json" };
527
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
415
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
528
416
  return h;
529
417
  }
418
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
419
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
420
+ * doubling every failing request. */
421
+ refreshToken() {
422
+ if (!this.tokenProvider) return false;
423
+ let next;
424
+ try {
425
+ next = this.tokenProvider();
426
+ } catch {
427
+ return false;
428
+ }
429
+ if (next === this.token) return false;
430
+ this.token = next;
431
+ return true;
432
+ }
433
+ /**
434
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
435
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
436
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
437
+ * not.
438
+ *
439
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
440
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
441
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
442
+ * bounds the whole call.
443
+ */
444
+ async fetchWithAuth(url, init) {
445
+ const send = () => fetch(url, { ...init, headers: this.headers() });
446
+ const r = await send();
447
+ if (r.status !== 401 || !this.refreshToken()) return r;
448
+ return send();
449
+ }
450
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
451
+ * server answers identically for both — only the client knows which it sent. */
452
+ authHint(status) {
453
+ if (status !== 401) return "";
454
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
455
+ }
530
456
  bankUrl(suffix = "") {
531
457
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
532
458
  }
533
459
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
534
460
  async req(method, url, body, tolerate = []) {
535
- const r = await fetch(url, {
461
+ const r = await this.fetchWithAuth(url, {
536
462
  method,
537
- headers: this.headers(),
538
463
  body: body ? JSON.stringify(body) : void 0,
539
464
  signal: AbortSignal.timeout(15e3)
540
465
  });
541
466
  if (r.status === 429 && !tolerate.includes(429))
542
467
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
543
468
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
544
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
469
+ throw new Error(
470
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
471
+ );
545
472
  return r;
546
473
  }
547
474
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -552,7 +479,11 @@ var HindsightClient = class {
552
479
  context,
553
480
  document_id: documentId,
554
481
  tags,
555
- strategy
482
+ strategy,
483
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
484
+ // observations were built under is a property of the write rather than of whichever server
485
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
486
+ observation_scopes: this.observationScopes
556
487
  };
557
488
  if (opts.timestamp) item.timestamp = opts.timestamp;
558
489
  if (opts.metadata) item.metadata = opts.metadata;
@@ -631,7 +562,7 @@ var HindsightClient = class {
631
562
  this.log(
632
563
  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
564
  );
634
- await this.seedPages();
565
+ await this.seedPages(opts.pageTrigger);
635
566
  }
636
567
  /**
637
568
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -689,7 +620,7 @@ var HindsightClient = class {
689
620
  let backoffMs = POLL_CYCLE_MS;
690
621
  await pool([...pending], this.maxParallelRetains, async (id) => {
691
622
  try {
692
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
623
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
693
624
  if (r.status === 429) {
694
625
  backoffMs = Math.min(
695
626
  RETRY_AFTER_CEILING_MS,
@@ -715,18 +646,23 @@ var HindsightClient = class {
715
646
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
716
647
  );
717
648
  }
718
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
719
- async reflect(query, opts = {}) {
649
+ /**
650
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
651
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
652
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
653
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
654
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
655
+ */
656
+ async reflect(query, opts) {
720
657
  const ctrl = new AbortController();
721
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
658
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
722
659
  try {
723
- const resp = await fetch(this.bankUrl("/reflect"), {
660
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
724
661
  method: "POST",
725
- headers: this.headers(),
726
662
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
727
663
  signal: ctrl.signal
728
664
  });
729
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
665
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
730
666
  const data = await resp.json();
731
667
  return (data.text || "").trim();
732
668
  } finally {
@@ -810,16 +746,18 @@ var HindsightClient = class {
810
746
  }));
811
747
  }
812
748
  /**
813
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
749
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
814
750
  *
815
751
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
816
752
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
817
753
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
818
754
  *
819
755
  * 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.
756
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
757
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
821
758
  */
822
- async seedPages() {
759
+ async seedPages(pageTrigger = buildPageTrigger()) {
760
+ const pages = pagesFor(this.project ?? this.bank);
823
761
  const existing = /* @__PURE__ */ new Map();
824
762
  let roots;
825
763
  try {
@@ -836,14 +774,14 @@ var HindsightClient = class {
836
774
  }
837
775
  let created = 0;
838
776
  let updated = 0;
839
- for (const page of PAGES) {
777
+ for (const page of pages) {
840
778
  const hit = existing.get(page.name.toLowerCase());
841
779
  const body = {
842
780
  name: page.name,
843
781
  source_query: page.source_query,
844
782
  tags: page.tags,
845
783
  max_tokens: PAGE_MAX_TOKENS,
846
- trigger: PAGE_TRIGGER
784
+ trigger: pageTrigger
847
785
  };
848
786
  if (!hit) {
849
787
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -872,7 +810,7 @@ var HindsightClient = class {
872
810
  }
873
811
  }
874
812
  this.log(
875
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
813
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
876
814
  );
877
815
  }
878
816
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -882,7 +820,8 @@ var HindsightClient = class {
882
820
  /**
883
821
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
884
822
  * 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.
823
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
824
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
886
825
  */
887
826
  async captureInitiative(args) {
888
827
  let pageId = args.relatesToPageId;
@@ -893,10 +832,7 @@ var HindsightClient = class {
893
832
  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
833
  parent_id: folderId,
895
834
  tags: ["knowledge:feature-work"],
896
- trigger: {
897
- fact_types: ["world", "experience", "observation"],
898
- refresh_after_consolidation: true
899
- }
835
+ trigger: args.pageTrigger ?? buildPageTrigger()
900
836
  });
901
837
  try {
902
838
  const j = await r.json();
@@ -905,7 +841,7 @@ var HindsightClient = class {
905
841
  }
906
842
  pageId ||= `initiative-${this.slugify(args.title)}`;
907
843
  }
908
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
844
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
909
845
  const content = `${verb}: ${args.title}. ${args.summary}`;
910
846
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
911
847
  const tags = [
@@ -943,6 +879,244 @@ var HindsightClient = class {
943
879
  }
944
880
  };
945
881
 
882
+ // src/core/config.ts
883
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
884
+ var DEFAULT_DAEMON_PORT = 9077;
885
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
886
+ function resolvePageTriggerType(raw) {
887
+ if (raw.pageTriggerType === "manual") return "manual";
888
+ if (raw.pageTriggerType === "cron") {
889
+ if (raw.pageTriggerCron?.trim()) return "cron";
890
+ log.warn(
891
+ "config",
892
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
893
+ );
894
+ }
895
+ return "auto-refresh";
896
+ }
897
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
898
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
899
+ function resolveReflectBudget(raw) {
900
+ const value = raw.reflectBudget;
901
+ if (value === void 0) return "high";
902
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
903
+ return value;
904
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
905
+ return "high";
906
+ }
907
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
908
+ function resolveObservationScopes(raw) {
909
+ const value = raw;
910
+ if (typeof value === "string")
911
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
912
+ if (Array.isArray(value)) {
913
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
914
+ if (scopes.length) return scopes;
915
+ }
916
+ return DEFAULT_OBSERVATION_SCOPES;
917
+ }
918
+ function resolveConfig(raw = {}) {
919
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
920
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
921
+ return {
922
+ serverMode,
923
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
924
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
925
+ // daemon needs no plumbing through eight separate constructors.
926
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
927
+ apiToken: raw.apiToken || void 0,
928
+ apiPort,
929
+ daemonIdleTimeout: raw.daemonIdleTimeout,
930
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
931
+ embedVersion: raw.embedVersion || void 0,
932
+ embedPackagePath: raw.embedPackagePath || void 0,
933
+ bankId: raw.bankId,
934
+ dynamicBankId: raw.dynamicBankId,
935
+ bankIdTemplate: raw.bankIdTemplate,
936
+ mapPathToBank: raw.mapPathToBank,
937
+ resolveWorktrees: raw.resolveWorktrees,
938
+ optInOnly: raw.optInOnly ?? false,
939
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
940
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
941
+ harness: raw.harness ?? "opencode",
942
+ disabled: raw.disabled ?? false,
943
+ retainSessions: raw.retainSessions ?? true,
944
+ // write sessions back by default, every harness
945
+ maxParallelRetains: raw.maxParallelRetains || 10,
946
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
947
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
948
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
949
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
950
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
951
+ reflectBudget: resolveReflectBudget(raw),
952
+ autoReflect: raw.autoReflect ?? true,
953
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
954
+ pageTriggerType: resolvePageTriggerType(raw),
955
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
956
+ autoSeed: raw.autoSeed ?? true,
957
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
958
+ codebaseSurvey: raw.codebaseSurvey ?? true,
959
+ surveyModel: raw.surveyModel || "haiku",
960
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
961
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
962
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
963
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
964
+ // nested object cannot reach the API as a tag and fail the whole retain.
965
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
966
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
967
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
968
+ ) : {},
969
+ observationScopes: resolveObservationScopes(raw.observationScopes),
970
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
971
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
972
+ };
973
+ }
974
+ function readRaw(path) {
975
+ try {
976
+ return JSON.parse(readFileSync(path, "utf8"));
977
+ } catch (e) {
978
+ if (e?.code !== "ENOENT") {
979
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
980
+ }
981
+ return {};
982
+ }
983
+ }
984
+ function mergeRaw(a, b) {
985
+ const { harnesses: _drop, ...flat } = b;
986
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
987
+ }
988
+ function applyLayer(raw, layer, harness) {
989
+ let out = mergeRaw(raw, layer);
990
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
991
+ if (perHarness) out = mergeRaw(out, perHarness);
992
+ return out;
993
+ }
994
+ var ENV_KEYS = {
995
+ serverMode: "HINDSIGHT_SERVER_MODE",
996
+ apiUrl: "HINDSIGHT_API_URL",
997
+ apiToken: "HINDSIGHT_API_TOKEN",
998
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
999
+ // it can carry their existing environment over unchanged.
1000
+ apiPort: "HINDSIGHT_API_PORT",
1001
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1002
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1003
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1004
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1005
+ bankId: "HINDSIGHT_BANK_ID",
1006
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1007
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1008
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1009
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1010
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1011
+ harness: "HINDSIGHT_HARNESS",
1012
+ disabled: "HINDSIGHT_DISABLED",
1013
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1014
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1015
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1016
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1017
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1018
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1019
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1020
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1021
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1022
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1023
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1024
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1025
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1026
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1027
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1028
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1029
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1030
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1031
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1032
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1033
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1034
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1035
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1036
+ };
1037
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1038
+ "dynamicBankId",
1039
+ "resolveWorktrees",
1040
+ "optInOnly",
1041
+ "disabled",
1042
+ "retainSessions",
1043
+ "autoReflect",
1044
+ "autoSeed",
1045
+ "codebaseSurvey"
1046
+ ]);
1047
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1048
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1049
+ "apiPort",
1050
+ "daemonIdleTimeout",
1051
+ "maxParallelRetains",
1052
+ "reflectTimeoutMs",
1053
+ "reflectToolTimeoutMs",
1054
+ "pageRefreshEveryTurns",
1055
+ "seedLimit",
1056
+ "surveyBudgetUsd",
1057
+ "surveyRefreshCommits"
1058
+ ]);
1059
+ function readEnvConfig(env = process.env) {
1060
+ const out = {};
1061
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1062
+ const value = env[name];
1063
+ if (value === void 0 || value.trim() === "") continue;
1064
+ if (ENV_BOOLEANS.has(key)) {
1065
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1066
+ } else if (ENV_LISTS.has(key)) {
1067
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1068
+ if (items.length) out[key] = items;
1069
+ } else if (ENV_NUMBERS.has(key)) {
1070
+ const n = Number(value);
1071
+ if (Number.isFinite(n)) out[key] = n;
1072
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1073
+ } else {
1074
+ out[key] = value;
1075
+ }
1076
+ }
1077
+ return out;
1078
+ }
1079
+ function loadConfig(opts = {}) {
1080
+ const o = typeof opts === "string" ? { path: opts } : opts;
1081
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1082
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1083
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1084
+ return resolveConfig(raw);
1085
+ }
1086
+ var BANK_OVERRIDE_EXCLUDED = [
1087
+ "bankId",
1088
+ "bankIdTemplate",
1089
+ "mapPathToBank",
1090
+ "dynamicBankId",
1091
+ "resolveWorktrees",
1092
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1093
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1094
+ "optInOnly",
1095
+ "optInPaths",
1096
+ "harness"
1097
+ ];
1098
+ function applyBankConfig(cfg2, resolvedId, directory) {
1099
+ if (directory !== void 0 && !isOptedIn(cfg2, directory))
1100
+ return { cfg: { ...cfg2, disabled: true }, bankId: resolvedId };
1101
+ const section = cfg2.banks[resolvedId];
1102
+ if (!section) return { cfg: cfg2, bankId: resolvedId };
1103
+ const safe = { ...section };
1104
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1105
+ delete safe.banks;
1106
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1107
+ delete safe.bank;
1108
+ return { cfg: { ...cfg2, ...resolvePartial(cfg2, safe) }, bankId };
1109
+ }
1110
+ function resolvePartial(cfg2, patch) {
1111
+ const full = resolveConfig(patch);
1112
+ const out = {};
1113
+ for (const key of Object.keys(patch)) {
1114
+ if (key in full)
1115
+ out[key] = full[key];
1116
+ }
1117
+ return out;
1118
+ }
1119
+
946
1120
  // src/core/status.ts
947
1121
  import { execFileSync as execFileSync3 } from "child_process";
948
1122
 
@@ -981,7 +1155,7 @@ function parsePageList(raw) {
981
1155
  import { spawn as realSpawn2 } from "child_process";
982
1156
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
983
1157
  import { homedir as homedir3 } from "os";
984
- import { delimiter, dirname as dirname3, join as join4 } from "path";
1158
+ import { delimiter, dirname as dirname4, join as join5 } from "path";
985
1159
  import { fileURLToPath as fileURLToPath2 } from "url";
986
1160
  var SURVEY_DOC_IDS = [
987
1161
  "repository-component-map",
@@ -1069,7 +1243,8 @@ var client = new HindsightClient({
1069
1243
  apiUrl: arg("api-url") ?? cfg.apiUrl,
1070
1244
  apiToken: arg("api-token") ?? cfg.apiToken,
1071
1245
  bank: FINAL_BANK,
1072
- maxParallelRetains: cfg.maxParallelRetains
1246
+ maxParallelRetains: cfg.maxParallelRetains,
1247
+ observationScopes: cfg.observationScopes
1073
1248
  });
1074
1249
  syncStatus(client, FINAL_BANK, REPO).then((s) => console.log(JSON.stringify(s))).catch((e) => {
1075
1250
  console.error("status failed:", e.message || e);