@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/kilo.js CHANGED
@@ -7,11 +7,48 @@ var __export = (target, all) => {
7
7
  // src/harness/plugin-entry.ts
8
8
  import { posix, win32 } from "path";
9
9
 
10
+ // src/core/config.ts
11
+ import { readFileSync } from "fs";
12
+ import { homedir as homedir2 } from "os";
13
+ import { join as join4 } from "path";
14
+
15
+ // src/core/seed.ts
16
+ import { spawn as realSpawn } from "child_process";
17
+ import { dirname, join } from "path";
18
+ import { fileURLToPath } from "url";
19
+ var DEFAULT_SEED_LIMIT = 300;
20
+ function startBackgroundSeed(repoDir, opts = {}) {
21
+ try {
22
+ const spawnFn = opts.spawn ?? realSpawn;
23
+ const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
24
+ const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
25
+ const child = spawnFn(
26
+ "node",
27
+ [
28
+ enginePath,
29
+ "--repo",
30
+ repoDir,
31
+ "--gitlog-limit",
32
+ String(limit),
33
+ ...opts.harness ? ["--harness", opts.harness] : []
34
+ ],
35
+ {
36
+ detached: true,
37
+ stdio: "ignore"
38
+ }
39
+ );
40
+ child.on("error", () => {
41
+ });
42
+ child.unref();
43
+ } catch {
44
+ }
45
+ }
46
+
10
47
  // src/core/bank.ts
11
48
  import { execFileSync } from "child_process";
12
49
  import { existsSync } from "fs";
13
50
  import { homedir } from "os";
14
- import { basename, dirname, join, normalize, sep } from "path";
51
+ import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
15
52
 
16
53
  // src/core/template.ts
17
54
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
@@ -40,20 +77,20 @@ function getProjectRootFromGit(directory) {
40
77
  { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
41
78
  ).trim();
42
79
  if (!commonDir) return null;
43
- return basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
80
+ return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
44
81
  } catch {
45
82
  return null;
46
83
  }
47
84
  }
