@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/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.",
@@ -439,15 +319,28 @@ var PAGES = [
439
319
  },
440
320
  {
441
321
  name: "Initiatives and enhancements",
442
- 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.",
322
+ 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.",
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_TAGS_MATCH = "all";
332
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
333
+ function buildPageTrigger(cfg = {}) {
334
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
335
+ switch (cfg.pageTriggerType) {
336
+ case "cron":
337
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
338
+ case "manual":
339
+ return { ...base, refresh_after_consolidation: false };
340
+ default:
341
+ return { ...base, refresh_after_consolidation: true };
342
+ }
343
+ }
451
344
  var CODING_BANK_TEMPLATE = {
452
345
  version: "1",
453
346
  bank: {
@@ -502,6 +395,7 @@ async function pool(items, n, fn, onError, onProgress) {
502
395
  }
503
396
 
504
397
  // src/core/hindsight.ts
398
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
505
399
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
506
400
  var RateLimitedError = class extends Error {
507
401
  constructor(retryAfterMs2) {
@@ -534,8 +428,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
534
428
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
535
429
  var HindsightClient = class {
536
430
  apiUrl;
537
- apiToken;
431
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
432
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
433
+ token;
434
+ tokenProvider;
538
435
  bank;
436
+ project;
539
437
  opIds = [];
540
438
  // async operation ids collected by retain(), for drain()
541
439
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -544,34 +442,81 @@ var HindsightClient = class {
544
442
  idempotentRetain;
545
443
  log;
546
444
  maxParallelRetains;
445
+ observationScopes;
547
446
  constructor(o) {
548
447
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
549
- this.apiToken = o.apiToken;
448
+ this.token = o.apiToken;
449
+ this.tokenProvider = o.tokenProvider;
550
450
  this.bank = o.bank;
451
+ this.project = o.project;
551
452
  this.log = o.log ?? (() => {
552
453
  });
553
454
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
455
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
456
+ }
457
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
458
+ get apiToken() {
459
+ return this.token;
554
460
  }
555
461
  headers() {
556
462
  const h = { "Content-Type": "application/json" };
557
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
463
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
558
464
  return h;
559
465
  }
466
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
467
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
468
+ * doubling every failing request. */
469
+ refreshToken() {
470
+ if (!this.tokenProvider) return false;
471
+ let next;
472
+ try {
473
+ next = this.tokenProvider();
474
+ } catch {
475
+ return false;
476
+ }
477
+ if (next === this.token) return false;
478
+ this.token = next;
479
+ return true;
480
+ }
481
+ /**
482
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
483
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
484
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
485
+ * not.
486
+ *
487
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
488
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
489
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
490
+ * bounds the whole call.
491
+ */
492
+ async fetchWithAuth(url2, init) {
493
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
494
+ const r = await send();
495
+ if (r.status !== 401 || !this.refreshToken()) return r;
496
+ return send();
497
+ }
498
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
499
+ * server answers identically for both — only the client knows which it sent. */
500
+ authHint(status) {
501
+ if (status !== 401) return "";
502
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
503
+ }
560
504
  bankUrl(suffix = "") {
561
505
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
562
506
  }
563
507
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
564
508
  async req(method, url2, body, tolerate = []) {
565
- const r = await fetch(url2, {
509
+ const r = await this.fetchWithAuth(url2, {
566
510
  method,
567
- headers: this.headers(),
568
511
  body: body ? JSON.stringify(body) : void 0,
569
512
  signal: AbortSignal.timeout(15e3)
570
513
  });
571
514
  if (r.status === 429 && !tolerate.includes(429))
572
515
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
573
516
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
574
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
517
+ throw new Error(
518
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
519
+ );
575
520
  return r;
576
521
  }
577
522
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -582,7 +527,11 @@ var HindsightClient = class {
582
527
  context,
583
528
  document_id: documentId,
584
529
  tags,
585
- strategy
530
+ strategy,
531
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
532
+ // observations were built under is a property of the write rather than of whichever server
533
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
534
+ observation_scopes: this.observationScopes
586
535
  };
587
536
  if (opts.timestamp) item.timestamp = opts.timestamp;
588
537
  if (opts.metadata) item.metadata = opts.metadata;
@@ -661,7 +610,7 @@ var HindsightClient = class {
661
610
  this.log(
662
611
  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
612
  );
664
- await this.seedPages();
613
+ await this.seedPages(opts.pageTrigger);
665
614
  }
666
615
  /**
667
616
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -719,7 +668,7 @@ var HindsightClient = class {
719
668
  let backoffMs = POLL_CYCLE_MS;
720
669
  await pool([...pending], this.maxParallelRetains, async (id) => {
721
670
  try {
722
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
671
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
723
672
  if (r.status === 429) {
724
673
  backoffMs = Math.min(
725
674
  RETRY_AFTER_CEILING_MS,
@@ -745,18 +694,23 @@ var HindsightClient = class {
745
694
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
746
695
  );
747
696
  }
748
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
749
- async reflect(query, opts = {}) {
697
+ /**
698
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
699
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
700
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
701
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
702
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
703
+ */
704
+ async reflect(query, opts) {
750
705
  const ctrl = new AbortController();
751
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
706
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
752
707
  try {
753
- const resp = await fetch(this.bankUrl("/reflect"), {
708
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
754
709
  method: "POST",
755
- headers: this.headers(),
756
710
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
757
711
  signal: ctrl.signal
758
712
  });
759
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
713
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
760
714
  const data = await resp.json();
761
715
  return (data.text || "").trim();
762
716
  } finally {
@@ -840,16 +794,18 @@ var HindsightClient = class {
840
794
  }));
841
795
  }
842
796
  /**
843
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
797
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
844
798
  *
845
799
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
846
800
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
847
801
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
848
802
  *
849
803
  * 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.
804
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
805
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
851
806
  */
852
- async seedPages() {
807
+ async seedPages(pageTrigger = buildPageTrigger()) {
808
+ const pages = pagesFor(this.project ?? this.bank);
853
809
  const existing = /* @__PURE__ */ new Map();
854
810
  let roots;
855
811
  try {
@@ -866,14 +822,14 @@ var HindsightClient = class {
866
822
  }
867
823
  let created = 0;
868
824
  let updated = 0;
869
- for (const page of PAGES) {
825
+ for (const page of pages) {
870
826
  const hit = existing.get(page.name.toLowerCase());
871
827
  const body = {
872
828
  name: page.name,
873
829
  source_query: page.source_query,
874
830
  tags: page.tags,
875
831
  max_tokens: PAGE_MAX_TOKENS,
876
- trigger: PAGE_TRIGGER
832
+ trigger: pageTrigger
877
833
  };
878
834
  if (!hit) {
879
835
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -885,11 +841,18 @@ var HindsightClient = class {
885
841
  return;
886
842
  }
887
843
  if (r.status !== 409) created++;
888
- } else if (hit.description !== page.source_query) {
844
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
845
+ const patch = {
846
+ trigger: pageTrigger
847
+ };
848
+ if (hit.description !== page.source_query) {
849
+ patch.source_query = page.source_query;
850
+ patch.tags = page.tags;
851
+ }
889
852
  const r = await this.req(
890
853
  "PATCH",
891
854
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
892
- { source_query: page.source_query, tags: page.tags }
855
+ patch
893
856
  );
894
857
  if ([404, 405, 501].includes(r.status)) {
895
858
  this.knowledgePagesSupported = false;
@@ -902,7 +865,7 @@ var HindsightClient = class {
902
865
  }
903
866
  }
904
867
  this.log(
905
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
868
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
906
869
  );
907
870
  }
908
871
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -910,9 +873,17 @@ var HindsightClient = class {
910
873
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
911
874
  }
912
875
  /**
913
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
914
- * 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.
876
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
877
+ * New initiative → creates a page under the Initiatives folder.
878
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
879
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
880
+ *
881
+ * The marker carries its page id in two places, neither of them a tag (#3641):
882
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
883
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
884
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
885
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
886
+ * vocabulary that exists to be matched with exact set-ops.
916
887
  */
917
888
  async captureInitiative(args) {
918
889
  let pageId = args.relatesToPageId;
@@ -923,10 +894,7 @@ var HindsightClient = class {
923
894
  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
895
  parent_id: folderId,
925
896
  tags: ["knowledge:feature-work"],
926
- trigger: {
927
- fact_types: ["world", "experience", "observation"],
928
- refresh_after_consolidation: true
929
- }
897
+ trigger: args.pageTrigger ?? buildPageTrigger()
930
898
  });
931
899
  try {
932
900
  const j = await r.json();
@@ -935,23 +903,14 @@ var HindsightClient = class {
935
903
  }
936
904
  pageId ||= `initiative-${this.slugify(args.title)}`;
937
905
  }
938
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
906
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
939
907
  const content = `${verb}: ${args.title}. ${args.summary}`;
940
908
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
941
- const tags = [
942
- .../* @__PURE__ */ new Set([
943
- ...args.stamp?.tags ?? [],
944
- "knowledge:feature-work",
945
- `relatedPageId:${pageId}`
946
- ])
947
- ];
948
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
949
- await this.retain(content, "initiative marker", markerId, tags, "document", {
950
- metadata: args.stamp?.metadata
951
- });
952
- } else {
953
- await this.retain(content, "initiative marker", markerId, tags, "document");
954
- }
909
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
910
+ const context = `initiative marker for [[page:${pageId}]]`;
911
+ await this.retain(content, context, markerId, tags, "document", {
912
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
913
+ });
955
914
  return { page_id: pageId };
956
915
  }
957
916
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -971,59 +930,279 @@ var HindsightClient = class {
971
930
  return void 0;
972
931
  }
973
932
  }
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;
933
+ };
934
+
935
+ // src/core/config.ts
936
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
937
+ var DEFAULT_DAEMON_PORT = 9077;
938
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
939
+ function resolvePageTriggerType(raw) {
940
+ if (raw.pageTriggerType === "manual") return "manual";
941
+ if (raw.pageTriggerType === "cron") {
942
+ if (raw.pageTriggerCron?.trim()) return "cron";
943
+ log.warn(
944
+ "config",
945
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
946
+ );
947
+ }
948
+ return "auto-refresh";
949
+ }
950
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
951
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
952
+ function resolveReflectBudget(raw) {
953
+ const value = raw.reflectBudget;
954
+ if (value === void 0) return "high";
955
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
956
+ return value;
957
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
958
+ return "high";
959
+ }
960
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
961
+ function resolveObservationScopes(raw) {
962
+ const value = raw;
963
+ if (typeof value === "string")
964
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
965
+ if (Array.isArray(value)) {
966
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
967
+ if (scopes.length) return scopes;
968
+ }
969
+ return DEFAULT_OBSERVATION_SCOPES;
970
+ }
971
+ function resolveConfig(raw = {}) {
972
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
973
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
974
+ return {
975
+ serverMode,
976
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
977
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
978
+ // daemon needs no plumbing through eight separate constructors.
979
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
980
+ apiToken: raw.apiToken || void 0,
981
+ apiPort,
982
+ daemonIdleTimeout: raw.daemonIdleTimeout,
983
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
984
+ embedVersion: raw.embedVersion || void 0,
985
+ embedPackagePath: raw.embedPackagePath || void 0,
986
+ bankId: raw.bankId,
987
+ dynamicBankId: raw.dynamicBankId,
988
+ bankIdTemplate: raw.bankIdTemplate,
989
+ mapPathToBank: raw.mapPathToBank,
990
+ resolveWorktrees: raw.resolveWorktrees,
991
+ optInOnly: raw.optInOnly ?? false,
992
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
993
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
994
+ harness: raw.harness ?? "opencode",
995
+ disabled: raw.disabled ?? false,
996
+ retainSessions: raw.retainSessions ?? true,
997
+ // write sessions back by default, every harness
998
+ maxParallelRetains: raw.maxParallelRetains || 10,
999
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1000
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1001
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1002
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1003
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1004
+ reflectBudget: resolveReflectBudget(raw),
1005
+ autoReflect: raw.autoReflect ?? true,
1006
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1007
+ pageTriggerType: resolvePageTriggerType(raw),
1008
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1009
+ autoSeed: raw.autoSeed ?? true,
1010
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1011
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1012
+ surveyModel: raw.surveyModel || "haiku",
1013
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1014
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1015
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1016
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1017
+ // nested object cannot reach the API as a tag and fail the whole retain.
1018
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1019
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1020
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1021
+ ) : {},
1022
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1023
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1024
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1025
+ };
1026
+ }
1027
+ function readRaw(path) {
1028
+ try {
1029
+ return JSON.parse(readFileSync(path, "utf8"));
1030
+ } catch (e) {
1031
+ if (e?.code !== "ENOENT") {
1032
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1033
+ }
1034
+ return {};
1035
+ }
989
1036
  }
990
- function logFilePath() {
991
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
1037
+ function mergeRaw(a, b) {
1038
+ const { harnesses: _drop, ...flat } = b;
1039
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
992
1040
  }
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
- }
1041
+ function applyLayer(raw, layer, harness) {
1042
+ let out = mergeRaw(raw, layer);
1043
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1044
+ if (perHarness) out = mergeRaw(out, perHarness);
1045
+ return out;
1004
1046
  }
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)
1047
+ var ENV_KEYS = {
1048
+ serverMode: "HINDSIGHT_SERVER_MODE",
1049
+ apiUrl: "HINDSIGHT_API_URL",
1050
+ apiToken: "HINDSIGHT_API_TOKEN",
1051
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1052
+ // it can carry their existing environment over unchanged.
1053
+ apiPort: "HINDSIGHT_API_PORT",
1054
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1055
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1056
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1057
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1058
+ bankId: "HINDSIGHT_BANK_ID",
1059
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1060
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1061
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1062
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1063
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1064
+ harness: "HINDSIGHT_HARNESS",
1065
+ disabled: "HINDSIGHT_DISABLED",
1066
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1067
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1068
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1069
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1070
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1071
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1072
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1073
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1074
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1075
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1076
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1077
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1078
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1079
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1080
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1081
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1082
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1083
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1084
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1085
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1086
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1087
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1088
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
1010
1089
  };
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;
1090
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1091
+ "dynamicBankId",
1092
+ "resolveWorktrees",
1093
+ "optInOnly",
1094
+ "disabled",
1095
+ "retainSessions",
1096
+ "autoReflect",
1097
+ "autoSeed",
1098
+ "codebaseSurvey"
1099
+ ]);
1100
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1101
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1102
+ "apiPort",
1103
+ "daemonIdleTimeout",
1104
+ "maxParallelRetains",
1105
+ "reflectTimeoutMs",
1106
+ "reflectToolTimeoutMs",
1107
+ "pageRefreshEveryTurns",
1108
+ "seedLimit",
1109
+ "surveyBudgetUsd",
1110
+ "surveyRefreshCommits"
1111
+ ]);
1112
+ function readEnvConfig(env = process.env) {
1113
+ const out = {};
1114
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1115
+ const value = env[name];
1116
+ if (value === void 0 || value.trim() === "") continue;
1117
+ if (ENV_BOOLEANS.has(key)) {
1118
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1119
+ } else if (ENV_LISTS.has(key)) {
1120
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1121
+ if (items.length) out[key] = items;
1122
+ } else if (ENV_NUMBERS.has(key)) {
1123
+ const n = Number(value);
1124
+ if (Number.isFinite(n)) out[key] = n;
1125
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1126
+ } else {
1127
+ out[key] = value;
1128
+ }
1022
1129
  }
1023
- return (parts.join(": ") || String(value)).slice(0, maxChars);
1130
+ return out;
1131
+ }
1132
+ function loadConfig(opts = {}) {
1133
+ const o = typeof opts === "string" ? { path: opts } : opts;
1134
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1135
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1136
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1137
+ return resolveConfig(raw);
1138
+ }
1139
+ var BANK_OVERRIDE_EXCLUDED = [
1140
+ "bankId",
1141
+ "bankIdTemplate",
1142
+ "mapPathToBank",
1143
+ "dynamicBankId",
1144
+ "resolveWorktrees",
1145
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1146
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1147
+ "optInOnly",
1148
+ "optInPaths",
1149
+ "harness"
1150
+ ];
1151
+ function applyBankConfig(cfg, resolvedId, directory) {
1152
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1153
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1154
+ const section = cfg.banks[resolvedId];
1155
+ if (!section) return { cfg, bankId: resolvedId };
1156
+ const safe = { ...section };
1157
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1158
+ delete safe.banks;
1159
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1160
+ delete safe.bank;
1161
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1162
+ }
1163
+ function resolvePartial(cfg, patch) {
1164
+ const full = resolveConfig(patch);
1165
+ const out = {};
1166
+ for (const key of Object.keys(patch)) {
1167
+ if (key in full)
1168
+ out[key] = full[key];
1169
+ }
1170
+ return out;
1171
+ }
1172
+
1173
+ // src/core/host-client.ts
1174
+ function resolveHostConfig(harness, directory) {
1175
+ const cfg0 = loadConfig({ harness });
1176
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
1177
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
1178
+ }
1179
+ function resolveHostMemory(harness, directory) {
1180
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
1181
+ return {
1182
+ cfg,
1183
+ bankId,
1184
+ client: new HindsightClient({
1185
+ apiUrl: cfg.apiUrl,
1186
+ apiToken: cfg.apiToken,
1187
+ bank: bankId,
1188
+ maxParallelRetains: cfg.maxParallelRetains,
1189
+ observationScopes: cfg.observationScopes,
1190
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
1191
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
1192
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
1193
+ // honoured on re-resolution exactly as it was on the first one.
1194
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
1195
+ })
1196
+ };
1024
1197
  }
1025
1198
 
1199
+ // src/core/daemon.ts
1200
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1201
+ import { dirname as dirname4, join as join5 } from "path";
1202
+ import { fileURLToPath as fileURLToPath2 } from "url";
1203
+
1026
1204
  // src/core/diag.ts
1205
+ import { appendFileSync as appendFileSync2 } from "fs";
1027
1206
  function diagFilePath() {
1028
1207
  return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1029
1208
  }
@@ -1038,6 +1217,120 @@ function diag(harness, event, extra = {}) {
1038
1217
  }
1039
1218
  }
1040
1219
 
1220
+ // src/core/daemon.ts
1221
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
1222
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
1223
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
1224
+ try {
1225
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
1226
+ return res.ok;
1227
+ } catch {
1228
+ return false;
1229
+ }
1230
+ }
1231
+ function hasRustToolchain() {
1232
+ if (process.platform !== "darwin") return true;
1233
+ try {
1234
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
1235
+ return true;
1236
+ } catch {
1237
+ return false;
1238
+ }
1239
+ }
1240
+ function hasUvx() {
1241
+ try {
1242
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
1243
+ return true;
1244
+ } catch {
1245
+ return false;
1246
+ }
1247
+ }
1248
+ var PROVIDER_PROBES = [
1249
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
1250
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
1251
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
1252
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
1253
+ ];
1254
+ function detectLlm(env = process.env) {
1255
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
1256
+ if (explicit) {
1257
+ return {
1258
+ provider: explicit,
1259
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
1260
+ source: "HINDSIGHT_API_LLM_PROVIDER"
1261
+ };
1262
+ }
1263
+ for (const probe of PROVIDER_PROBES) {
1264
+ const key = env[probe.keyEnv]?.trim();
1265
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
1266
+ }
1267
+ if (onPath("claude")) {
1268
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
1269
+ }
1270
+ return void 0;
1271
+ }
1272
+ function onPath(bin) {
1273
+ try {
1274
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
1275
+ return true;
1276
+ } catch {
1277
+ return false;
1278
+ }
1279
+ }
1280
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1281
+ try {
1282
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
1283
+ const child = spawnFn("node", [starter, "--harness", harness], {
1284
+ detached: true,
1285
+ stdio: "ignore"
1286
+ });
1287
+ child.on("error", () => {
1288
+ });
1289
+ child.unref();
1290
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
1291
+ } catch {
1292
+ }
1293
+ }
1294
+ async function ensureDaemon(cfg, harness, opts = {}) {
1295
+ if (cfg.serverMode !== "daemon") return;
1296
+ if (await isServerHealthy(cfg.apiUrl)) return;
1297
+ if (!preflightDaemon(cfg, harness)) return;
1298
+ startDaemonDetached(cfg, harness, opts.spawnFn);
1299
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
1300
+ }
1301
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1302
+ const deadline = Date.now() + budgetMs;
1303
+ while (Date.now() < deadline) {
1304
+ await new Promise((r) => setTimeout(r, pollMs));
1305
+ if (await isServerHealthy(baseUrl)) return true;
1306
+ }
1307
+ return false;
1308
+ }
1309
+ function preflightDaemon(cfg, harness) {
1310
+ if (!hasUvx()) {
1311
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
1312
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
1313
+ return false;
1314
+ }
1315
+ if (!hasRustToolchain()) {
1316
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
1317
+ log.warn(
1318
+ harness,
1319
+ "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`"
1320
+ );
1321
+ return false;
1322
+ }
1323
+ if (!detectLlm()) {
1324
+ diag(harness, "daemon_no_llm", {});
1325
+ log.warn(
1326
+ harness,
1327
+ "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"
1328
+ );
1329
+ return false;
1330
+ }
1331
+ return true;
1332
+ }
1333
+
1041
1334
  // node_modules/zod/v4/classic/external.js
