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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cline.js CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
  // src/core/config.ts
8
8
  import { readFileSync } from "fs";
9
9
  import { homedir as homedir2 } from "os";
10
- import { join as join3 } from "path";
10
+ import { join as join4 } from "path";
11
11
 
12
12
  // src/core/seed.ts
13
13
  import { spawn as realSpawn } from "child_process";
@@ -79,8 +79,8 @@ function getProjectRootFromGit(directory) {
79
79
  return null;
80
80
  }
81
81
  }
82
- function projectNameOf(directory) {
83
- return gitProjectName(directory, true);
82
+ function projectNameOf(directory, sessionRoot) {
83
+ return gitProjectName(directory, true, sessionRoot);
84
84
  }
85
85
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
86
86
  function nearestExistingDir(directory) {
@@ -96,18 +96,24 @@ function nearestExistingDir(directory) {
96
96
  function dirName(directory) {
97
97
  return directory && basename(directory) || "unknown";
98
98
  }
99
- function gitProjectName(directory, resolveWorktrees) {
99
+ function mainWorktreeRoot(directory, sessionRoot = "") {
100
+ const candidates = [
101
+ nearestExistingDir(directory),
102
+ sessionRoot,
103
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
104
+ ];
105
+ for (const candidate of candidates) {
106
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
107
+ if (root) return root;
108
+ }
109
+ return null;
110
+ }
111
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
100
112
  if (resolveWorktrees) {
101
- const candidates = [
102
- nearestExistingDir(directory),
103
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
104
- ];
105
- for (const candidate of candidates) {
106
- const root = candidate ? getProjectRootFromGit(candidate) : null;
107
- if (root) return basename(root);
108
- }
113
+ const root = mainWorktreeRoot(directory, sessionRoot);
114
+ if (root) return basename(root);
109
115
  }
110
- return dirName(directory);
116
+ return dirName(sessionRoot || directory);
111
117
  }
112
118
  function configuredDir(dir) {
113
119
  const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
@@ -127,218 +133,89 @@ function mapLookup(map2, directory) {
127
133
  }
128
134
  return best?.bank;
129
135
  }
136
+ function lookupDirectories(config2, directory, sessionRoot = "") {
137
+ const directories = [normalize(directory)];
138
+ if (config2.resolveWorktrees ?? true) {
139
+ const root = mainWorktreeRoot(directory, sessionRoot);
140
+ const normalizedRoot = root ? normalize(root) : "";
141
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
142
+ }
143
+ return directories;
144
+ }
130
145
  function isOptedIn(config2, directory) {
131
146
  if (!config2.optInOnly) return true;
132
147
  if (!directory) return false;
133
- const cwd = normalize(directory);
134
- if ((config2.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
148
+ const directories = lookupDirectories(config2, directory);
149
+ if (directories.some(
150
+ (candidate) => (config2.optInPaths ?? []).some(
151
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
152
+ )
153
+ ))
135
154
  return true;
136
- return Boolean(config2.mapPathToBank && mapLookup(config2.mapPathToBank, directory));
155
+ const pathMap = config2.mapPathToBank;
156
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
137
157
  }
138
- function deriveBankId(config2, directory, harness = "coding") {
139
- const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
158
+ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
159
+ const pathMap = config2.mapPathToBank;
160
+ const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
140
161
  if (mapped) return mapped;
141
162
  const dynamic = config2.dynamicBankId ?? !config2.bankId;
142
163
  if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
143
164
  const resolvers = {
144
165
  harness: () => harness,
145
166
  project: () => dirName(directory),
146
- gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
167
+ gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot),
147
168
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
148
169
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
149
170
  };
150
171
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
151
172
  }
152
173
 
153
- // src/core/config.ts
154
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
155
- var DEFAULT_DAEMON_PORT = 9077;
156
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
157
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
158
- function resolveConfig(raw = {}) {
159
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
160
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
161
- return {
162
- serverMode,
163
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
164
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
165
- // daemon needs no plumbing through eight separate constructors.
166
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
167
- apiToken: raw.apiToken || void 0,
168
- apiPort,
169
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
170
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
171
- embedVersion: raw.embedVersion || void 0,
172
- embedPackagePath: raw.embedPackagePath || void 0,
173
- bankId: raw.bankId,
174
- dynamicBankId: raw.dynamicBankId,
175
- bankIdTemplate: raw.bankIdTemplate,
176
- mapPathToBank: raw.mapPathToBank,
177
- resolveWorktrees: raw.resolveWorktrees,
178
- optInOnly: raw.optInOnly ?? false,
179
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
180
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
181
- harness: raw.harness ?? "opencode",
182
- disabled: raw.disabled ?? false,
183
- retainSessions: raw.retainSessions ?? true,
184
- // opencode: write back by default (parity with hook-harness Stop)
185
- maxParallelRetains: raw.maxParallelRetains || 10,
186
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
187
- autoReflect: raw.autoReflect ?? true,
188
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
189
- autoSeed: raw.autoSeed ?? true,
190
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
191
- codebaseSurvey: raw.codebaseSurvey ?? true,
192
- surveyModel: raw.surveyModel || "haiku",
193
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
194
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
195
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
196
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
197
- // nested object cannot reach the API as a tag and fail the whole retain.
198
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
199
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
200
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
201
- ) : {},
202
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
203
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
204
- };
174
+ // src/core/log.ts
175
+ import { appendFileSync, mkdirSync } from "fs";
176
+ import { tmpdir } from "os";
177
+ import { dirname as dirname3, join as join3 } from "path";
178
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
179
+ var current = ["debug", "info", "warn", "error"].find(
180
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
181
+ ) ?? "info";
182
+ function setLogLevel(level) {
183
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
205
184
  }
206
- function readRaw(path) {
185
+ function logFilePath() {
186
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
187
+ }
188
+ function write(level, scope, msg, extra) {
189
+ if (WEIGHT[level] < WEIGHT[current]) return;
207
190
  try {
208
- return JSON.parse(readFileSync(path, "utf8"));
209
- } catch (e) {
210
- if (e?.code !== "ENOENT") {
211
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
212
- }
213
- return {};
191
+ const file2 = logFilePath();
192
+ mkdirSync(dirname3(file2), { recursive: true });
193
+ appendFileSync(
194
+ file2,
195
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
196
+ );
197
+ } catch {
214
198
  }
215
199
  }
216
- function mergeRaw(a, b) {
217
- const { harnesses: _drop, ...flat } = b;
218
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
219
- }
220
- function applyLayer(raw, layer, harness) {
221
- let out = mergeRaw(raw, layer);
222
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
223
- if (perHarness) out = mergeRaw(out, perHarness);
224
- return out;
225
- }
226
- var ENV_KEYS = {
227
- serverMode: "HINDSIGHT_SERVER_MODE",
228
- apiUrl: "HINDSIGHT_API_URL",
229
- apiToken: "HINDSIGHT_API_TOKEN",
230
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
231
- // it can carry their existing environment over unchanged.
232
- apiPort: "HINDSIGHT_API_PORT",
233
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
234
- embedVersion: "HINDSIGHT_EMBED_VERSION",
235
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
236
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
237
- bankId: "HINDSIGHT_BANK_ID",
238
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
239
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
240
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
241
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
242
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
243
- harness: "HINDSIGHT_HARNESS",
244
- disabled: "HINDSIGHT_DISABLED",
245
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
246
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
247
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
248
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
249
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
250
- autoSeed: "HINDSIGHT_AUTO_SEED",
251
- seedLimit: "HINDSIGHT_SEED_LIMIT",
252
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
253
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
254
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
255
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
256
- logLevel: "HINDSIGHT_LOG_LEVEL",
257
- gitIngest: "HINDSIGHT_GIT_INGEST",
258
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
259
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
260
- retainTags: "HINDSIGHT_RETAIN_TAGS"
200
+ var log = {
201
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
202
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
203
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
204
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
261
205
  };
262
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
263
- "dynamicBankId",
264
- "resolveWorktrees",
265
- "optInOnly",
266
- "disabled",
267
- "retainSessions",
268
- "autoReflect",
269
- "autoSeed",
270
- "codebaseSurvey"
271
- ]);
272
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
273
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
274
- "apiPort",
275
- "daemonIdleTimeout",
276
- "maxParallelRetains",
277
- "reflectTimeoutMs",
278
- "pageRefreshEveryTurns",
279
- "seedLimit",
280
- "surveyBudgetUsd",
281
- "surveyRefreshCommits"
282
- ]);
283
- function readEnvConfig(env = process.env) {
284
- const out = {};
285
- for (const [key, name] of Object.entries(ENV_KEYS)) {
286
- const value = env[name];
287
- if (value === void 0 || value.trim() === "") continue;
288
- if (ENV_BOOLEANS.has(key)) {
289
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
290
- } else if (ENV_LISTS.has(key)) {
291
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
292
- if (items.length) out[key] = items;
293
- } else if (ENV_NUMBERS.has(key)) {
294
- const n = Number(value);
295
- if (Number.isFinite(n)) out[key] = n;
296
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
297
- } else {
298
- out[key] = value;
299
- }
300
- }
301
- return out;
302
- }
303
- function loadConfig(opts = {}) {
304
- const o = typeof opts === "string" ? { path: opts } : opts;
305
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
306
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
307
- if (!raw.harness && o.harness) raw.harness = o.harness;
308
- return resolveConfig(raw);
309
- }
310
- var BANK_OVERRIDE_EXCLUDED = [
311
- "bankId",
312
- "bankIdTemplate",
313
- "mapPathToBank",
314
- "dynamicBankId",
315
- "resolveWorktrees",
316
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
317
- // only ever arrive too late to matter — strip them rather than let them read as effective.
318
- "optInOnly",
319
- "optInPaths",
320
- "harness"
321
- ];
322
- function applyBankConfig(cfg, resolvedId, directory) {
323
- if (directory !== void 0 && !isOptedIn(cfg, directory))
324
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
325
- const section = cfg.banks[resolvedId];
326
- if (!section) return { cfg, bankId: resolvedId };
327
- const safe = { ...section };
328
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
329
- delete safe.banks;
330
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
331
- delete safe.bank;
332
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
333
- }
334
- function resolvePartial(cfg, patch) {
335
- const full = resolveConfig(patch);
336
- const out = {};
337
- for (const key of Object.keys(patch)) {
338
- if (key in full)
339
- out[key] = full[key];
206
+ function describeError(value, maxChars = 200) {
207
+ const parts = [];
208
+ const seen = /* @__PURE__ */ new Set();
209
+ let current2 = value;
210
+ while (current2 && !seen.has(current2)) {
211
+ seen.add(current2);
212
+ const error51 = current2;
213
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
214
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
215
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
216
+ current2 = error51.cause;
340
217
  }
341
- return out;
218
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
342
219
  }
343
220
 
344
221
  // src/core/missions.ts
@@ -416,7 +293,10 @@ var KNOWLEDGE_LABELS = {
416
293
  }
417
294
  ]
418
295
  };
419
- var PAGES = [
296
+ function pageScopeRule(project) {
297
+ 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.`;
298
+ }
299
+ var PAGE_TAXONOMY = [
420
300
  {
421
301
  name: "Component map",
422
302
  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.",
@@ -443,11 +323,23 @@ var PAGES = [
443
323
  tags: ["knowledge:feature-work"]
444
324
  }
445
325
  ];
326
+ function pagesFor(project) {
327
+ const scope = pageScopeRule(project);
328
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
329
+ }
446
330
  var PAGE_MAX_TOKENS = 4096;
447
- var PAGE_TRIGGER = {
448
- fact_types: ["world", "experience", "observation"],
449
- refresh_after_consolidation: true
450
- };
331
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
332
+ function buildPageTrigger(cfg = {}) {
333
+ const base = { fact_types: PAGE_FACT_TYPES };
334
+ switch (cfg.pageTriggerType) {
335
+ case "cron":
336
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
337
+ case "manual":
338
+ return { ...base, refresh_after_consolidation: false };
339
+ default:
340
+ return { ...base, refresh_after_consolidation: true };
341
+ }
342
+ }
451
343
  var CODING_BANK_TEMPLATE = {
452
344
  version: "1",
453
345
  bank: {
@@ -502,6 +394,7 @@ async function pool(items, n, fn, onError, onProgress) {
502
394
  }
503
395
 
504
396
  // src/core/hindsight.ts
397
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
505
398
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
506
399
  var RateLimitedError = class extends Error {
507
400
  constructor(retryAfterMs2) {
@@ -534,8 +427,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
534
427
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
535
428
  var HindsightClient = class {
536
429
  apiUrl;
537
- apiToken;
430
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
431
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
432
+ token;
433
+ tokenProvider;
538
434
  bank;
435
+ project;
539
436
  opIds = [];
540
437
  // async operation ids collected by retain(), for drain()
541
438
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -544,34 +441,81 @@ var HindsightClient = class {
544
441
  idempotentRetain;
545
442
  log;
546
443
  maxParallelRetains;
444
+ observationScopes;
547
445
  constructor(o) {
548
446
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
549
- this.apiToken = o.apiToken;
447
+ this.token = o.apiToken;
448
+ this.tokenProvider = o.tokenProvider;
550
449
  this.bank = o.bank;
450
+ this.project = o.project;
551
451
  this.log = o.log ?? (() => {
552
452
  });
553
453
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
454
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
455
+ }
456
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
457
+ get apiToken() {
458
+ return this.token;
554
459
  }
555
460
  headers() {
556
461
  const h = { "Content-Type": "application/json" };
557
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
462
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
558
463
  return h;
559
464
  }
465
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
466
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
467
+ * doubling every failing request. */
468
+ refreshToken() {
469
+ if (!this.tokenProvider) return false;
470
+ let next;
471
+ try {
472
+ next = this.tokenProvider();
473
+ } catch {
474
+ return false;
475
+ }
476
+ if (next === this.token) return false;
477
+ this.token = next;
478
+ return true;
479
+ }
480
+ /**
481
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
482
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
483
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
484
+ * not.
485
+ *
486
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
487
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
488
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
489
+ * bounds the whole call.
490
+ */
491
+ async fetchWithAuth(url2, init) {
492
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
493
+ const r = await send();
494
+ if (r.status !== 401 || !this.refreshToken()) return r;
495
+ return send();
496
+ }
497
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
498
+ * server answers identically for both — only the client knows which it sent. */
499
+ authHint(status) {
500
+ if (status !== 401) return "";
501
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
502
+ }
560
503
  bankUrl(suffix = "") {
561
504
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
562
505
  }
563
506
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
564
507
  async req(method, url2, body, tolerate = []) {
565
- const r = await fetch(url2, {
508
+ const r = await this.fetchWithAuth(url2, {
566
509
  method,
567
- headers: this.headers(),
568
510
  body: body ? JSON.stringify(body) : void 0,
569
511
  signal: AbortSignal.timeout(15e3)
570
512
  });
571
513
  if (r.status === 429 && !tolerate.includes(429))
572
514
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
573
515
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
574
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
516
+ throw new Error(
517
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
518
+ );
575
519
  return r;
576
520
  }
577
521
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -582,7 +526,11 @@ var HindsightClient = class {
582
526
  context,
583
527
  document_id: documentId,
584
528
  tags,
585
- strategy
529
+ strategy,
530
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
531
+ // observations were built under is a property of the write rather than of whichever server
532
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
533
+ observation_scopes: this.observationScopes
586
534
  };
587
535
  if (opts.timestamp) item.timestamp = opts.timestamp;
588
536
  if (opts.metadata) item.metadata = opts.metadata;
@@ -661,7 +609,7 @@ var HindsightClient = class {
661
609
  this.log(
662
610
  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}`
663
611
  );
664
- await this.seedPages();
612
+ await this.seedPages(opts.pageTrigger);
665
613
  }
666
614
  /**
667
615
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -719,7 +667,7 @@ var HindsightClient = class {
719
667
  let backoffMs = POLL_CYCLE_MS;
720
668
  await pool([...pending], this.maxParallelRetains, async (id) => {
721
669
  try {
722
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
670
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
723
671
  if (r.status === 429) {
724
672
  backoffMs = Math.min(
725
673
  RETRY_AFTER_CEILING_MS,
@@ -745,18 +693,23 @@ var HindsightClient = class {
745
693
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
746
694
  );
747
695
  }
748
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
749
- async reflect(query, opts = {}) {
696
+ /**
697
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
698
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
699
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
700
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
701
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
702
+ */
703
+ async reflect(query, opts) {
750
704
  const ctrl = new AbortController();
751
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
705
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
752
706
  try {
753
- const resp = await fetch(this.bankUrl("/reflect"), {
707
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
754
708
  method: "POST",
755
- headers: this.headers(),
756
709
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
757
710
  signal: ctrl.signal
758
711
  });
759
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
712
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
760
713
  const data = await resp.json();
761
714
  return (data.text || "").trim();
762
715
  } finally {
@@ -840,16 +793,18 @@ var HindsightClient = class {
840
793
  }));
841
794
  }
842
795
  /**
843
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
796
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
844
797
  *
845
798
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
846
799
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
847
800
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
848
801
  *
849
802
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
850
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
803
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
804
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
851
805
  */
852
- async seedPages() {
806
+ async seedPages(pageTrigger = buildPageTrigger()) {
807
+ const pages = pagesFor(this.project ?? this.bank);
853
808
  const existing = /* @__PURE__ */ new Map();
854
809
  let roots;
855
810
  try {
@@ -866,14 +821,14 @@ var HindsightClient = class {
866
821
  }
867
822
  let created = 0;
868
823
  let updated = 0;
869
- for (const page of PAGES) {
824
+ for (const page of pages) {
870
825
  const hit = existing.get(page.name.toLowerCase());
871
826
  const body = {
872
827
  name: page.name,
873
828
  source_query: page.source_query,
874
829
  tags: page.tags,
875
830
  max_tokens: PAGE_MAX_TOKENS,
876
- trigger: PAGE_TRIGGER
831
+ trigger: pageTrigger
877
832
  };
878
833
  if (!hit) {
879
834
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -902,7 +857,7 @@ var HindsightClient = class {
902
857
  }
903
858
  }
904
859
  this.log(
905
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
860
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
906
861
  );
907
862
  }
908
863
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -912,7 +867,8 @@ var HindsightClient = class {
912
867
  /**
913
868
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
914
869
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
915
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
870
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
871
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
916
872
  */
917
873
  async captureInitiative(args) {
918
874
  let pageId = args.relatesToPageId;
@@ -923,10 +879,7 @@ var HindsightClient = class {
923
879
  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.`,
924
880
  parent_id: folderId,
925
881
  tags: ["knowledge:feature-work"],
926
- trigger: {
927
- fact_types: ["world", "experience", "observation"],
928
- refresh_after_consolidation: true
929
- }
882
+ trigger: args.pageTrigger ?? buildPageTrigger()
930
883
  });
931
884
  try {
932
885
  const j = await r.json();
@@ -935,7 +888,7 @@ var HindsightClient = class {
935
888
  }
936
889
  pageId ||= `initiative-${this.slugify(args.title)}`;
937
890
  }
938
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
891
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
939
892
  const content = `${verb}: ${args.title}. ${args.summary}`;
940
893
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
941
894
  const tags = [
@@ -971,59 +924,279 @@ var HindsightClient = class {
971
924
  return void 0;
972
925
  }
973
926
  }
974
- };
975
-
976
- // src/core/diag.ts
977
- import { appendFileSync as appendFileSync2 } from "fs";
978
-
979
- // src/core/log.ts
980
- import { appendFileSync, mkdirSync } from "fs";
981
- import { tmpdir } from "os";
982
- import { dirname as dirname3, join as join4 } from "path";
983
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
984
- var current = ["debug", "info", "warn", "error"].find(
985
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
986
- ) ?? "info";
987
- function setLogLevel(level) {
988
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
927
+ };
928
+
929
+ // src/core/config.ts
930
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
931
+ var DEFAULT_DAEMON_PORT = 9077;
932
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
933
+ function resolvePageTriggerType(raw) {
934
+ if (raw.pageTriggerType === "manual") return "manual";
935
+ if (raw.pageTriggerType === "cron") {
936
+ if (raw.pageTriggerCron?.trim()) return "cron";
937
+ log.warn(
938
+ "config",
939
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
940
+ );
941
+ }
942
+ return "auto-refresh";
943
+ }
944
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
945
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
946
+ function resolveReflectBudget(raw) {
947
+ const value = raw.reflectBudget;
948
+ if (value === void 0) return "high";
949
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
950
+ return value;
951
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
952
+ return "high";
953
+ }
954
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
955
+ function resolveObservationScopes(raw) {
956
+ const value = raw;
957
+ if (typeof value === "string")
958
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
959
+ if (Array.isArray(value)) {
960
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
961
+ if (scopes.length) return scopes;
962
+ }
963
+ return DEFAULT_OBSERVATION_SCOPES;
964
+ }
965
+ function resolveConfig(raw = {}) {
966
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
967
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
968
+ return {
969
+ serverMode,
970
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
971
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
972
+ // daemon needs no plumbing through eight separate constructors.
973
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
974
+ apiToken: raw.apiToken || void 0,
975
+ apiPort,
976
+ daemonIdleTimeout: raw.daemonIdleTimeout,
977
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
978
+ embedVersion: raw.embedVersion || void 0,
979
+ embedPackagePath: raw.embedPackagePath || void 0,
980
+ bankId: raw.bankId,
981
+ dynamicBankId: raw.dynamicBankId,
982
+ bankIdTemplate: raw.bankIdTemplate,
983
+ mapPathToBank: raw.mapPathToBank,
984
+ resolveWorktrees: raw.resolveWorktrees,
985
+ optInOnly: raw.optInOnly ?? false,
986
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
987
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
988
+ harness: raw.harness ?? "opencode",
989
+ disabled: raw.disabled ?? false,
990
+ retainSessions: raw.retainSessions ?? true,
991
+ // write sessions back by default, every harness
992
+ maxParallelRetains: raw.maxParallelRetains || 10,
993
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
994
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
995
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
996
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
997
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
998
+ reflectBudget: resolveReflectBudget(raw),
999
+ autoReflect: raw.autoReflect ?? true,
1000
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1001
+ pageTriggerType: resolvePageTriggerType(raw),
1002
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1003
+ autoSeed: raw.autoSeed ?? true,
1004
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1005
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1006
+ surveyModel: raw.surveyModel || "haiku",
1007
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1008
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1009
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1010
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1011
+ // nested object cannot reach the API as a tag and fail the whole retain.
1012
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1013
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1014
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1015
+ ) : {},
1016
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1017
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1018
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1019
+ };
1020
+ }
1021
+ function readRaw(path) {
1022
+ try {
1023
+ return JSON.parse(readFileSync(path, "utf8"));
1024
+ } catch (e) {
1025
+ if (e?.code !== "ENOENT") {
1026
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1027
+ }
1028
+ return {};
1029
+ }
989
1030
  }
990
- function logFilePath() {
991
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
1031
+ function mergeRaw(a, b) {
1032
+ const { harnesses: _drop, ...flat } = b;
1033
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
992
1034
  }
993
- function write(level, scope, msg, extra) {
994
- if (WEIGHT[level] < WEIGHT[current]) return;
995
- try {
996
- const file2 = logFilePath();
997
- mkdirSync(dirname3(file2), { recursive: true });
998
- appendFileSync(
999
- file2,
1000
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
1001
- );
1002
- } catch {
1003
- }
1035
+ function applyLayer(raw, layer, harness) {
1036
+ let out = mergeRaw(raw, layer);
1037
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1038
+ if (perHarness) out = mergeRaw(out, perHarness);
1039
+ return out;
1004
1040
  }
1005
- var log = {
1006
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
1007
- info: (scope, msg, extra) => write("info", scope, msg, extra),
1008
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
1009
- error: (scope, msg, extra) => write("error", scope, msg, extra)
1041
+ var ENV_KEYS = {
1042
+ serverMode: "HINDSIGHT_SERVER_MODE",
1043
+ apiUrl: "HINDSIGHT_API_URL",
1044
+ apiToken: "HINDSIGHT_API_TOKEN",
1045
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1046
+ // it can carry their existing environment over unchanged.
1047
+ apiPort: "HINDSIGHT_API_PORT",
1048
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1049
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1050
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1051
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1052
+ bankId: "HINDSIGHT_BANK_ID",
1053
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1054
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1055
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1056
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1057
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1058
+ harness: "HINDSIGHT_HARNESS",
1059
+ disabled: "HINDSIGHT_DISABLED",
1060
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1061
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1062
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1063
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1064
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1065
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1066
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1067
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1068
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1069
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1070
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1071
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1072
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1073
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1074
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1075
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1076
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1077
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1078
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1079
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1080
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1081
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1082
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1010
1083
  };
1011
- function describeError(value, maxChars = 200) {
1012
- const parts = [];
1013
- const seen = /* @__PURE__ */ new Set();
1014
- let current2 = value;
1015
- while (current2 && !seen.has(current2)) {
1016
- seen.add(current2);
1017
- const error51 = current2;
1018
- const text = typeof error51.message === "string" ? error51.message : String(current2);
1019
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
1020
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
1021
- current2 = error51.cause;
1084
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1085
+ "dynamicBankId",
1086
+ "resolveWorktrees",
1087
+ "optInOnly",
1088
+ "disabled",
1089
+ "retainSessions",
1090
+ "autoReflect",
1091
+ "autoSeed",
1092
+ "codebaseSurvey"
1093
+ ]);
1094
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1095
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1096
+ "apiPort",
1097
+ "daemonIdleTimeout",
1098
+ "maxParallelRetains",
1099
+ "reflectTimeoutMs",
1100
+ "reflectToolTimeoutMs",
1101
+ "pageRefreshEveryTurns",
1102
+ "seedLimit",
1103
+ "surveyBudgetUsd",
1104
+ "surveyRefreshCommits"
1105
+ ]);
1106
+ function readEnvConfig(env = process.env) {
1107
+ const out = {};
1108
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1109
+ const value = env[name];
1110
+ if (value === void 0 || value.trim() === "") continue;
1111
+ if (ENV_BOOLEANS.has(key)) {
1112
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1113
+ } else if (ENV_LISTS.has(key)) {
1114
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1115
+ if (items.length) out[key] = items;
1116
+ } else if (ENV_NUMBERS.has(key)) {
1117
+ const n = Number(value);
1118
+ if (Number.isFinite(n)) out[key] = n;
1119
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1120
+ } else {
1121
+ out[key] = value;
1122
+ }
1022
1123
  }
1023
- return (parts.join(": ") || String(value)).slice(0, maxChars);
1124
+ return out;
1125
+ }
1126
+ function loadConfig(opts = {}) {
1127
+ const o = typeof opts === "string" ? { path: opts } : opts;
1128
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1129
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1130
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1131
+ return resolveConfig(raw);
1132
+ }
1133
+ var BANK_OVERRIDE_EXCLUDED = [
1134
+ "bankId",
1135
+ "bankIdTemplate",
1136
+ "mapPathToBank",
1137
+ "dynamicBankId",
1138
+ "resolveWorktrees",
1139
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1140
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1141
+ "optInOnly",
1142
+ "optInPaths",
1143
+ "harness"
1144
+ ];
1145
+ function applyBankConfig(cfg, resolvedId, directory) {
1146
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1147
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1148
+ const section = cfg.banks[resolvedId];
1149
+ if (!section) return { cfg, bankId: resolvedId };
1150
+ const safe = { ...section };
1151
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1152
+ delete safe.banks;
1153
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1154
+ delete safe.bank;
1155
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1156
+ }
1157
+ function resolvePartial(cfg, patch) {
1158
+ const full = resolveConfig(patch);
1159
+ const out = {};
1160
+ for (const key of Object.keys(patch)) {
1161
+ if (key in full)
1162
+ out[key] = full[key];
1163
+ }
1164
+ return out;
1165
+ }
1166
+
1167
+ // src/core/host-client.ts
1168
+ function resolveHostConfig(harness, directory) {
1169
+ const cfg0 = loadConfig({ harness });
1170
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1171
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1172
+ }
1173
+ function resolveHostMemory(harness, directory) {
1174
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
1175
+ return {
1176
+ cfg,
1177
+ bankId,
1178
+ client: new HindsightClient({
1179
+ apiUrl: cfg.apiUrl,
1180
+ apiToken: cfg.apiToken,
1181
+ bank: bankId,
1182
+ maxParallelRetains: cfg.maxParallelRetains,
1183
+ observationScopes: cfg.observationScopes,
1184
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
1185
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
1186
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
1187
+ // honoured on re-resolution exactly as it was on the first one.
1188
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
1189
+ })
1190
+ };
1024
1191
  }
1025
1192
 
1193
+ // src/core/daemon.ts
1194
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1195
+ import { dirname as dirname4, join as join5 } from "path";
1196
+ import { fileURLToPath as fileURLToPath2 } from "url";
1197
+
1026
1198
  // src/core/diag.ts
1199
+ import { appendFileSync as appendFileSync2 } from "fs";
1027
1200
  function diagFilePath() {
1028
1201
  return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1029
1202
  }
@@ -1038,6 +1211,120 @@ function diag(harness, event, extra = {}) {
1038
1211
  }
1039
1212
  }
1040
1213
 
1214
+ // src/core/daemon.ts
1215
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
1216
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
1217
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1218
+ try {
1219
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
1220
+ return res.ok;
1221
+ } catch {
1222
+ return false;
1223
+ }
1224
+ }
1225
+ function hasRustToolchain() {
1226
+ if (process.platform !== "darwin") return true;
1227
+ try {
1228
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
1229
+ return true;
1230
+ } catch {
1231
+ return false;
1232
+ }
1233
+ }
1234
+ function hasUvx() {
1235
+ try {
1236
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
1237
+ return true;
1238
+ } catch {
1239
+ return false;
1240
+ }
1241
+ }
1242
+ var PROVIDER_PROBES = [
1243
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
1244
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
1245
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
1246
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
1247
+ ];
1248
+ function detectLlm(env = process.env) {
1249
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
1250
+ if (explicit) {
1251
+ return {
1252
+ provider: explicit,
1253
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
1254
+ source: "HINDSIGHT_API_LLM_PROVIDER"
1255
+ };
1256
+ }
1257
+ for (const probe of PROVIDER_PROBES) {
1258
+ const key = env[probe.keyEnv]?.trim();
1259
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
1260
+ }
1261
+ if (onPath("claude")) {
1262
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
1263
+ }
1264
+ return void 0;
1265
+ }
1266
+ function onPath(bin) {
1267
+ try {
1268
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
1269
+ return true;
1270
+ } catch {
1271
+ return false;
1272
+ }
1273
+ }
1274
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1275
+ try {
1276
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1277
+ const child = spawnFn("node", [starter, "--harness", harness], {
1278
+ detached: true,
1279
+ stdio: "ignore"
1280
+ });
1281
+ child.on("error", () => {
1282
+ });
1283
+ child.unref();
1284
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
1285
+ } catch {
1286
+ }
1287
+ }
1288
+ async function ensureDaemon(cfg, harness, opts = {}) {
1289
+ if (cfg.serverMode !== "daemon") return;
1290
+ if (await isServerHealthy(cfg.apiUrl)) return;
1291
+ if (!preflightDaemon(cfg, harness)) return;
1292
+ startDaemonDetached(cfg, harness, opts.spawnFn);
1293
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
1294
+ }
1295
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1296
+ const deadline = Date.now() + budgetMs;
1297
+ while (Date.now() < deadline) {
1298
+ await new Promise((r) => setTimeout(r, pollMs));
1299
+ if (await isServerHealthy(baseUrl)) return true;
1300
+ }
1301
+ return false;
1302
+ }
1303
+ function preflightDaemon(cfg, harness) {
1304
+ if (!hasUvx()) {
1305
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
1306
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
1307
+ return false;
1308
+ }
1309
+ if (!hasRustToolchain()) {
1310
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
1311
+ log.warn(
1312
+ harness,
1313
+ "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`"
1314
+ );
1315
+ return false;
1316
+ }
1317
+ if (!detectLlm()) {
1318
+ diag(harness, "daemon_no_llm", {});
1319
+ log.warn(
1320
+ harness,
1321
+ "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"
1322
+ );
1323
+ return false;
1324
+ }
1325
+ return true;
1326
+ }
1327
+
1041
1328
  // node_modules/zod/v4/classic/external.js
1042
1329
  var external_exports = {};
1043
1330
  __export(external_exports, {
@@ -15555,16 +15842,16 @@ config(en_default());
15555
15842
  // src/core/knowledge-tools.ts
15556
15843
  import { existsSync as existsSync3 } from "fs";
15557
15844
  import { homedir as homedir4 } from "os";
15558
- import { join as join6 } from "path";
15845
+ import { join as join7 } from "path";
15559
15846
 
15560
15847
  // src/core/status.ts
15561
- import { execFileSync as execFileSync3 } from "child_process";
15848
+ import { execFileSync as execFileSync4 } from "child_process";
15562
15849
 
15563
15850
  // src/core/git.ts
15564
- import { execFileSync as execFileSync2 } from "child_process";
15851
+ import { execFileSync as execFileSync3 } from "child_process";
15565
15852
  import { resolve } from "path";
15566
15853
  function git(repo, ...args) {
15567
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15854
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15568
15855
  }
15569
15856
  function repoNameOf(repo) {
15570
15857
  return projectNameOf(resolve(repo));
@@ -15610,7 +15897,7 @@ function roster(pages) {
15610
15897
  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>".
15611
15898
  - 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.
15612
15899
  - 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>").
15613
- - 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.
15900
+ - 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.
15614
15901
  - 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).`;
15615
15902
  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";
15616
15903
  function toolGuide(opts) {
@@ -15637,11 +15924,11 @@ ${toolGuide(opts)}
15637
15924
  }
15638
15925
 
15639
15926
  // src/core/survey.ts
15640
- import { spawn as realSpawn2 } from "child_process";
15927
+ import { spawn as realSpawn3 } from "child_process";
15641
15928
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15642
15929
  import { homedir as homedir3 } from "os";
15643
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15644
- import { fileURLToPath as fileURLToPath2 } from "url";
15930
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15931
+ import { fileURLToPath as fileURLToPath3 } from "url";
15645
15932
  var SURVEY_DOC_IDS = [
15646
15933
  "repository-component-map",
15647
15934
  "repository-core-concepts",
@@ -15651,7 +15938,7 @@ var SURVEY_DOC_IDS = [
15651
15938
  function resolveClaudeBin(explicit) {
15652
15939
  if (explicit) return explicit;
15653
15940
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15654
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15941
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15655
15942
  try {
15656
15943
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15657
15944
  } catch {
@@ -15680,7 +15967,7 @@ function binExists(bin) {
15680
15967
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15681
15968
  if (!dir) continue;
15682
15969
  try {
15683
- accessSync(join5(dir, bin), constants.X_OK);
15970
+ accessSync(join6(dir, bin), constants.X_OK);
15684
15971
  return true;
15685
15972
  } catch {
15686
15973
  }
@@ -15724,7 +16011,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15724
16011
  hindsight: {
15725
16012
  command: "node",
15726
16013
  args: [opts.mcpServerPath],
15727
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16014
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16015
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16016
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16017
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16018
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15728
16019
  }
15729
16020
  }
15730
16021
  });
@@ -15764,6 +16055,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15764
16055
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15765
16056
  "-c",
15766
16057
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16058
+ "-c",
16059
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15767
16060
  SURVEY_PROMPT
15768
16061
  ],
15769
16062
  env
@@ -15787,9 +16080,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15787
16080
  }
15788
16081
  function startCodebaseSurvey(repoDir, opts = {}) {
15789
16082
  try {
15790
- const spawnFn = opts.spawn ?? realSpawn2;
16083
+ const spawnFn = opts.spawn ?? realSpawn3;
15791
16084
  const exists = opts.exists ?? binExists;
15792
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16085
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15793
16086
  const preferred = opts.harness ?? "claude-code";
15794
16087
  const order = [
15795
16088
  preferred,
@@ -15828,7 +16121,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15828
16121
  var DEEPEN_DIFF_TARGET = 300;
15829
16122
  function commitCount(repoDir) {
15830
16123
  try {
15831
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16124
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15832
16125
  encoding: "utf8"
15833
16126
  });
15834
16127
  return Number(out.trim()) || 0;
@@ -15919,9 +16212,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15919
16212
  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.",
15920
16213
  inputSchema: {},
15921
16214
  handler: async (_args) => {
15922
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16215
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15923
16216
  const harness = opts.harness ?? "unknown";
15924
- const cfg = loadConfig({ harness: opts.harness });
16217
+ const cfg = applyBankConfig(
16218
+ loadConfig({ harness: opts.harness }),
16219
+ bankId,
16220
+ opts.repoDir
16221
+ ).cfg;
15925
16222
  return ok({
15926
16223
  bank_id: bankId,
15927
16224
  harness,
@@ -15933,6 +16230,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15933
16230
  api_token_configured: Boolean(cfg.apiToken),
15934
16231
  disabled: cfg.disabled
15935
16232
  },
16233
+ // What the LIVE client is signing with, which is not the same question as what the file
16234
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16235
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16236
+ // value is never returned.
16237
+ credential: {
16238
+ api_token_in_use: Boolean(client.apiToken),
16239
+ api_token_matches_config: client.apiToken === cfg.apiToken
16240
+ },
15936
16241
  environment: {
15937
16242
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15938
16243
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15981,12 +16286,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15981
16286
  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>".`,
15982
16287
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15983
16288
  handler: guarded(
15984
- async ({ query }) => client.reflect(query, { budget: "high" })
16289
+ async ({ query }) => client.reflect(query, {
16290
+ budget: opts.reflectBudget ?? "high",
16291
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16292
+ })
15985
16293
  )
15986
16294
  },
15987
16295
  {
15988
16296
  name: "hindsight_capture_initiative",
15989
- 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.",
16297
+ 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.",
15990
16298
  inputSchema: {
15991
16299
  title: external_exports.string(),
15992
16300
  summary: external_exports.string(),
@@ -15997,7 +16305,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15997
16305
  title,
15998
16306
  summary,
15999
16307
  relatesToPageId: relates_to_page_id,
16000
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16308
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16309
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
16001
16310
  })
16002
16311
  )
16003
16312
  },
@@ -16204,7 +16513,7 @@ function resolversFor(ctx) {
16204
16513
  return {
16205
16514
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16206
16515
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16207
- gitProject: () => projectNameOf(ctx.directory),
16516
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16208
16517
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16209
16518
  harness: () => ctx.harness,
16210
16519
  bankId: () => ctx.bankId,
@@ -16250,11 +16559,6 @@ import { readFileSync as readFileSync4 } from "fs";
16250
16559
  // src/core/skill-sync.ts
16251
16560
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16252
16561
  import { homedir as homedir5 } from "os";
16253
- import { dirname as dirname5, join as join7 } from "path";
16254
- import { fileURLToPath as fileURLToPath3 } from "url";
16255
-
16256
- // src/core/daemon.ts
16257
- import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
16258
16562
  import { dirname as dirname6, join as join8 } from "path";
16259
16563
  import { fileURLToPath as fileURLToPath4 } from "url";
16260
16564
 
@@ -16345,7 +16649,7 @@ async function buildSessionStartContext(args) {
16345
16649
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16346
16650
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16347
16651
  const countCommitsSince = args.commitsSince ?? commitsSince;
16348
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16652
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16349
16653
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16350
16654
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16351
16655
  const recordSurveyBaseline = (sha) => {
@@ -16621,6 +16925,9 @@ var RuntimeCore = class {
16621
16925
  return buildKnowledgeTools(this.client, this.bankId, {
16622
16926
  repoDir: this.projectDir,
16623
16927
  harness: this.harness,
16928
+ pageTrigger: buildPageTrigger(this.cfg),
16929
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16930
+ reflectBudget: this.cfg.reflectBudget,
16624
16931
  stampFor: () => buildRetainStamp(this.cfg, {
16625
16932
  directory: this.projectDir,
16626
16933
  harness: this.harness,
@@ -16639,6 +16946,7 @@ var RuntimeCore = class {
16639
16946
  */
16640
16947
  async seedIfCold(repoPath) {
16641
16948
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16949
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16642
16950
  try {
16643
16951
  const out = await buildSessionStartContext({
16644
16952
  cwd: repoPath || process.cwd(),
@@ -16762,15 +17070,17 @@ var RuntimeCore = class {
16762
17070
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16763
17071
  retain(sessionId2, turns, startTs, trigger = "turn") {
16764
17072
  const t0 = Date.now();
16765
- void retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
16766
- cursors: this.cursors,
16767
- stamp: buildRetainStamp(this.cfg, {
16768
- directory: this.projectDir,
16769
- harness: this.harness,
16770
- bankId: this.bankId,
16771
- sessionId: sessionId2
17073
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17074
+ () => retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
17075
+ cursors: this.cursors,
17076
+ stamp: buildRetainStamp(this.cfg, {
17077
+ directory: this.projectDir,
17078
+ harness: this.harness,
17079
+ bankId: this.bankId,
17080
+ sessionId: sessionId2
17081
+ })
16772
17082
  })
16773
- }).then(
17083
+ ).then(
16774
17084
  () => diag(this.harness, "retain_ok", {
16775
17085
  ms: Date.now() - t0,
16776
17086
  turns: turns.length,
@@ -16839,7 +17149,7 @@ function createClineHooks(core, configuredSessionId, sessionStart) {
16839
17149
  }) {
16840
17150
  if (!sessionStartAwaited) {
16841
17151
  sessionStartAwaited = true;
16842
- await sessionStart;
17152
+ await settleWithinHookBudget(sessionStart ?? Promise.resolve());
16843
17153
  }
16844
17154
  const user = latestUserMessage(snapshot.messages);
16845
17155
  if (!user) return void 0;
@@ -16883,22 +17193,10 @@ function createClineHooks(core, configuredSessionId, sessionStart) {
16883
17193
  };
16884
17194
  }
16885
17195
  function createRuntime(workspaceRoot) {
16886
- let cfg = loadConfig({ harness: HARNESS2 });
17196
+ const dir = workspaceRoot || process.cwd();
17197
+ const { cfg, bankId, client } = resolveHostMemory(HARNESS2, dir);
16887
17198
  if (cfg.disabled) return void 0;
16888
- const resolved = applyBankConfig(
16889
- cfg,
16890
- deriveBankId(cfg, workspaceRoot || process.cwd(), HARNESS2),
16891
- workspaceRoot || process.cwd()
16892
- );
16893
- cfg = resolved.cfg;
16894
- if (cfg.disabled) return void 0;
16895
- const client = new HindsightClient({
16896
- apiUrl: cfg.apiUrl,
16897
- apiToken: cfg.apiToken,
16898
- bank: resolved.bankId,
16899
- maxParallelRetains: cfg.maxParallelRetains
16900
- });
16901
- return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, workspaceRoot || process.cwd());
17199
+ return new RuntimeCore(client, bankId, cfg, HARNESS2, dir);
16902
17200
  }
16903
17201
  var plugin = {
16904
17202
  name: "hindsight-coding-agents",