@vectorize-io/hindsight-coding-agents 0.3.3 → 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;
@@ -376,6 +206,20 @@ var log = {
376
206
  warn: (scope, msg, extra) => write("warn", scope, msg, extra),
377
207
  error: (scope, msg, extra) => write("error", scope, msg, extra)
378
208
  };
209
+ function describeError(value, maxChars = 200) {
210
+ const parts = [];
211
+ const seen = /* @__PURE__ */ new Set();
212
+ let current2 = value;
213
+ while (current2 && !seen.has(current2)) {
214
+ seen.add(current2);
215
+ const error95 = current2;
216
+ const text = typeof error95.message === "string" ? error95.message : String(current2);
217
+ const withCode = error95.code ? `${text} (${String(error95.code)})` : text;
218
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
219
+ current2 = error95.cause;
220
+ }
221
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
222
+ }
379
223
 
380
224
  // src/core/missions.ts
381
225
  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.";
@@ -452,7 +296,10 @@ var KNOWLEDGE_LABELS = {
452
296
  }
453
297
  ]
454
298
  };
455
- 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 = [
456
303
  {
457
304
  name: "Component map",
458
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.",
@@ -479,11 +326,23 @@ var PAGES = [
479
326
  tags: ["knowledge:feature-work"]
480
327
  }
481
328
  ];
329
+ function pagesFor(project) {
330
+ const scope = pageScopeRule(project);
331
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
332
+ }
482
333
  var PAGE_MAX_TOKENS = 4096;
483
- var PAGE_TRIGGER = {
484
- fact_types: ["world", "experience", "observation"],
485
- refresh_after_consolidation: true
486
- };
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
+ }
487
346
  var CODING_BANK_TEMPLATE = {
488
347
  version: "1",
489
348
  bank: {
@@ -538,6 +397,7 @@ async function pool(items, n, fn, onError, onProgress) {
538
397
  }
539
398
 
540
399
  // src/core/hindsight.ts
400
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
541
401
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
542
402
  var RateLimitedError = class extends Error {
543
403
  constructor(retryAfterMs2) {
@@ -570,8 +430,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
570
430
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
571
431
  var HindsightClient = class {
572
432
  apiUrl;
573
- 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;
574
437
  bank;
438
+ project;
575
439
  opIds = [];
576
440
  // async operation ids collected by retain(), for drain()
577
441
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -580,34 +444,81 @@ var HindsightClient = class {
580
444
  idempotentRetain;
581
445
  log;
582
446
  maxParallelRetains;
447
+ observationScopes;
583
448
  constructor(o) {
584
449
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
585
- this.apiToken = o.apiToken;
450
+ this.token = o.apiToken;
451
+ this.tokenProvider = o.tokenProvider;
586
452
  this.bank = o.bank;
453
+ this.project = o.project;
587
454
  this.log = o.log ?? (() => {
588
455
  });
589
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;
590
462
  }
591
463
  headers() {
592
464
  const h = { "Content-Type": "application/json" };
593
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
465
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
594
466
  return h;
595
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
+ }
596
506
  bankUrl(suffix = "") {
597
507
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
598
508
  }
599
509
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
600
510
  async req(method, url3, body, tolerate = []) {
601
- const r = await fetch(url3, {
511
+ const r = await this.fetchWithAuth(url3, {
602
512
  method,
603
- headers: this.headers(),
604
513
  body: body ? JSON.stringify(body) : void 0,
605
514
  signal: AbortSignal.timeout(15e3)
606
515
  });
607
516
  if (r.status === 429 && !tolerate.includes(429))
608
517
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
609
518
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
610
- 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
+ );
611
522
  return r;
612
523
  }
613
524
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -618,7 +529,11 @@ var HindsightClient = class {
618
529
  context,
619
530
  document_id: documentId,
620
531
  tags,
621
- 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
622
537
  };
623
538
  if (opts.timestamp) item.timestamp = opts.timestamp;
624
539
  if (opts.metadata) item.metadata = opts.metadata;
@@ -697,7 +612,7 @@ var HindsightClient = class {
697
612
  this.log(
698
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}`
699
614
  );
700
- await this.seedPages();
615
+ await this.seedPages(opts.pageTrigger);
701
616
  }
702
617
  /**
703
618
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -755,7 +670,7 @@ var HindsightClient = class {
755
670
  let backoffMs = POLL_CYCLE_MS;
756
671
  await pool([...pending], this.maxParallelRetains, async (id) => {
757
672
  try {
758
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
673
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
759
674
  if (r.status === 429) {
760
675
  backoffMs = Math.min(
761
676
  RETRY_AFTER_CEILING_MS,
@@ -781,18 +696,23 @@ var HindsightClient = class {
781
696
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
782
697
  );
783
698
  }
784
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
785
- 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) {
786
707
  const ctrl = new AbortController();
787
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
708
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
788
709
  try {
789
- const resp = await fetch(this.bankUrl("/reflect"), {
710
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
790
711
  method: "POST",
791
- headers: this.headers(),
792
712
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
793
713
  signal: ctrl.signal
794
714
  });
795
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
715
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
796
716
  const data = await resp.json();
797
717
  return (data.text || "").trim();
798
718
  } finally {
@@ -876,16 +796,18 @@ var HindsightClient = class {
876
796
  }));
877
797
  }
878
798
  /**
879
- * 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.
880
800
  *
881
801
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
882
802
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
883
803
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
884
804
  *
885
805
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
886
- * `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.
887
808
  */
888
- async seedPages() {
809
+ async seedPages(pageTrigger = buildPageTrigger()) {
810
+ const pages = pagesFor(this.project ?? this.bank);
889
811
  const existing = /* @__PURE__ */ new Map();
890
812
  let roots;
891
813
  try {
@@ -902,14 +824,14 @@ var HindsightClient = class {
902
824
  }
903
825
  let created = 0;
904
826
  let updated = 0;
905
- for (const page of PAGES) {
827
+ for (const page of pages) {
906
828
  const hit = existing.get(page.name.toLowerCase());
907
829
  const body = {
908
830
  name: page.name,
909
831
  source_query: page.source_query,
910
832
  tags: page.tags,
911
833
  max_tokens: PAGE_MAX_TOKENS,
912
- trigger: PAGE_TRIGGER
834
+ trigger: pageTrigger
913
835
  };
914
836
  if (!hit) {
915
837
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -938,7 +860,7 @@ var HindsightClient = class {
938
860
  }
939
861
  }
940
862
  this.log(
941
- `[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`
942
864
  );
943
865
  }
944
866
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -948,7 +870,8 @@ var HindsightClient = class {
948
870
  /**
949
871
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
950
872
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
951
- * 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.
952
875
  */
953
876
  async captureInitiative(args) {
954
877
  let pageId = args.relatesToPageId;
@@ -959,10 +882,7 @@ var HindsightClient = class {
959
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.`,
960
883
  parent_id: folderId,
961
884
  tags: ["knowledge:feature-work"],
962
- trigger: {
963
- fact_types: ["world", "experience", "observation"],
964
- refresh_after_consolidation: true
965
- }
885
+ trigger: args.pageTrigger ?? buildPageTrigger()
966
886
  });
967
887
  try {
968
888
  const j = await r.json();
@@ -971,43 +891,312 @@ var HindsightClient = class {
971
891
  }
972
892
  pageId ||= `initiative-${this.slugify(args.title)}`;
973
893
  }
974
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
975
- const content = `${verb}: ${args.title}. ${args.summary}`;
976
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
977
- const tags = [
978
- .../* @__PURE__ */ new Set([
979
- ...args.stamp?.tags ?? [],
980
- "knowledge:feature-work",
981
- `relatedPageId:${pageId}`
982
- ])
983
- ];
984
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
985
- await this.retain(content, "initiative marker", markerId, tags, "document", {
986
- metadata: args.stamp?.metadata
987
- });
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`);
988
1123
  } else {
989
- await this.retain(content, "initiative marker", markerId, tags, "document");
1124
+ out[key] = value;
990
1125
  }
991
- return { page_id: pageId };
992
1126
  }
993
- /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
994
- async ensureFolder(name) {
995
- try {
996
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
997
- const hit = (tree.roots || []).find(
998
- (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
999
- );
1000
- if (hit?.id) return hit.id;
1001
- } catch {
1002
- }
1003
- try {
1004
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1005
- return (await r.json()).id;
1006
- } catch {
1007
- return void 0;
1008
- }
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];
1009
1166
  }
1010
- };
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";
1011
1200
 
1012
1201
  // src/core/diag.ts
1013
1202
  import { appendFileSync as appendFileSync2 } from "fs";
@@ -1025,6 +1214,120 @@ function diag(harness, event, extra = {}) {
1025
1214
  }
1026
1215
  }
1027
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
+
1028
1331
  // node_modules/zod/v4/classic/external.js
1029
1332
  var external_exports = {};
1030
1333
  __export(external_exports, {
@@ -15542,16 +15845,16 @@ config(en_default());
15542
15845
  // src/core/knowledge-tools.ts
15543
15846
  import { existsSync as existsSync3 } from "fs";
15544
15847
  import { homedir as homedir4 } from "os";
15545
- import { join as join6 } from "path";
15848
+ import { join as join7 } from "path";
15546
15849
 
15547
15850
  // src/core/status.ts
15548
- import { execFileSync as execFileSync3 } from "child_process";
15851
+ import { execFileSync as execFileSync4 } from "child_process";
15549
15852
 
15550
15853
  // src/core/git.ts
15551
- import { execFileSync as execFileSync2 } from "child_process";
15854
+ import { execFileSync as execFileSync3 } from "child_process";
15552
15855
  import { resolve } from "path";
15553
15856
  function git(repo, ...args) {
15554
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15857
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15555
15858
  }
15556
15859
  function repoNameOf(repo) {
15557
15860
  return projectNameOf(resolve(repo));
@@ -15597,7 +15900,7 @@ function roster(pages) {
15597
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>".
15598
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.
15599
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>").
15600
- - 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.
15601
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).`;
15602
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";
15603
15906
  function toolGuide(opts) {
@@ -15624,11 +15927,11 @@ ${toolGuide(opts)}
15624
15927
  }
15625
15928
 
15626
15929
  // src/core/survey.ts
15627
- import { spawn as realSpawn2 } from "child_process";
15930
+ import { spawn as realSpawn3 } from "child_process";
15628
15931
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15629
15932
  import { homedir as homedir3 } from "os";
15630
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15631
- import { fileURLToPath as fileURLToPath2 } from "url";
15933
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15934
+ import { fileURLToPath as fileURLToPath3 } from "url";
15632
15935
  var SURVEY_DOC_IDS = [
15633
15936
  "repository-component-map",
15634
15937
  "repository-core-concepts",
@@ -15638,7 +15941,7 @@ var SURVEY_DOC_IDS = [
15638
15941
  function resolveClaudeBin(explicit) {
15639
15942
  if (explicit) return explicit;
15640
15943
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15641
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15944
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15642
15945
  try {
15643
15946
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15644
15947
  } catch {
@@ -15678,7 +15981,7 @@ function binExists(bin) {
15678
15981
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15679
15982
  if (!dir) continue;
15680
15983
  try {
15681
- accessSync(join5(dir, bin), constants.X_OK);
15984
+ accessSync(join6(dir, bin), constants.X_OK);
15682
15985
  return true;
15683
15986
  } catch {
15684
15987
  }
@@ -15722,7 +16025,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15722
16025
  hindsight: {
15723
16026
  command: "node",
15724
16027
  args: [opts.mcpServerPath],
15725
- 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" }
15726
16033
  }
15727
16034
  }
15728
16035
  });
@@ -15762,6 +16069,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15762
16069
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15763
16070
  "-c",
15764
16071
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16072
+ "-c",
16073
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15765
16074
  SURVEY_PROMPT
15766
16075
  ],
15767
16076
  env
@@ -15785,9 +16094,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15785
16094
  }
15786
16095
  function startCodebaseSurvey(repoDir, opts = {}) {
15787
16096
  try {
15788
- const spawnFn = opts.spawn ?? realSpawn2;
16097
+ const spawnFn = opts.spawn ?? realSpawn3;
15789
16098
  const exists = opts.exists ?? binExists;
15790
- 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");
15791
16100
  const preferred = opts.harness ?? "claude-code";
15792
16101
  const order = [
15793
16102
  preferred,
@@ -15826,7 +16135,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15826
16135
  var DEEPEN_DIFF_TARGET = 300;
15827
16136
  function commitCount(repoDir) {
15828
16137
  try {
15829
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16138
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15830
16139
  encoding: "utf8"
15831
16140
  });
15832
16141
  return Number(out.trim()) || 0;
@@ -15886,7 +16195,7 @@ function ok(value) {
15886
16195
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
15887
16196
  }
15888
16197
  function err(e) {
15889
- const message = String(e?.message ?? e);
16198
+ const message = describeError(e);
15890
16199
  return { content: [{ type: "text", text: JSON.stringify({ error: message }) }], isError: true };
15891
16200
  }
15892
16201
  function guarded(fn) {
@@ -15917,9 +16226,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15917
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.",
15918
16227
  inputSchema: {},
15919
16228
  handler: async (_args) => {
15920
- 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");
15921
16230
  const harness = opts.harness ?? "unknown";
15922
- const cfg = loadConfig({ harness: opts.harness });
16231
+ const cfg = applyBankConfig(
16232
+ loadConfig({ harness: opts.harness }),
16233
+ bankId,
16234
+ opts.repoDir
16235
+ ).cfg;
15923
16236
  return ok({
15924
16237
  bank_id: bankId,
15925
16238
  harness,
@@ -15931,6 +16244,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15931
16244
  api_token_configured: Boolean(cfg.apiToken),
15932
16245
  disabled: cfg.disabled
15933
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
+ },
15934
16255
  environment: {
15935
16256
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15936
16257
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15979,12 +16300,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15979
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>".`,
15980
16301
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15981
16302
  handler: guarded(
15982
- 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
+ })
15983
16307
  )
15984
16308
  },
15985
16309
  {
15986
16310
  name: "hindsight_capture_initiative",
15987
- 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.",
15988
16312
  inputSchema: {
15989
16313
  title: external_exports.string(),
15990
16314
  summary: external_exports.string(),
@@ -15995,7 +16319,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15995
16319
  title,
15996
16320
  summary,
15997
16321
  relatesToPageId: relates_to_page_id,
15998
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16322
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16323
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
15999
16324
  })
16000
16325
  )
16001
16326
  },
@@ -16202,7 +16527,7 @@ function resolversFor(ctx) {
16202
16527
  return {
16203
16528
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16204
16529
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16205
- gitProject: () => projectNameOf(ctx.directory),
16530
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16206
16531
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16207
16532
  harness: () => ctx.harness,
16208
16533
  bankId: () => ctx.bankId,
@@ -16248,11 +16573,6 @@ import { readFileSync as readFileSync4 } from "fs";
16248
16573
  // src/core/skill-sync.ts
16249
16574
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16250
16575
  import { homedir as homedir5 } from "os";
16251
- import { dirname as dirname5, join as join7 } from "path";
16252
- import { fileURLToPath as fileURLToPath3 } from "url";
16253
-
16254
- // src/core/daemon.ts
16255
- import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
16256
16576
  import { dirname as dirname6, join as join8 } from "path";
16257
16577
  import { fileURLToPath as fileURLToPath4 } from "url";
16258
16578
 
@@ -16343,7 +16663,7 @@ async function buildSessionStartContext(args) {
16343
16663
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16344
16664
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16345
16665
  const countCommitsSince = args.commitsSince ?? commitsSince;
16346
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16666
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16347
16667
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16348
16668
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16349
16669
  const recordSurveyBaseline = (sha) => {
@@ -16519,11 +16839,11 @@ async function buildHookOutput(args) {
16519
16839
  reflectAnswer = "";
16520
16840
  reflectFailed = true;
16521
16841
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
16522
- error: String(e?.message || e).slice(0, 200)
16842
+ error: describeError(e)
16523
16843
  });
16524
16844
  diag(harness, "reflect_failed", {
16525
16845
  ms: Date.now() - t0,
16526
- error: String(e?.message || e).slice(0, 200),
16846
+ error: describeError(e),
16527
16847
  query: prompt.slice(0, 80)
16528
16848
  });
16529
16849
  }
@@ -16542,7 +16862,7 @@ async function buildHookOutput(args) {
16542
16862
  client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
16543
16863
  {
16544
16864
  ms: Date.now() - t0,
16545
- error: String(e?.message || e).slice(0, 200)
16865
+ error: describeError(e)
16546
16866
  }
16547
16867
  );
16548
16868
  }
@@ -16619,6 +16939,9 @@ var RuntimeCore = class {
16619
16939
  return buildKnowledgeTools(this.client, this.bankId, {
16620
16940
  repoDir: this.projectDir,
16621
16941
  harness: this.harness,
16942
+ pageTrigger: buildPageTrigger(this.cfg),
16943
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16944
+ reflectBudget: this.cfg.reflectBudget,
16622
16945
  stampFor: () => buildRetainStamp(this.cfg, {
16623
16946
  directory: this.projectDir,
16624
16947
  harness: this.harness,
@@ -16637,6 +16960,7 @@ var RuntimeCore = class {
16637
16960
  */
16638
16961
  async seedIfCold(repoPath) {
16639
16962
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16963
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16640
16964
  try {
16641
16965
  const out = await buildSessionStartContext({
16642
16966
  cwd: repoPath || process.cwd(),
@@ -16738,7 +17062,7 @@ var RuntimeCore = class {
16738
17062
  turns = await this.fetchTranscript(sessionId);
16739
17063
  } catch (e) {
16740
17064
  diag(this.harness, "idle_fetch_failed", {
16741
- error: String(e?.message || e).slice(0, 200),
17065
+ error: describeError(e),
16742
17066
  session: sessionId
16743
17067
  });
16744
17068
  return;
@@ -16760,15 +17084,17 @@ var RuntimeCore = class {
16760
17084
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16761
17085
  retain(sessionId, turns, startTs, trigger = "turn") {
16762
17086
  const t0 = Date.now();
16763
- void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16764
- cursors: this.cursors,
16765
- stamp: buildRetainStamp(this.cfg, {
16766
- directory: this.projectDir,
16767
- harness: this.harness,
16768
- bankId: this.bankId,
16769
- 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
+ })
16770
17096
  })
16771
- }).then(
17097
+ ).then(
16772
17098
  () => diag(this.harness, "retain_ok", {
16773
17099
  ms: Date.now() - t0,
16774
17100
  turns: turns.length,
@@ -16778,7 +17104,7 @@ var RuntimeCore = class {
16778
17104
  ).catch(
16779
17105
  (e) => diag(this.harness, "retain_failed", {
16780
17106
  ms: Date.now() - t0,
16781
- error: String(e?.message || e).slice(0, 200),
17107
+ error: describeError(e),
16782
17108
  session: sessionId,
16783
17109
  trigger
16784
17110
  })
@@ -29366,23 +29692,10 @@ function resolveProjectDirectory(input) {
29366
29692
  function createPluginEntry(harness) {
29367
29693
  return async (input) => {
29368
29694
  const projectDir = resolveProjectDirectory(input);
29369
- let cfg = loadConfig({ harness });
29370
- if (cfg.disabled) return {};
29371
- const resolved = applyBankConfig(
29372
- cfg,
29373
- deriveBankId(cfg, projectDir || process.cwd(), harness),
29374
- projectDir || process.cwd()
29375
- );
29376
- cfg = resolved.cfg;
29377
- const bankId = resolved.bankId;
29695
+ const dir = projectDir || process.cwd();
29696
+ const { cfg, bankId, client } = resolveHostMemory(harness, dir);
29378
29697
  if (cfg.disabled) return {};
29379
- const client = new HindsightClient({
29380
- apiUrl: cfg.apiUrl,
29381
- apiToken: cfg.apiToken,
29382
- bank: bankId,
29383
- maxParallelRetains: cfg.maxParallelRetains
29384
- });
29385
- const core = new RuntimeCore(client, bankId, cfg, harness, projectDir || process.cwd());
29698
+ const core = new RuntimeCore(client, bankId, cfg, harness, dir);
29386
29699
  const oc = input?.client;
29387
29700
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
29388
29701
  if (oc?.tui?.showToast) {