48
- function projectNameOf(directory) {
49
- return gitProjectName(directory, true);
85
+ function projectNameOf(directory, sessionRoot) {
86
+ return gitProjectName(directory, true, sessionRoot);
50
87
  }
51
88
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
52
89
  function nearestExistingDir(directory) {
53
90
  let current2 = directory;
54
91
  while (current2) {
55
92
  if (existsSync(current2)) return current2;
56
- const parent = dirname(current2);
93
+ const parent = dirname2(current2);
57
94
  if (parent === current2) return "";
58
95
  current2 = parent;
59
96
  }
@@ -62,21 +99,27 @@ function nearestExistingDir(directory) {
62
99
  function dirName(directory) {
63
100
  return directory && basename(directory) || "unknown";
64
101
  }
65
- function gitProjectName(directory, resolveWorktrees) {
102
+ function mainWorktreeRoot(directory, sessionRoot = "") {
103
+ const candidates = [
104
+ nearestExistingDir(directory),
105
+ sessionRoot,
106
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
107
+ ];
108
+ for (const candidate of candidates) {
109
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
110
+ if (root) return root;
111
+ }
112
+ return null;
113
+ }
114
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
66
115
  if (resolveWorktrees) {
67
- const candidates = [
68
- nearestExistingDir(directory),
69
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
70
- ];
71
- for (const candidate of candidates) {
72
- const root = candidate ? getProjectRootFromGit(candidate) : null;
73
- if (root) return basename(root);
74
- }
116
+ const root = mainWorktreeRoot(directory, sessionRoot);
117
+ if (root) return basename(root);
75
118
  }
76
- return dirName(directory);
119
+ return dirName(sessionRoot || directory);
77
120
  }
78
121
  function configuredDir(dir) {
79
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
122
+ const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
80
123
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
81
124
  }
82
125
  function isWithin(directory, configured) {
@@ -93,261 +136,48 @@ function mapLookup(map3, directory) {
93
136
  }
94
137
  return best?.bank;
95
138
  }
139
+ function lookupDirectories(config3, directory, sessionRoot = "") {
140
+ const directories = [normalize(directory)];
141
+ if (config3.resolveWorktrees ?? true) {
142
+ const root = mainWorktreeRoot(directory, sessionRoot);
143
+ const normalizedRoot = root ? normalize(root) : "";
144
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
145
+ }
146
+ return directories;
147
+ }
96
148
  function isOptedIn(config3, directory) {
97
149
  if (!config3.optInOnly) return true;
98
150
  if (!directory) return false;
99
- const cwd = normalize(directory);
100
- if ((config3.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
151
+ const directories = lookupDirectories(config3, directory);
152
+ if (directories.some(
153
+ (candidate) => (config3.optInPaths ?? []).some(
154
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
155
+ )
156
+ ))
101
157
  return true;
102
- return Boolean(config3.mapPathToBank && mapLookup(config3.mapPathToBank, directory));
158
+ const pathMap = config3.mapPathToBank;
159
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
103
160
  }
104
- function deriveBankId(config3, directory, harness = "coding") {
105
- const mapped = directory && config3.mapPathToBank ? mapLookup(config3.mapPathToBank, directory) : void 0;
161
+ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
162
+ const pathMap = config3.mapPathToBank;
163
+ const mapped = directory && pathMap ? lookupDirectories(config3, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
106
164
  if (mapped) return mapped;
107
165
  const dynamic = config3.dynamicBankId ?? !config3.bankId;
108
166
  if (!dynamic) return config3.bankId || DEFAULT_BANK_NAME;
109
167
  const resolvers = {
110
168
  harness: () => harness,
111
169
  project: () => dirName(directory),
112
- gitProject: () => gitProjectName(directory, config3.resolveWorktrees ?? true),
170
+ gitProject: () => gitProjectName(directory, config3.resolveWorktrees ?? true, sessionRoot),
113
171
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
114
172
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
115
173
  };
116
174
  return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
117
175
  }
118
176
 
119
- // src/core/config.ts
120
- import { readFileSync } from "fs";
121
- import { homedir as homedir2 } from "os";
122
- import { join as join3 } from "path";
123
-
124
- // src/core/seed.ts
125
- import { spawn as realSpawn } from "child_process";
126
- import { dirname as dirname2, join as join2 } from "path";
127
- import { fileURLToPath } from "url";
128
- var DEFAULT_SEED_LIMIT = 300;
129
- function startBackgroundSeed(repoDir, opts = {}) {
130
- try {
131
- const spawnFn = opts.spawn ?? realSpawn;
132
- const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
133
- const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
134
- const child = spawnFn(
135
- "node",
136
- [
137
- enginePath,
138
- "--repo",
139
- repoDir,
140
- "--gitlog-limit",
141
- String(limit),
142
- ...opts.harness ? ["--harness", opts.harness] : []
143
- ],
144
- {
145
- detached: true,
146
- stdio: "ignore"
147
- }
148
- );
149
- child.on("error", () => {
150
- });
151
- child.unref();
152
- } catch {
153
- }
154
- }
155
-
156
- // src/core/config.ts
157
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
158
- var DEFAULT_DAEMON_PORT = 9077;
159
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
160
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
161
- function resolveConfig(raw = {}) {
162
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
163
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
164
- return {
165
- serverMode,
166
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
167
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
168
- // daemon needs no plumbing through eight separate constructors.
169
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
170
- apiToken: raw.apiToken || void 0,
171
- apiPort,
172
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
173
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
174
- embedVersion: raw.embedVersion || void 0,
175
- embedPackagePath: raw.embedPackagePath || void 0,
176
- bankId: raw.bankId,
177
- dynamicBankId: raw.dynamicBankId,
178
- bankIdTemplate: raw.bankIdTemplate,
179
- mapPathToBank: raw.mapPathToBank,
180
- resolveWorktrees: raw.resolveWorktrees,
181
- optInOnly: raw.optInOnly ?? false,
182
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
183
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
184
- harness: raw.harness ?? "opencode",
185
- disabled: raw.disabled ?? false,
186
- retainSessions: raw.retainSessions ?? true,
187
- // opencode: write back by default (parity with hook-harness Stop)
188
- maxParallelRetains: raw.maxParallelRetains || 10,
189
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
190
- autoReflect: raw.autoReflect ?? true,
191
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
192
- autoSeed: raw.autoSeed ?? true,
193
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
194
- codebaseSurvey: raw.codebaseSurvey ?? true,
195
- surveyModel: raw.surveyModel || "haiku",
196
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
197
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
198
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
199
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
200
- // nested object cannot reach the API as a tag and fail the whole retain.
201
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
202
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
203
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
204
- ) : {},
205
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
206
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
207
- };
208
- }
209
- function readRaw(path) {
210
- try {
211
- return JSON.parse(readFileSync(path, "utf8"));
212
- } catch (e) {
213
- if (e?.code !== "ENOENT") {
214
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
215
- }
216
- return {};
217
- }
218
- }
219
- function mergeRaw(a, b) {
220
- const { harnesses: _drop, ...flat } = b;
221
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
222
- }
223
- function applyLayer(raw, layer, harness) {
224
- let out = mergeRaw(raw, layer);
225
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
226
- if (perHarness) out = mergeRaw(out, perHarness);
227
- return out;
228
- }
229
- var ENV_KEYS = {
230
- serverMode: "HINDSIGHT_SERVER_MODE",
231
- apiUrl: "HINDSIGHT_API_URL",
232
- apiToken: "HINDSIGHT_API_TOKEN",
233
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
234
- // it can carry their existing environment over unchanged.
235
- apiPort: "HINDSIGHT_API_PORT",
236
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
237
- embedVersion: "HINDSIGHT_EMBED_VERSION",
238
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
239
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
240
- bankId: "HINDSIGHT_BANK_ID",
241
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
242
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
243
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
244
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
245
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
246
- harness: "HINDSIGHT_HARNESS",
247
- disabled: "HINDSIGHT_DISABLED",
248
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
249
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
250
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
251
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
252
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
253
- autoSeed: "HINDSIGHT_AUTO_SEED",
254
- seedLimit: "HINDSIGHT_SEED_LIMIT",
255
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
256
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
257
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
258
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
259
- logLevel: "HINDSIGHT_LOG_LEVEL",
260
- gitIngest: "HINDSIGHT_GIT_INGEST",
261
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
262
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
263
- retainTags: "HINDSIGHT_RETAIN_TAGS"
264
- };
265
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
266
- "dynamicBankId",
267
- "resolveWorktrees",
268
- "optInOnly",
269
- "disabled",
270
- "retainSessions",
271
- "autoReflect",
272
- "autoSeed",
273
- "codebaseSurvey"
274
- ]);
275
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
276
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
277
- "apiPort",
278
- "daemonIdleTimeout",
279
- "maxParallelRetains",
280
- "reflectTimeoutMs",
281
- "pageRefreshEveryTurns",
282
- "seedLimit",
283
- "surveyBudgetUsd",
284
- "surveyRefreshCommits"
285
- ]);
286
- function readEnvConfig(env = process.env) {
287
- const out = {};
288
- for (const [key, name] of Object.entries(ENV_KEYS)) {
289
- const value = env[name];
290
- if (value === void 0 || value.trim() === "") continue;
291
- if (ENV_BOOLEANS.has(key)) {
292
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
293
- } else if (ENV_LISTS.has(key)) {
294
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
295
- if (items.length) out[key] = items;
296
- } else if (ENV_NUMBERS.has(key)) {
297
- const n = Number(value);
298
- if (Number.isFinite(n)) out[key] = n;
299
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
300
- } else {
301
- out[key] = value;
302
- }
303
- }
304
- return out;
305
- }
306
- function loadConfig(opts = {}) {
307
- const o = typeof opts === "string" ? { path: opts } : opts;
308
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
309
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
310
- if (!raw.harness && o.harness) raw.harness = o.harness;
311
- return resolveConfig(raw);
312
- }
313
- var BANK_OVERRIDE_EXCLUDED = [
314
- "bankId",
315
- "bankIdTemplate",
316
- "mapPathToBank",
317
- "dynamicBankId",
318
- "resolveWorktrees",
319
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
320
- // only ever arrive too late to matter — strip them rather than let them read as effective.
321
- "optInOnly",
322
- "optInPaths",
323
- "harness"
324
- ];
325
- function applyBankConfig(cfg, resolvedId, directory) {
326
- if (directory !== void 0 && !isOptedIn(cfg, directory))
327
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
328
- const section = cfg.banks[resolvedId];
329
- if (!section) return { cfg, bankId: resolvedId };
330
- const safe = { ...section };
331
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
332
- delete safe.banks;
333
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
334
- delete safe.bank;
335
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
336
- }
337
- function resolvePartial(cfg, patch) {
338
- const full = resolveConfig(patch);
339
- const out = {};
340
- for (const key of Object.keys(patch)) {
341
- if (key in full)
342
- out[key] = full[key];
343
- }
344
- return out;
345
- }
346
-
347
177
  // src/core/log.ts
348
178
  import { appendFileSync, mkdirSync } from "fs";
349
179
  import { tmpdir } from "os";
350
- import { dirname as dirname3, join as join4 } from "path";
180
+ import { dirname as dirname3, join as join3 } from "path";
351
181
  var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
352
182
  var current = ["debug", "info", "warn", "error"].find(
353
183
  (l) => l === process.env.HINDSIGHT_LOG_LEVEL
@@ -356,7 +186,7 @@ function setLogLevel(level) {
356
186
  if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
357
187
  }
358
188
  function logFilePath() {
359
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
189
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
360
190
  }
361
191
  function write(level, scope, msg, extra) {
362
192
  if (WEIGHT[level] < WEIGHT[current]) return;
@@ -466,7 +296,10 @@ var KNOWLEDGE_LABELS = {
466
296
  }
467
297
  ]
468
298
  };
469
- var PAGES = [
299
+ function pageScopeRule(project) {
300
+ 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.`;
301
+ }
302
+ var PAGE_TAXONOMY = [
470
303
  {
471
304
  name: "Component map",
472
305
  source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
@@ -493,11 +326,23 @@ var PAGES = [
493
326
  tags: ["knowledge:feature-work"]
494
327
  }
495
328
  ];
329
+ function pagesFor(project) {
330
+ const scope = pageScopeRule(project);
331
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
332
+ }
496
333
  var PAGE_MAX_TOKENS = 4096;
497
- var PAGE_TRIGGER = {
498
- fact_types: ["world", "experience", "observation"],
499
- refresh_after_consolidation: true
500
- };
334
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
335
+ function buildPageTrigger(cfg = {}) {
336
+ const base = { fact_types: PAGE_FACT_TYPES };
337
+ switch (cfg.pageTriggerType) {
338
+ case "cron":
339
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
340
+ case "manual":
341
+ return { ...base, refresh_after_consolidation: false };
342
+ default:
343
+ return { ...base, refresh_after_consolidation: true };
344
+ }
345
+ }
501
346
  var CODING_BANK_TEMPLATE = {
502
347
  version: "1",
503
348
  bank: {
@@ -552,6 +397,7 @@ async function pool(items, n, fn, onError, onProgress) {
552
397
  }
553
398
 
554
399
  // src/core/hindsight.ts
400
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
555
401
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
556
402
  var RateLimitedError = class extends Error {
557
403
  constructor(retryAfterMs2) {
@@ -584,8 +430,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
584
430
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
585
431
  var HindsightClient = class {
586
432
  apiUrl;
587
- apiToken;
433
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
434
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
435
+ token;
436
+ tokenProvider;
588
437
  bank;
438
+ project;
589
439
  opIds = [];
590
440
  // async operation ids collected by retain(), for drain()
591
441
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -594,34 +444,81 @@ var HindsightClient = class {
594
444
  idempotentRetain;
595
445
  log;
596
446
  maxParallelRetains;
447
+ observationScopes;
597
448
  constructor(o) {
598
449
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
599
- this.apiToken = o.apiToken;
450
+ this.token = o.apiToken;
451
+ this.tokenProvider = o.tokenProvider;
600
452
  this.bank = o.bank;
453
+ this.project = o.project;
601
454
  this.log = o.log ?? (() => {
602
455
  });
603
456
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
457
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
458
+ }
459
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
460
+ get apiToken() {
461
+ return this.token;
604
462
  }
605
463
  headers() {
606
464
  const h = { "Content-Type": "application/json" };
607
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
465
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
608
466
  return h;
609
467
  }
468
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
469
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
470
+ * doubling every failing request. */
471
+ refreshToken() {
472
+ if (!this.tokenProvider) return false;
473
+ let next;
474
+ try {
475
+ next = this.tokenProvider();
476
+ } catch {
477
+ return false;
478
+ }
479
+ if (next === this.token) return false;
480
+ this.token = next;
481
+ return true;
482
+ }
483
+ /**
484
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
485
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
486
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
487
+ * not.
488
+ *
489
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
490
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
491
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
492
+ * bounds the whole call.
493
+ */
494
+ async fetchWithAuth(url3, init) {
495
+ const send = () => fetch(url3, { ...init, headers: this.headers() });
496
+ const r = await send();
497
+ if (r.status !== 401 || !this.refreshToken()) return r;
498
+ return send();
499
+ }
500
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
501
+ * server answers identically for both — only the client knows which it sent. */
502
+ authHint(status) {
503
+ if (status !== 401) return "";
504
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
505
+ }
610
506
  bankUrl(suffix = "") {
611
507
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
612
508
  }
613
509
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
614
510
  async req(method, url3, body, tolerate = []) {
615
- const r = await fetch(url3, {
511
+ const r = await this.fetchWithAuth(url3, {
616
512
  method,
617
- headers: this.headers(),
618
513
  body: body ? JSON.stringify(body) : void 0,
619
514
  signal: AbortSignal.timeout(15e3)
620
515
  });
621
516
  if (r.status === 429 && !tolerate.includes(429))
622
517
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
623
518
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
624
- throw new Error(`${method} ${url3} -> ${r.status} ${await r.text()}`);
519
+ throw new Error(
520
+ `${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
521
+ );
625
522
  return r;
626
523
  }
627
524
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -632,7 +529,11 @@ var HindsightClient = class {
632
529
  context,
633
530
  document_id: documentId,
634
531
  tags,
635
- strategy
532
+ strategy,
533
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
534
+ // observations were built under is a property of the write rather than of whichever server
535
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
536
+ observation_scopes: this.observationScopes
636
537
  };
637
538
  if (opts.timestamp) item.timestamp = opts.timestamp;
638
539
  if (opts.metadata) item.metadata = opts.metadata;
@@ -711,7 +612,7 @@ var HindsightClient = class {
711
612
  this.log(
712
613
  seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
713
614
  );
714
- await this.seedPages();
615
+ await this.seedPages(opts.pageTrigger);
715
616
  }
716
617
  /**
717
618
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -769,7 +670,7 @@ var HindsightClient = class {
769
670
  let backoffMs = POLL_CYCLE_MS;
770
671
  await pool([...pending], this.maxParallelRetains, async (id) => {
771
672
  try {
772
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
673
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
773
674
  if (r.status === 429) {
774
675
  backoffMs = Math.min(
775
676
  RETRY_AFTER_CEILING_MS,
@@ -795,18 +696,23 @@ var HindsightClient = class {
795
696
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
796
697
  );
797
698
  }
798
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
799
- async reflect(query, opts = {}) {
699
+ /**
700
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
701
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
702
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
703
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
704
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
705
+ */
706
+ async reflect(query, opts) {
800
707
  const ctrl = new AbortController();
801
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
708
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
802
709
  try {
803
- const resp = await fetch(this.bankUrl("/reflect"), {
710
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
804
711
  method: "POST",
805
- headers: this.headers(),
806
712
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
807
713
  signal: ctrl.signal
808
714
  });
809
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
715
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
810
716
  const data = await resp.json();
811
717
  return (data.text || "").trim();
812
718
  } finally {
@@ -890,16 +796,18 @@ var HindsightClient = class {
890
796
  }));
891
797
  }
892
798
  /**
893
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
799
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
894
800
  *
895
801
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
896
802
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
897
803
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
898
804
  *
899
805
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
900
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
806
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
807
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
901
808
  */
902
- async seedPages() {
809
+ async seedPages(pageTrigger = buildPageTrigger()) {
810
+ const pages = pagesFor(this.project ?? this.bank);
903
811
  const existing = /* @__PURE__ */ new Map();
904
812
  let roots;
905
813
  try {
@@ -916,14 +824,14 @@ var HindsightClient = class {
916
824
  }
917
825
  let created = 0;
918
826
  let updated = 0;
919
- for (const page of PAGES) {
827
+ for (const page of pages) {
920
828
  const hit = existing.get(page.name.toLowerCase());
921
829
  const body = {
922
830
  name: page.name,
923
831
  source_query: page.source_query,
924
832
  tags: page.tags,
925
833
  max_tokens: PAGE_MAX_TOKENS,
926
- trigger: PAGE_TRIGGER
834
+ trigger: pageTrigger
927
835
  };
928
836
  if (!hit) {
929
837
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -952,7 +860,7 @@ var HindsightClient = class {
952
860
  }
953
861
  }
954
862
  this.log(
955
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
863
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
956
864
  );
957
865
  }
958
866
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -962,7 +870,8 @@ var HindsightClient = class {
962
870
  /**
963
871
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
964
872
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
965
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
873
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
874
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
966
875
  */
967
876
  async captureInitiative(args) {
968
877
  let pageId = args.relatesToPageId;
@@ -973,10 +882,7 @@ var HindsightClient = class {
973
882
  source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
974
883
  parent_id: folderId,
975
884
  tags: ["knowledge:feature-work"],
976
- trigger: {
977
- fact_types: ["world", "experience", "observation"],
978
- refresh_after_consolidation: true
979
- }
885
+ trigger: args.pageTrigger ?? buildPageTrigger()
980
886
  });
981
887
  try {
982
888
  const j = await r.json();
@@ -985,43 +891,312 @@ var HindsightClient = class {
985
891
  }
986
892
  pageId ||= `initiative-${this.slugify(args.title)}`;
987
893
  }
988
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
989
- const content = `${verb}: ${args.title}. ${args.summary}`;
990
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
991
- const tags = [
992
- .../* @__PURE__ */ new Set([
993
- ...args.stamp?.tags ?? [],
994
- "knowledge:feature-work",
995
- `relatedPageId:${pageId}`
996
- ])
997
- ];
998
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
999
- await this.retain(content, "initiative marker", markerId, tags, "document", {
1000
- metadata: args.stamp?.metadata
1001
- });
894
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
895
+ const content = `${verb}: ${args.title}. ${args.summary}`;
896
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
897
+ const tags = [
898
+ .../* @__PURE__ */ new Set([
899
+ ...args.stamp?.tags ?? [],
900
+ "knowledge:feature-work",
901
+ `relatedPageId:${pageId}`
902
+ ])
903
+ ];
904
+ if (Object.keys(args.stamp?.metadata ?? {}).length) {
905
+ await this.retain(content, "initiative marker", markerId, tags, "document", {
906
+ metadata: args.stamp?.metadata
907
+ });
908
+ } else {
909
+ await this.retain(content, "initiative marker", markerId, tags, "document");
910
+ }
911
+ return { page_id: pageId };
912
+ }
913
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
914
+ async ensureFolder(name) {
915
+ try {
916
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
917
+ const hit = (tree.roots || []).find(
918
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
919
+ );
920
+ if (hit?.id) return hit.id;
921
+ } catch {
922
+ }
923
+ try {
924
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
925
+ return (await r.json()).id;
926
+ } catch {
927
+ return void 0;
928
+ }
929
+ }
930
+ };
931
+
932
+ // src/core/config.ts
933
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
934
+ var DEFAULT_DAEMON_PORT = 9077;
935
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
936
+ function resolvePageTriggerType(raw) {
937
+ if (raw.pageTriggerType === "manual") return "manual";
938
+ if (raw.pageTriggerType === "cron") {
939
+ if (raw.pageTriggerCron?.trim()) return "cron";
940
+ log.warn(
941
+ "config",
942
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
943
+ );
944
+ }
945
+ return "auto-refresh";
946
+ }
947
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
948
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
949
+ function resolveReflectBudget(raw) {
950
+ const value = raw.reflectBudget;
951
+ if (value === void 0) return "high";
952
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
953
+ return value;
954
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
955
+ return "high";
956
+ }
957
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
958
+ function resolveObservationScopes(raw) {
959
+ const value = raw;
960
+ if (typeof value === "string")
961
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
962
+ if (Array.isArray(value)) {
963
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
964
+ if (scopes.length) return scopes;
965
+ }
966
+ return DEFAULT_OBSERVATION_SCOPES;
967
+ }
968
+ function resolveConfig(raw = {}) {
969
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
970
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
971
+ return {
972
+ serverMode,
973
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
974
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
975
+ // daemon needs no plumbing through eight separate constructors.
976
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
977
+ apiToken: raw.apiToken || void 0,
978
+ apiPort,
979
+ daemonIdleTimeout: raw.daemonIdleTimeout,
980
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
981
+ embedVersion: raw.embedVersion || void 0,
982
+ embedPackagePath: raw.embedPackagePath || void 0,
983
+ bankId: raw.bankId,
984
+ dynamicBankId: raw.dynamicBankId,
985
+ bankIdTemplate: raw.bankIdTemplate,
986
+ mapPathToBank: raw.mapPathToBank,
987
+ resolveWorktrees: raw.resolveWorktrees,
988
+ optInOnly: raw.optInOnly ?? false,
989
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
990
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
991
+ harness: raw.harness ?? "opencode",
992
+ disabled: raw.disabled ?? false,
993
+ retainSessions: raw.retainSessions ?? true,
994
+ // write sessions back by default, every harness
995
+ maxParallelRetains: raw.maxParallelRetains || 10,
996
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
997
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
998
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
999
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1000
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1001
+ reflectBudget: resolveReflectBudget(raw),
1002
+ autoReflect: raw.autoReflect ?? true,
1003
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1004
+ pageTriggerType: resolvePageTriggerType(raw),
1005
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1006
+ autoSeed: raw.autoSeed ?? true,
1007
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1008
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1009
+ surveyModel: raw.surveyModel || "haiku",
1010
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1011
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1012
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1013
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1014
+ // nested object cannot reach the API as a tag and fail the whole retain.
1015
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1016
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1017
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1018
+ ) : {},
1019
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1020
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1021
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1022
+ };
1023
+ }
1024
+ function readRaw(path) {
1025
+ try {
1026
+ return JSON.parse(readFileSync(path, "utf8"));
1027
+ } catch (e) {
1028
+ if (e?.code !== "ENOENT") {
1029
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1030
+ }
1031
+ return {};
1032
+ }
1033
+ }
1034
+ function mergeRaw(a, b) {
1035
+ const { harnesses: _drop, ...flat } = b;
1036
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1037
+ }
1038
+ function applyLayer(raw, layer, harness) {
1039
+ let out = mergeRaw(raw, layer);
1040
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1041
+ if (perHarness) out = mergeRaw(out, perHarness);
1042
+ return out;
1043
+ }
1044
+ var ENV_KEYS = {
1045
+ serverMode: "HINDSIGHT_SERVER_MODE",
1046
+ apiUrl: "HINDSIGHT_API_URL",
1047
+ apiToken: "HINDSIGHT_API_TOKEN",
1048
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1049
+ // it can carry their existing environment over unchanged.
1050
+ apiPort: "HINDSIGHT_API_PORT",
1051
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1052
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1053
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1054
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1055
+ bankId: "HINDSIGHT_BANK_ID",
1056
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1057
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1058
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1059
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1060
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1061
+ harness: "HINDSIGHT_HARNESS",
1062
+ disabled: "HINDSIGHT_DISABLED",
1063
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1064
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1065
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1066
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1067
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1068
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1069
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1070
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1071
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1072
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1073
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1074
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1075
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1076
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1077
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1078
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1079
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1080
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1081
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1082
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1083
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1084
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1085
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1086
+ };
1087
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1088
+ "dynamicBankId",
1089
+ "resolveWorktrees",
1090
+ "optInOnly",
1091
+ "disabled",
1092
+ "retainSessions",
1093
+ "autoReflect",
1094
+ "autoSeed",
1095
+ "codebaseSurvey"
1096
+ ]);
1097
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1098
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1099
+ "apiPort",
1100
+ "daemonIdleTimeout",
1101
+ "maxParallelRetains",
1102
+ "reflectTimeoutMs",
1103
+ "reflectToolTimeoutMs",
1104
+ "pageRefreshEveryTurns",
1105
+ "seedLimit",
1106
+ "surveyBudgetUsd",
1107
+ "surveyRefreshCommits"
1108
+ ]);
1109
+ function readEnvConfig(env = process.env) {
1110
+ const out = {};
1111
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1112
+ const value = env[name];
1113
+ if (value === void 0 || value.trim() === "") continue;
1114
+ if (ENV_BOOLEANS.has(key)) {
1115
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1116
+ } else if (ENV_LISTS.has(key)) {
1117
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1118
+ if (items.length) out[key] = items;
1119
+ } else if (ENV_NUMBERS.has(key)) {
1120
+ const n = Number(value);
1121
+ if (Number.isFinite(n)) out[key] = n;
1122
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1002
1123
  } else {
1003
- await this.retain(content, "initiative marker", markerId, tags, "document");
1124
+ out[key] = value;
1004
1125
  }
1005
- return { page_id: pageId };
1006
1126
  }
