@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.
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.",
@@ -500,15 +315,28 @@ var PAGES = [
500
315
  },
501
316
  {
502
317
  name: "Initiatives and enhancements",
503
- 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.",
318
+ 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.",
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_TAGS_MATCH = "all";
328
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
329
+ function buildPageTrigger(cfg = {}) {
330
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
331
+ switch (cfg.pageTriggerType) {
332
+ case "cron":
333
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
334
+ case "manual":
335
+ return { ...base, refresh_after_consolidation: false };
336
+ default:
337
+ return { ...base, refresh_after_consolidation: true };
338
+ }
339
+ }
512
340
  var CODING_BANK_TEMPLATE = {
513
341
  version: "1",
514
342
  bank: {
@@ -563,6 +391,7 @@ async function pool(items, n, fn, onError, onProgress) {
563
391
  }
564
392
 
565
393
  // src/core/hindsight.ts
394
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
566
395
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
567
396
  var RateLimitedError = class extends Error {
568
397
  constructor(retryAfterMs2) {
@@ -595,8 +424,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
595
424
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
596
425
  var HindsightClient = class {
597
426
  apiUrl;
598
- apiToken;
427
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
428
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
429
+ token;
430
+ tokenProvider;
599
431
  bank;
432
+ project;
600
433
  opIds = [];
601
434
  // async operation ids collected by retain(), for drain()
602
435
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -605,34 +438,81 @@ var HindsightClient = class {
605
438
  idempotentRetain;
606
439
  log;
607
440
  maxParallelRetains;
441
+ observationScopes;
608
442
  constructor(o) {
609
443
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
610
- this.apiToken = o.apiToken;
444
+ this.token = o.apiToken;
445
+ this.tokenProvider = o.tokenProvider;
611
446
  this.bank = o.bank;
447
+ this.project = o.project;
612
448
  this.log = o.log ?? (() => {
613
449
  });
614
450
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
451
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
452
+ }
453
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
454
+ get apiToken() {
455
+ return this.token;
615
456
  }
616
457
  headers() {
617
458
  const h = { "Content-Type": "application/json" };
618
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
459
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
619
460
  return h;
620
461
  }
462
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
463
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
464
+ * doubling every failing request. */
465
+ refreshToken() {
466
+ if (!this.tokenProvider) return false;
467
+ let next;
468
+ try {
469
+ next = this.tokenProvider();
470
+ } catch {
471
+ return false;
472
+ }
473
+ if (next === this.token) return false;
474
+ this.token = next;
475
+ return true;
476
+ }
477
+ /**
478
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
479
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
480
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
481
+ * not.
482
+ *
483
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
484
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
485
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
486
+ * bounds the whole call.
487
+ */
488
+ async fetchWithAuth(url, init) {
489
+ const send = () => fetch(url, { ...init, headers: this.headers() });
490
+ const r = await send();
491
+ if (r.status !== 401 || !this.refreshToken()) return r;
492
+ return send();
493
+ }
494
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
495
+ * server answers identically for both — only the client knows which it sent. */
496
+ authHint(status) {
497
+ if (status !== 401) return "";
498
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
499
+ }
621
500
  bankUrl(suffix = "") {
622
501
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
623
502
  }
624
503
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
625
504
  async req(method, url, body, tolerate = []) {
626
- const r = await fetch(url, {
505
+ const r = await this.fetchWithAuth(url, {
627
506
  method,
628
- headers: this.headers(),
629
507
  body: body ? JSON.stringify(body) : void 0,
630
508
  signal: AbortSignal.timeout(15e3)
631
509
  });
632
510
  if (r.status === 429 && !tolerate.includes(429))
633
511
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
634
512
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
635
- throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
513
+ throw new Error(
514
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
515
+ );
636
516
  return r;
637
517
  }
638
518
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -643,7 +523,11 @@ var HindsightClient = class {
643
523
  context,
644
524
  document_id: documentId,
645
525
  tags,
646
- strategy
526
+ strategy,
527
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
528
+ // observations were built under is a property of the write rather than of whichever server
529
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
530
+ observation_scopes: this.observationScopes
647
531
  };
648
532
  if (opts.timestamp) item.timestamp = opts.timestamp;
649
533
  if (opts.metadata) item.metadata = opts.metadata;
@@ -722,7 +606,7 @@ var HindsightClient = class {
722
606
  this.log(
723
607
  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
608
  );
725
- await this.seedPages();
609
+ await this.seedPages(opts.pageTrigger);
726
610
  }
727
611
  /**
728
612
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -780,7 +664,7 @@ var HindsightClient = class {
780
664
  let backoffMs = POLL_CYCLE_MS;
781
665
  await pool([...pending], this.maxParallelRetains, async (id) => {
782
666
  try {
783
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
667
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
784
668
  if (r.status === 429) {
785
669
  backoffMs = Math.min(
786
670
  RETRY_AFTER_CEILING_MS,
@@ -806,18 +690,23 @@ var HindsightClient = class {
806
690
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
807
691
  );
808
692
  }
809
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
810
- async reflect(query, opts = {}) {
693
+ /**
694
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
695
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
696
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
697
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
698
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
699
+ */
700
+ async reflect(query, opts) {
811
701
  const ctrl = new AbortController();
812
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
702
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
813
703
  try {
814
- const resp = await fetch(this.bankUrl("/reflect"), {
704
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
815
705
  method: "POST",
816
- headers: this.headers(),
817
706
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
818
707
  signal: ctrl.signal
819
708
  });
820
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
709
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
821
710
  const data = await resp.json();
822
711
  return (data.text || "").trim();
823
712
  } finally {
@@ -901,16 +790,18 @@ var HindsightClient = class {
901
790
  }));
902
791
  }
903
792
  /**
904
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
793
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
905
794
  *
906
795
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
907
796
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
908
797
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
909
798
  *
910
799
  * 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.
800
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
801
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
912
802
  */
913
- async seedPages() {
803
+ async seedPages(pageTrigger = buildPageTrigger()) {
804
+ const pages = pagesFor(this.project ?? this.bank);
914
805
  const existing = /* @__PURE__ */ new Map();
915
806
  let roots;
916
807
  try {
@@ -927,14 +818,14 @@ var HindsightClient = class {
927
818
  }
928
819
  let created = 0;
929
820
  let updated = 0;
930
- for (const page of PAGES) {
821
+ for (const page of pages) {
931
822
  const hit = existing.get(page.name.toLowerCase());
932
823
  const body = {
933
824
  name: page.name,
934
825
  source_query: page.source_query,
935
826
  tags: page.tags,
936
827
  max_tokens: PAGE_MAX_TOKENS,
937
- trigger: PAGE_TRIGGER
828
+ trigger: pageTrigger
938
829
  };
939
830
  if (!hit) {
940
831
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -946,11 +837,18 @@ var HindsightClient = class {
946
837
  return;
947
838
  }
948
839
  if (r.status !== 409) created++;
949
- } else if (hit.description !== page.source_query) {
840
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
841
+ const patch = {
842
+ trigger: pageTrigger
843
+ };
844
+ if (hit.description !== page.source_query) {
845
+ patch.source_query = page.source_query;
846
+ patch.tags = page.tags;
847
+ }
950
848
  const r = await this.req(
951
849
  "PATCH",
952
850
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
953
- { source_query: page.source_query, tags: page.tags }
851
+ patch
954
852
  );
955
853
  if ([404, 405, 501].includes(r.status)) {
956
854
  this.knowledgePagesSupported = false;
@@ -963,7 +861,7 @@ var HindsightClient = class {
963
861
  }
964
862
  }
965
863
  this.log(
966
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
864
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
967
865
  );
968
866
  }
969
867
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -971,9 +869,17 @@ var HindsightClient = class {
971
869
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
972
870
  }
973
871
  /**
974
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
975
- * 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.
872
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
873
+ * New initiative → creates a page under the Initiatives folder.
874
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
875
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
876
+ *
877
+ * The marker carries its page id in two places, neither of them a tag (#3641):
878
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
879
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
880
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
881
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
882
+ * vocabulary that exists to be matched with exact set-ops.
977
883
  */
978
884
  async captureInitiative(args) {
979
885
  let pageId = args.relatesToPageId;
@@ -984,10 +890,7 @@ var HindsightClient = class {
984
890
  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
891
  parent_id: folderId,
986
892
  tags: ["knowledge:feature-work"],
987
- trigger: {
988
- fact_types: ["world", "experience", "observation"],
989
- refresh_after_consolidation: true
990
- }
893
+ trigger: args.pageTrigger ?? buildPageTrigger()
991
894
  });
992
895
  try {
993
896
  const j = await r.json();
@@ -996,23 +899,14 @@ var HindsightClient = class {
996
899
  }
997
900
  pageId ||= `initiative-${this.slugify(args.title)}`;
998
901
  }
999
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
902
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1000
903
  const content = `${verb}: ${args.title}. ${args.summary}`;
1001
904
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1002
- const tags = [
1003
- .../* @__PURE__ */ new Set([
1004
- ...args.stamp?.tags ?? [],
1005
- "knowledge:feature-work",
1006
- `relatedPageId:${pageId}`
1007
- ])
1008
- ];
1009
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
1010
- await this.retain(content, "initiative marker", markerId, tags, "document", {
1011
- metadata: args.stamp?.metadata
1012
- });
1013
- } else {
1014
- await this.retain(content, "initiative marker", markerId, tags, "document");
1015
- }
905
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
906
+ const context = `initiative marker for [[page:${pageId}]]`;
907
+ await this.retain(content, context, markerId, tags, "document", {
908
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
909
+ });
1016
910
  return { page_id: pageId };
1017
911
  }
1018
912
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -1034,6 +928,260 @@ var HindsightClient = class {
1034
928
  }
1035
929
  };
1036
930
 
931
+ // src/core/config.ts
932
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
933
+ var DEFAULT_DAEMON_PORT = 9077;
934
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
935
+ function resolvePageTriggerType(raw) {
936
+ if (raw.pageTriggerType === "manual") return "manual";
937
+ if (raw.pageTriggerType === "cron") {
938
+ if (raw.pageTriggerCron?.trim()) return "cron";
939
+ log.warn(
940
+ "config",
941
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
942
+ );
943
+ }
944
+ return "auto-refresh";
945
+ }
946
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
947
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
948
+ function resolveReflectBudget(raw) {
949
+ const value = raw.reflectBudget;
950
+ if (value === void 0) return "high";
951
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
952
+ return value;
953
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
954
+ return "high";
955
+ }
956
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
957
+ function resolveObservationScopes(raw) {
958
+ const value = raw;
959
+ if (typeof value === "string")
960
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
961
+ if (Array.isArray(value)) {
962
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
963
+ if (scopes.length) return scopes;
964
+ }
965
+ return DEFAULT_OBSERVATION_SCOPES;
966
+ }
967
+ function resolveConfig(raw = {}) {
968
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
969
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
970
+ return {
971
+ serverMode,
972
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
973
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
974
+ // daemon needs no plumbing through eight separate constructors.
975
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
976
+ apiToken: raw.apiToken || void 0,
977
+ apiPort,
978
+ daemonIdleTimeout: raw.daemonIdleTimeout,
979
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
980
+ embedVersion: raw.embedVersion || void 0,
981
+ embedPackagePath: raw.embedPackagePath || void 0,
982
+ bankId: raw.bankId,
983
+ dynamicBankId: raw.dynamicBankId,
984
+ bankIdTemplate: raw.bankIdTemplate,
985
+ mapPathToBank: raw.mapPathToBank,
986
+ resolveWorktrees: raw.resolveWorktrees,
987
+ optInOnly: raw.optInOnly ?? false,
988
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
989
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
990
+ harness: raw.harness ?? "opencode",
991
+ disabled: raw.disabled ?? false,
992
+ retainSessions: raw.retainSessions ?? true,
993
+ // write sessions back by default, every harness
994
+ maxParallelRetains: raw.maxParallelRetains || 10,
995
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
996
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
997
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
998
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
999
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1000
+ reflectBudget: resolveReflectBudget(raw),
1001
+ autoReflect: raw.autoReflect ?? true,
1002
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1003
+ pageTriggerType: resolvePageTriggerType(raw),
1004
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1005
+ autoSeed: raw.autoSeed ?? true,
1006
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1007
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1008
+ surveyModel: raw.surveyModel || "haiku",
1009
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1010
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1011
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1012
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1013
+ // nested object cannot reach the API as a tag and fail the whole retain.
1014
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1015
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1016
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1017
+ ) : {},
1018
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1019
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1020
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1021
+ };
1022
+ }
1023
+ function readRaw(path) {
1024
+ try {
1025
+ return JSON.parse(readFileSync(path, "utf8"));
1026
+ } catch (e) {
1027
+ if (e?.code !== "ENOENT") {
1028
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1029
+ }
1030
+ return {};
1031
+ }
1032
+ }
1033
+ function mergeRaw(a, b) {
1034
+ const { harnesses: _drop, ...flat } = b;
1035
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1036
+ }
1037
+ function applyLayer(raw, layer, harness) {
1038
+ let out = mergeRaw(raw, layer);
1039
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1040
+ if (perHarness) out = mergeRaw(out, perHarness);
1041
+ return out;
1042
+ }
1043
+ var ENV_KEYS = {
1044
+ serverMode: "HINDSIGHT_SERVER_MODE",
1045
+ apiUrl: "HINDSIGHT_API_URL",
1046
+ apiToken: "HINDSIGHT_API_TOKEN",
1047
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1048
+ // it can carry their existing environment over unchanged.
1049
+ apiPort: "HINDSIGHT_API_PORT",
1050
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1051
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1052
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1053
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1054
+ bankId: "HINDSIGHT_BANK_ID",
1055
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1056
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1057
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1058
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1059
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1060
+ harness: "HINDSIGHT_HARNESS",
1061
+ disabled: "HINDSIGHT_DISABLED",
1062
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1063
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1064
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1065
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1066
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1067
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1068
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1069
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1070
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1071
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1072
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1073
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1074
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1075
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1076
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1077
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1078
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1079
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1080
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1081
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1082
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1083
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1084
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1085
+ };
1086
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1087
+ "dynamicBankId",
1088
+ "resolveWorktrees",
1089
+ "optInOnly",
1090
+ "disabled",
1091
+ "retainSessions",
1092
+ "autoReflect",
1093
+ "autoSeed",
1094
+ "codebaseSurvey"
1095
+ ]);
1096
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1097
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1098
+ "apiPort",
1099
+ "daemonIdleTimeout",
1100
+ "maxParallelRetains",
1101
+ "reflectTimeoutMs",
1102
+ "reflectToolTimeoutMs",
1103
+ "pageRefreshEveryTurns",
1104
+ "seedLimit",
1105
+ "surveyBudgetUsd",
1106
+ "surveyRefreshCommits"
1107
+ ]);
1108
+ function readEnvConfig(env = process.env) {
1109
+ const out = {};
1110
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1111
+ const value = env[name];
1112
+ if (value === void 0 || value.trim() === "") continue;
1113
+ if (ENV_BOOLEANS.has(key)) {
1114
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1115
+ } else if (ENV_LISTS.has(key)) {
1116
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1117
+ if (items.length) out[key] = items;
1118
+ } else if (ENV_NUMBERS.has(key)) {
1119
+ const n = Number(value);
1120
+ if (Number.isFinite(n)) out[key] = n;
1121
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1122
+ } else {
1123
+ out[key] = value;
1124
+ }
1125
+ }
1126
+ return out;
1127
+ }
1128
+ function loadConfig(opts = {}) {
1129
+ const o = typeof opts === "string" ? { path: opts } : opts;
1130
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1131
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1132
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1133
+ return resolveConfig(raw);
1134
+ }
1135
+ var BANK_OVERRIDE_EXCLUDED = [
1136
+ "bankId",
1137
+ "bankIdTemplate",
1138
+ "mapPathToBank",
1139
+ "dynamicBankId",
1140
+ "resolveWorktrees",
1141
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1142
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1143
+ "optInOnly",
1144
+ "optInPaths",
1145
+ "harness"
1146
+ ];
1147
+ function applyBankConfig(cfg, resolvedId, directory) {
1148
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1149
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1150
+ const section = cfg.banks[resolvedId];
1151
+ if (!section) return { cfg, bankId: resolvedId };
1152
+ const safe = { ...section };
1153
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1154
+ delete safe.banks;
1155
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1156
+ delete safe.bank;
1157
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1158
+ }
1159
+ function resolvePartial(cfg, patch) {
1160
+ const full = resolveConfig(patch);
1161
+ const out = {};
1162
+ for (const key of Object.keys(patch)) {
1163
+ if (key in full)
1164
+ out[key] = full[key];
1165
+ }
1166
+ return out;
1167
+ }
1168
+
1169
+ // src/core/diag.ts
1170
+ import { appendFileSync as appendFileSync2 } from "fs";
1171
+ function diagFilePath() {
1172
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1173
+ }
1174
+ function diag(harness, event, extra = {}) {
1175
+ log.debug(harness, `diag:${event}`, extra);
1176
+ try {
1177
+ appendFileSync2(
1178
+ diagFilePath(),
1179
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1180
+ );
1181
+ } catch {
1182
+ }
1183
+ }
1184
+
1037
1185
  // src/core/brand.ts
1038
1186
  function brandWord() {
1039
1187
  const start = [0, 116, 217];
@@ -1095,7 +1243,7 @@ function roster(pages) {
1095
1243
  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
1244
  - 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
1245
  - 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.
1246
+ - 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
1247
  - 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
1248
  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
1249
  function toolGuide(opts) {
@@ -1144,6 +1292,23 @@ function writeSessionCache(cacheFile, cache) {
1144
1292
  } catch {
1145
1293
  }
1146
1294
  }
1295
+ function sessionRootFile(harness, sessionId) {
1296
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1297
+ }
1298
+ function sessionRootDir(harness, sessionId, cwd) {
1299
+ if (!sessionId || !cwd) return cwd;
1300
+ const file = sessionRootFile(harness, sessionId);
1301
+ try {
1302
+ const recorded = readFileSync2(file, "utf8").trim();
1303
+ if (recorded) return recorded;
1304
+ } catch {
1305
+ }
1306
+ try {
1307
+ writeFileAtomic(file, cwd);
1308
+ } catch {
1309
+ }
1310
+ return cwd;
1311
+ }
1147
1312
 
1148
1313
  // src/core/hook.ts
1149
1314
  var HOOK_REFLECT_CAP_MS = 25e3;
@@ -1251,7 +1416,8 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1251
1416
  return;
1252
1417
  }
1253
1418
  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);
1419
+ const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
1420
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
1255
1421
  cfg = resolved.cfg;
1256
1422
  const bankId = resolved.bankId;
1257
1423
  if (cfg.disabled) {
@@ -1262,7 +1428,8 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1262
1428
  apiUrl: cfg.apiUrl,
1263
1429
  apiToken: cfg.apiToken,
1264
1430
  bank: bankId,
1265
- maxParallelRetains: cfg.maxParallelRetains
1431
+ maxParallelRetains: cfg.maxParallelRetains,
1432
+ observationScopes: cfg.observationScopes
1266
1433
  });
1267
1434
  const cacheFile = sessionCacheFile(spec.harness, sessionId || "no-session");
1268
1435
  if (cfg.autoSeed !== false && !existsSync2(cacheFile)) {