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