1007
- /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1008
- async ensureFolder(name) {
1009
- try {
1010
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1011
- const hit = (tree.roots || []).find(
1012
- (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1013
- );
1014
- if (hit?.id) return hit.id;
1015
- } catch {
1016
- }
1017
- try {
1018
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1019
- return (await r.json()).id;
1020
- } catch {
1021
- return void 0;
1022
- }
1127
+ return out;
1128
+ }
1129
+ function loadConfig(opts = {}) {
1130
+ const o = typeof opts === "string" ? { path: opts } : opts;
1131
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1132
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1133
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1134
+ return resolveConfig(raw);
1135
+ }
1136
+ var BANK_OVERRIDE_EXCLUDED = [
1137
+ "bankId",
1138
+ "bankIdTemplate",
1139
+ "mapPathToBank",
1140
+ "dynamicBankId",
1141
+ "resolveWorktrees",
1142
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1143
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1144
+ "optInOnly",
1145
+ "optInPaths",
1146
+ "harness"
1147
+ ];
1148
+ function applyBankConfig(cfg, resolvedId, directory) {
1149
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1150
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1151
+ const section = cfg.banks[resolvedId];
1152
+ if (!section) return { cfg, bankId: resolvedId };
1153
+ const safe = { ...section };
1154
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1155
+ delete safe.banks;
1156
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1157
+ delete safe.bank;
1158
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1159
+ }
1160
+ function resolvePartial(cfg, patch) {
1161
+ const full = resolveConfig(patch);
1162
+ const out = {};
1163
+ for (const key of Object.keys(patch)) {
1164
+ if (key in full)
1165
+ out[key] = full[key];
1023
1166
  }
1024
- };
1167
+ return out;
1168
+ }
1169
+
1170
+ // src/core/host-client.ts
1171
+ function resolveHostConfig(harness, directory) {
1172
+ const cfg0 = loadConfig({ harness });
1173
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1174
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1175
+ }
1176
+ function resolveHostMemory(harness, directory) {
1177
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
1178
+ return {
1179
+ cfg,
1180
+ bankId,
1181
+ client: new HindsightClient({
1182
+ apiUrl: cfg.apiUrl,
1183
+ apiToken: cfg.apiToken,
1184
+ bank: bankId,
1185
+ maxParallelRetains: cfg.maxParallelRetains,
1186
+ observationScopes: cfg.observationScopes,
1187
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
1188
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
1189
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
1190
+ // honoured on re-resolution exactly as it was on the first one.
1191
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
1192
+ })
1193
+ };
1194
+ }
1195
+
1196
+ // src/core/daemon.ts
1197
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1198
+ import { dirname as dirname4, join as join5 } from "path";
1199
+ import { fileURLToPath as fileURLToPath2 } from "url";
1025
1200
 
