@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.
@@ -55,18 +55,24 @@ function nearestExistingDir(directory) {
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";
@@ -146,204 +167,10 @@ function startBackgroundSeed(repoDir, opts = {}) {
146
167
  }
147
168
  }
148
169
 
149
- // src/core/config.ts
150
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
151
- var DEFAULT_DAEMON_PORT = 9077;
152
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
153
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
154
- function resolveConfig(raw = {}) {
155
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
156
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
157
- return {
158
- serverMode,
159
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
160
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
161
- // daemon needs no plumbing through eight separate constructors.
162
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
163
- apiToken: raw.apiToken || void 0,
164
- apiPort,
165
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
166
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
167
- embedVersion: raw.embedVersion || void 0,
168
- embedPackagePath: raw.embedPackagePath || void 0,
169
- bankId: raw.bankId,
170
- dynamicBankId: raw.dynamicBankId,
171
- bankIdTemplate: raw.bankIdTemplate,
172
- mapPathToBank: raw.mapPathToBank,
173
- resolveWorktrees: raw.resolveWorktrees,
174
- optInOnly: raw.optInOnly ?? false,
175
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
176
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
177
- harness: raw.harness ?? "opencode",
178
- disabled: raw.disabled ?? false,
179
- retainSessions: raw.retainSessions ?? true,
180
- // opencode: write back by default (parity with hook-harness Stop)
181
- maxParallelRetains: raw.maxParallelRetains || 10,
182
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
183
- autoReflect: raw.autoReflect ?? true,
184
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
185
- autoSeed: raw.autoSeed ?? true,
186
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
187
- codebaseSurvey: raw.codebaseSurvey ?? true,
188
- surveyModel: raw.surveyModel || "haiku",
189
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
190
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
191
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
192
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
193
- // nested object cannot reach the API as a tag and fail the whole retain.
194
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
195
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
196
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
197
- ) : {},
198
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
199
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
200
- };
201
- }
202
- function readRaw(path) {
203
- try {
204
- return JSON.parse(readFileSync(path, "utf8"));
205
- } catch (e) {
206
- if (e?.code !== "ENOENT") {
207
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
208
- }
209
- return {};
210
- }
211
- }
212
- function mergeRaw(a, b) {
213
- const { harnesses: _drop, ...flat } = b;
214
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
215
- }
216
- function applyLayer(raw, layer, harness) {
217
- let out = mergeRaw(raw, layer);
218
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
219
- if (perHarness) out = mergeRaw(out, perHarness);
220
- return out;
221
- }
222
- var ENV_KEYS = {
223
- serverMode: "HINDSIGHT_SERVER_MODE",
224
- apiUrl: "HINDSIGHT_API_URL",
225
- apiToken: "HINDSIGHT_API_TOKEN",
226
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
227
- // it can carry their existing environment over unchanged.
228
- apiPort: "HINDSIGHT_API_PORT",
229
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
230
- embedVersion: "HINDSIGHT_EMBED_VERSION",
231
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
232
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
233
- bankId: "HINDSIGHT_BANK_ID",
234
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
235
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
236
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
237
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
238
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
239
- harness: "HINDSIGHT_HARNESS",
240
- disabled: "HINDSIGHT_DISABLED",
241
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
242
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
243
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
244
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
245
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
246
- autoSeed: "HINDSIGHT_AUTO_SEED",
247
- seedLimit: "HINDSIGHT_SEED_LIMIT",
248
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
249
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
250
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
251
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
252
- logLevel: "HINDSIGHT_LOG_LEVEL",
253
- gitIngest: "HINDSIGHT_GIT_INGEST",
254
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
255
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
256
- retainTags: "HINDSIGHT_RETAIN_TAGS"
257
- };
258
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
259
- "dynamicBankId",
260
- "resolveWorktrees",
261
- "optInOnly",
262
- "disabled",
263
- "retainSessions",
264
- "autoReflect",
265
- "autoSeed",
266
- "codebaseSurvey"
267
- ]);
268
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
269
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
270
- "apiPort",
271
- "daemonIdleTimeout",
272
- "maxParallelRetains",
273
- "reflectTimeoutMs",
274
- "pageRefreshEveryTurns",
275
- "seedLimit",
276
- "surveyBudgetUsd",
277
- "surveyRefreshCommits"
278
- ]);
279
- function readEnvConfig(env = process.env) {
280
- const out = {};
281
- for (const [key, name] of Object.entries(ENV_KEYS)) {
282
- const value = env[name];
283
- if (value === void 0 || value.trim() === "") continue;
284
- if (ENV_BOOLEANS.has(key)) {
285
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
286
- } else if (ENV_LISTS.has(key)) {
287
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
288
- if (items.length) out[key] = items;
289
- } else if (ENV_NUMBERS.has(key)) {
290
- const n = Number(value);
291
- if (Number.isFinite(n)) out[key] = n;
292
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
293
- } else {
294
- out[key] = value;
295
- }
296
- }
297
- return out;
298
- }
299
- function loadConfig(opts = {}) {
300
- const o = typeof opts === "string" ? { path: opts } : opts;
301
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
302
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
303
- if (!raw.harness && o.harness) raw.harness = o.harness;
304
- return resolveConfig(raw);
305
- }
306
- var BANK_OVERRIDE_EXCLUDED = [
307
- "bankId",
308
- "bankIdTemplate",
309
- "mapPathToBank",
310
- "dynamicBankId",
311
- "resolveWorktrees",
312
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
313
- // only ever arrive too late to matter — strip them rather than let them read as effective.
314
- "optInOnly",
315
- "optInPaths",
316
- "harness"
317
- ];
318
- function applyBankConfig(cfg, resolvedId, directory) {
319
- if (directory !== void 0 && !isOptedIn(cfg, directory))
320
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
321
- const section = cfg.banks[resolvedId];
322
- if (!section) return { cfg, bankId: resolvedId };
323
- const safe = { ...section };
324
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
325
- delete safe.banks;
326
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
327
- delete safe.bank;
328
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
329
- }
330
- function resolvePartial(cfg, patch) {
331
- const full = resolveConfig(patch);
332
- const out = {};
333
- for (const key of Object.keys(patch)) {
334
- if (key in full)
335
- out[key] = full[key];
336
- }
337
- return out;
338
- }
339
-
340
- // src/core/diag.ts
341
- import { appendFileSync as appendFileSync2 } from "fs";
342
-
343
170
  // src/core/log.ts
