@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.
@@ -6,7 +6,11 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
10
14
  };
11
15
  var __export = (target, all) => {
12
16
  for (var name in all)
@@ -3640,7 +3644,12 @@ var require_fast_uri = __commonJS({
3640
3644
  }
3641
3645
  function resolve2(baseURI, relativeURI, options) {
3642
3646
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3643
- const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
3647
+ const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);
3648
+ const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);
3649
+ if (baseMalformed || relativeMalformed) {
3650
+ throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
3651
+ }
3652
+ const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
3644
3653
  schemelessOptions.skipEscape = true;
3645
3654
  return serialize(resolved, schemelessOptions);
3646
3655
  }
@@ -3766,6 +3775,7 @@ var require_fast_uri = __commonJS({
3766
3775
  }
3767
3776
  var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
3768
3777
  var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
3778
+ var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
3769
3779
  function getParseError(parsed, matches) {
3770
3780
  if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
3771
3781
  return 'URI path must start with "/" when authority is present.';
@@ -3800,6 +3810,20 @@ var require_fast_uri = __commonJS({
3800
3810
  parsed.error = "URI authority must not contain a literal backslash.";
3801
3811
  malformedAuthorityOrPort = true;
3802
3812
  }
3813
+ const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
3814
+ if (introducerMatch !== null) {
3815
+ const region = introducerMatch[1];
3816
+ const normalizedRegion = region.replace(/[\t\n\r]/g, "");
3817
+ if (normalizedRegion.length >= 2) {
3818
+ if (normalizedRegion.slice(0, 2) !== "//") {
3819
+ parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
3820
+ malformedAuthorityOrPort = true;
3821
+ } else if (region.length !== normalizedRegion.length) {
3822
+ parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
3823
+ malformedAuthorityOrPort = true;
3824
+ }
3825
+ }
3826
+ }
3803
3827
  const matches = uri.match(URI_PARSE);
3804
3828
  if (matches) {
3805
3829
  parsed.scheme = matches[1];
@@ -30960,7 +30984,7 @@ var StdioServerTransport = class {
30960
30984
  // src/core/config.ts
30961
30985
  import { readFileSync } from "fs";
30962
30986
  import { homedir as homedir2 } from "os";
30963
- import { join as join3 } from "path";
30987
+ import { join as join4 } from "path";
30964
30988
 
30965
30989
  // src/core/seed.ts
30966
30990
  import { spawn as realSpawn } from "child_process";
@@ -31006,8 +31030,8 @@ function getProjectRootFromGit(directory) {
31006
31030
  return null;
31007
31031
  }
31008
31032
  }
31009
- function projectNameOf(directory) {
31010
- return gitProjectName(directory, true);
31033
+ function projectNameOf(directory, sessionRoot) {
31034
+ return gitProjectName(directory, true, sessionRoot);
31011
31035
  }
31012
31036
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
31013
31037
  function nearestExistingDir(directory) {
@@ -31023,18 +31047,24 @@ function nearestExistingDir(directory) {
31023
31047
  function dirName(directory) {
31024
31048
  return directory && basename(directory) || "unknown";
31025
31049
  }
31026
- function gitProjectName(directory, resolveWorktrees) {
31050
+ function mainWorktreeRoot(directory, sessionRoot = "") {
31051
+ const candidates = [
31052
+ nearestExistingDir(directory),
31053
+ sessionRoot,
31054
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
31055
+ ];
31056
+ for (const candidate of candidates) {
31057
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
31058
+ if (root) return root;
31059
+ }
31060
+ return null;
31061
+ }
31062
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
31027
31063
  if (resolveWorktrees) {
31028
- const candidates = [
31029
- nearestExistingDir(directory),
31030
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
31031
- ];
31032
- for (const candidate of candidates) {
31033
- const root = candidate ? getProjectRootFromGit(candidate) : null;
31034
- if (root) return basename(root);
31035
- }
31064
+ const root = mainWorktreeRoot(directory, sessionRoot);
31065
+ if (root) return basename(root);
31036
31066
  }
31037
- return dirName(directory);
31067
+ return dirName(sessionRoot || directory);
31038
31068
  }
31039
31069
  function configuredDir(dir) {
31040
31070
  const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
@@ -31054,218 +31084,86 @@ function mapLookup(map2, directory) {
31054
31084
  }
31055
31085
  return best?.bank;
31056
31086
  }
31087
+ function lookupDirectories(config2, directory, sessionRoot = "") {
31088
+ const directories = [normalize(directory)];
31089
+ if (config2.resolveWorktrees ?? true) {
31090
+ const root = mainWorktreeRoot(directory, sessionRoot);
31091
+ const normalizedRoot = root ? normalize(root) : "";
31092
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
31093
+ }
31094
+ return directories;
31095
+ }
31057
31096
  function isOptedIn(config2, directory) {
31058
31097
  if (!config2.optInOnly) return true;
31059
31098
  if (!directory) return false;
31060
- const cwd = normalize(directory);
31061
- if ((config2.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
31099
+ const directories = lookupDirectories(config2, directory);
31100
+ if (directories.some(
31101
+ (candidate) => (config2.optInPaths ?? []).some(
31102
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
31103
+ )
31104
+ ))
31062
31105
  return true;
31063
- return Boolean(config2.mapPathToBank && mapLookup(config2.mapPathToBank, directory));
31106
+ const pathMap = config2.mapPathToBank;
31107
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
31064
31108
  }
31065
- function deriveBankId(config2, directory, harness = "coding") {
31066
- const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
31109
+ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
31110
+ const pathMap = config2.mapPathToBank;
31111
+ const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
31067
31112
  if (mapped) return mapped;
31068
31113
  const dynamic = config2.dynamicBankId ?? !config2.bankId;
31069
31114
  if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
31070
31115
  const resolvers = {
31071
31116
  harness: () => harness,
31072
31117
  project: () => dirName(directory),
31073
- gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
31118
+ gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot),
31074
31119
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
31075
31120
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
31076
31121
  };
31077
31122
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
31078
31123
  }
31079
31124
 
31080
- // src/core/config.ts
31081
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
31082
- var DEFAULT_DAEMON_PORT = 9077;
31083
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
31084
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
31085
- function resolveConfig(raw = {}) {
31086
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
31087
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
31088
- return {
31089
- serverMode,
31090
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
31091
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
31092
- // daemon needs no plumbing through eight separate constructors.
31093
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
31094
- apiToken: raw.apiToken || void 0,
31095
- apiPort,
31096
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
31097
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
31098
- embedVersion: raw.embedVersion || void 0,
31099
- embedPackagePath: raw.embedPackagePath || void 0,
31100
- bankId: raw.bankId,
31101
- dynamicBankId: raw.dynamicBankId,
31102
- bankIdTemplate: raw.bankIdTemplate,
31103
- mapPathToBank: raw.mapPathToBank,
31104
- resolveWorktrees: raw.resolveWorktrees,
31105
- optInOnly: raw.optInOnly ?? false,
31106
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
31107
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
31108
- harness: raw.harness ?? "opencode",
31109
- disabled: raw.disabled ?? false,
31110
- retainSessions: raw.retainSessions ?? true,
31111
- // opencode: write back by default (parity with hook-harness Stop)
31112
- maxParallelRetains: raw.maxParallelRetains || 10,
31113
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
31114
- autoReflect: raw.autoReflect ?? true,
31115
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
31116
- autoSeed: raw.autoSeed ?? true,
31117
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
31118
- codebaseSurvey: raw.codebaseSurvey ?? true,
31119
- surveyModel: raw.surveyModel || "haiku",
31120
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
31121
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
31122
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
31123
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
31124
- // nested object cannot reach the API as a tag and fail the whole retain.
31125
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
31126
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
31127
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
31128
- ) : {},
31129
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
31130
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
31131
- };
31125
+ // src/core/log.ts
31126
+ import { appendFileSync, mkdirSync } from "fs";
31127
+ import { tmpdir } from "os";
31128
+ import { dirname as dirname3, join as join3 } from "path";
31129
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
31130
+ var current = ["debug", "info", "warn", "error"].find(
31131
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
31132
+ ) ?? "info";
31133
+ function logFilePath() {
31134
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
31132
31135
  }
31133
- function readRaw(path) {
31136
+ function write(level, scope, msg, extra) {
31137
+ if (WEIGHT[level] < WEIGHT[current]) return;
31134
31138
  try {
31135
- return JSON.parse(readFileSync(path, "utf8"));
31136
- } catch (e) {
31137
- if (e?.code !== "ENOENT") {
31138
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
31139
- }
31140
- return {};
31139
+ const file2 = logFilePath();
31140
+ mkdirSync(dirname3(file2), { recursive: true });
31141
+ appendFileSync(
31142
+ file2,
31143
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
31144
+ );
31145
+ } catch {
31141
31146
  }
31142
31147
  }
31143
- function mergeRaw(a, b) {
31144
- const { harnesses: _drop, ...flat } = b;
31145
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
31146
- }
31147
- function applyLayer(raw, layer, harness) {
31148
- let out = mergeRaw(raw, layer);
31149
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
31150
- if (perHarness) out = mergeRaw(out, perHarness);
31151
- return out;
31152
- }
31153
- var ENV_KEYS = {
31154
- serverMode: "HINDSIGHT_SERVER_MODE",
31155
- apiUrl: "HINDSIGHT_API_URL",
31156
- apiToken: "HINDSIGHT_API_TOKEN",
31157
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
31158
- // it can carry their existing environment over unchanged.
31159
- apiPort: "HINDSIGHT_API_PORT",
31160
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
31161
- embedVersion: "HINDSIGHT_EMBED_VERSION",
31162
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
31163
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
31164
- bankId: "HINDSIGHT_BANK_ID",
31165
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
31166
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
31167
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
31168
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
31169
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
31170
- harness: "HINDSIGHT_HARNESS",
31171
- disabled: "HINDSIGHT_DISABLED",
31172
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
31173
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
31174
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
31175
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
31176
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
31177
- autoSeed: "HINDSIGHT_AUTO_SEED",
31178
- seedLimit: "HINDSIGHT_SEED_LIMIT",
31179
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
31180
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
31181
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
31182
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
31183
- logLevel: "HINDSIGHT_LOG_LEVEL",
31184
- gitIngest: "HINDSIGHT_GIT_INGEST",
31185
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
31186
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
31187
- retainTags: "HINDSIGHT_RETAIN_TAGS"
31148
+ var log = {
31149
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
31150
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
31151
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
31152
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
31188
31153
  };
31189
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
31190
- "dynamicBankId",
31191
- "resolveWorktrees",
31192
- "optInOnly",
31193
- "disabled",
31194
- "retainSessions",
31195
- "autoReflect",
31196
- "autoSeed",
31197
- "codebaseSurvey"
31198
- ]);
31199
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
31200
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
31201
- "apiPort",
31202
- "daemonIdleTimeout",
31203
- "maxParallelRetains",
31204
- "reflectTimeoutMs",
31205
- "pageRefreshEveryTurns",
31206
- "seedLimit",
31207
- "surveyBudgetUsd",
31208
- "surveyRefreshCommits"
31209
- ]);
31210
- function readEnvConfig(env = process.env) {
31211
- const out = {};
31212
- for (const [key, name] of Object.entries(ENV_KEYS)) {
31213
- const value = env[name];
31214
- if (value === void 0 || value.trim() === "") continue;
31215
- if (ENV_BOOLEANS.has(key)) {
31216
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
31217
- } else if (ENV_LISTS.has(key)) {
31218
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
31219
- if (items.length) out[key] = items;
31220
- } else if (ENV_NUMBERS.has(key)) {
31221
- const n = Number(value);
31222
- if (Number.isFinite(n)) out[key] = n;
31223
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
31224
- } else {
31225
- out[key] = value;
31226
- }
31227
- }
31228
- return out;
31229
- }
31230
- function loadConfig(opts = {}) {
31231
- const o = typeof opts === "string" ? { path: opts } : opts;
31232
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
31233
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
31234
- if (!raw.harness && o.harness) raw.harness = o.harness;
31235
- return resolveConfig(raw);
31236
- }
31237
- var BANK_OVERRIDE_EXCLUDED = [
31238
- "bankId",
31239
- "bankIdTemplate",
31240
- "mapPathToBank",
31241
- "dynamicBankId",
31242
- "resolveWorktrees",
31243
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
31244
- // only ever arrive too late to matter — strip them rather than let them read as effective.
31245
- "optInOnly",
31246
- "optInPaths",
31247
- "harness"
31248
- ];
31249
- function applyBankConfig(cfg, resolvedId, directory) {
31250
- if (directory !== void 0 && !isOptedIn(cfg, directory))
31251
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
31252
- const section = cfg.banks[resolvedId];
31253
- if (!section) return { cfg, bankId: resolvedId };
31254
- const safe = { ...section };
31255
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
31256
- delete safe.banks;
31257
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
31258
- delete safe.bank;
31259
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
31260
- }
31261
- function resolvePartial(cfg, patch) {
31262
- const full = resolveConfig(patch);
31263
- const out = {};
31264
- for (const key of Object.keys(patch)) {
31265
- if (key in full)
31266
- out[key] = full[key];
31154
+ function describeError(value, maxChars = 200) {
31155
+ const parts = [];
31156
+ const seen = /* @__PURE__ */ new Set();
31157
+ let current2 = value;
31158
+ while (current2 && !seen.has(current2)) {
31159
+ seen.add(current2);
31160
+ const error51 = current2;
31161
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
31162
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
31163
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
31164
+ current2 = error51.cause;
31267
31165
  }
31268
- return out;
31166
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
31269
31167
  }
31270
31168
 
31271
31169
  // src/core/missions.ts
@@ -31343,7 +31241,10 @@ var KNOWLEDGE_LABELS = {
31343
31241
  }
31344
31242
  ]
31345
31243
  };
31346
- var PAGES = [
31244
+ function pageScopeRule(project) {
31245
+ 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.`;
31246
+ }
31247
+ var PAGE_TAXONOMY = [
31347
31248
  {
31348
31249
  name: "Component map",
31349
31250
  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.",
@@ -31370,11 +31271,23 @@ var PAGES = [
31370
31271
  tags: ["knowledge:feature-work"]
31371
31272
  }
31372
31273
  ];
31274
+ function pagesFor(project) {
31275
+ const scope = pageScopeRule(project);
31276
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
31277
+ }
31373
31278
  var PAGE_MAX_TOKENS = 4096;
31374
- var PAGE_TRIGGER = {
31375
- fact_types: ["world", "experience", "observation"],
31376
- refresh_after_consolidation: true
31377
- };
31279
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
31280
+ function buildPageTrigger(cfg = {}) {
31281
+ const base = { fact_types: PAGE_FACT_TYPES };
31282
+ switch (cfg.pageTriggerType) {
31283
+ case "cron":
31284
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
31285
+ case "manual":
31286
+ return { ...base, refresh_after_consolidation: false };
31287
+ default:
31288
+ return { ...base, refresh_after_consolidation: true };
31289
+ }
31290
+ }
31378
31291
  var CODING_BANK_TEMPLATE = {
31379
31292
  version: "1",
31380
31293
  bank: {
@@ -31429,6 +31342,7 @@ async function pool(items, n, fn, onError, onProgress) {
31429
31342
  }
31430
31343
 
31431
31344
  // src/core/hindsight.ts
31345
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
31432
31346
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
31433
31347
  var RateLimitedError = class extends Error {
31434
31348
  constructor(retryAfterMs2) {
@@ -31461,8 +31375,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
31461
31375
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31462
31376
  var HindsightClient = class {
31463
31377
  apiUrl;
31464
- apiToken;
31378
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
31379
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
31380
+ token;
31381
+ tokenProvider;
31465
31382
  bank;
31383
+ project;
31466
31384
  opIds = [];
31467
31385
  // async operation ids collected by retain(), for drain()
31468
31386
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -31471,34 +31389,81 @@ var HindsightClient = class {
31471
31389
  idempotentRetain;
31472
31390
  log;
31473
31391
  maxParallelRetains;
31392
+ observationScopes;
31474
31393
  constructor(o) {
31475
31394
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
31476
- this.apiToken = o.apiToken;
31395
+ this.token = o.apiToken;
31396
+ this.tokenProvider = o.tokenProvider;
31477
31397
  this.bank = o.bank;
31398
+ this.project = o.project;
31478
31399
  this.log = o.log ?? (() => {
31479
31400
  });
31480
31401
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
31402
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
31403
+ }
31404
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
31405
+ get apiToken() {
31406
+ return this.token;
31481
31407
  }
31482
31408
  headers() {
31483
31409
  const h = { "Content-Type": "application/json" };
31484
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
31410
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
31485
31411
  return h;
31486
31412
  }
31413
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
31414
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
31415
+ * doubling every failing request. */
31416
+ refreshToken() {
31417
+ if (!this.tokenProvider) return false;
31418
+ let next;
31419
+ try {
31420
+ next = this.tokenProvider();
31421
+ } catch {
31422
+ return false;
31423
+ }
31424
+ if (next === this.token) return false;
31425
+ this.token = next;
31426
+ return true;
31427
+ }
31428
+ /**
31429
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
31430
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
31431
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
31432
+ * not.
31433
+ *
31434
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
31435
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
31436
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
31437
+ * bounds the whole call.
31438
+ */
31439
+ async fetchWithAuth(url2, init) {
31440
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
31441
+ const r = await send();
31442
+ if (r.status !== 401 || !this.refreshToken()) return r;
31443
+ return send();
31444
+ }
31445
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
31446
+ * server answers identically for both — only the client knows which it sent. */
31447
+ authHint(status) {
31448
+ if (status !== 401) return "";
31449
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
31450
+ }
31487
31451
  bankUrl(suffix = "") {
31488
31452
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
31489
31453
  }
31490
31454
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
31491
31455
  async req(method, url2, body, tolerate = []) {
31492
- const r = await fetch(url2, {
31456
+ const r = await this.fetchWithAuth(url2, {
31493
31457
  method,
31494
- headers: this.headers(),
31495
31458
  body: body ? JSON.stringify(body) : void 0,
31496
31459
  signal: AbortSignal.timeout(15e3)
31497
31460
  });
31498
31461
  if (r.status === 429 && !tolerate.includes(429))
31499
31462
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
31500
31463
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
31501
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
31464
+ throw new Error(
31465
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
31466
+ );
31502
31467
  return r;
31503
31468
  }
31504
31469
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -31509,7 +31474,11 @@ var HindsightClient = class {
31509
31474
  context,
31510
31475
  document_id: documentId,
31511
31476
  tags,
31512
- strategy
31477
+ strategy,
31478
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
31479
+ // observations were built under is a property of the write rather than of whichever server
31480
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
31481
+ observation_scopes: this.observationScopes
31513
31482
  };
31514
31483
  if (opts.timestamp) item.timestamp = opts.timestamp;
31515
31484
  if (opts.metadata) item.metadata = opts.metadata;
@@ -31588,7 +31557,7 @@ var HindsightClient = class {
31588
31557
  this.log(
31589
31558
  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}`
31590
31559
  );
31591
- await this.seedPages();
31560
+ await this.seedPages(opts.pageTrigger);
31592
31561
  }
31593
31562
  /**
31594
31563
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -31646,7 +31615,7 @@ var HindsightClient = class {
31646
31615
  let backoffMs = POLL_CYCLE_MS;
31647
31616
  await pool([...pending], this.maxParallelRetains, async (id) => {
31648
31617
  try {
31649
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
31618
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
31650
31619
  if (r.status === 429) {
31651
31620
  backoffMs = Math.min(
31652
31621
  RETRY_AFTER_CEILING_MS,
@@ -31672,18 +31641,23 @@ var HindsightClient = class {
31672
31641
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
31673
31642
  );
31674
31643
  }
31675
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
31676
- async reflect(query, opts = {}) {
31644
+ /**
31645
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
31646
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
31647
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
31648
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
31649
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
31650
+ */
31651
+ async reflect(query, opts) {
31677
31652
  const ctrl = new AbortController();
31678
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
31653
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
31679
31654
  try {
31680
- const resp = await fetch(this.bankUrl("/reflect"), {
31655
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
31681
31656
  method: "POST",
31682
- headers: this.headers(),
31683
31657
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
31684
31658
  signal: ctrl.signal
31685
31659
  });
31686
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
31660
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
31687
31661
  const data = await resp.json();
31688
31662
  return (data.text || "").trim();
31689
31663
  } finally {
@@ -31767,16 +31741,18 @@ var HindsightClient = class {
31767
31741
  }));
31768
31742
  }
31769
31743
  /**
31770
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
31744
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
31771
31745
  *
31772
31746
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
31773
31747
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
31774
31748
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
31775
31749
  *
31776
31750
  * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
31777
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
31751
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
31752
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
31778
31753
  */
31779
- async seedPages() {
31754
+ async seedPages(pageTrigger = buildPageTrigger()) {
31755
+ const pages = pagesFor(this.project ?? this.bank);
31780
31756
  const existing = /* @__PURE__ */ new Map();
31781
31757
  let roots;
31782
31758
  try {
@@ -31793,14 +31769,14 @@ var HindsightClient = class {
31793
31769
  }
31794
31770
  let created = 0;
31795
31771
  let updated = 0;
31796
- for (const page of PAGES) {
31772
+ for (const page of pages) {
31797
31773
  const hit = existing.get(page.name.toLowerCase());
31798
31774
  const body = {
31799
31775
  name: page.name,
31800
31776
  source_query: page.source_query,
31801
31777
  tags: page.tags,
31802
31778
  max_tokens: PAGE_MAX_TOKENS,
31803
- trigger: PAGE_TRIGGER
31779
+ trigger: pageTrigger
31804
31780
  };
31805
31781
  if (!hit) {
31806
31782
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -31829,7 +31805,7 @@ var HindsightClient = class {
31829
31805
  }
31830
31806
  }
31831
31807
  this.log(
31832
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
31808
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
31833
31809
  );
31834
31810
  }
31835
31811
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -31839,7 +31815,8 @@ var HindsightClient = class {
31839
31815
  /**
31840
31816
  * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
31841
31817
  * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
31842
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
31818
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
31819
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
31843
31820
  */
31844
31821
  async captureInitiative(args) {
31845
31822
  let pageId = args.relatesToPageId;
@@ -31850,10 +31827,7 @@ var HindsightClient = class {
31850
31827
  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.`,
31851
31828
  parent_id: folderId,
31852
31829
  tags: ["knowledge:feature-work"],
31853
- trigger: {
31854
- fact_types: ["world", "experience", "observation"],
31855
- refresh_after_consolidation: true
31856
- }
31830
+ trigger: args.pageTrigger ?? buildPageTrigger()
31857
31831
  });
31858
31832
  try {
31859
31833
  const j = await r.json();
@@ -31862,7 +31836,7 @@ var HindsightClient = class {
31862
31836
  }
31863
31837
  pageId ||= `initiative-${this.slugify(args.title)}`;
31864
31838
  }
31865
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
31839
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
31866
31840
  const content = `${verb}: ${args.title}. ${args.summary}`;
31867
31841
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
31868
31842
  const tags = [
@@ -31900,6 +31874,270 @@ var HindsightClient = class {
31900
31874
  }
31901
31875
  };
31902
31876
 
31877
+ // src/core/config.ts
31878
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
31879
+ var DEFAULT_DAEMON_PORT = 9077;
31880
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
31881
+ function resolvePageTriggerType(raw) {
31882
+ if (raw.pageTriggerType === "manual") return "manual";
31883
+ if (raw.pageTriggerType === "cron") {
31884
+ if (raw.pageTriggerCron?.trim()) return "cron";
31885
+ log.warn(
31886
+ "config",
31887
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
31888
+ );
31889
+ }
31890
+ return "auto-refresh";
31891
+ }
31892
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
31893
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
31894
+ function resolveReflectBudget(raw) {
31895
+ const value = raw.reflectBudget;
31896
+ if (value === void 0) return "high";
31897
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
31898
+ return value;
31899
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
31900
+ return "high";
31901
+ }
31902
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
31903
+ function resolveObservationScopes(raw) {
31904
+ const value = raw;
31905
+ if (typeof value === "string")
31906
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
31907
+ if (Array.isArray(value)) {
31908
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
31909
+ if (scopes.length) return scopes;
31910
+ }
31911
+ return DEFAULT_OBSERVATION_SCOPES;
31912
+ }
31913
+ function resolveConfig(raw = {}) {
31914
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
31915
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
31916
+ return {
31917
+ serverMode,
31918
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
31919
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
31920
+ // daemon needs no plumbing through eight separate constructors.
31921
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
31922
+ apiToken: raw.apiToken || void 0,
31923
+ apiPort,
31924
+ daemonIdleTimeout: raw.daemonIdleTimeout,
31925
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
31926
+ embedVersion: raw.embedVersion || void 0,
31927
+ embedPackagePath: raw.embedPackagePath || void 0,
31928
+ bankId: raw.bankId,
31929
+ dynamicBankId: raw.dynamicBankId,
31930
+ bankIdTemplate: raw.bankIdTemplate,
31931
+ mapPathToBank: raw.mapPathToBank,
31932
+ resolveWorktrees: raw.resolveWorktrees,
31933
+ optInOnly: raw.optInOnly ?? false,
31934
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
31935
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
31936
+ harness: raw.harness ?? "opencode",
31937
+ disabled: raw.disabled ?? false,
31938
+ retainSessions: raw.retainSessions ?? true,
31939
+ // write sessions back by default, every harness
31940
+ maxParallelRetains: raw.maxParallelRetains || 10,
31941
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
31942
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
31943
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
31944
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
31945
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
31946
+ reflectBudget: resolveReflectBudget(raw),
31947
+ autoReflect: raw.autoReflect ?? true,
31948
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
31949
+ pageTriggerType: resolvePageTriggerType(raw),
31950
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
31951
+ autoSeed: raw.autoSeed ?? true,
31952
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
31953
+ codebaseSurvey: raw.codebaseSurvey ?? true,
31954
+ surveyModel: raw.surveyModel || "haiku",
31955
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
31956
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
31957
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
31958
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
31959
+ // nested object cannot reach the API as a tag and fail the whole retain.
31960
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
31961
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
31962
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
31963
+ ) : {},
31964
+ observationScopes: resolveObservationScopes(raw.observationScopes),
31965
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
31966
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
31967
+ };
31968
+ }
31969
+ function readRaw(path) {
31970
+ try {
31971
+ return JSON.parse(readFileSync(path, "utf8"));
31972
+ } catch (e) {
31973
+ if (e?.code !== "ENOENT") {
31974
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
31975
+ }
31976
+ return {};
31977
+ }
31978
+ }
31979
+ function mergeRaw(a, b) {
31980
+ const { harnesses: _drop, ...flat } = b;
31981
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
31982
+ }
31983
+ function applyLayer(raw, layer, harness) {
31984
+ let out = mergeRaw(raw, layer);
31985
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
31986
+ if (perHarness) out = mergeRaw(out, perHarness);
31987
+ return out;
31988
+ }
31989
+ var ENV_KEYS = {
31990
+ serverMode: "HINDSIGHT_SERVER_MODE",
31991
+ apiUrl: "HINDSIGHT_API_URL",
31992
+ apiToken: "HINDSIGHT_API_TOKEN",
31993
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
31994
+ // it can carry their existing environment over unchanged.
31995
+ apiPort: "HINDSIGHT_API_PORT",
31996
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
31997
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
31998
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
31999
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
32000
+ bankId: "HINDSIGHT_BANK_ID",
32001
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
32002
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
32003
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
32004
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
32005
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
32006
+ harness: "HINDSIGHT_HARNESS",
32007
+ disabled: "HINDSIGHT_DISABLED",
32008
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
32009
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
32010
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
32011
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
32012
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
32013
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
32014
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
32015
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
32016
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
32017
+ autoSeed: "HINDSIGHT_AUTO_SEED",
32018
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
32019
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
32020
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
32021
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
32022
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
32023
+ logLevel: "HINDSIGHT_LOG_LEVEL",
32024
+ gitIngest: "HINDSIGHT_GIT_INGEST",
32025
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
32026
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
32027
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
32028
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
32029
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
32030
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
32031
+ };
32032
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
32033
+ "dynamicBankId",
32034
+ "resolveWorktrees",
32035
+ "optInOnly",
32036
+ "disabled",
32037
+ "retainSessions",
32038
+ "autoReflect",
32039
+ "autoSeed",
32040
+ "codebaseSurvey"
32041
+ ]);
32042
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
32043
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
32044
+ "apiPort",
32045
+ "daemonIdleTimeout",
32046
+ "maxParallelRetains",
32047
+ "reflectTimeoutMs",
32048
+ "reflectToolTimeoutMs",
32049
+ "pageRefreshEveryTurns",
32050
+ "seedLimit",
32051
+ "surveyBudgetUsd",
32052
+ "surveyRefreshCommits"
32053
+ ]);
32054
+ function readEnvConfig(env = process.env) {
32055
+ const out = {};
32056
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
32057
+ const value = env[name];
32058
+ if (value === void 0 || value.trim() === "") continue;
32059
+ if (ENV_BOOLEANS.has(key)) {
32060
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
32061
+ } else if (ENV_LISTS.has(key)) {
32062
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
32063
+ if (items.length) out[key] = items;
32064
+ } else if (ENV_NUMBERS.has(key)) {
32065
+ const n = Number(value);
32066
+ if (Number.isFinite(n)) out[key] = n;
32067
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
32068
+ } else {
32069
+ out[key] = value;
32070
+ }
32071
+ }
32072
+ return out;
32073
+ }
32074
+ function loadConfig(opts = {}) {
32075
+ const o = typeof opts === "string" ? { path: opts } : opts;
32076
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
32077
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
32078
+ if (!raw.harness && o.harness) raw.harness = o.harness;
32079
+ return resolveConfig(raw);
32080
+ }
32081
+ var BANK_OVERRIDE_EXCLUDED = [
32082
+ "bankId",
32083
+ "bankIdTemplate",
32084
+ "mapPathToBank",
32085
+ "dynamicBankId",
32086
+ "resolveWorktrees",
32087
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
32088
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
32089
+ "optInOnly",
32090
+ "optInPaths",
32091
+ "harness"
32092
+ ];
32093
+ function applyBankConfig(cfg, resolvedId, directory) {
32094
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
32095
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
32096
+ const section = cfg.banks[resolvedId];
32097
+ if (!section) return { cfg, bankId: resolvedId };
32098
+ const safe = { ...section };
32099
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
32100
+ delete safe.banks;
32101
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
32102
+ delete safe.bank;
32103
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
32104
+ }
32105
+ function resolvePartial(cfg, patch) {
32106
+ const full = resolveConfig(patch);
32107
+ const out = {};
32108
+ for (const key of Object.keys(patch)) {
32109
+ if (key in full)
32110
+ out[key] = full[key];
32111
+ }
32112
+ return out;
32113
+ }
32114
+
32115
+ // src/core/host-client.ts
32116
+ function resolveHostConfig(harness, directory) {
32117
+ const cfg0 = loadConfig({ harness });
32118
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
32119
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
32120
+ }
32121
+ function resolveHostMemory(harness, directory) {
32122
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
32123
+ return {
32124
+ cfg,
32125
+ bankId,
32126
+ client: new HindsightClient({
32127
+ apiUrl: cfg.apiUrl,
32128
+ apiToken: cfg.apiToken,
32129
+ bank: bankId,
32130
+ maxParallelRetains: cfg.maxParallelRetains,
32131
+ observationScopes: cfg.observationScopes,
32132
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
32133
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
32134
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
32135
+ // honoured on re-resolution exactly as it was on the first one.
32136
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
32137
+ })
32138
+ };
32139
+ }
32140
+
31903
32141
  // src/core/knowledge-tools.ts
31904
32142
  import { existsSync as existsSync3 } from "fs";
31905
32143
  import { homedir as homedir4 } from "os";
@@ -31943,7 +32181,7 @@ function parsePageList(raw) {
31943
32181
  import { spawn as realSpawn2 } from "child_process";
31944
32182
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
31945
32183
  import { homedir as homedir3 } from "os";
31946
- import { delimiter, dirname as dirname3, join as join4 } from "path";
32184
+ import { delimiter, dirname as dirname4, join as join5 } from "path";
31947
32185
  import { fileURLToPath as fileURLToPath2 } from "url";
31948
32186
  var SURVEY_DOC_IDS = [
31949
32187
  "repository-component-map",
@@ -32011,50 +32249,6 @@ async function syncStatus(client, bank, repoDir) {
32011
32249
  };
32012
32250
  }
32013
32251
 
32014
- // src/core/log.ts
32015
- import { appendFileSync, mkdirSync } from "fs";
32016
- import { tmpdir } from "os";
32017
- import { dirname as dirname4, join as join5 } from "path";
32018
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
32019
- var current = ["debug", "info", "warn", "error"].find(
32020
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
32021
- ) ?? "info";
32022
- function logFilePath() {
32023
- return process.env.HINDSIGHT_LOG_FILE || join5(tmpdir(), "hindsight-coding-agent", "plugin.log");
32024
- }
32025
- function write(level, scope, msg, extra) {
32026
- if (WEIGHT[level] < WEIGHT[current]) return;
32027
- try {
32028
- const file2 = logFilePath();
32029
- mkdirSync(dirname4(file2), { recursive: true });
32030
- appendFileSync(
32031
- file2,
32032
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
32033
- );
32034
- } catch {
32035
- }
32036
- }
32037
- var log = {
32038
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
32039
- info: (scope, msg, extra) => write("info", scope, msg, extra),
32040
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
32041
- error: (scope, msg, extra) => write("error", scope, msg, extra)
32042
- };
32043
- function describeError(value, maxChars = 200) {
32044
- const parts = [];
32045
- const seen = /* @__PURE__ */ new Set();
32046
- let current2 = value;
32047
- while (current2 && !seen.has(current2)) {
32048
- seen.add(current2);
32049
- const error51 = current2;
32050
- const text = typeof error51.message === "string" ? error51.message : String(current2);
32051
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
32052
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
32053
- current2 = error51.cause;
32054
- }
32055
- return (parts.join(": ") || String(value)).slice(0, maxChars);
32056
- }
32057
-
32058
32252
  // src/core/knowledge-tools.ts
32059
32253
  function ok(value) {
32060
32254
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
@@ -32093,7 +32287,11 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32093
32287
  handler: async (_args) => {
32094
32288
  const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
32095
32289
  const harness = opts.harness ?? "unknown";
32096
- const cfg = loadConfig({ harness: opts.harness });
32290
+ const cfg = applyBankConfig(
32291
+ loadConfig({ harness: opts.harness }),
32292
+ bankId,
32293
+ opts.repoDir
32294
+ ).cfg;
32097
32295
  return ok({
32098
32296
  bank_id: bankId,
32099
32297
  harness,
@@ -32105,6 +32303,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32105
32303
  api_token_configured: Boolean(cfg.apiToken),
32106
32304
  disabled: cfg.disabled
32107
32305
  },
32306
+ // What the LIVE client is signing with, which is not the same question as what the file
32307
+ // says. A long-lived host used to keep a credential the config had already replaced, and
32308
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
32309
+ // value is never returned.
32310
+ credential: {
32311
+ api_token_in_use: Boolean(client.apiToken),
32312
+ api_token_matches_config: client.apiToken === cfg.apiToken
32313
+ },
32108
32314
  environment: {
32109
32315
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
32110
32316
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -32153,12 +32359,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32153
32359
  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>".`,
32154
32360
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
32155
32361
  handler: guarded(
32156
- async ({ query }) => client.reflect(query, { budget: "high" })
32362
+ async ({ query }) => client.reflect(query, {
32363
+ budget: opts.reflectBudget ?? "high",
32364
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
32365
+ })
32157
32366
  )
32158
32367
  },
32159
32368
  {
32160
32369
  name: "hindsight_capture_initiative",
32161
- 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.",
32370
+ 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.",
32162
32371
  inputSchema: {
32163
32372
  title: external_exports.string(),
32164
32373
  summary: external_exports.string(),
@@ -32169,7 +32378,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32169
32378
  title,
32170
32379
  summary,
32171
32380
  relatesToPageId: relates_to_page_id,
32172
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
32381
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
32382
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
32173
32383
  })
32174
32384
  )
32175
32385
  },
@@ -32211,7 +32421,7 @@ function resolversFor(ctx) {
32211
32421
  return {
32212
32422
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
32213
32423
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
32214
- gitProject: () => projectNameOf(ctx.directory),
32424
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
32215
32425
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
32216
32426
  harness: () => ctx.harness,
32217
32427
  bankId: () => ctx.bankId,
@@ -32258,24 +32468,38 @@ function selectTools(cfg, client, bankId, opts = {}) {
32258
32468
  return cfg.disabled ? [] : buildKnowledgeTools(client, bankId, {
32259
32469
  repoDir: cwd,
32260
32470
  harness,
32471
+ pageTrigger: buildPageTrigger(cfg),
32472
+ reflectTimeoutMs: cfg.reflectToolTimeoutMs,
32473
+ reflectBudget: cfg.reflectBudget,
32261
32474
  stampFor: () => buildRetainStamp(cfg, { directory: cwd, harness, bankId })
32262
32475
  });
32263
32476
  }
32264
- async function main() {
32265
- const cwd = process.env.HINDSIGHT_MCP_PROJECT_CWD || process.cwd();
32266
- const harness = process.env.HINDSIGHT_MCP_HARNESS || "claude-code";
32267
- const cfg0 = loadConfig({ harness });
32268
- const { cfg, bankId } = applyBankConfig(cfg0, deriveBankId(cfg0, cwd, harness), cwd);
32269
- const client = new HindsightClient({
32270
- apiUrl: cfg.apiUrl,
32271
- apiToken: cfg.apiToken,
32272
- bank: bankId,
32273
- maxParallelRetains: cfg.maxParallelRetains
32274
- });
32477
+ function resolveHarness(env = process.env) {
32478
+ const harness = env.HINDSIGHT_MCP_HARNESS;
32479
+ if (!harness) {
32480
+ throw new Error(
32481
+ "HINDSIGHT_MCP_HARNESS is not set. Every coding agent launches this same mcp-server.js, so only that variable identifies the caller \u2014 it decides the harness:<id> stamp on everything ingested and which bank this session resolves. Re-run `npx @vectorize-io/hindsight-coding-agents install <harness>` to repair a registration written before the installer set it."
32482
+ );
32483
+ }
32484
+ return harness;
32485
+ }
32486
+ function buildMcpServer(tools) {
32275
32487
  const server = new McpServer({ name: "hindsight", version: "0.1.0" });
32276
- for (const t of selectTools(cfg, client, bankId, { cwd, harness })) {
32277
- server.tool(t.name, t.description, t.inputSchema, t.handler);
32488
+ if (tools.length === 0) {
32489
+ server.server.registerCapabilities({ tools: { listChanged: false } });
32490
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [] }));
32491
+ return server;
32492
+ }
32493
+ for (const tool of tools) {
32494
+ server.tool(tool.name, tool.description, tool.inputSchema, tool.handler);
32278
32495
  }
32496
+ return server;
32497
+ }
32498
+ async function main() {
32499
+ const cwd = process.env.HINDSIGHT_MCP_PROJECT_CWD || process.cwd();
32500
+ const harness = resolveHarness();
32501
+ const { cfg, bankId, client } = resolveHostMemory(harness, cwd);
32502
+ const server = buildMcpServer(selectTools(cfg, client, bankId, { cwd, harness }));
32279
32503
  await server.connect(new StdioServerTransport());
32280
32504
  }
32281
32505
  if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
@@ -32285,5 +32509,7 @@ if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
32285
32509
  });
32286
32510
  }
32287
32511
  export {
32512
+ buildMcpServer,
32513
+ resolveHarness,
32288
32514
  selectTools
32289
32515
  };