1026
1201
  // src/core/diag.ts
1027
1202
  import { appendFileSync as appendFileSync2 } from "fs";
@@ -1039,6 +1214,120 @@ function diag(harness, event, extra = {}) {
1039
1214
  }
1040
1215
  }
1041
1216
 
1217
+ // src/core/daemon.ts
1218
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
1219
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
1220
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1221
+ try {
1222
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
1223
+ return res.ok;
1224
+ } catch {
1225
+ return false;
1226
+ }
1227
+ }
1228
+ function hasRustToolchain() {
1229
+ if (process.platform !== "darwin") return true;
1230
+ try {
1231
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
1232
+ return true;
1233
+ } catch {
1234
+ return false;
1235
+ }
1236
+ }
1237
+ function hasUvx() {
1238
+ try {
1239
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
1240
+ return true;
1241
+ } catch {
1242
+ return false;
1243
+ }
1244
+ }
1245
+ var PROVIDER_PROBES = [
1246
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
1247
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
1248
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
1249
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
1250
+ ];
1251
+ function detectLlm(env = process.env) {
1252
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
1253
+ if (explicit) {
1254
+ return {
1255
+ provider: explicit,
1256
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
1257
+ source: "HINDSIGHT_API_LLM_PROVIDER"
1258
+ };
1259
+ }
1260
+ for (const probe of PROVIDER_PROBES) {
1261
+ const key = env[probe.keyEnv]?.trim();
1262
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
1263
+ }
1264
+ if (onPath("claude")) {
1265
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
1266
+ }
1267
+ return void 0;
1268
+ }
1269
+ function onPath(bin) {
1270
+ try {
1271
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
1272
+ return true;
1273
+ } catch {
1274
+ return false;
1275
+ }
1276
+ }
1277
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1278
+ try {
1279
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1280
+ const child = spawnFn("node", [starter, "--harness", harness], {
1281
+ detached: true,
1282
+ stdio: "ignore"
1283
+ });
1284
+ child.on("error", () => {
1285
+ });
1286
+ child.unref();
1287
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
1288
+ } catch {
1289
+ }
1290
+ }
1291
+ async function ensureDaemon(cfg, harness, opts = {}) {
1292
+ if (cfg.serverMode !== "daemon") return;
1293
+ if (await isServerHealthy(cfg.apiUrl)) return;
1294
+ if (!preflightDaemon(cfg, harness)) return;
1295
+ startDaemonDetached(cfg, harness, opts.spawnFn);
1296
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
1297
+ }
1298
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1299
+ const deadline = Date.now() + budgetMs;
1300
+ while (Date.now() < deadline) {
1301
+ await new Promise((r) => setTimeout(r, pollMs));
1302
+ if (await isServerHealthy(baseUrl)) return true;
1303
+ }
1304
+ return false;
1305
+ }
1306
+ function preflightDaemon(cfg, harness) {
1307
+ if (!hasUvx()) {
1308
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
1309
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
1310
+ return false;
1311
+ }
1312
+ if (!hasRustToolchain()) {
1313
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
1314
+ log.warn(
1315
+ harness,
1316
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
1317
+ );
1318
+ return false;
1319
+ }
1320
+ if (!detectLlm()) {
1321
+ diag(harness, "daemon_no_llm", {});
1322
+ log.warn(
1323
+ harness,
1324
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
1325
+ );
1326
+ return false;
1327
+ }
1328
+ return true;
1329
+ }
1330
+
1042
1331
  // node_modules/zod/v4/classic/external.js