344
171
  import { appendFileSync, mkdirSync } from "fs";
345
172
  import { tmpdir } from "os";
346
- import { dirname as dirname3, join as join4 } from "path";
173
+ import { dirname as dirname3, join as join3 } from "path";
347
174
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
348
175
  var current = ["debug", "info", "warn", "error"].find(
349
176
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -352,7 +179,7 @@ function setLogLevel(level) {
352
179
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
353
180
  }
354
181
  function logFilePath() {
355
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
182
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
356
183
  }
357
184
  function write(level, scope, msg, extra) {
358
185
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -372,20 +199,19 @@ var log = {
372
199
  warn: (scope, msg, extra) => write("warn", scope, msg, extra),
373
200
  error: (scope, msg, extra) => write("error", scope, msg, extra)
374
201
  };
375
-
376
- // src/core/diag.ts
377
- function diagFilePath() {
378
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
379
- }
380
- function diag(harness, event, extra = {}) {
381
- log.debug(harness, `diag:${event}`, extra);
382
- try {
383
- appendFileSync2(
384
- diagFilePath(),
385
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
386
- );
387
- } catch {
388
- }
202
+ function describeError(value, maxChars = 200) {
203
+ const parts = [];
204
+ const seen = /* @__PURE__ */ new Set();
205
+ let current2 = value;
206
+ while (current2 && !seen.has(current2)) {
207
+ seen.add(current2);
208
+ const error = current2;
209
+ const text = typeof error.message === "string" ? error.message : String(current2);
210
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
211
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
212
+ current2 = error.cause;
213
+ }
214
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
389
215
  }
390
216
 
391
217
  // src/core/missions.ts
@@ -463,7 +289,10 @@ var KNOWLEDGE_LABELS = {
463
289
  }
464
290
  ]
465
291
  };
466
- var PAGES = [
292
+ function pageScopeRule(project) {
293
+ 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.`;
294
+ }
295
+ var PAGE_TAXONOMY = [
467
296
  {
468
297
  name: "Component map",
469
298
  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.",
@@ -490,11 +319,23 @@ var PAGES = [
490
319
  tags: ["knowledge:feature-work"]
491
320
  }
492
321
  ];
322
+ function pagesFor(project) {
323
+ const scope = pageScopeRule(project);
324
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
325
+ }
493
326
  var PAGE_MAX_TOKENS = 4096;
494
- var PAGE_TRIGGER = {
495
- fact_types: ["world", "experience", "observation"],
496
- refresh_after_consolidation: true
497
- };
327
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
328
+ function buildPageTrigger(cfg = {}) {
329
+ const base = { fact_types: PAGE_FACT_TYPES };
330
+ switch (cfg.pageTriggerType) {
331
+ case "cron":
332
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
333
+ case "manual":
334
+ return { ...base, refresh_after_consolidation: false };
335
+ default:
336
+ return { ...base, refresh_after_consolidation: true };
337
+ }
338
+ }
498
339
  var CODING_BANK_TEMPLATE = {
499
340
  version: "1",
500
341
  bank: {
@@ -549,6 +390,7 @@ async function pool(items, n, fn, onError, onProgress) {
549
390
  }
550
391
 
551
392
  // src/core/hindsight.ts
393
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
552
394
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
553
395
  var RateLimitedError = class extends Error {
554
396
  constructor(retryAfterMs2) {
@@ -581,8 +423,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
581
423
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
582
424
  var HindsightClient = class {
583
425
  apiUrl;
584
- apiToken;
426
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
427
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
428
+ token;
429
+ tokenProvider;
585
430
  bank;
431
+ project;
586
432
  opIds = [];
587
433
  // async operation ids collected by retain(), for drain()
588
434
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -591,34 +437,81 @@ var HindsightClient = class {
591
437
  idempotentRetain;
592
438
  log;
593
439
  maxParallelRetains;
440
+ observationScopes;
594
441
  constructor(o) {
595
442
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
596
- this.apiToken = o.apiToken;
443
+ this.token = o.apiToken;
444
+ this.tokenProvider = o.tokenProvider;
597
445
  this.bank = o.bank;
446
+ this.project = o.project;
598
447
  this.log = o.log ?? (() => {
599
448
  });
600
449
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
450
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
451
+ }
452
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
453
+ get apiToken() {
454
+ return this.token;
601
455
  }
602
456
  headers() {
603
457
  const h = { "Content-Type": "application/json" };
604
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
458
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
605
459
  return h;
606
460
  }
461
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
462
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
463
+ * doubling every failing request. */
464
+ refreshToken() {
465
+ if (!this.tokenProvider) return false;
466
+ let next;
467
+ try {
468
+ next = this.tokenProvider();
469
+ } catch {
470
+ return false;
471
+ }
472
+ if (next === this.token) return false;
473
+ this.token = next;
474
+ return true;
475
+ }
476
+ /**
477
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
478
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
479
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
480
+ * not.
481
+ *
482
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
483
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
484
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
485
+ * bounds the whole call.
486
+ */
487
+ async fetchWithAuth(url, init) {
488
+ const send = () => fetch(url, { ...init, headers: this.headers() });
489
+ const r = await send();
490
+ if (r.status !== 401 || !this.refreshToken()) return r;
491
+ return send();
492
+ }
493
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
494
+ * server answers identically for both — only the client knows which it sent. */
495
+ authHint(status) {
496
+ if (status !== 401) return "";
497
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
498
+ }
607
499
  bankUrl(suffix = "") {
608
500
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
609
501
  }
610
502
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
611
503
  async req(method, url, body, tolerate = []) {
612
- const r = await fetch(url, {
504
+ const r = await this.fetchWithAuth(url, {
613
505
  method,
614
- headers: this.headers(),
615
506
  body: body ? JSON.stringify(body) : void 0,
616
507
  signal: AbortSignal.timeout(15e3)
617
508
  });
618
509
  if (r.status === 429 && !tolerate.includes(429))
619
510
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
620
511
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
621
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
512
+ throw new Error(
513
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
514
+ );
622
515
  return r;
623
516
  }
624
517
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -629,7 +522,11 @@ var HindsightClient = class {
629
522
  context,
630
523
  document_id: documentId,
631
524
  tags,
632
- strategy
525
+ strategy,
526
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
527
+ // observations were built under is a property of the write rather than of whichever server
528
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
529
+ observation_scopes: this.observationScopes
633
530
  };
634
531
  if (opts.timestamp) item.timestamp = opts.timestamp;
635
532
  if (opts.metadata) item.metadata = opts.metadata;
@@ -708,7 +605,7 @@ var HindsightClient = class {
708
605
  this.log(
709
606
  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}`
710
607
  );
711
- await this.seedPages();
608
+ await this.seedPages(opts.pageTrigger);
712
609
  }
713
610
  /**
714
611
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -766,7 +663,7 @@ var HindsightClient = class {
766
663
  let backoffMs = POLL_CYCLE_MS;
767
664
  await pool([...pending], this.maxParallelRetains, async (id) => {
768
665
  try {
769
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
666
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
770
667
  if (r.status === 429) {
771
668
  backoffMs = Math.min(
772
669
  RETRY_AFTER_CEILING_MS,
@@ -792,18 +689,23 @@ var HindsightClient = class {
792
689
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
793
690
  );
794
691
  }
795
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
796
- async reflect(query, opts = {}) {
692
+ /**
693
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
694
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
695
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
696
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
697
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
698
+ */
699
+ async reflect(query, opts) {
797
700
  const ctrl = new AbortController();
798
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
701
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
799
702
  try {
800
- const resp = await fetch(this.bankUrl("/reflect"), {
703
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
801
704
  method: "POST",
802
- headers: this.headers(),
803
705
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
804
706
  signal: ctrl.signal
805
707
  });
806
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
708
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
807
709
  const data = await resp.json();
808
710
  return (data.text || "").trim();
809
711
  } finally {
@@ -887,16 +789,18 @@ var HindsightClient = class {
887
789
  }));
888
790
  }
