@vectorize-io/hindsight-coding-agents 0.3.4 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.",
@@ -489,15 +304,28 @@ var PAGES = [
489
304
  },
490
305
  {
491
306
  name: "Initiatives and enhancements",
492
- source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
307
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
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_TAGS_MATCH = "all";
317
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
318
+ function buildPageTrigger(cfg = {}) {
319
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
320
+ switch (cfg.pageTriggerType) {
321
+ case "cron":
322
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
323
+ case "manual":
324
+ return { ...base, refresh_after_consolidation: false };
325
+ default:
326
+ return { ...base, refresh_after_consolidation: true };
327
+ }
328
+ }
501
329
  var CODING_BANK_TEMPLATE = {
502
330
  version: "1",
503
331
  bank: {
@@ -552,6 +380,7 @@ async function pool(items, n, fn, onError, onProgress) {
552
380
  }
553
381
 
554
382
  // src/core/hindsight.ts
383
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
555
384
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
556
385
  var RateLimitedError = class extends Error {
557
386
  constructor(retryAfterMs2) {
@@ -584,8 +413,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
584
413
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
585
414
  var HindsightClient = class {
586
415
  apiUrl;
587
- apiToken;
416
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
417
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
418
+ token;
419
+ tokenProvider;
588
420
  bank;
421
+ project;
589
422
  opIds = [];
590
423
  // async operation ids collected by retain(), for drain()
591
424
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -594,34 +427,81 @@ var HindsightClient = class {
594
427
  idempotentRetain;
595
428
  log;
596
429
  maxParallelRetains;
430
+ observationScopes;
597
431
  constructor(o) {
598
432
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
599
- this.apiToken = o.apiToken;
433
+ this.token = o.apiToken;
434
+ this.tokenProvider = o.tokenProvider;
600
435
  this.bank = o.bank;
436
+ this.project = o.project;
601
437
  this.log = o.log ?? (() => {
602
438
  });
603
439
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
440
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
441
+ }
442
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
443
+ get apiToken() {
444
+ return this.token;
604
445
  }
605
446
  headers() {
606
447
  const h = { "Content-Type": "application/json" };
607
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
448
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
608
449
  return h;
609
450
  }
451
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
452
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
453
+ * doubling every failing request. */
454
+ refreshToken() {
455
+ if (!this.tokenProvider) return false;
456
+ let next;
457
+ try {
458
+ next = this.tokenProvider();
459
+ } catch {
460
+ return false;
461
+ }
462
+ if (next === this.token) return false;
463
+ this.token = next;
464
+ return true;
465
+ }
466
+ /**
467
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
468
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
469
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
470
+ * not.
471
+ *
472
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
473
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
474
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
475
+ * bounds the whole call.
476
+ */
477
+ async fetchWithAuth(url, init) {
478
+ const send = () => fetch(url, { ...init, headers: this.headers() });
479
+ const r = await send();
480
+ if (r.status !== 401 || !this.refreshToken()) return r;
481
+ return send();
482
+ }
483
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
484
+ * server answers identically for both — only the client knows which it sent. */
485
+ authHint(status) {
486
+ if (status !== 401) return "";
487
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
488
+ }
610
489
  bankUrl(suffix = "") {
611
490
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
612
491
  }
613
492
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
614
493
  async req(method, url, body, tolerate = []) {
615
- const r = await fetch(url, {
494
+ const r = await this.fetchWithAuth(url, {
616
495
  method,
617
- headers: this.headers(),
618
496
  body: body ? JSON.stringify(body) : void 0,
619
497
  signal: AbortSignal.timeout(15e3)
620
498
  });
621
499
  if (r.status === 429 && !tolerate.includes(429))
622
500
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
623
501
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
624
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
502
+ throw new Error(
503
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
504
+ );
625
505
  return r;
626
506
  }
627
507
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -632,7 +512,11 @@ var HindsightClient = class {
632
512
  context,
633
513
  document_id: documentId,
634
514
  tags,
635
- strategy
515
+ strategy,
516
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
517
+ // observations were built under is a property of the write rather than of whichever server
518
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
519
+ observation_scopes: this.observationScopes
636
520
  };
637
521
  if (opts.timestamp) item.timestamp = opts.timestamp;
638
522
  if (opts.metadata) item.metadata = opts.metadata;
@@ -711,7 +595,7 @@ var HindsightClient = class {
711
595
  this.log(
712
596
  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
597
  );
714
- await this.seedPages();
598
+ await this.seedPages(opts.pageTrigger);
715
599
  }
716
600
  /**
717
601
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -769,7 +653,7 @@ var HindsightClient = class {
769
653
  let backoffMs = POLL_CYCLE_MS;
770
654
  await pool([...pending], this.maxParallelRetains, async (id) => {
771
655
  try {
772
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
656
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
773
657
  if (r.status === 429) {
774
658
  backoffMs = Math.min(
775
659
  RETRY_AFTER_CEILING_MS,
@@ -795,18 +679,23 @@ var HindsightClient = class {
795
679
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
796
680
  );
797
681
  }
798
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
799
- async reflect(query, opts = {}) {
682
+ /**
683
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
684
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
685
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
686
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
687
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
688
+ */
689
+ async reflect(query, opts) {
800
690
  const ctrl = new AbortController();
801
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
691
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
802
692
  try {
803
- const resp = await fetch(this.bankUrl("/reflect"), {
693
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
804
694
  method: "POST",
805
- headers: this.headers(),
806
695
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
807
696
  signal: ctrl.signal
808
697
  });
809
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
698
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
810
699
  const data = await resp.json();
811
700
  return (data.text || "").trim();
812
701
  } finally {
@@ -890,16 +779,18 @@ var HindsightClient = class {
890
779
  }));
891
780
  }
892
781
  /**
893
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
782
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
894
783
  *
895
784
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
896
785
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
897
786
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
898
787
  *
899
788
  * 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.
789
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
790
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
901
791
  */
902
- async seedPages() {
792
+ async seedPages(pageTrigger = buildPageTrigger()) {
793
+ const pages = pagesFor(this.project ?? this.bank);
903
794
  const existing = /* @__PURE__ */ new Map();
904
795
  let roots;
905
796
  try {
@@ -916,14 +807,14 @@ var HindsightClient = class {
916
807
  }
917
808
  let created = 0;
918
809
  let updated = 0;
919
- for (const page of PAGES) {
810
+ for (const page of pages) {
920
811
  const hit = existing.get(page.name.toLowerCase());
921
812
  const body = {
922
813
  name: page.name,
923
814
  source_query: page.source_query,
924
815
  tags: page.tags,
925
816
  max_tokens: PAGE_MAX_TOKENS,
926
- trigger: PAGE_TRIGGER
817
+ trigger: pageTrigger
927
818
  };
928
819
  if (!hit) {
929
820
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -935,11 +826,18 @@ var HindsightClient = class {
935
826
  return;
936
827
  }
937
828
  if (r.status !== 409) created++;
938
- } else if (hit.description !== page.source_query) {
829
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
830
+ const patch = {
831
+ trigger: pageTrigger
832
+ };
833
+ if (hit.description !== page.source_query) {
834
+ patch.source_query = page.source_query;
835
+ patch.tags = page.tags;
836
+ }
939
837
  const r = await this.req(
940
838
  "PATCH",
941
839
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
942
- { source_query: page.source_query, tags: page.tags }
840
+ patch
943
841
  );
944
842
  if ([404, 405, 501].includes(r.status)) {
945
843
  this.knowledgePagesSupported = false;
@@ -952,7 +850,7 @@ var HindsightClient = class {
952
850
  }
953
851
  }
954
852
  this.log(
955
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
853
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
956
854
  );
957
855
  }
958
856
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -960,9 +858,17 @@ var HindsightClient = class {
960
858
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
961
859
  }
962
860
  /**
963
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
964
- * 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.
861
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
862
+ * New initiative → creates a page under the Initiatives folder.
863
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
864
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
865
+ *
866
+ * The marker carries its page id in two places, neither of them a tag (#3641):
867
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
868
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
869
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
870
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
871
+ * vocabulary that exists to be matched with exact set-ops.
966
872
  */
967
873
  async captureInitiative(args) {
968
874
  let pageId = args.relatesToPageId;
@@ -973,10 +879,7 @@ var HindsightClient = class {
973
879
  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
880
  parent_id: folderId,
975
881
  tags: ["knowledge:feature-work"],
976
- trigger: {
977
- fact_types: ["world", "experience", "observation"],
978
- refresh_after_consolidation: true
979
- }
882
+ trigger: args.pageTrigger ?? buildPageTrigger()
980
883
  });
981
884
  try {
982
885
  const j = await r.json();
@@ -985,23 +888,14 @@ var HindsightClient = class {
985
888
  }
986
889
  pageId ||= `initiative-${this.slugify(args.title)}`;
987
890
  }
988
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
891
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
989
892
  const content = `${verb}: ${args.title}. ${args.summary}`;
990
893
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
991
- const tags = [
992
- .../* @__PURE__ */ new Set([
993
- ...args.stamp?.tags ?? [],
994
- "knowledge:feature-work",
995
- `relatedPageId:${pageId}`
996
- ])
997
- ];
998
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
999
- await this.retain(content, "initiative marker", markerId, tags, "document", {
1000
- metadata: args.stamp?.metadata
1001
- });
1002
- } else {
1003
- await this.retain(content, "initiative marker", markerId, tags, "document");
1004
- }
894
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
895
+ const context = `initiative marker for [[page:${pageId}]]`;
896
+ await this.retain(content, context, markerId, tags, "document", {
897
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
898
+ });
1005
899
  return { page_id: pageId };
1006
900
  }
1007
901
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -1023,6 +917,260 @@ var HindsightClient = class {
1023
917
  }
1024
918
  };
1025
919
 
920
+ // src/core/config.ts
921
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
922
+ var DEFAULT_DAEMON_PORT = 9077;
923
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
924
+ function resolvePageTriggerType(raw) {
925
+ if (raw.pageTriggerType === "manual") return "manual";
926
+ if (raw.pageTriggerType === "cron") {
927
+ if (raw.pageTriggerCron?.trim()) return "cron";
928
+ log.warn(
929
+ "config",
930
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
931
+ );
932
+ }
933
+ return "auto-refresh";
934
+ }
935
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
936
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
937
+ function resolveReflectBudget(raw) {
938
+ const value = raw.reflectBudget;
939
+ if (value === void 0) return "high";
940
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
941
+ return value;
942
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
943
+ return "high";
944
+ }
945
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
946
+ function resolveObservationScopes(raw) {
947
+ const value = raw;
948
+ if (typeof value === "string")
949
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
950
+ if (Array.isArray(value)) {
951
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
952
+ if (scopes.length) return scopes;
953
+ }
954
+ return DEFAULT_OBSERVATION_SCOPES;
955
+ }
956
+ function resolveConfig(raw = {}) {
957
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
958
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
959
+ return {
960
+ serverMode,
961
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
962
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
963
+ // daemon needs no plumbing through eight separate constructors.
964
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
965
+ apiToken: raw.apiToken || void 0,
966
+ apiPort,
967
+ daemonIdleTimeout: raw.daemonIdleTimeout,
968
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
969
+ embedVersion: raw.embedVersion || void 0,
970
+ embedPackagePath: raw.embedPackagePath || void 0,
971
+ bankId: raw.bankId,
972
+ dynamicBankId: raw.dynamicBankId,
973
+ bankIdTemplate: raw.bankIdTemplate,
974
+ mapPathToBank: raw.mapPathToBank,
975
+ resolveWorktrees: raw.resolveWorktrees,
976
+ optInOnly: raw.optInOnly ?? false,
977
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
978
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
979
+ harness: raw.harness ?? "opencode",
980
+ disabled: raw.disabled ?? false,
981
+ retainSessions: raw.retainSessions ?? true,
982
+ // write sessions back by default, every harness
983
+ maxParallelRetains: raw.maxParallelRetains || 10,
984
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
985
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
986
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
987
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
988
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
989
+ reflectBudget: resolveReflectBudget(raw),
990
+ autoReflect: raw.autoReflect ?? true,
991
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
992
+ pageTriggerType: resolvePageTriggerType(raw),
993
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
994
+ autoSeed: raw.autoSeed ?? true,
995
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
996
+ codebaseSurvey: raw.codebaseSurvey ?? true,
997
+ surveyModel: raw.surveyModel || "haiku",
998
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
999
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1000
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1001
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1002
+ // nested object cannot reach the API as a tag and fail the whole retain.
1003
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1004
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1005
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1006
+ ) : {},
1007
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1008
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1009
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1010
+ };
1011
+ }
1012
+ function readRaw(path) {
1013
+ try {
1014
+ return JSON.parse(readFileSync(path, "utf8"));
1015
+ } catch (e) {
1016
+ if (e?.code !== "ENOENT") {
1017
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1018
+ }
1019
+ return {};
1020
+ }
1021
+ }
1022
+ function mergeRaw(a, b) {
1023
+ const { harnesses: _drop, ...flat } = b;
1024
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1025
+ }
1026
+ function applyLayer(raw, layer, harness) {
1027
+ let out = mergeRaw(raw, layer);
1028
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1029
+ if (perHarness) out = mergeRaw(out, perHarness);
1030
+ return out;
1031
+ }
1032
+ var ENV_KEYS = {
1033
+ serverMode: "HINDSIGHT_SERVER_MODE",
1034
+ apiUrl: "HINDSIGHT_API_URL",
1035
+ apiToken: "HINDSIGHT_API_TOKEN",
1036
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1037
+ // it can carry their existing environment over unchanged.
1038
+ apiPort: "HINDSIGHT_API_PORT",
1039
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1040
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1041
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1042
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1043
+ bankId: "HINDSIGHT_BANK_ID",
1044
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1045
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1046
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1047
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1048
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1049
+ harness: "HINDSIGHT_HARNESS",
1050
+ disabled: "HINDSIGHT_DISABLED",
1051
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1052
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1053
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1054
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1055
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1056
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1057
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1058
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1059
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1060
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1061
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1062
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1063
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1064
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1065
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1066
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1067
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1068
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1069
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1070
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1071
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1072
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1073
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1074
+ };
1075
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1076
+ "dynamicBankId",
1077
+ "resolveWorktrees",
1078
+ "optInOnly",
1079
+ "disabled",
1080
+ "retainSessions",
1081
+ "autoReflect",
1082
+ "autoSeed",
1083
+ "codebaseSurvey"
1084
+ ]);
1085
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1086
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1087
+ "apiPort",
1088
+ "daemonIdleTimeout",
1089
+ "maxParallelRetains",
1090
+ "reflectTimeoutMs",
1091
+ "reflectToolTimeoutMs",
1092
+ "pageRefreshEveryTurns",
1093
+ "seedLimit",
1094
+ "surveyBudgetUsd",
1095
+ "surveyRefreshCommits"
1096
+ ]);
1097
+ function readEnvConfig(env = process.env) {
1098
+ const out = {};
1099
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1100
+ const value = env[name];
1101
+ if (value === void 0 || value.trim() === "") continue;
1102
+ if (ENV_BOOLEANS.has(key)) {
1103
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1104
+ } else if (ENV_LISTS.has(key)) {
1105
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1106
+ if (items.length) out[key] = items;
1107
+ } else if (ENV_NUMBERS.has(key)) {
1108
+ const n = Number(value);
1109
+ if (Number.isFinite(n)) out[key] = n;
1110
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1111
+ } else {
1112
+ out[key] = value;
1113
+ }
1114
+ }
1115
+ return out;
1116
+ }
1117
+ function loadConfig(opts = {}) {
1118
+ const o = typeof opts === "string" ? { path: opts } : opts;
1119
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1120
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1121
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1122
+ return resolveConfig(raw);
1123
+ }
1124
+ var BANK_OVERRIDE_EXCLUDED = [
1125
+ "bankId",
1126
+ "bankIdTemplate",
1127
+ "mapPathToBank",
1128
+ "dynamicBankId",
1129
+ "resolveWorktrees",
1130
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1131
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1132
+ "optInOnly",
1133
+ "optInPaths",
1134
+ "harness"
1135
+ ];
1136
+ function applyBankConfig(cfg, resolvedId, directory) {
1137
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1138
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1139
+ const section = cfg.banks[resolvedId];
1140
+ if (!section) return { cfg, bankId: resolvedId };
1141
+ const safe = { ...section };
1142
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1143
+ delete safe.banks;
1144
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1145
+ delete safe.bank;
1146
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1147
+ }
1148
+ function resolvePartial(cfg, patch) {
1149
+ const full = resolveConfig(patch);
1150
+ const out = {};
1151
+ for (const key of Object.keys(patch)) {
1152
+ if (key in full)
1153
+ out[key] = full[key];
1154
+ }
1155
+ return out;
1156
+ }
1157
+
1158
+ // src/core/diag.ts
1159
+ import { appendFileSync as appendFileSync2 } from "fs";
1160
+ function diagFilePath() {
1161
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1162
+ }
1163
+ function diag(harness, event, extra = {}) {
1164
+ log.debug(harness, `diag:${event}`, extra);
1165
+ try {
1166
+ appendFileSync2(
1167
+ diagFilePath(),
1168
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1169
+ );
1170
+ } catch {
1171
+ }
1172
+ }
1173
+
1026
1174
  // src/core/brand.ts
1027
1175
  function brandWord() {
1028
1176
  const start = [0, 116, 217];
@@ -1055,7 +1203,7 @@ function roster(pages) {
1055
1203
  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
1204
  - 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
1205
  - 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.
1206
+ - 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
1207
  - 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
1208
  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
1209
  function toolGuide(opts) {
@@ -1100,6 +1248,23 @@ function writeSessionCache(cacheFile, cache) {
1100
1248
  } catch {
1101
1249
  }
1102
1250
  }
1251
+ function sessionRootFile(harness, sessionId) {
1252
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1253
+ }
1254
+ function sessionRootDir(harness, sessionId, cwd) {
1255
+ if (!sessionId || !cwd) return cwd;
1256
+ const file = sessionRootFile(harness, sessionId);
1257
+ try {
1258
+ const recorded = readFileSync2(file, "utf8").trim();
1259
+ if (recorded) return recorded;
1260
+ } catch {
1261
+ }
1262
+ try {
1263
+ writeFileAtomic(file, cwd);
1264
+ } catch {
1265
+ }
1266
+ return cwd;
1267
+ }
1103
1268
 
1104
1269
  // src/core/retain-hook.ts
1105
1270
  import { readFileSync as readFileSync4 } from "fs";
@@ -1233,7 +1398,7 @@ function resolversFor(ctx) {
1233
1398
  return {
1234
1399
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
1235
1400
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
1236
- gitProject: () => projectNameOf(ctx.directory),
1401
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
1237
1402
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
1238
1403
  harness: () => ctx.harness,
1239
1404
  bankId: () => ctx.bankId,
@@ -1492,7 +1657,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1492
1657
  hindsight: {
1493
1658
  command: "node",
1494
1659
  args: [opts.mcpServerPath],
1495
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
1660
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
1661
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
1662
+ // "claude-code", which is how the codex recipe below silently stamped its findings
1663
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
1664
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
1496
1665
  }
1497
1666
  }
1498
1667
  });
@@ -1532,6 +1701,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1532
1701
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
1533
1702
  "-c",
1534
1703
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
1704
+ "-c",
1705
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
1535
1706
  SURVEY_PROMPT
1536
1707
  ],
1537
1708
  env
@@ -1665,7 +1836,7 @@ async function buildSessionStartContext(args) {
1665
1836
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
1666
1837
  const resolveHeadSha = args.headSha ?? gitHeadSha;
1667
1838
  const countCommitsSince = args.commitsSince ?? commitsSince;
1668
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
1839
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
1669
1840
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
1670
1841
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
1671
1842
  const recordSurveyBaseline = (sha) => {
@@ -1789,7 +1960,8 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1789
1960
  setLogLevel(cfg.logLevel);
1790
1961
  syncCompanionSkill(harness);
1791
1962
  if (cfg.disabled) return;
1792
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness), cwd);
1963
+ const sessionRoot = sessionRootDir(harness, sessionId, cwd);
1964
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness, sessionRoot), cwd);
1793
1965
  cfg = resolved.cfg;
1794
1966
  const bankId = resolved.bankId;
1795
1967
  if (cfg.disabled) return;
@@ -1798,9 +1970,10 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1798
1970
  apiUrl: cfg.apiUrl,
1799
1971
  apiToken: cfg.apiToken,
1800
1972
  bank: bankId,
1801
- maxParallelRetains: cfg.maxParallelRetains
1973
+ maxParallelRetains: cfg.maxParallelRetains,
1974
+ observationScopes: cfg.observationScopes
1802
1975
  });
1803
- const out = await buildSessionStartContext({ cwd, bankId, cfg, client, harness });
1976
+ const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
1804
1977
  if (out.deferInitialReflect && sessionId) {
1805
1978
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
1806
1979
  }