1043
1332
  var external_exports = {};
1044
1333
  __export(external_exports, {
@@ -15556,16 +15845,16 @@ config(en_default());
15556
15845
  // src/core/knowledge-tools.ts
15557
15846
  import { existsSync as existsSync3 } from "fs";
15558
15847
  import { homedir as homedir4 } from "os";
15559
- import { join as join6 } from "path";
15848
+ import { join as join7 } from "path";
15560
15849
 
15561
15850
  // src/core/status.ts
15562
- import { execFileSync as execFileSync3 } from "child_process";
15851
+ import { execFileSync as execFileSync4 } from "child_process";
15563
15852
 
15564
15853
  // src/core/git.ts
15565
- import { execFileSync as execFileSync2 } from "child_process";
15854
+ import { execFileSync as execFileSync3 } from "child_process";
15566
15855
  import { resolve } from "path";
15567
15856
  function git(repo, ...args) {
15568
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15857
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15569
15858
  }
15570
15859
  function repoNameOf(repo) {
15571
15860
  return projectNameOf(resolve(repo));
@@ -15611,7 +15900,7 @@ function roster(pages) {
15611
15900
  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>".
15612
15901
  - 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.
15613
15902
  - 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>").
15614
- - 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.
15903
+ - 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.
15615
15904
  - 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).`;
15616
15905
  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";
15617
15906
  function toolGuide(opts) {
@@ -15638,11 +15927,11 @@ ${toolGuide(opts)}
15638
15927
  }
15639
15928
 
15640
15929
  // src/core/survey.ts
15641
- import { spawn as realSpawn2 } from "child_process";
15930
+ import { spawn as realSpawn3 } from "child_process";
15642
15931
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15643
15932
  import { homedir as homedir3 } from "os";
15644
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15645
- import { fileURLToPath as fileURLToPath2 } from "url";
15933
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15934
+ import { fileURLToPath as fileURLToPath3 } from "url";
15646
15935
  var SURVEY_DOC_IDS = [
15647
15936
  "repository-component-map",
15648
15937
  "repository-core-concepts",
@@ -15652,7 +15941,7 @@ var SURVEY_DOC_IDS = [
15652
15941
  function resolveClaudeBin(explicit) {
15653
15942
  if (explicit) return explicit;
15654
15943
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15655
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15944
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15656
15945
  try {
15657
15946
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15658
15947
  } catch {
@@ -15692,7 +15981,7 @@ function binExists(bin) {
15692
15981
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15693
15982
  if (!dir) continue;
15694
15983
  try {
15695
- accessSync(join5(dir, bin), constants.X_OK);
15984
+ accessSync(join6(dir, bin), constants.X_OK);
15696
15985
  return true;
15697
15986
  } catch {
15698
15987
  }
@@ -15736,7 +16025,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15736
16025
  hindsight: {
15737
16026
  command: "node",
15738
16027
  args: [opts.mcpServerPath],
15739
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16028
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16029
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16030
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16031
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16032
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15740
16033
  }
15741
16034
  }
15742
16035
  });
@@ -15776,6 +16069,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15776
16069
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15777
16070
  "-c",
15778
16071
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16072
+ "-c",
16073
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15779
16074
  SURVEY_PROMPT
15780
16075
  ],
15781
16076
  env
@@ -15799,9 +16094,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15799
16094
  }
15800
16095
  function startCodebaseSurvey(repoDir, opts = {}) {
15801
16096
  try {
15802
- const spawnFn = opts.spawn ?? realSpawn2;
16097
+ const spawnFn = opts.spawn ?? realSpawn3;
15803
16098
  const exists = opts.exists ?? binExists;
15804
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16099
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15805
16100
  const preferred = opts.harness ?? "claude-code";
15806
16101
  const order = [
15807
16102
  preferred,
@@ -15840,7 +16135,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15840
16135
  var DEEPEN_DIFF_TARGET = 300;
15841
16136
  function commitCount(repoDir) {
15842
16137
  try {
15843
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16138
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15844
16139
  encoding: "utf8"
15845
16140
  });
15846
16141
  return Number(out.trim()) || 0;
@@ -15931,9 +16226,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15931
16226
  description: "Report safe Hindsight runtime diagnostics for this coding-agent session: resolved bank, workspace, harness, config location, API endpoint, and non-secret environment overrides. Use this when memory, hooks, MCP tools, or configuration appear not to work. Tokens and other secret values are never returned.",
15932
16227
  inputSchema: {},
15933
16228
  handler: async (_args) => {
15934
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16229
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15935
16230
  const harness = opts.harness ?? "unknown";
15936
- const cfg = loadConfig({ harness: opts.harness });
16231
+ const cfg = applyBankConfig(
16232
+ loadConfig({ harness: opts.harness }),
16233
+ bankId,
16234
+ opts.repoDir
16235
+ ).cfg;
15937
16236
  return ok({
15938
16237
  bank_id: bankId,
15939
16238
  harness,
@@ -15945,6 +16244,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15945
16244
  api_token_configured: Boolean(cfg.apiToken),
15946
16245
  disabled: cfg.disabled
15947
16246
  },
16247
+ // What the LIVE client is signing with, which is not the same question as what the file
16248
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16249
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16250
+ // value is never returned.
16251
+ credential: {
16252
+ api_token_in_use: Boolean(client.apiToken),
16253
+ api_token_matches_config: client.apiToken === cfg.apiToken
16254
+ },
15948
16255
  environment: {
15949
16256
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15950
16257
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15993,12 +16300,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15993
16300
  description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
15994
16301
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15995
16302
  handler: guarded(
15996
- async ({ query }) => client.reflect(query, { budget: "high" })
16303
+ async ({ query }) => client.reflect(query, {
16304
+ budget: opts.reflectBudget ?? "high",
16305
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16306
+ })
15997
16307
  )
15998
16308
  },
15999
16309
  {
16000
16310
  name: "hindsight_capture_initiative",
16001
- description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it.\n\nWHEN TO CALL: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Call it ONCE, EARLY.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, and chores are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat').\n- summary: 2-3 sentences on what you're building and why (the intent, not a code diff).\n- relates_to_page_id: leave empty for a new initiative. Set it only to attach to an initiative that already has a page \u2014 pass that page's id from hindsight_list_knowledge_pages.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
16311
+ description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_knowledge_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
16002
16312
  inputSchema: {
16003
16313
  title: external_exports.string(),
16004
16314
  summary: external_exports.string(),
@@ -16009,7 +16319,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16009
16319
  title,
16010
16320
  summary,
16011
16321
  relatesToPageId: relates_to_page_id,
16012
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16322
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16323
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
16013
16324
  })
16014
16325
  )
16015
16326
  },
@@ -16216,7 +16527,7 @@ function resolversFor(ctx) {
16216
16527
  return {
16217
16528
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16218
16529
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16219
- gitProject: () => projectNameOf(ctx.directory),
16530
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16220
16531
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16221
16532
  harness: () => ctx.harness,
16222
16533
  bankId: () => ctx.bankId,
@@ -16262,11 +16573,6 @@ import { readFileSync as readFileSync4 } from "fs";
16262
16573
  // src/core/skill-sync.ts
16263
16574
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16264
16575
  import { homedir as homedir5 } from "os";
16265
- import { dirname as dirname5, join as join7 } from "path";
16266
- import { fileURLToPath as fileURLToPath3 } from "url";
16267
-
16268
- // src/core/daemon.ts
16269
- import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
16270
16576
  import { dirname as dirname6, join as join8 } from "path";
16271
16577
  import { fileURLToPath as fileURLToPath4 } from "url";
16272
16578
 
@@ -16357,7 +16663,7 @@ async function buildSessionStartContext(args) {
16357
16663
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16358
16664
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16359
16665
  const countCommitsSince = args.commitsSince ?? commitsSince;
16360
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16666
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16361
16667
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16362
16668
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16363
16669
  const recordSurveyBaseline = (sha) => {
@@ -16633,6 +16939,9 @@ var RuntimeCore = class {
16633
16939
  return buildKnowledgeTools(this.client, this.bankId, {
16634
16940
  repoDir: this.projectDir,
16635
16941
  harness: this.harness,
16942
+ pageTrigger: buildPageTrigger(this.cfg),
16943
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16944
+ reflectBudget: this.cfg.reflectBudget,
16636
16945
  stampFor: () => buildRetainStamp(this.cfg, {
16637
16946
  directory: this.projectDir,
16638
16947
  harness: this.harness,
@@ -16651,6 +16960,7 @@ var RuntimeCore = class {
16651
16960
  */
16652
16961
  async seedIfCold(repoPath) {
16653
16962
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16963
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16654
16964
  try {
16655
16965
  const out = await buildSessionStartContext({
16656
16966
  cwd: repoPath || process.cwd(),
@@ -16774,15 +17084,17 @@ var RuntimeCore = class {
16774
17084
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16775
17085
  retain(sessionId, turns, startTs, trigger = "turn") {
16776
17086
  const t0 = Date.now();
16777
- void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16778
- cursors: this.cursors,
16779
- stamp: buildRetainStamp(this.cfg, {
16780
- directory: this.projectDir,
16781
- harness: this.harness,
16782
- bankId: this.bankId,
16783
- sessionId
17087
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17088
+ () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
17089
+ cursors: this.cursors,
17090
+ stamp: buildRetainStamp(this.cfg, {
17091
+ directory: this.projectDir,
17092
+ harness: this.harness,
17093
+ bankId: this.bankId,
17094
+ sessionId
17095
+ })
16784
17096
  })
16785
- }).then(
17097
+ ).then(
16786
17098
  () => diag(this.harness, "retain_ok", {
16787
17099
  ms: Date.now() - t0,
16788
17100
  turns: turns.length,
@@ -29380,23 +29692,10 @@ function resolveProjectDirectory(input) {
29380
29692
  function createPluginEntry(harness) {
29381
29693
  return async (input) => {
29382
29694
  const projectDir = resolveProjectDirectory(input);
29383
- let cfg = loadConfig({ harness });
29384
- if (cfg.disabled) return {};
29385
- const resolved = applyBankConfig(
29386
- cfg,
29387
- deriveBankId(cfg, projectDir || process.cwd(), harness),
29388
- projectDir || process.cwd()
29389
- );
29390
- cfg = resolved.cfg;
29391
- const bankId = resolved.bankId;
29695
+ const dir = projectDir || process.cwd();
29696
+ const { cfg, bankId, client } = resolveHostMemory(harness, dir);
29392
29697
  if (cfg.disabled) return {};
29393
- const client = new HindsightClient({
29394
- apiUrl: cfg.apiUrl,
29395
- apiToken: cfg.apiToken,
29396
- bank: bankId,
29397
- maxParallelRetains: cfg.maxParallelRetains
29398
- });
29399
- const core = new RuntimeCore(client, bankId, cfg, harness, projectDir || process.cwd());
29698
+ const core = new RuntimeCore(client, bankId, cfg, harness, dir);
29400
29699
  const oc = input?.client;
29401
29700
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
29402
29701
  if (oc?.tui?.showToast) {