889
791
  /**
890
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
792
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
891
793
  *
892
794
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
893
795
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
894
796
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
895
797
  *
896
798
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
897
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
799
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
800
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
898
801
  */
899
- async seedPages() {
802
+ async seedPages(pageTrigger = buildPageTrigger()) {
803
+ const pages = pagesFor(this.project ?? this.bank);
900
804
  const existing = /* @__PURE__ */ new Map();
901
805
  let roots;
902
806
  try {
@@ -913,14 +817,14 @@ var HindsightClient = class {
913
817
  }
914
818
  let created = 0;
915
819
  let updated = 0;
916
- for (const page of PAGES) {
820
+ for (const page of pages) {
917
821
  const hit = existing.get(page.name.toLowerCase());
918
822
  const body = {
919
823
  name: page.name,
920
824
  source_query: page.source_query,
921
825
  tags: page.tags,
922
826
  max_tokens: PAGE_MAX_TOKENS,
923
- trigger: PAGE_TRIGGER
827
+ trigger: pageTrigger
924
828
  };
925
829
  if (!hit) {
926
830
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -949,7 +853,7 @@ var HindsightClient = class {
949
853
  }
950
854
  }
951
855
  this.log(
952
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
856
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
953
857
  );
954
858
  }
955
859
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -959,7 +863,8 @@ var HindsightClient = class {
959
863
  /**
960
864
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
961
865
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
962
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
866
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
867
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
963
868
  */
964
869
  async captureInitiative(args) {
965
870
  let pageId = args.relatesToPageId;
@@ -970,10 +875,7 @@ var HindsightClient = class {
970
875
  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.`,
971
876
  parent_id: folderId,
972
877
  tags: ["knowledge:feature-work"],
973
- trigger: {
974
- fact_types: ["world", "experience", "observation"],
975
- refresh_after_consolidation: true
976
- }
878
+ trigger: args.pageTrigger ?? buildPageTrigger()
977
879
  });
978
880
  try {
979
881
  const j = await r.json();
@@ -982,7 +884,7 @@ var HindsightClient = class {
982
884
  }
983
885
  pageId ||= `initiative-${this.slugify(args.title)}`;
984
886
  }
985
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
887
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
986
888
  const content = `${verb}: ${args.title}. ${args.summary}`;
987
889
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
988
890
  const tags = [
@@ -1020,6 +922,260 @@ var HindsightClient = class {
1020
922
  }
1021
923
  };
1022
924
 
925
+ // src/core/config.ts
926
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
927
+ var DEFAULT_DAEMON_PORT = 9077;
928
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
929
+ function resolvePageTriggerType(raw) {
930
+ if (raw.pageTriggerType === "manual") return "manual";
931
+ if (raw.pageTriggerType === "cron") {
932
+ if (raw.pageTriggerCron?.trim()) return "cron";
933
+ log.warn(
934
+ "config",
935
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
936
+ );
937
+ }
938
+ return "auto-refresh";
939
+ }
940
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
941
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
942
+ function resolveReflectBudget(raw) {
943
+ const value = raw.reflectBudget;
944
+ if (value === void 0) return "high";
945
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
946
+ return value;
947
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
948
+ return "high";
949
+ }
950
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
951
+ function resolveObservationScopes(raw) {
952
+ const value = raw;
953
+ if (typeof value === "string")
954
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
955
+ if (Array.isArray(value)) {
956
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
957
+ if (scopes.length) return scopes;
958
+ }
959
+ return DEFAULT_OBSERVATION_SCOPES;
960
+ }
961
+ function resolveConfig(raw = {}) {
962
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
963
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
964
+ return {
965
+ serverMode,
966
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
967
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
968
+ // daemon needs no plumbing through eight separate constructors.
969
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
970
+ apiToken: raw.apiToken || void 0,
971
+ apiPort,
972
+ daemonIdleTimeout: raw.daemonIdleTimeout,
973
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
974
+ embedVersion: raw.embedVersion || void 0,
975
+ embedPackagePath: raw.embedPackagePath || void 0,
976
+ bankId: raw.bankId,
977
+ dynamicBankId: raw.dynamicBankId,
978
+ bankIdTemplate: raw.bankIdTemplate,
979
+ mapPathToBank: raw.mapPathToBank,
980
+ resolveWorktrees: raw.resolveWorktrees,
981
+ optInOnly: raw.optInOnly ?? false,
982
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
983
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
984
+ harness: raw.harness ?? "opencode",
985
+ disabled: raw.disabled ?? false,
986
+ retainSessions: raw.retainSessions ?? true,
987
+ // write sessions back by default, every harness
988
+ maxParallelRetains: raw.maxParallelRetains || 10,
989
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
990
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
991
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
992
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
993
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
994
+ reflectBudget: resolveReflectBudget(raw),
995
+ autoReflect: raw.autoReflect ?? true,
996
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
997
+ pageTriggerType: resolvePageTriggerType(raw),
998
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
999
+ autoSeed: raw.autoSeed ?? true,
1000
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1001
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1002
+ surveyModel: raw.surveyModel || "haiku",
1003
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1004
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1005
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1006
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1007
+ // nested object cannot reach the API as a tag and fail the whole retain.
1008
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1009
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1010
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1011
+ ) : {},
1012
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1013
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1014
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1015
+ };
1016
+ }
1017
+ function readRaw(path) {
1018
+ try {
1019
+ return JSON.parse(readFileSync(path, "utf8"));
1020
+ } catch (e) {
1021
+ if (e?.code !== "ENOENT") {
1022
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1023
+ }
1024
+ return {};
1025
+ }
1026
+ }
1027
+ function mergeRaw(a, b) {
1028
+ const { harnesses: _drop, ...flat } = b;
1029
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1030
+ }
1031
+ function applyLayer(raw, layer, harness) {
1032
+ let out = mergeRaw(raw, layer);
1033
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1034
+ if (perHarness) out = mergeRaw(out, perHarness);
1035
+ return out;
1036
+ }
1037
+ var ENV_KEYS = {
1038
+ serverMode: "HINDSIGHT_SERVER_MODE",
1039
+ apiUrl: "HINDSIGHT_API_URL",
1040
+ apiToken: "HINDSIGHT_API_TOKEN",
1041
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1042
+ // it can carry their existing environment over unchanged.
1043
+ apiPort: "HINDSIGHT_API_PORT",
1044
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1045
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1046
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1047
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1048
+ bankId: "HINDSIGHT_BANK_ID",
1049
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1050
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1051
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1052
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1053
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1054
+ harness: "HINDSIGHT_HARNESS",
1055
+ disabled: "HINDSIGHT_DISABLED",
1056
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1057
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1058
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1059
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1060
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1061
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1062
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1063
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1064
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1065
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1066
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1067
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1068
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1069
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1070
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1071
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1072
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1073
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1074
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1075
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1076
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1077
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1078
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1079
+ };
1080
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1081
+ "dynamicBankId",
1082
+ "resolveWorktrees",
1083
+ "optInOnly",
1084
+ "disabled",
1085
+ "retainSessions",
1086
+ "autoReflect",
1087
+ "autoSeed",
1088
+ "codebaseSurvey"
1089
+ ]);
1090
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1091
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1092
+ "apiPort",
1093
+ "daemonIdleTimeout",
1094
+ "maxParallelRetains",
1095
+ "reflectTimeoutMs",
1096
+ "reflectToolTimeoutMs",
1097
+ "pageRefreshEveryTurns",
1098
+ "seedLimit",
1099
+ "surveyBudgetUsd",
1100
+ "surveyRefreshCommits"
1101
+ ]);
1102
+ function readEnvConfig(env = process.env) {
1103
+ const out = {};
1104
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1105
+ const value = env[name];
1106
+ if (value === void 0 || value.trim() === "") continue;
1107
+ if (ENV_BOOLEANS.has(key)) {
1108
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1109
+ } else if (ENV_LISTS.has(key)) {
1110
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1111
+ if (items.length) out[key] = items;
1112
+ } else if (ENV_NUMBERS.has(key)) {
1113
+ const n = Number(value);
1114
+ if (Number.isFinite(n)) out[key] = n;
1115
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1116
+ } else {
1117
+ out[key] = value;
1118
+ }
1119
+ }
1120
+ return out;
1121
+ }
1122
+ function loadConfig(opts = {}) {
1123
+ const o = typeof opts === "string" ? { path: opts } : opts;
1124
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1125
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1126
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1127
+ return resolveConfig(raw);
1128
+ }
1129
+ var BANK_OVERRIDE_EXCLUDED = [
1130
+ "bankId",
1131
+ "bankIdTemplate",
1132
+ "mapPathToBank",
1133
+ "dynamicBankId",
1134
+ "resolveWorktrees",
1135
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1136
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1137
+ "optInOnly",
1138
+ "optInPaths",
1139
+ "harness"
1140
+ ];
1141
+ function applyBankConfig(cfg, resolvedId, directory) {
1142
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1143
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1144
+ const section = cfg.banks[resolvedId];
1145
+ if (!section) return { cfg, bankId: resolvedId };
1146
+ const safe = { ...section };
1147
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1148
+ delete safe.banks;
1149
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1150
+ delete safe.bank;
1151
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1152
+ }
1153
+ function resolvePartial(cfg, patch) {
1154
+ const full = resolveConfig(patch);
1155
+ const out = {};
1156
+ for (const key of Object.keys(patch)) {
1157
+ if (key in full)
1158
+ out[key] = full[key];
1159
+ }
1160
+ return out;
1161
+ }
1162
+
1163
+ // src/core/diag.ts
1164
+ import { appendFileSync as appendFileSync2 } from "fs";
1165
+ function diagFilePath() {
1166
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1167
+ }
1168
+ function diag(harness, event, extra = {}) {
1169
+ log.debug(harness, `diag:${event}`, extra);
1170
+ try {
1171
+ appendFileSync2(
1172
+ diagFilePath(),
1173
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1174
+ );
1175
+ } catch {
1176
+ }
1177
+ }
1178
+
1023
1179
  // src/core/brand.ts
1024
1180
  function brandWord() {
1025
1181
  const start = [0, 116, 217];
@@ -1081,7 +1237,7 @@ function roster(pages) {
1081
1237
  var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP for any question the project's accumulated knowledge might answer (components, conventions, past decisions, initiatives): search the knowledge pages and credit results visibly with a markdown blockquote so it renders as a callout, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>".
1082
1238
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
1083
1239
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
1084
- - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this ONCE to record it as a tracked page. Skip bug fixes, small tweaks, and chores.
1240
+ - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this to record it as a tracked page; then call it AGAIN with relates_to_page_id set to that page whenever the goal, scope, or rationale materially changes mid-work, so the page tracks the current plan and not the opening one. Skip bug fixes, small tweaks, chores, and trivial course-corrections.
1085
1241
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
1086
1242
  var REFLECT_ON_GOALS = "- The user just set a NEW task or goal \u2192 call hindsight_reflect with that goal FIRST, before planning: no memory is injected automatically in this configuration, so this call is the only way past decisions, constraints, and failed attempts relevant to the goal reach you.\n";
1087
1243
  function toolGuide(opts) {
@@ -1130,6 +1286,23 @@ function writeSessionCache(cacheFile, cache) {
1130
1286
  } catch {
1131
1287
  }
1132
1288
  }
1289
+ function sessionRootFile(harness, sessionId) {
1290
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1291
+ }
1292
+ function sessionRootDir(harness, sessionId, cwd) {
1293
+ if (!sessionId || !cwd) return cwd;
1294
+ const file = sessionRootFile(harness, sessionId);
1295
+ try {
1296
+ const recorded = readFileSync2(file, "utf8").trim();
1297
+ if (recorded) return recorded;
1298
+ } catch {
1299
+ }
1300
+ try {
1301
+ writeFileAtomic(file, cwd);
1302
+ } catch {
1303
+ }
1304
+ return cwd;
1305
+ }
1133
1306
 
1134
1307
  // src/core/hook.ts
1135
1308
  var HOOK_REFLECT_CAP_MS = 25e3;
@@ -1166,11 +1339,11 @@ async function buildHookOutput(args) {
1166
1339
  reflectAnswer = "";
1167
1340
  reflectFailed = true;
1168
1341
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
1169
- error: String(e?.message || e).slice(0, 200)
1342
+ error: describeError(e)
1170
1343
  });
1171
1344
  diag(harness, "reflect_failed", {
1172
1345
  ms: Date.now() - t0,
1173
- error: String(e?.message || e).slice(0, 200),
1346
+ error: describeError(e),
1174
1347
  query: prompt.slice(0, 80)
1175
1348
  });
1176
1349
  }
@@ -1189,7 +1362,7 @@ async function buildHookOutput(args) {
1189
1362
  client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
1190
1363
  {
1191
1364
  ms: Date.now() - t0,
1192
- error: String(e?.message || e).slice(0, 200)
1365
+ error: describeError(e)
1193
1366
  }
1194
1367
  );
1195
1368
  }
@@ -1237,7 +1410,8 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1237
1410
  return;
1238
1411
  }
1239
1412
  const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
1240
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness), cwd);
1413
+ const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
1414
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
1241
1415
  cfg = resolved.cfg;
1242
1416
  const bankId = resolved.bankId;
1243
1417
  if (cfg.disabled) {
@@ -1248,7 +1422,8 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1248
1422
  apiUrl: cfg.apiUrl,
1249
1423
  apiToken: cfg.apiToken,
1250
1424
  bank: bankId,
1251
- maxParallelRetains: cfg.maxParallelRetains
1425
+ maxParallelRetains: cfg.maxParallelRetains,
1426
+ observationScopes: cfg.observationScopes
1252
1427
  });
1253
1428
  const cacheFile = sessionCacheFile(spec.harness, sessionId || "no-session");
1254
1429
  if (cfg.autoSeed !== false && !existsSync2(cacheFile)) {