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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.",
@@ -489,15 +322,28 @@ var PAGES = [
489
322
  },
490
323
  {
491
324
  name: "Initiatives and enhancements",
492
- source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
325
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
493
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_TAGS_MATCH = "all";
335
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
336
+ function buildPageTrigger(cfg = {}) {
337
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
338
+ switch (cfg.pageTriggerType) {
339
+ case "cron":
340
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
341
+ case "manual":
342
+ return { ...base, refresh_after_consolidation: false };
343
+ default:
344
+ return { ...base, refresh_after_consolidation: true };
345
+ }
346
+ }
501
347
  var CODING_BANK_TEMPLATE = {
502
348
  version: "1",
503
349
  bank: {
@@ -552,6 +398,7 @@ async function pool(items, n, fn, onError, onProgress) {
552
398
  }
553
399
 
554
400
  // src/core/hindsight.ts
401
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
555
402
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
556
403
  var RateLimitedError = class extends Error {
557
404
  constructor(retryAfterMs2) {
@@ -584,8 +431,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
584
431
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
585
432
  var HindsightClient = class {
586
433
  apiUrl;
587
- apiToken;
434
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
435
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
436
+ token;
437
+ tokenProvider;
588
438
  bank;
439
+ project;
589
440
  opIds = [];
590
441
  // async operation ids collected by retain(), for drain()
591
442
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -594,34 +445,81 @@ var HindsightClient = class {
594
445
  idempotentRetain;
595
446
  log;
596
447
  maxParallelRetains;
448
+ observationScopes;
597
449
  constructor(o) {
598
450
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
599
- this.apiToken = o.apiToken;
451
+ this.token = o.apiToken;
452
+ this.tokenProvider = o.tokenProvider;
600
453
  this.bank = o.bank;
454
+ this.project = o.project;
601
455
  this.log = o.log ?? (() => {
602
456
  });
603
457
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
458
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
459
+ }
460
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
461
+ get apiToken() {
462
+ return this.token;
604
463
  }
605
464
  headers() {
606
465
  const h = { "Content-Type": "application/json" };
607
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
466
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
608
467
  return h;
609
468
  }
469
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
470
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
471
+ * doubling every failing request. */
472
+ refreshToken() {
473
+ if (!this.tokenProvider) return false;
474
+ let next;
475
+ try {
476
+ next = this.tokenProvider();
477
+ } catch {
478
+ return false;
479
+ }
480
+ if (next === this.token) return false;
481
+ this.token = next;
482
+ return true;
483
+ }
484
+ /**
485
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
486
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
487
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
488
+ * not.
489
+ *
490
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
491
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
492
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
493
+ * bounds the whole call.
494
+ */
495
+ async fetchWithAuth(url3, init) {
496
+ const send = () => fetch(url3, { ...init, headers: this.headers() });
497
+ const r = await send();
498
+ if (r.status !== 401 || !this.refreshToken()) return r;
499
+ return send();
500
+ }
501
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
502
+ * server answers identically for both — only the client knows which it sent. */
503
+ authHint(status) {
504
+ if (status !== 401) return "";
505
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
506
+ }
610
507
  bankUrl(suffix = "") {
611
508
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
612
509
  }
613
510
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
614
511
  async req(method, url3, body, tolerate = []) {
615
- const r = await fetch(url3, {
512
+ const r = await this.fetchWithAuth(url3, {
616
513
  method,
617
- headers: this.headers(),
618
514
  body: body ? JSON.stringify(body) : void 0,
619
515
  signal: AbortSignal.timeout(15e3)
620
516
  });
621
517
  if (r.status === 429 && !tolerate.includes(429))
622
518
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
623
519
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
624
- throw new Error(`${method} ${url3} -> ${r.status} ${await r.text()}`);
520
+ throw new Error(
521
+ `${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
522
+ );
625
523
  return r;
626
524
  }
627
525
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -632,7 +530,11 @@ var HindsightClient = class {
632
530
  context,
633
531
  document_id: documentId,
634
532
  tags,
635
- strategy
533
+ strategy,
534
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
535
+ // observations were built under is a property of the write rather than of whichever server
536
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
537
+ observation_scopes: this.observationScopes
636
538
  };
637
539
  if (opts.timestamp) item.timestamp = opts.timestamp;
638
540
  if (opts.metadata) item.metadata = opts.metadata;
@@ -711,7 +613,7 @@ var HindsightClient = class {
711
613
  this.log(
712
614
  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
615
  );
714
- await this.seedPages();
616
+ await this.seedPages(opts.pageTrigger);
715
617
  }
716
618
  /**
717
619
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -769,7 +671,7 @@ var HindsightClient = class {
769
671
  let backoffMs = POLL_CYCLE_MS;
770
672
  await pool([...pending], this.maxParallelRetains, async (id) => {
771
673
  try {
772
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
674
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
773
675
  if (r.status === 429) {
774
676
  backoffMs = Math.min(
775
677
  RETRY_AFTER_CEILING_MS,
@@ -795,18 +697,23 @@ var HindsightClient = class {
795
697
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
796
698
  );
797
699
  }
798
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
799
- async reflect(query, opts = {}) {
700
+ /**
701
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
702
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
703
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
704
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
705
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
706
+ */
707
+ async reflect(query, opts) {
800
708
  const ctrl = new AbortController();
801
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
709
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
802
710
  try {
803
- const resp = await fetch(this.bankUrl("/reflect"), {
711
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
804
712
  method: "POST",
805
- headers: this.headers(),
806
713
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
807
714
  signal: ctrl.signal
808
715
  });
809
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
716
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
810
717
  const data = await resp.json();
811
718
  return (data.text || "").trim();
812
719
  } finally {
@@ -890,16 +797,18 @@ var HindsightClient = class {
890
797
  }));
891
798
  }
892
799
  /**
893
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
800
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
894
801
  *
895
802
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
896
803
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
897
804
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
898
805
  *
899
806
  * 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.
807
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
808
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
901
809
  */
902
- async seedPages() {
810
+ async seedPages(pageTrigger = buildPageTrigger()) {
811
+ const pages = pagesFor(this.project ?? this.bank);
903
812
  const existing = /* @__PURE__ */ new Map();
904
813
  let roots;
905
814
  try {
@@ -916,14 +825,14 @@ var HindsightClient = class {
916
825
  }
917
826
  let created = 0;
918
827
  let updated = 0;
919
- for (const page of PAGES) {
828
+ for (const page of pages) {
920
829
  const hit = existing.get(page.name.toLowerCase());
921
830
  const body = {
922
831
  name: page.name,
923
832
  source_query: page.source_query,
924
833
  tags: page.tags,
925
834
  max_tokens: PAGE_MAX_TOKENS,
926
- trigger: PAGE_TRIGGER
835
+ trigger: pageTrigger
927
836
  };
928
837
  if (!hit) {
929
838
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -935,11 +844,18 @@ var HindsightClient = class {
935
844
  return;
936
845
  }
937
846
  if (r.status !== 409) created++;
938
- } else if (hit.description !== page.source_query) {
847
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
848
+ const patch = {
849
+ trigger: pageTrigger
850
+ };
851
+ if (hit.description !== page.source_query) {
852
+ patch.source_query = page.source_query;
853
+ patch.tags = page.tags;
854
+ }
939
855
  const r = await this.req(
940
856
  "PATCH",
941
857
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
942
- { source_query: page.source_query, tags: page.tags }
858
+ patch
943
859
  );
944
860
  if ([404, 405, 501].includes(r.status)) {
945
861
  this.knowledgePagesSupported = false;
@@ -952,7 +868,7 @@ var HindsightClient = class {
952
868
  }
953
869
  }
954
870
  this.log(
955
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
871
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
956
872
  );
957
873
  }
958
874
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -960,9 +876,17 @@ var HindsightClient = class {
960
876
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
961
877
  }
962
878
  /**
963
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
964
- * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
965
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
879
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
880
+ * New initiative → creates a page under the Initiatives folder.
881
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
882
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
883
+ *
884
+ * The marker carries its page id in two places, neither of them a tag (#3641):
885
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
886
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
887
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
888
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
889
+ * vocabulary that exists to be matched with exact set-ops.
966
890
  */
967
891
  async captureInitiative(args) {
968
892
  let pageId = args.relatesToPageId;
@@ -973,10 +897,7 @@ var HindsightClient = class {
973
897
  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
898
  parent_id: folderId,
975
899
  tags: ["knowledge:feature-work"],
976
- trigger: {
977
- fact_types: ["world", "experience", "observation"],
978
- refresh_after_consolidation: true
979
- }
900
+ trigger: args.pageTrigger ?? buildPageTrigger()
980
901
  });
981
902
  try {
982
903
  const j = await r.json();
@@ -985,43 +906,303 @@ var HindsightClient = class {
985
906
  }
986
907
  pageId ||= `initiative-${this.slugify(args.title)}`;
987
908
  }
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
- });
909
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
910
+ const content = `${verb}: ${args.title}. ${args.summary}`;
911
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
912
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
913
+ const context = `initiative marker for [[page:${pageId}]]`;
914
+ await this.retain(content, context, markerId, tags, "document", {
915
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
916
+ });
917
+ return { page_id: pageId };
918
+ }
919
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
920
+ async ensureFolder(name) {
921
+ try {
922
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
923
+ const hit = (tree.roots || []).find(
924
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
925
+ );
926
+ if (hit?.id) return hit.id;
927
+ } catch {
928
+ }
929
+ try {
930
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
931
+ return (await r.json()).id;
932
+ } catch {
933
+ return void 0;
934
+ }
935
+ }
936
+ };
937
+
938
+ // src/core/config.ts
939
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
940
+ var DEFAULT_DAEMON_PORT = 9077;
941
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
942
+ function resolvePageTriggerType(raw) {
943
+ if (raw.pageTriggerType === "manual") return "manual";
944
+ if (raw.pageTriggerType === "cron") {
945
+ if (raw.pageTriggerCron?.trim()) return "cron";
946
+ log.warn(
947
+ "config",
948
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
949
+ );
950
+ }
951
+ return "auto-refresh";
952
+ }
953
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
954
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
955
+ function resolveReflectBudget(raw) {
956
+ const value = raw.reflectBudget;
957
+ if (value === void 0) return "high";
958
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
959
+ return value;
960
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
961
+ return "high";
962
+ }
963
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
964
+ function resolveObservationScopes(raw) {
965
+ const value = raw;
966
+ if (typeof value === "string")
967
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
968
+ if (Array.isArray(value)) {
969
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
970
+ if (scopes.length) return scopes;
971
+ }
972
+ return DEFAULT_OBSERVATION_SCOPES;
973
+ }
974
+ function resolveConfig(raw = {}) {
975
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
976
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
977
+ return {
978
+ serverMode,
979
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
980
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
981
+ // daemon needs no plumbing through eight separate constructors.
982
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
983
+ apiToken: raw.apiToken || void 0,
984
+ apiPort,
985
+ daemonIdleTimeout: raw.daemonIdleTimeout,
986
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
987
+ embedVersion: raw.embedVersion || void 0,
988
+ embedPackagePath: raw.embedPackagePath || void 0,
989
+ bankId: raw.bankId,
990
+ dynamicBankId: raw.dynamicBankId,
991
+ bankIdTemplate: raw.bankIdTemplate,
992
+ mapPathToBank: raw.mapPathToBank,
993
+ resolveWorktrees: raw.resolveWorktrees,
994
+ optInOnly: raw.optInOnly ?? false,
995
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
996
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
997
+ harness: raw.harness ?? "opencode",
998
+ disabled: raw.disabled ?? false,
999
+ retainSessions: raw.retainSessions ?? true,
1000
+ // write sessions back by default, every harness
1001
+ maxParallelRetains: raw.maxParallelRetains || 10,
1002
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1003
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1004
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1005
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1006
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1007
+ reflectBudget: resolveReflectBudget(raw),
1008
+ autoReflect: raw.autoReflect ?? true,
1009
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1010
+ pageTriggerType: resolvePageTriggerType(raw),
1011
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1012
+ autoSeed: raw.autoSeed ?? true,
1013
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1014
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1015
+ surveyModel: raw.surveyModel || "haiku",
1016
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1017
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1018
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1019
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1020
+ // nested object cannot reach the API as a tag and fail the whole retain.
1021
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1022
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1023
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1024
+ ) : {},
1025
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1026
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1027
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1028
+ };
1029
+ }
1030
+ function readRaw(path) {
1031
+ try {
1032
+ return JSON.parse(readFileSync(path, "utf8"));
1033
+ } catch (e) {
1034
+ if (e?.code !== "ENOENT") {
1035
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1036
+ }
1037
+ return {};
1038
+ }
1039
+ }
1040
+ function mergeRaw(a, b) {
1041
+ const { harnesses: _drop, ...flat } = b;
1042
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1043
+ }
1044
+ function applyLayer(raw, layer, harness) {
1045
+ let out = mergeRaw(raw, layer);
1046
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1047
+ if (perHarness) out = mergeRaw(out, perHarness);
1048
+ return out;
1049
+ }
1050
+ var ENV_KEYS = {
1051
+ serverMode: "HINDSIGHT_SERVER_MODE",
1052
+ apiUrl: "HINDSIGHT_API_URL",
1053
+ apiToken: "HINDSIGHT_API_TOKEN",
1054
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1055
+ // it can carry their existing environment over unchanged.
1056
+ apiPort: "HINDSIGHT_API_PORT",
1057
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1058
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1059
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1060
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1061
+ bankId: "HINDSIGHT_BANK_ID",
1062
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1063
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1064
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1065
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1066
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1067
+ harness: "HINDSIGHT_HARNESS",
1068
+ disabled: "HINDSIGHT_DISABLED",
1069
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1070
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1071
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1072
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1073
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1074
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1075
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1076
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1077
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1078
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1079
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1080
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1081
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1082
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1083
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1084
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1085
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1086
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1087
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1088
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1089
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1090
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1091
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1092
+ };
1093
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1094
+ "dynamicBankId",
1095
+ "resolveWorktrees",
1096
+ "optInOnly",
1097
+ "disabled",
1098
+ "retainSessions",
1099
+ "autoReflect",
1100
+ "autoSeed",
1101
+ "codebaseSurvey"
1102
+ ]);
1103
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1104
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1105
+ "apiPort",
1106
+ "daemonIdleTimeout",
1107
+ "maxParallelRetains",
1108
+ "reflectTimeoutMs",
1109
+ "reflectToolTimeoutMs",
1110
+ "pageRefreshEveryTurns",
1111
+ "seedLimit",
1112
+ "surveyBudgetUsd",
1113
+ "surveyRefreshCommits"
1114
+ ]);
1115
+ function readEnvConfig(env = process.env) {
1116
+ const out = {};
1117
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1118
+ const value = env[name];
1119
+ if (value === void 0 || value.trim() === "") continue;
1120
+ if (ENV_BOOLEANS.has(key)) {
1121
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1122
+ } else if (ENV_LISTS.has(key)) {
1123
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1124
+ if (items.length) out[key] = items;
1125
+ } else if (ENV_NUMBERS.has(key)) {
1126
+ const n = Number(value);
1127
+ if (Number.isFinite(n)) out[key] = n;
1128
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1002
1129
  } else {
1003
- await this.retain(content, "initiative marker", markerId, tags, "document");
1130
+ out[key] = value;
1004
1131
  }
1005
- return { page_id: pageId };
1006
1132
  }
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
- }
1133
+ return out;
1134
+ }
1135
+ function loadConfig(opts = {}) {
1136
+ const o = typeof opts === "string" ? { path: opts } : opts;
1137
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1138
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1139
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1140
+ return resolveConfig(raw);
1141
+ }
1142
+ var BANK_OVERRIDE_EXCLUDED = [
1143
+ "bankId",
1144
+ "bankIdTemplate",
1145
+ "mapPathToBank",
1146
+ "dynamicBankId",
1147
+ "resolveWorktrees",
1148
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1149
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1150
+ "optInOnly",
1151
+ "optInPaths",
1152
+ "harness"
1153
+ ];
1154
+ function applyBankConfig(cfg, resolvedId, directory) {
1155
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1156
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1157
+ const section = cfg.banks[resolvedId];
1158
+ if (!section) return { cfg, bankId: resolvedId };
1159
+ const safe = { ...section };
1160
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1161
+ delete safe.banks;
1162
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1163
+ delete safe.bank;
1164
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1165
+ }
1166
+ function resolvePartial(cfg, patch) {
1167
+ const full = resolveConfig(patch);
1168
+ const out = {};
1169
+ for (const key of Object.keys(patch)) {
1170
+ if (key in full)
1171
+ out[key] = full[key];
1023
1172
  }
1024
- };
1173
+ return out;
1174
+ }
1175
+
1176
+ // src/core/host-client.ts
1177
+ function resolveHostConfig(harness, directory) {
1178
+ const cfg0 = loadConfig({ harness });
1179
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1180
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1181
+ }
1182
+ function resolveHostMemory(harness, directory) {
1183
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
1184
+ return {
1185
+ cfg,
1186
+ bankId,
1187
+ client: new HindsightClient({
1188
+ apiUrl: cfg.apiUrl,
1189
+ apiToken: cfg.apiToken,
1190
+ bank: bankId,
1191
+ maxParallelRetains: cfg.maxParallelRetains,
1192
+ observationScopes: cfg.observationScopes,
1193
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
1194
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
1195
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
1196
+ // honoured on re-resolution exactly as it was on the first one.
1197
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
1198
+ })
1199
+ };
1200
+ }
1201
+
1202
+ // src/core/daemon.ts
1203
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1204
+ import { dirname as dirname4, join as join5 } from "path";
1205
+ import { fileURLToPath as fileURLToPath2 } from "url";
1025
1206
 
1026
1207
  // src/core/diag.ts
1027
1208
  import { appendFileSync as appendFileSync2 } from "fs";
@@ -1039,6 +1220,120 @@ function diag(harness, event, extra = {}) {
1039
1220
  }
1040
1221
  }
1041
1222
 
1223
+ // src/core/daemon.ts
1224
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
1225
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
1226
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1227
+ try {
1228
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
1229
+ return res.ok;
1230
+ } catch {
1231
+ return false;
1232
+ }
1233
+ }
1234
+ function hasRustToolchain() {
1235
+ if (process.platform !== "darwin") return true;
1236
+ try {
1237
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
1238
+ return true;
1239
+ } catch {
1240
+ return false;
1241
+ }
1242
+ }
1243
+ function hasUvx() {
1244
+ try {
1245
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
1246
+ return true;
1247
+ } catch {
1248
+ return false;
1249
+ }
1250
+ }
1251
+ var PROVIDER_PROBES = [
1252
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
1253
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
1254
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
1255
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
1256
+ ];
1257
+ function detectLlm(env = process.env) {
1258
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
1259
+ if (explicit) {
1260
+ return {
1261
+ provider: explicit,
1262
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
1263
+ source: "HINDSIGHT_API_LLM_PROVIDER"
1264
+ };
1265
+ }
1266
+ for (const probe of PROVIDER_PROBES) {
1267
+ const key = env[probe.keyEnv]?.trim();
1268
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
1269
+ }
1270
+ if (onPath("claude")) {
1271
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
1272
+ }
1273
+ return void 0;
1274
+ }
1275
+ function onPath(bin) {
1276
+ try {
1277
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
1278
+ return true;
1279
+ } catch {
1280
+ return false;
1281
+ }
1282
+ }
1283
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1284
+ try {
1285
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1286
+ const child = spawnFn("node", [starter, "--harness", harness], {
1287
+ detached: true,
1288
+ stdio: "ignore"
1289
+ });
1290
+ child.on("error", () => {
1291
+ });
1292
+ child.unref();
1293
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
1294
+ } catch {
1295
+ }
1296
+ }
1297
+ async function ensureDaemon(cfg, harness, opts = {}) {
1298
+ if (cfg.serverMode !== "daemon") return;
1299
+ if (await isServerHealthy(cfg.apiUrl)) return;
1300
+ if (!preflightDaemon(cfg, harness)) return;
1301
+ startDaemonDetached(cfg, harness, opts.spawnFn);
1302
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
1303
+ }
1304
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1305
+ const deadline = Date.now() + budgetMs;
1306
+ while (Date.now() < deadline) {
1307
+ await new Promise((r) => setTimeout(r, pollMs));
1308
+ if (await isServerHealthy(baseUrl)) return true;
1309
+ }
1310
+ return false;
1311
+ }
1312
+ function preflightDaemon(cfg, harness) {
1313
+ if (!hasUvx()) {
1314
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
1315
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
1316
+ return false;
1317
+ }
1318
+ if (!hasRustToolchain()) {
1319
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
1320
+ log.warn(
1321
+ harness,
1322
+ "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`"
1323
+ );
1324
+ return false;
1325
+ }
1326
+ if (!detectLlm()) {
1327
+ diag(harness, "daemon_no_llm", {});
1328
+ log.warn(
1329
+ harness,
1330
+ "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"
1331
+ );
1332
+ return false;
1333
+ }
1334
+ return true;
1335
+ }
1336
+
1042
1337
  // node_modules/zod/v4/classic/external.js
1043
1338
  var external_exports = {};
1044
1339
  __export(external_exports, {
@@ -15556,16 +15851,16 @@ config(en_default());
15556
15851
  // src/core/knowledge-tools.ts
15557
15852
  import { existsSync as existsSync3 } from "fs";
15558
15853
  import { homedir as homedir4 } from "os";
15559
- import { join as join6 } from "path";
15854
+ import { join as join7 } from "path";
15560
15855
 
15561
15856
  // src/core/status.ts
15562
- import { execFileSync as execFileSync3 } from "child_process";
15857
+ import { execFileSync as execFileSync4 } from "child_process";
15563
15858
 
15564
15859
  // src/core/git.ts
15565
- import { execFileSync as execFileSync2 } from "child_process";
15860
+ import { execFileSync as execFileSync3 } from "child_process";
15566
15861
  import { resolve } from "path";
15567
15862
  function git(repo, ...args) {
15568
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15863
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15569
15864
  }
15570
15865
  function repoNameOf(repo) {
15571
15866
  return projectNameOf(resolve(repo));
@@ -15611,7 +15906,7 @@ function roster(pages) {
15611
15906
  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
15907
  - 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
15908
  - 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.
15909
+ - 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
15910
  - 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
15911
  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
15912
  function toolGuide(opts) {
@@ -15638,11 +15933,11 @@ ${toolGuide(opts)}
15638
15933
  }
15639
15934
 
15640
15935
  // src/core/survey.ts
15641
- import { spawn as realSpawn2 } from "child_process";
15936
+ import { spawn as realSpawn3 } from "child_process";
15642
15937
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15643
15938
  import { homedir as homedir3 } from "os";
15644
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15645
- import { fileURLToPath as fileURLToPath2 } from "url";
15939
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15940
+ import { fileURLToPath as fileURLToPath3 } from "url";
15646
15941
  var SURVEY_DOC_IDS = [
15647
15942
  "repository-component-map",
15648
15943
  "repository-core-concepts",
@@ -15652,7 +15947,7 @@ var SURVEY_DOC_IDS = [
15652
15947
  function resolveClaudeBin(explicit) {
15653
15948
  if (explicit) return explicit;
15654
15949
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15655
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15950
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15656
15951
  try {
15657
15952
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15658
15953
  } catch {
@@ -15692,7 +15987,7 @@ function binExists(bin) {
15692
15987
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15693
15988
  if (!dir) continue;
15694
15989
  try {
15695
- accessSync(join5(dir, bin), constants.X_OK);
15990
+ accessSync(join6(dir, bin), constants.X_OK);
15696
15991
  return true;
15697
15992
  } catch {
15698
15993
  }
@@ -15736,7 +16031,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15736
16031
  hindsight: {
15737
16032
  command: "node",
15738
16033
  args: [opts.mcpServerPath],
15739
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16034
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16035
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16036
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16037
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16038
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15740
16039
  }
15741
16040
  }
15742
16041
  });
@@ -15776,6 +16075,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15776
16075
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15777
16076
  "-c",
15778
16077
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16078
+ "-c",
16079
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15779
16080
  SURVEY_PROMPT
15780
16081
  ],
15781
16082
  env
@@ -15799,9 +16100,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15799
16100
  }
15800
16101
  function startCodebaseSurvey(repoDir, opts = {}) {
15801
16102
  try {
15802
- const spawnFn = opts.spawn ?? realSpawn2;
16103
+ const spawnFn = opts.spawn ?? realSpawn3;
15803
16104
  const exists = opts.exists ?? binExists;
15804
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16105
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15805
16106
  const preferred = opts.harness ?? "claude-code";
15806
16107
  const order = [
15807
16108
  preferred,
@@ -15840,7 +16141,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15840
16141
  var DEEPEN_DIFF_TARGET = 300;
15841
16142
  function commitCount(repoDir) {
15842
16143
  try {
15843
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16144
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15844
16145
  encoding: "utf8"
15845
16146
  });
15846
16147
  return Number(out.trim()) || 0;
@@ -15931,9 +16232,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15931
16232
  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
16233
  inputSchema: {},
15933
16234
  handler: async (_args) => {
15934
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16235
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15935
16236
  const harness = opts.harness ?? "unknown";
15936
- const cfg = loadConfig({ harness: opts.harness });
16237
+ const cfg = applyBankConfig(
16238
+ loadConfig({ harness: opts.harness }),
16239
+ bankId,
16240
+ opts.repoDir
16241
+ ).cfg;
15937
16242
  return ok({
15938
16243
  bank_id: bankId,
15939
16244
  harness,
@@ -15945,6 +16250,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15945
16250
  api_token_configured: Boolean(cfg.apiToken),
15946
16251
  disabled: cfg.disabled
15947
16252
  },
16253
+ // What the LIVE client is signing with, which is not the same question as what the file
16254
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16255
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16256
+ // value is never returned.
16257
+ credential: {
16258
+ api_token_in_use: Boolean(client.apiToken),
16259
+ api_token_matches_config: client.apiToken === cfg.apiToken
16260
+ },
15948
16261
  environment: {
15949
16262
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15950
16263
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15993,12 +16306,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15993
16306
  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
16307
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15995
16308
  handler: guarded(
15996
- async ({ query }) => client.reflect(query, { budget: "high" })
16309
+ async ({ query }) => client.reflect(query, {
16310
+ budget: opts.reflectBudget ?? "high",
16311
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16312
+ })
15997
16313
  )
15998
16314
  },
15999
16315
  {
16000
16316
  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.",
16317
+ 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
16318
  inputSchema: {
16003
16319
  title: external_exports.string(),
16004
16320
  summary: external_exports.string(),
@@ -16009,7 +16325,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16009
16325
  title,
16010
16326
  summary,
16011
16327
  relatesToPageId: relates_to_page_id,
16012
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16328
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16329
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
16013
16330
  })
16014
16331
  )
16015
16332
  },
@@ -16216,7 +16533,7 @@ function resolversFor(ctx) {
16216
16533
  return {
16217
16534
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16218
16535
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16219
- gitProject: () => projectNameOf(ctx.directory),
16536
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16220
16537
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16221
16538
  harness: () => ctx.harness,
16222
16539
  bankId: () => ctx.bankId,
@@ -16262,11 +16579,6 @@ import { readFileSync as readFileSync4 } from "fs";
16262
16579
  // src/core/skill-sync.ts
16263
16580
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16264
16581
  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
16582
  import { dirname as dirname6, join as join8 } from "path";
16271
16583
  import { fileURLToPath as fileURLToPath4 } from "url";
16272
16584
 
@@ -16357,7 +16669,7 @@ async function buildSessionStartContext(args) {
16357
16669
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16358
16670
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16359
16671
  const countCommitsSince = args.commitsSince ?? commitsSince;
16360
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16672
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16361
16673
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16362
16674
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16363
16675
  const recordSurveyBaseline = (sha) => {
@@ -16633,6 +16945,9 @@ var RuntimeCore = class {
16633
16945
  return buildKnowledgeTools(this.client, this.bankId, {
16634
16946
  repoDir: this.projectDir,
16635
16947
  harness: this.harness,
16948
+ pageTrigger: buildPageTrigger(this.cfg),
16949
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16950
+ reflectBudget: this.cfg.reflectBudget,
16636
16951
  stampFor: () => buildRetainStamp(this.cfg, {
16637
16952
  directory: this.projectDir,
16638
16953
  harness: this.harness,
@@ -16651,6 +16966,7 @@ var RuntimeCore = class {
16651
16966
  */
16652
16967
  async seedIfCold(repoPath) {
16653
16968
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16969
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16654
16970
  try {
16655
16971
  const out = await buildSessionStartContext({
16656
16972
  cwd: repoPath || process.cwd(),
@@ -16774,15 +17090,17 @@ var RuntimeCore = class {
16774
17090
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16775
17091
  retain(sessionId, turns, startTs, trigger = "turn") {
16776
17092
  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
17093
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17094
+ () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
17095
+ cursors: this.cursors,
17096
+ stamp: buildRetainStamp(this.cfg, {
17097
+ directory: this.projectDir,
17098
+ harness: this.harness,
17099
+ bankId: this.bankId,
17100
+ sessionId
17101
+ })
16784
17102
  })
16785
- }).then(
17103
+ ).then(
16786
17104
  () => diag(this.harness, "retain_ok", {
16787
17105
  ms: Date.now() - t0,
16788
17106
  turns: turns.length,
@@ -29380,23 +29698,10 @@ function resolveProjectDirectory(input) {
29380
29698
  function createPluginEntry(harness) {
29381
29699
  return async (input) => {
29382
29700
  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;
29701
+ const dir = projectDir || process.cwd();
29702
+ const { cfg, bankId, client } = resolveHostMemory(harness, dir);
29392
29703
  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());
29704
+ const core = new RuntimeCore(client, bankId, cfg, harness, dir);
29400
29705
  const oc = input?.client;
29401
29706
  log.debug(harness, "toast channel", { wired: Boolean(oc?.tui?.showToast) });
29402
29707
  if (oc?.tui?.showToast) {