1042
1335
  var external_exports = {};
1043
1336
  __export(external_exports, {
@@ -15555,16 +15848,16 @@ config(en_default());
15555
15848
  // src/core/knowledge-tools.ts
15556
15849
  import { existsSync as existsSync3 } from "fs";
15557
15850
  import { homedir as homedir4 } from "os";
15558
- import { join as join6 } from "path";
15851
+ import { join as join7 } from "path";
15559
15852
 
15560
15853
  // src/core/status.ts
15561
- import { execFileSync as execFileSync3 } from "child_process";
15854
+ import { execFileSync as execFileSync4 } from "child_process";
15562
15855
 
15563
15856
  // src/core/git.ts
15564
- import { execFileSync as execFileSync2 } from "child_process";
15857
+ import { execFileSync as execFileSync3 } from "child_process";
15565
15858
  import { resolve } from "path";
15566
15859
  function git(repo, ...args) {
15567
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15860
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15568
15861
  }
15569
15862
  function repoNameOf(repo) {
15570
15863
  return projectNameOf(resolve(repo));
@@ -15610,7 +15903,7 @@ function roster(pages) {
15610
15903
  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
15904
  - 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
15905
  - 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.
15906
+ - 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
15907
  - 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
15908
  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
15909
  function toolGuide(opts) {
@@ -15637,11 +15930,11 @@ ${toolGuide(opts)}
15637
15930
  }
15638
15931
 
15639
15932
  // src/core/survey.ts
15640
- import { spawn as realSpawn2 } from "child_process";
15933
+ import { spawn as realSpawn3 } from "child_process";
15641
15934
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15642
15935
  import { homedir as homedir3 } from "os";
15643
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15644
- import { fileURLToPath as fileURLToPath2 } from "url";
15936
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15937
+ import { fileURLToPath as fileURLToPath3 } from "url";
15645
15938
  var SURVEY_DOC_IDS = [
15646
15939
  "repository-component-map",
15647
15940
  "repository-core-concepts",
@@ -15651,7 +15944,7 @@ var SURVEY_DOC_IDS = [
15651
15944
  function resolveClaudeBin(explicit) {
15652
15945
  if (explicit) return explicit;
15653
15946
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15654
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15947
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15655
15948
  try {
15656
15949
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15657
15950
  } catch {
@@ -15680,7 +15973,7 @@ function binExists(bin) {
15680
15973
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15681
15974
  if (!dir) continue;
15682
15975
  try {
15683
- accessSync(join5(dir, bin), constants.X_OK);
15976
+ accessSync(join6(dir, bin), constants.X_OK);
15684
15977
  return true;
15685
15978
  } catch {
15686
15979
  }
@@ -15724,7 +16017,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15724
16017
  hindsight: {
15725
16018
  command: "node",
15726
16019
  args: [opts.mcpServerPath],
15727
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16020
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16021
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16022
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16023
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16024
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15728
16025
  }
15729
16026
  }
15730
16027
  });
@@ -15764,6 +16061,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15764
16061
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15765
16062
  "-c",
15766
16063
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16064
+ "-c",
16065
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15767
16066
  SURVEY_PROMPT
15768
16067
  ],
15769
16068
  env
@@ -15787,9 +16086,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15787
16086
  }
15788
16087
  function startCodebaseSurvey(repoDir, opts = {}) {
15789
16088
  try {
15790
- const spawnFn = opts.spawn ?? realSpawn2;
16089
+ const spawnFn = opts.spawn ?? realSpawn3;
15791
16090
  const exists = opts.exists ?? binExists;
15792
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16091
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15793
16092
  const preferred = opts.harness ?? "claude-code";
15794
16093
  const order = [
15795
16094
  preferred,
@@ -15828,7 +16127,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15828
16127
  var DEEPEN_DIFF_TARGET = 300;
15829
16128
  function commitCount(repoDir) {
15830
16129
  try {
15831
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16130
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15832
16131
  encoding: "utf8"
15833
16132
  });
15834
16133
  return Number(out.trim()) || 0;
@@ -15919,9 +16218,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15919
16218
  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
16219
  inputSchema: {},
15921
16220
  handler: async (_args) => {
15922
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16221
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15923
16222
  const harness = opts.harness ?? "unknown";
15924
- const cfg = loadConfig({ harness: opts.harness });
16223
+ const cfg = applyBankConfig(
16224
+ loadConfig({ harness: opts.harness }),
16225
+ bankId,
16226
+ opts.repoDir
16227
+ ).cfg;
15925
16228
  return ok({
15926
16229
  bank_id: bankId,
15927
16230
  harness,
@@ -15933,6 +16236,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15933
16236
  api_token_configured: Boolean(cfg.apiToken),
15934
16237
  disabled: cfg.disabled
15935
16238
  },
16239
+ // What the LIVE client is signing with, which is not the same question as what the file
16240
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16241
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16242
+ // value is never returned.
16243
+ credential: {
16244
+ api_token_in_use: Boolean(client.apiToken),
16245
+ api_token_matches_config: client.apiToken === cfg.apiToken
16246
+ },
15936
16247
  environment: {
15937
16248
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15938
16249
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15981,12 +16292,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15981
16292
  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
16293
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15983
16294
  handler: guarded(
15984
- async ({ query }) => client.reflect(query, { budget: "high" })
16295
+ async ({ query }) => client.reflect(query, {
16296
+ budget: opts.reflectBudget ?? "high",
16297
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16298
+ })
15985
16299
  )
15986
16300
  },
15987
16301
  {
15988
16302
  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.",
16303
+ 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
16304
  inputSchema: {
15991
16305
  title: external_exports.string(),
15992
16306
  summary: external_exports.string(),
@@ -15997,7 +16311,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15997
16311
  title,
15998
16312
  summary,
15999
16313
  relatesToPageId: relates_to_page_id,
16000
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16314
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16315
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
16001
16316
  })
16002
16317
  )
16003
16318
  },
@@ -16204,7 +16519,7 @@ function resolversFor(ctx) {
16204
16519
  return {
16205
16520
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16206
16521
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16207
- gitProject: () => projectNameOf(ctx.directory),
16522
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16208
16523
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16209
16524
  harness: () => ctx.harness,
16210
16525
  bankId: () => ctx.bankId,
@@ -16250,11 +16565,6 @@ import { readFileSync as readFileSync4 } from "fs";
16250
16565
  // src/core/skill-sync.ts
16251
16566
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16252
16567
  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
16568
  import { dirname as dirname6, join as join8 } from "path";
16259
16569
  import { fileURLToPath as fileURLToPath4 } from "url";
16260
16570
 
@@ -16345,7 +16655,7 @@ async function buildSessionStartContext(args) {
16345
16655
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16346
16656
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16347
16657
  const countCommitsSince = args.commitsSince ?? commitsSince;
16348
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16658
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16349
16659
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16350
16660
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16351
16661
  const recordSurveyBaseline = (sha) => {
@@ -16621,6 +16931,9 @@ var RuntimeCore = class {
16621
16931
  return buildKnowledgeTools(this.client, this.bankId, {
16622
16932
  repoDir: this.projectDir,
16623
16933
  harness: this.harness,
16934
+ pageTrigger: buildPageTrigger(this.cfg),
16935
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16936
+ reflectBudget: this.cfg.reflectBudget,
16624
16937
  stampFor: () => buildRetainStamp(this.cfg, {
16625
16938
  directory: this.projectDir,
16626
16939
  harness: this.harness,
@@ -16639,6 +16952,7 @@ var RuntimeCore = class {
16639
16952
  */
16640
16953
  async seedIfCold(repoPath) {
16641
16954
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16955
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16642
16956
  try {
16643
16957
  const out = await buildSessionStartContext({
16644
16958
  cwd: repoPath || process.cwd(),
@@ -16762,15 +17076,17 @@ var RuntimeCore = class {
16762
17076
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16763
17077
  retain(sessionId2, turns, startTs, trigger = "turn") {
16764
17078
  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
17079
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17080
+ () => retainLiveSession(this.client, sessionId2, turns, startTs, this.harness, {
17081
+ cursors: this.cursors,
17082
+ stamp: buildRetainStamp(this.cfg, {
17083
+ directory: this.projectDir,
17084
+ harness: this.harness,
17085
+ bankId: this.bankId,
17086
+ sessionId: sessionId2
17087
+ })
16772
17088
  })
16773
- }).then(
17089
+ ).then(
16774
17090
  () => diag(this.harness, "retain_ok", {
16775
17091
  ms: Date.now() - t0,
16776
17092
  turns: turns.length,
@@ -16839,7 +17155,7 @@ function createClineHooks(core, configuredSessionId, sessionStart) {
16839
17155
  }) {
16840
17156
  if (!sessionStartAwaited) {
16841
17157
  sessionStartAwaited = true;
16842
- await sessionStart;
17158
+ await settleWithinHookBudget(sessionStart ?? Promise.resolve());
16843
17159
  }
16844
17160
  const user = latestUserMessage(snapshot.messages);
16845
17161
  if (!user) return void 0;
@@ -16883,22 +17199,10 @@ function createClineHooks(core, configuredSessionId, sessionStart) {
16883
17199
  };
16884
17200
  }
16885
17201
  function createRuntime(workspaceRoot) {
16886
- let cfg = loadConfig({ harness: HARNESS2 });
17202
+ const dir = workspaceRoot || process.cwd();
17203
+ const { cfg, bankId, client } = resolveHostMemory(HARNESS2, dir);
16887
17204
  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());
17205
+ return new RuntimeCore(client, bankId, cfg, HARNESS2, dir);
16902
17206
  }
16903
17207
  var plugin = {
16904
17208
  name: "hindsight-coding-agents",