@vectorize-io/hindsight-coding-agents 0.3.4 → 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.
@@ -41,8 +41,8 @@ function getProjectRootFromGit(directory) {
41
41
  return null;
42
42
  }
43
43
  }
44
- function projectNameOf(directory) {
45
- return gitProjectName(directory, true);
44
+ function projectNameOf(directory, sessionRoot) {
45
+ return gitProjectName(directory, true, sessionRoot);
46
46
  }
47
47
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
48
48
  function nearestExistingDir(directory) {
@@ -58,18 +58,24 @@ function nearestExistingDir(directory) {
58
58
  function dirName(directory) {
59
59
  return directory && basename(directory) || "unknown";
60
60
  }
61
- function gitProjectName(directory, resolveWorktrees) {
61
+ function mainWorktreeRoot(directory, sessionRoot = "") {
62
+ const candidates = [
63
+ nearestExistingDir(directory),
64
+ sessionRoot,
65
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
66
+ ];
67
+ for (const candidate of candidates) {
68
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
69
+ if (root) return root;
70
+ }
71
+ return null;
72
+ }
73
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
62
74
  if (resolveWorktrees) {
63
- const candidates = [
64
- nearestExistingDir(directory),
65
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
66
- ];
67
- for (const candidate of candidates) {
68
- const root = candidate ? getProjectRootFromGit(candidate) : null;
69
- if (root) return basename(root);
70
- }
75
+ const root = mainWorktreeRoot(directory, sessionRoot);
76
+ if (root) return basename(root);
71
77
  }
72
- return dirName(directory);
78
+ return dirName(sessionRoot || directory);
73
79
  }
74
80
  function configuredDir(dir) {
75
81
  const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
@@ -89,23 +95,38 @@ function mapLookup(map, directory) {
89
95
  }
90
96
  return best?.bank;
91
97
  }
98
+ function lookupDirectories(config, directory, sessionRoot = "") {
99
+ const directories = [normalize(directory)];
100
+ if (config.resolveWorktrees ?? true) {
101
+ const root = mainWorktreeRoot(directory, sessionRoot);
102
+ const normalizedRoot = root ? normalize(root) : "";
103
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
104
+ }
105
+ return directories;
106
+ }
92
107
  function isOptedIn(config, directory) {
93
108
  if (!config.optInOnly) return true;
94
109
  if (!directory) return false;
95
- const cwd = normalize(directory);
96
- if ((config.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
110
+ const directories = lookupDirectories(config, directory);
111
+ if (directories.some(
112
+ (candidate) => (config.optInPaths ?? []).some(
113
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
114
+ )
115
+ ))
97
116
  return true;
98
- return Boolean(config.mapPathToBank && mapLookup(config.mapPathToBank, directory));
117
+ const pathMap = config.mapPathToBank;
118
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
99
119
  }
100
- function deriveBankId(config, directory, harness = "coding") {
101
- const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
120
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
121
+ const pathMap = config.mapPathToBank;
122
+ const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
102
123
  if (mapped) return mapped;
103
124
  const dynamic = config.dynamicBankId ?? !config.bankId;
104
125
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
105
126
  const resolvers = {
106
127
  harness: () => harness,
107
128
  project: () => dirName(directory),
108
- gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
129
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
109
130
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
110
131
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
111
132
  };
@@ -115,7 +136,7 @@ function deriveBankId(config, directory, harness = "coding") {
115
136
  // src/core/config.ts
116
137
  import { readFileSync } from "fs";
117
138
  import { homedir as homedir2 } from "os";
118
- import { join as join3 } from "path";
139
+ import { join as join4 } from "path";
119
140
 
120
141
  // src/core/seed.ts
121
142
  import { spawn as realSpawn } from "child_process";
@@ -149,204 +170,10 @@ function startBackgroundSeed(repoDir, opts = {}) {
149
170
  }
150
171
  }
151
172
 
152
- // src/core/config.ts
153
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
154
- var DEFAULT_DAEMON_PORT = 9077;
155
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
156
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
157
- function resolveConfig(raw = {}) {
158
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
159
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
160
- return {
161
- serverMode,
162
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
163
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
164
- // daemon needs no plumbing through eight separate constructors.
165
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
166
- apiToken: raw.apiToken || void 0,
167
- apiPort,
168
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
169
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
170
- embedVersion: raw.embedVersion || void 0,
171
- embedPackagePath: raw.embedPackagePath || void 0,
172
- bankId: raw.bankId,
173
- dynamicBankId: raw.dynamicBankId,
174
- bankIdTemplate: raw.bankIdTemplate,
175
- mapPathToBank: raw.mapPathToBank,
176
- resolveWorktrees: raw.resolveWorktrees,
177
- optInOnly: raw.optInOnly ?? false,
178
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
179
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
180
- harness: raw.harness ?? "opencode",
181
- disabled: raw.disabled ?? false,
182
- retainSessions: raw.retainSessions ?? true,
183
- // opencode: write back by default (parity with hook-harness Stop)
184
- maxParallelRetains: raw.maxParallelRetains || 10,
185
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
186
- autoReflect: raw.autoReflect ?? true,
187
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
188
- autoSeed: raw.autoSeed ?? true,
189
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
190
- codebaseSurvey: raw.codebaseSurvey ?? true,
191
- surveyModel: raw.surveyModel || "haiku",
192
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
193
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
194
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
195
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
196
- // nested object cannot reach the API as a tag and fail the whole retain.
197
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
198
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
199
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
200
- ) : {},
201
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
202
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
203
- };
204
- }
205
- function readRaw(path) {
206
- try {
207
- return JSON.parse(readFileSync(path, "utf8"));
208
- } catch (e) {
209
- if (e?.code !== "ENOENT") {
210
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
211
- }
212
- return {};
213
- }
214
- }
215
- function mergeRaw(a, b) {
216
- const { harnesses: _drop, ...flat } = b;
217
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
218
- }
219
- function applyLayer(raw, layer, harness) {
220
- let out = mergeRaw(raw, layer);
221
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
222
- if (perHarness) out = mergeRaw(out, perHarness);
223
- return out;
224
- }
225
- var ENV_KEYS = {
226
- serverMode: "HINDSIGHT_SERVER_MODE",
227
- apiUrl: "HINDSIGHT_API_URL",
228
- apiToken: "HINDSIGHT_API_TOKEN",
229
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
230
- // it can carry their existing environment over unchanged.
231
- apiPort: "HINDSIGHT_API_PORT",
232
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
233
- embedVersion: "HINDSIGHT_EMBED_VERSION",
234
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
235
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
236
- bankId: "HINDSIGHT_BANK_ID",
237
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
238
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
239
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
240
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
241
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
242
- harness: "HINDSIGHT_HARNESS",
243
- disabled: "HINDSIGHT_DISABLED",
244
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
245
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
246
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
247
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
248
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
249
- autoSeed: "HINDSIGHT_AUTO_SEED",
250
- seedLimit: "HINDSIGHT_SEED_LIMIT",
251
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
252
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
253
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
254
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
255
- logLevel: "HINDSIGHT_LOG_LEVEL",
256
- gitIngest: "HINDSIGHT_GIT_INGEST",
257
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
258
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
259
- retainTags: "HINDSIGHT_RETAIN_TAGS"
260
- };
261
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
262
- "dynamicBankId",
263
- "resolveWorktrees",
264
- "optInOnly",
265
- "disabled",
266
- "retainSessions",
267
- "autoReflect",
268
- "autoSeed",
269
- "codebaseSurvey"
270
- ]);
271
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
272
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
273
- "apiPort",
274
- "daemonIdleTimeout",
275
- "maxParallelRetains",
276
- "reflectTimeoutMs",
277
- "pageRefreshEveryTurns",
278
- "seedLimit",
279
- "surveyBudgetUsd",
280
- "surveyRefreshCommits"
281
- ]);
282
- function readEnvConfig(env = process.env) {
283
- const out = {};
284
- for (const [key, name] of Object.entries(ENV_KEYS)) {
285
- const value = env[name];
286
- if (value === void 0 || value.trim() === "") continue;
287
- if (ENV_BOOLEANS.has(key)) {
288
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
289
- } else if (ENV_LISTS.has(key)) {
290
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
291
- if (items.length) out[key] = items;
292
- } else if (ENV_NUMBERS.has(key)) {
293
- const n = Number(value);
294
- if (Number.isFinite(n)) out[key] = n;
295
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
296
- } else {
297
- out[key] = value;
298
- }
299
- }
300
- return out;
301
- }
302
- function loadConfig(opts = {}) {
303
- const o = typeof opts === "string" ? { path: opts } : opts;
304
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
305
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
306
- if (!raw.harness && o.harness) raw.harness = o.harness;
307
- return resolveConfig(raw);
308
- }
309
- var BANK_OVERRIDE_EXCLUDED = [
310
- "bankId",
311
- "bankIdTemplate",
312
- "mapPathToBank",
313
- "dynamicBankId",
314
- "resolveWorktrees",
315
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
316
- // only ever arrive too late to matter — strip them rather than let them read as effective.
317
- "optInOnly",
318
- "optInPaths",
319
- "harness"
320
- ];
321
- function applyBankConfig(cfg, resolvedId, directory) {
322
- if (directory !== void 0 && !isOptedIn(cfg, directory))
323
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
324
- const section = cfg.banks[resolvedId];
325
- if (!section) return { cfg, bankId: resolvedId };
326
- const safe = { ...section };
327
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
328
- delete safe.banks;
329
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
330
- delete safe.bank;
331
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
332
- }
333
- function resolvePartial(cfg, patch) {
334
- const full = resolveConfig(patch);
335
- const out = {};
336
- for (const key of Object.keys(patch)) {
337
- if (key in full)
338
- out[key] = full[key];
339
- }
340
- return out;
341
- }
342
-
343
- // src/core/diag.ts
344
- import { appendFileSync as appendFileSync2 } from "fs";
345
-
346
173
  // src/core/log.ts
347
174
  import { appendFileSync, mkdirSync } from "fs";
348
175
  import { tmpdir } from "os";
349
- import { dirname as dirname3, join as join4 } from "path";
176
+ import { dirname as dirname3, join as join3 } from "path";
350
177
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
351
178
  var current = ["debug", "info", "warn", "error"].find(
352
179
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -355,7 +182,7 @@ function setLogLevel(level) {
355
182
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
356
183
  }
357
184
  function logFilePath() {
358
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
185
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
359
186
  }
360
187
  function write(level, scope, msg, extra) {
361
188
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -376,21 +203,6 @@ var log = {
376
203
  error: (scope, msg, extra) => write("error", scope, msg, extra)
377
204
  };
378
205
 
379
- // src/core/diag.ts
380
- function diagFilePath() {
381
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
382
- }
383
- function diag(harness, event, extra = {}) {
384
- log.debug(harness, `diag:${event}`, extra);
385
- try {
386
- appendFileSync2(
387
- diagFilePath(),
388
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
389
- );
390
- } catch {
391
- }
392
- }
393
-
394
206
  // src/core/missions.ts
395
207
  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.";
396
208
  var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
@@ -466,7 +278,10 @@ var KNOWLEDGE_LABELS = {
466
278
  }
467
279
  ]
468
280
  };
469
- var PAGES = [
281
+ function pageScopeRule(project) {
282
+ 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.`;
283
+ }
284
+ var PAGE_TAXONOMY = [
470
285
  {
471
286
  name: "Component map",
472
287
  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.",
@@ -493,11 +308,23 @@ var PAGES = [
493
308
  tags: ["knowledge:feature-work"]
494
309
  }
495
310
  ];
311
+ function pagesFor(project) {
312
+ const scope = pageScopeRule(project);
313
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
314
+ }
496
315
  var PAGE_MAX_TOKENS = 4096;
497
- var PAGE_TRIGGER = {
498
- fact_types: ["world", "experience", "observation"],
499
- refresh_after_consolidation: true
500
- };
316
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
317
+ function buildPageTrigger(cfg = {}) {
318
+ const base = { fact_types: PAGE_FACT_TYPES };
319
+ switch (cfg.pageTriggerType) {
320
+ case "cron":
321
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
322
+ case "manual":
323
+ return { ...base, refresh_after_consolidation: false };
324
+ default:
325
+ return { ...base, refresh_after_consolidation: true };
326
+ }
327
+ }
501
328
  var CODING_BANK_TEMPLATE = {
502
329
  version: "1",
503
330
  bank: {
@@ -552,6 +379,7 @@ async function pool(items, n, fn, onError, onProgress) {
552
379
  }
553
380
 
554
381
  // src/core/hindsight.ts
382
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
555
383
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
556
384
  var RateLimitedError = class extends Error {
557
385
  constructor(retryAfterMs2) {
@@ -584,8 +412,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
584
412
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
585
413
  var HindsightClient = class {
586
414
  apiUrl;
587
- apiToken;
415
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
416
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
417
+ token;
418
+ tokenProvider;
588
419
  bank;
420
+ project;
589
421
  opIds = [];
590
422
  // async operation ids collected by retain(), for drain()
591
423
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -594,34 +426,81 @@ var HindsightClient = class {
594
426
  idempotentRetain;
595
427
  log;
596
428
  maxParallelRetains;
429
+ observationScopes;
597
430
  constructor(o) {
598
431
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
599
- this.apiToken = o.apiToken;
432
+ this.token = o.apiToken;
433
+ this.tokenProvider = o.tokenProvider;
600
434
  this.bank = o.bank;
435
+ this.project = o.project;
601
436
  this.log = o.log ?? (() => {
602
437
  });
603
438
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
439
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
440
+ }
441
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
442
+ get apiToken() {
443
+ return this.token;
604
444
  }
605
445
  headers() {
606
446
  const h = { "Content-Type": "application/json" };
607
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
447
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
608
448
  return h;
609
449
  }
450
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
451
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
452
+ * doubling every failing request. */
453
+ refreshToken() {
454
+ if (!this.tokenProvider) return false;
455
+ let next;
456
+ try {
457
+ next = this.tokenProvider();
458
+ } catch {
459
+ return false;
460
+ }
461
+ if (next === this.token) return false;
462
+ this.token = next;
463
+ return true;
464
+ }
465
+ /**
466
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
467
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
468
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
469
+ * not.
470
+ *
471
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
472
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
473
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
474
+ * bounds the whole call.
475
+ */
476
+ async fetchWithAuth(url, init) {
477
+ const send = () => fetch(url, { ...init, headers: this.headers() });
478
+ const r = await send();
479
+ if (r.status !== 401 || !this.refreshToken()) return r;
480
+ return send();
481
+ }
482
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
483
+ * server answers identically for both — only the client knows which it sent. */
484
+ authHint(status) {
485
+ if (status !== 401) return "";
486
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
487
+ }
610
488
  bankUrl(suffix = "") {
611
489
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
612
490
  }
613
491
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
614
492
  async req(method, url, body, tolerate = []) {
615
- const r = await fetch(url, {
493
+ const r = await this.fetchWithAuth(url, {
616
494
  method,
617
- headers: this.headers(),
618
495
  body: body ? JSON.stringify(body) : void 0,
619
496
  signal: AbortSignal.timeout(15e3)
620
497
  });
621
498
  if (r.status === 429 && !tolerate.includes(429))
622
499
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
623
500
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
624
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
501
+ throw new Error(
502
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
503
+ );
625
504
  return r;
626
505
  }
627
506
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -632,7 +511,11 @@ var HindsightClient = class {
632
511
  context,
633
512
  document_id: documentId,
634
513
  tags,
635
- strategy
514
+ strategy,
515
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
516
+ // observations were built under is a property of the write rather than of whichever server
517
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
518
+ observation_scopes: this.observationScopes
636
519
  };
637
520
  if (opts.timestamp) item.timestamp = opts.timestamp;
638
521
  if (opts.metadata) item.metadata = opts.metadata;
@@ -711,7 +594,7 @@ var HindsightClient = class {
711
594
  this.log(
712
595
  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}`
713
596
  );
714
- await this.seedPages();
597
+ await this.seedPages(opts.pageTrigger);
715
598
  }
716
599
  /**
717
600
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -769,7 +652,7 @@ var HindsightClient = class {
769
652
  let backoffMs = POLL_CYCLE_MS;
770
653
  await pool([...pending], this.maxParallelRetains, async (id) => {
771
654
  try {
772
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
655
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
773
656
  if (r.status === 429) {
774
657
  backoffMs = Math.min(
775
658
  RETRY_AFTER_CEILING_MS,
@@ -795,18 +678,23 @@ var HindsightClient = class {
795
678
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
796
679
  );
797
680
  }
798
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
799
- async reflect(query, opts = {}) {
681
+ /**
682
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
683
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
684
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
685
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
686
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
687
+ */
688
+ async reflect(query, opts) {
800
689
  const ctrl = new AbortController();
801
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
690
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
802
691
  try {
803
- const resp = await fetch(this.bankUrl("/reflect"), {
692
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
804
693
  method: "POST",
805
- headers: this.headers(),
806
694
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
807
695
  signal: ctrl.signal
808
696
  });
809
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
697
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
810
698
  const data = await resp.json();
811
699
  return (data.text || "").trim();
812
700
  } finally {
@@ -890,16 +778,18 @@ var HindsightClient = class {
890
778
  }));
891
779
  }
892
780
  /**
893
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
781
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
894
782
  *
895
783
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
896
784
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
897
785
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
898
786
  *
899
787
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
900
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
788
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
789
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
901
790
  */
902
- async seedPages() {
791
+ async seedPages(pageTrigger = buildPageTrigger()) {
792
+ const pages = pagesFor(this.project ?? this.bank);
903
793
  const existing = /* @__PURE__ */ new Map();
904
794
  let roots;
905
795
  try {
@@ -916,14 +806,14 @@ var HindsightClient = class {
916
806
  }
917
807
  let created = 0;
918
808
  let updated = 0;
919
- for (const page of PAGES) {
809
+ for (const page of pages) {
920
810
  const hit = existing.get(page.name.toLowerCase());
921
811
  const body = {
922
812
  name: page.name,
923
813
  source_query: page.source_query,
924
814
  tags: page.tags,
925
815
  max_tokens: PAGE_MAX_TOKENS,
926
- trigger: PAGE_TRIGGER
816
+ trigger: pageTrigger
927
817
  };
928
818
  if (!hit) {
929
819
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -952,7 +842,7 @@ var HindsightClient = class {
952
842
  }
953
843
  }
954
844
  this.log(
955
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
845
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
956
846
  );
957
847
  }
958
848
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -962,7 +852,8 @@ var HindsightClient = class {
962
852
  /**
963
853
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
964
854
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
965
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
855
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
856
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
966
857
  */
967
858
  async captureInitiative(args) {
968
859
  let pageId = args.relatesToPageId;
@@ -973,10 +864,7 @@ var HindsightClient = class {
973
864
  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.`,
974
865
  parent_id: folderId,
975
866
  tags: ["knowledge:feature-work"],
976
- trigger: {
977
- fact_types: ["world", "experience", "observation"],
978
- refresh_after_consolidation: true
979
- }
867
+ trigger: args.pageTrigger ?? buildPageTrigger()
980
868
  });
981
869
  try {
982
870
  const j = await r.json();
@@ -985,7 +873,7 @@ var HindsightClient = class {
985
873
  }
986
874
  pageId ||= `initiative-${this.slugify(args.title)}`;
987
875
  }
988
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
876
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
989
877
  const content = `${verb}: ${args.title}. ${args.summary}`;
990
878
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
991
879
  const tags = [
@@ -1023,6 +911,260 @@ var HindsightClient = class {
1023
911
  }
1024
912
  };
1025
913
 
914
+ // src/core/config.ts
915
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
916
+ var DEFAULT_DAEMON_PORT = 9077;
917
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
918
+ function resolvePageTriggerType(raw) {
919
+ if (raw.pageTriggerType === "manual") return "manual";
920
+ if (raw.pageTriggerType === "cron") {
921
+ if (raw.pageTriggerCron?.trim()) return "cron";
922
+ log.warn(
923
+ "config",
924
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
925
+ );
926
+ }
927
+ return "auto-refresh";
928
+ }
929
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
930
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
931
+ function resolveReflectBudget(raw) {
932
+ const value = raw.reflectBudget;
933
+ if (value === void 0) return "high";
934
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
935
+ return value;
936
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
937
+ return "high";
938
+ }
939
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
940
+ function resolveObservationScopes(raw) {
941
+ const value = raw;
942
+ if (typeof value === "string")
943
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
944
+ if (Array.isArray(value)) {
945
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
946
+ if (scopes.length) return scopes;
947
+ }
948
+ return DEFAULT_OBSERVATION_SCOPES;
949
+ }
950
+ function resolveConfig(raw = {}) {
951
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
952
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
953
+ return {
954
+ serverMode,
955
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
956
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
957
+ // daemon needs no plumbing through eight separate constructors.
958
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
959
+ apiToken: raw.apiToken || void 0,
960
+ apiPort,
961
+ daemonIdleTimeout: raw.daemonIdleTimeout,
962
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
963
+ embedVersion: raw.embedVersion || void 0,
964
+ embedPackagePath: raw.embedPackagePath || void 0,
965
+ bankId: raw.bankId,
966
+ dynamicBankId: raw.dynamicBankId,
967
+ bankIdTemplate: raw.bankIdTemplate,
968
+ mapPathToBank: raw.mapPathToBank,
969
+ resolveWorktrees: raw.resolveWorktrees,
970
+ optInOnly: raw.optInOnly ?? false,
971
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
972
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
973
+ harness: raw.harness ?? "opencode",
974
+ disabled: raw.disabled ?? false,
975
+ retainSessions: raw.retainSessions ?? true,
976
+ // write sessions back by default, every harness
977
+ maxParallelRetains: raw.maxParallelRetains || 10,
978
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
979
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
980
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
981
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
982
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
983
+ reflectBudget: resolveReflectBudget(raw),
984
+ autoReflect: raw.autoReflect ?? true,
985
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
986
+ pageTriggerType: resolvePageTriggerType(raw),
987
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
988
+ autoSeed: raw.autoSeed ?? true,
989
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
990
+ codebaseSurvey: raw.codebaseSurvey ?? true,
991
+ surveyModel: raw.surveyModel || "haiku",
992
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
993
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
994
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
995
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
996
+ // nested object cannot reach the API as a tag and fail the whole retain.
997
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
998
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
999
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1000
+ ) : {},
1001
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1002
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1003
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1004
+ };
1005
+ }
1006
+ function readRaw(path) {
1007
+ try {
1008
+ return JSON.parse(readFileSync(path, "utf8"));
1009
+ } catch (e) {
1010
+ if (e?.code !== "ENOENT") {
1011
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1012
+ }
1013
+ return {};
1014
+ }
1015
+ }
1016
+ function mergeRaw(a, b) {
1017
+ const { harnesses: _drop, ...flat } = b;
1018
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1019
+ }
1020
+ function applyLayer(raw, layer, harness) {
1021
+ let out = mergeRaw(raw, layer);
1022
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1023
+ if (perHarness) out = mergeRaw(out, perHarness);
1024
+ return out;
1025
+ }
1026
+ var ENV_KEYS = {
1027
+ serverMode: "HINDSIGHT_SERVER_MODE",
1028
+ apiUrl: "HINDSIGHT_API_URL",
1029
+ apiToken: "HINDSIGHT_API_TOKEN",
1030
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1031
+ // it can carry their existing environment over unchanged.
1032
+ apiPort: "HINDSIGHT_API_PORT",
1033
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1034
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1035
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1036
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1037
+ bankId: "HINDSIGHT_BANK_ID",
1038
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1039
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1040
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1041
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1042
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1043
+ harness: "HINDSIGHT_HARNESS",
1044
+ disabled: "HINDSIGHT_DISABLED",
1045
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1046
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1047
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1048
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1049
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1050
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1051
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1052
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1053
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1054
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1055
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1056
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1057
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1058
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1059
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1060
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1061
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1062
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1063
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1064
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1065
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1066
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1067
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1068
+ };
1069
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1070
+ "dynamicBankId",
1071
+ "resolveWorktrees",
1072
+ "optInOnly",
1073
+ "disabled",
1074
+ "retainSessions",
1075
+ "autoReflect",
1076
+ "autoSeed",
1077
+ "codebaseSurvey"
1078
+ ]);
1079
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1080
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1081
+ "apiPort",
1082
+ "daemonIdleTimeout",
1083
+ "maxParallelRetains",
1084
+ "reflectTimeoutMs",
1085
+ "reflectToolTimeoutMs",
1086
+ "pageRefreshEveryTurns",
1087
+ "seedLimit",
1088
+ "surveyBudgetUsd",
1089
+ "surveyRefreshCommits"
1090
+ ]);
1091
+ function readEnvConfig(env = process.env) {
1092
+ const out = {};
1093
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1094
+ const value = env[name];
1095
+ if (value === void 0 || value.trim() === "") continue;
1096
+ if (ENV_BOOLEANS.has(key)) {
1097
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1098
+ } else if (ENV_LISTS.has(key)) {
1099
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1100
+ if (items.length) out[key] = items;
1101
+ } else if (ENV_NUMBERS.has(key)) {
1102
+ const n = Number(value);
1103
+ if (Number.isFinite(n)) out[key] = n;
1104
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1105
+ } else {
1106
+ out[key] = value;
1107
+ }
1108
+ }
1109
+ return out;
1110
+ }
1111
+ function loadConfig(opts = {}) {
1112
+ const o = typeof opts === "string" ? { path: opts } : opts;
1113
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1114
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1115
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1116
+ return resolveConfig(raw);
1117
+ }
1118
+ var BANK_OVERRIDE_EXCLUDED = [
1119
+ "bankId",
1120
+ "bankIdTemplate",
1121
+ "mapPathToBank",
1122
+ "dynamicBankId",
1123
+ "resolveWorktrees",
1124
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1125
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1126
+ "optInOnly",
1127
+ "optInPaths",
1128
+ "harness"
1129
+ ];
1130
+ function applyBankConfig(cfg, resolvedId, directory) {
1131
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1132
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1133
+ const section = cfg.banks[resolvedId];
1134
+ if (!section) return { cfg, bankId: resolvedId };
1135
+ const safe = { ...section };
1136
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1137
+ delete safe.banks;
1138
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1139
+ delete safe.bank;
1140
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1141
+ }
1142
+ function resolvePartial(cfg, patch) {
1143
+ const full = resolveConfig(patch);
1144
+ const out = {};
1145
+ for (const key of Object.keys(patch)) {
1146
+ if (key in full)
1147
+ out[key] = full[key];
1148
+ }
1149
+ return out;
1150
+ }
1151
+
1152
+ // src/core/diag.ts
1153
+ import { appendFileSync as appendFileSync2 } from "fs";
1154
+ function diagFilePath() {
1155
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1156
+ }
1157
+ function diag(harness, event, extra = {}) {
1158
+ log.debug(harness, `diag:${event}`, extra);
1159
+ try {
1160
+ appendFileSync2(
1161
+ diagFilePath(),
1162
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1163
+ );
1164
+ } catch {
1165
+ }
1166
+ }
1167
+
1026
1168
  // src/core/brand.ts
1027
1169
  function brandWord() {
1028
1170
  const start = [0, 116, 217];
@@ -1055,7 +1197,7 @@ function roster(pages) {
1055
1197
  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>".
1056
1198
  - 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.
1057
1199
  - 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>").
1058
- - 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.
1200
+ - 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.
1059
1201
  - 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).`;
1060
1202
  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";
1061
1203
  function toolGuide(opts) {
@@ -1100,6 +1242,23 @@ function writeSessionCache(cacheFile, cache) {
1100
1242
  } catch {
1101
1243
  }
1102
1244
  }
1245
+ function sessionRootFile(harness, sessionId) {
1246
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1247
+ }
1248
+ function sessionRootDir(harness, sessionId, cwd) {
1249
+ if (!sessionId || !cwd) return cwd;
1250
+ const file = sessionRootFile(harness, sessionId);
1251
+ try {
1252
+ const recorded = readFileSync2(file, "utf8").trim();
1253
+ if (recorded) return recorded;
1254
+ } catch {
1255
+ }
1256
+ try {
1257
+ writeFileAtomic(file, cwd);
1258
+ } catch {
1259
+ }
1260
+ return cwd;
1261
+ }
1103
1262
 
1104
1263
  // src/core/retain-hook.ts
1105
1264
  import { readFileSync as readFileSync4 } from "fs";
@@ -1233,7 +1392,7 @@ function resolversFor(ctx) {
1233
1392
  return {
1234
1393
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
1235
1394
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
1236
- gitProject: () => projectNameOf(ctx.directory),
1395
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
1237
1396
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1238
1397
  harness: () => ctx.harness,
1239
1398
  bankId: () => ctx.bankId,
@@ -1492,7 +1651,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1492
1651
  hindsight: {
1493
1652
  command: "node",
1494
1653
  args: [opts.mcpServerPath],
1495
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
1654
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
1655
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
1656
+ // "claude-code", which is how the codex recipe below silently stamped its findings
1657
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
1658
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
1496
1659
  }
1497
1660
  }
1498
1661
  });
@@ -1532,6 +1695,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1532
1695
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
1533
1696
  "-c",
1534
1697
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
1698
+ "-c",
1699
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
1535
1700
  SURVEY_PROMPT
1536
1701
  ],
1537
1702
  env
@@ -1665,7 +1830,7 @@ async function buildSessionStartContext(args) {
1665
1830
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
1666
1831
  const resolveHeadSha = args.headSha ?? gitHeadSha;
1667
1832
  const countCommitsSince = args.commitsSince ?? commitsSince;
1668
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
1833
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
1669
1834
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
1670
1835
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
1671
1836
  const recordSurveyBaseline = (sha) => {
@@ -1789,7 +1954,8 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1789
1954
  setLogLevel(cfg.logLevel);
1790
1955
  syncCompanionSkill(harness);
1791
1956
  if (cfg.disabled) return;
1792
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness), cwd);
1957
+ const sessionRoot = sessionRootDir(harness, sessionId, cwd);
1958
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness, sessionRoot), cwd);
1793
1959
  cfg = resolved.cfg;
1794
1960
  const bankId = resolved.bankId;
1795
1961
  if (cfg.disabled) return;
@@ -1798,9 +1964,10 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1798
1964
  apiUrl: cfg.apiUrl,
1799
1965
  apiToken: cfg.apiToken,
1800
1966
  bank: bankId,
1801
- maxParallelRetains: cfg.maxParallelRetains
1967
+ maxParallelRetains: cfg.maxParallelRetains,
1968
+ observationScopes: cfg.observationScopes
1802
1969
  });
1803
- const out = await buildSessionStartContext({ cwd, bankId, cfg, client, harness });
1970
+ const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
1804
1971
  if (out.deferInitialReflect && sessionId) {
1805
1972
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
1806
1973
  }