@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.
@@ -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.",
@@ -31366,15 +31267,28 @@ var PAGES = [
31366
31267
  },
31367
31268
  {
31368
31269
  name: "Initiatives and enhancements",
31369
- 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.",
31270
+ 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.",
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_TAGS_MATCH = "all";
31280
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
31281
+ function buildPageTrigger(cfg = {}) {
31282
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
31283
+ switch (cfg.pageTriggerType) {
31284
+ case "cron":
31285
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
31286
+ case "manual":
31287
+ return { ...base, refresh_after_consolidation: false };
31288
+ default:
31289
+ return { ...base, refresh_after_consolidation: true };
31290
+ }
31291
+ }
31378
31292
  var CODING_BANK_TEMPLATE = {
31379
31293
  version: "1",
31380
31294
  bank: {
@@ -31429,6 +31343,7 @@ async function pool(items, n, fn, onError, onProgress) {
31429
31343
  }
31430
31344
 
31431
31345
  // src/core/hindsight.ts
31346
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
31432
31347
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
31433
31348
  var RateLimitedError = class extends Error {
31434
31349
  constructor(retryAfterMs2) {
@@ -31461,8 +31376,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
31461
31376
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
31462
31377
  var HindsightClient = class {
31463
31378
  apiUrl;
31464
- apiToken;
31379
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
31380
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
31381
+ token;
31382
+ tokenProvider;
31465
31383
  bank;
31384
+ project;
31466
31385
  opIds = [];
31467
31386
  // async operation ids collected by retain(), for drain()
31468
31387
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -31471,34 +31390,81 @@ var HindsightClient = class {
31471
31390
  idempotentRetain;
31472
31391
  log;
31473
31392
  maxParallelRetains;
31393
+ observationScopes;
31474
31394
  constructor(o) {
31475
31395
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
31476
- this.apiToken = o.apiToken;
31396
+ this.token = o.apiToken;
31397
+ this.tokenProvider = o.tokenProvider;
31477
31398
  this.bank = o.bank;
31399
+ this.project = o.project;
31478
31400
  this.log = o.log ?? (() => {
31479
31401
  });
31480
31402
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
31403
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
31404
+ }
31405
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
31406
+ get apiToken() {
31407
+ return this.token;
31481
31408
  }
31482
31409
  headers() {
31483
31410
  const h = { "Content-Type": "application/json" };
31484
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
31411
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
31485
31412
  return h;
31486
31413
  }
31414
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
31415
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
31416
+ * doubling every failing request. */
31417
+ refreshToken() {
31418
+ if (!this.tokenProvider) return false;
31419
+ let next;
31420
+ try {
31421
+ next = this.tokenProvider();
31422
+ } catch {
31423
+ return false;
31424
+ }
31425
+ if (next === this.token) return false;
31426
+ this.token = next;
31427
+ return true;
31428
+ }
31429
+ /**
31430
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
31431
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
31432
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
31433
+ * not.
31434
+ *
31435
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
31436
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
31437
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
31438
+ * bounds the whole call.
31439
+ */
31440
+ async fetchWithAuth(url2, init) {
31441
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
31442
+ const r = await send();
31443
+ if (r.status !== 401 || !this.refreshToken()) return r;
31444
+ return send();
31445
+ }
31446
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
31447
+ * server answers identically for both — only the client knows which it sent. */
31448
+ authHint(status) {
31449
+ if (status !== 401) return "";
31450
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
31451
+ }
31487
31452
  bankUrl(suffix = "") {
31488
31453
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
31489
31454
  }
31490
31455
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
31491
31456
  async req(method, url2, body, tolerate = []) {
31492
- const r = await fetch(url2, {
31457
+ const r = await this.fetchWithAuth(url2, {
31493
31458
  method,
31494
- headers: this.headers(),
31495
31459
  body: body ? JSON.stringify(body) : void 0,
31496
31460
  signal: AbortSignal.timeout(15e3)
31497
31461
  });
31498
31462
  if (r.status === 429 && !tolerate.includes(429))
31499
31463
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
31500
31464
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
31501
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
31465
+ throw new Error(
31466
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
31467
+ );
31502
31468
  return r;
31503
31469
  }
31504
31470
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -31509,7 +31475,11 @@ var HindsightClient = class {
31509
31475
  context,
31510
31476
  document_id: documentId,
31511
31477
  tags,
31512
- strategy
31478
+ strategy,
31479
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
31480
+ // observations were built under is a property of the write rather than of whichever server
31481
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
31482
+ observation_scopes: this.observationScopes
31513
31483
  };
31514
31484
  if (opts.timestamp) item.timestamp = opts.timestamp;
31515
31485
  if (opts.metadata) item.metadata = opts.metadata;
@@ -31588,7 +31558,7 @@ var HindsightClient = class {
31588
31558
  this.log(
31589
31559
  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
31560
  );
31591
- await this.seedPages();
31561
+ await this.seedPages(opts.pageTrigger);
31592
31562
  }
31593
31563
  /**
31594
31564
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -31646,7 +31616,7 @@ var HindsightClient = class {
31646
31616
  let backoffMs = POLL_CYCLE_MS;
31647
31617
  await pool([...pending], this.maxParallelRetains, async (id) => {
31648
31618
  try {
31649
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
31619
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
31650
31620
  if (r.status === 429) {
31651
31621
  backoffMs = Math.min(
31652
31622
  RETRY_AFTER_CEILING_MS,
@@ -31672,18 +31642,23 @@ var HindsightClient = class {
31672
31642
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
31673
31643
  );
31674
31644
  }
31675
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
31676
- async reflect(query, opts = {}) {
31645
+ /**
31646
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
31647
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
31648
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
31649
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
31650
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
31651
+ */
31652
+ async reflect(query, opts) {
31677
31653
  const ctrl = new AbortController();
31678
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
31654
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
31679
31655
  try {
31680
- const resp = await fetch(this.bankUrl("/reflect"), {
31656
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
31681
31657
  method: "POST",
31682
- headers: this.headers(),
31683
31658
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
31684
31659
  signal: ctrl.signal
31685
31660
  });
31686
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
31661
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
31687
31662
  const data = await resp.json();
31688
31663
  return (data.text || "").trim();
31689
31664
  } finally {
@@ -31767,16 +31742,18 @@ var HindsightClient = class {
31767
31742
  }));
31768
31743
  }
31769
31744
  /**
31770
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
31745
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
31771
31746
  *
31772
31747
  * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
31773
31748
  * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
31774
31749
  * off a slug). Names are unique per folder server-side, which makes them a sound key.
31775
31750
  *
31776
31751
  * 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.
31752
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
31753
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
31778
31754
  */
31779
- async seedPages() {
31755
+ async seedPages(pageTrigger = buildPageTrigger()) {
31756
+ const pages = pagesFor(this.project ?? this.bank);
31780
31757
  const existing = /* @__PURE__ */ new Map();
31781
31758
  let roots;
31782
31759
  try {
@@ -31793,14 +31770,14 @@ var HindsightClient = class {
31793
31770
  }
31794
31771
  let created = 0;
31795
31772
  let updated = 0;
31796
- for (const page of PAGES) {
31773
+ for (const page of pages) {
31797
31774
  const hit = existing.get(page.name.toLowerCase());
31798
31775
  const body = {
31799
31776
  name: page.name,
31800
31777
  source_query: page.source_query,
31801
31778
  tags: page.tags,
31802
31779
  max_tokens: PAGE_MAX_TOKENS,
31803
- trigger: PAGE_TRIGGER
31780
+ trigger: pageTrigger
31804
31781
  };
31805
31782
  if (!hit) {
31806
31783
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -31812,11 +31789,18 @@ var HindsightClient = class {
31812
31789
  return;
31813
31790
  }
31814
31791
  if (r.status !== 409) created++;
31815
- } else if (hit.description !== page.source_query) {
31792
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
31793
+ const patch = {
31794
+ trigger: pageTrigger
31795
+ };
31796
+ if (hit.description !== page.source_query) {
31797
+ patch.source_query = page.source_query;
31798
+ patch.tags = page.tags;
31799
+ }
31816
31800
  const r = await this.req(
31817
31801
  "PATCH",
31818
31802
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
31819
- { source_query: page.source_query, tags: page.tags }
31803
+ patch
31820
31804
  );
31821
31805
  if ([404, 405, 501].includes(r.status)) {
31822
31806
  this.knowledgePagesSupported = false;
@@ -31829,7 +31813,7 @@ var HindsightClient = class {
31829
31813
  }
31830
31814
  }
31831
31815
  this.log(
31832
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
31816
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
31833
31817
  );
31834
31818
  }
31835
31819
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -31837,9 +31821,17 @@ var HindsightClient = class {
31837
31821
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
31838
31822
  }
31839
31823
  /**
31840
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
31841
- * 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.
31824
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
31825
+ * New initiative → creates a page under the Initiatives folder.
31826
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
31827
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
31828
+ *
31829
+ * The marker carries its page id in two places, neither of them a tag (#3641):
31830
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
31831
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
31832
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
31833
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
31834
+ * vocabulary that exists to be matched with exact set-ops.
31843
31835
  */
31844
31836
  async captureInitiative(args) {
31845
31837
  let pageId = args.relatesToPageId;
@@ -31850,10 +31842,7 @@ var HindsightClient = class {
31850
31842
  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
31843
  parent_id: folderId,
31852
31844
  tags: ["knowledge:feature-work"],
31853
- trigger: {
31854
- fact_types: ["world", "experience", "observation"],
31855
- refresh_after_consolidation: true
31856
- }
31845
+ trigger: args.pageTrigger ?? buildPageTrigger()
31857
31846
  });
31858
31847
  try {
31859
31848
  const j = await r.json();
@@ -31862,23 +31851,14 @@ var HindsightClient = class {
31862
31851
  }
31863
31852
  pageId ||= `initiative-${this.slugify(args.title)}`;
31864
31853
  }
31865
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
31854
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
31866
31855
  const content = `${verb}: ${args.title}. ${args.summary}`;
31867
31856
  const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
31868
- const tags = [
31869
- .../* @__PURE__ */ new Set([
31870
- ...args.stamp?.tags ?? [],
31871
- "knowledge:feature-work",
31872
- `relatedPageId:${pageId}`
31873
- ])
31874
- ];
31875
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
31876
- await this.retain(content, "initiative marker", markerId, tags, "document", {
31877
- metadata: args.stamp?.metadata
31878
- });
31879
- } else {
31880
- await this.retain(content, "initiative marker", markerId, tags, "document");
31881
- }
31857
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
31858
+ const context = `initiative marker for [[page:${pageId}]]`;
31859
+ await this.retain(content, context, markerId, tags, "document", {
31860
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
31861
+ });
31882
31862
  return { page_id: pageId };
31883
31863
  }
31884
31864
  /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
@@ -31900,6 +31880,270 @@ var HindsightClient = class {
31900
31880
  }
31901
31881
  };
31902
31882
 
31883
+ // src/core/config.ts
31884
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
31885
+ var DEFAULT_DAEMON_PORT = 9077;
31886
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
31887
+ function resolvePageTriggerType(raw) {
31888
+ if (raw.pageTriggerType === "manual") return "manual";
31889
+ if (raw.pageTriggerType === "cron") {
31890
+ if (raw.pageTriggerCron?.trim()) return "cron";
31891
+ log.warn(
31892
+ "config",
31893
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
31894
+ );
31895
+ }
31896
+ return "auto-refresh";
31897
+ }
31898
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
31899
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
31900
+ function resolveReflectBudget(raw) {
31901
+ const value = raw.reflectBudget;
31902
+ if (value === void 0) return "high";
31903
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
31904
+ return value;
31905
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
31906
+ return "high";
31907
+ }
31908
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
31909
+ function resolveObservationScopes(raw) {
31910
+ const value = raw;
31911
+ if (typeof value === "string")
31912
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
31913
+ if (Array.isArray(value)) {
31914
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
31915
+ if (scopes.length) return scopes;
31916
+ }
31917
+ return DEFAULT_OBSERVATION_SCOPES;
31918
+ }
31919
+ function resolveConfig(raw = {}) {
31920
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
31921
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
31922
+ return {
31923
+ serverMode,
31924
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
31925
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
31926
+ // daemon needs no plumbing through eight separate constructors.
31927
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
31928
+ apiToken: raw.apiToken || void 0,
31929
+ apiPort,
31930
+ daemonIdleTimeout: raw.daemonIdleTimeout,
31931
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
31932
+ embedVersion: raw.embedVersion || void 0,
31933
+ embedPackagePath: raw.embedPackagePath || void 0,
31934
+ bankId: raw.bankId,
31935
+ dynamicBankId: raw.dynamicBankId,
31936
+ bankIdTemplate: raw.bankIdTemplate,
31937
+ mapPathToBank: raw.mapPathToBank,
31938
+ resolveWorktrees: raw.resolveWorktrees,
31939
+ optInOnly: raw.optInOnly ?? false,
31940
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
31941
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
31942
+ harness: raw.harness ?? "opencode",
31943
+ disabled: raw.disabled ?? false,
31944
+ retainSessions: raw.retainSessions ?? true,
31945
+ // write sessions back by default, every harness
31946
+ maxParallelRetains: raw.maxParallelRetains || 10,
31947
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
31948
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
31949
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
31950
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
31951
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
31952
+ reflectBudget: resolveReflectBudget(raw),
31953
+ autoReflect: raw.autoReflect ?? true,
31954
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
31955
+ pageTriggerType: resolvePageTriggerType(raw),
31956
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
31957
+ autoSeed: raw.autoSeed ?? true,
31958
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
31959
+ codebaseSurvey: raw.codebaseSurvey ?? true,
31960
+ surveyModel: raw.surveyModel || "haiku",
31961
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
31962
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
31963
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
31964
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
31965
+ // nested object cannot reach the API as a tag and fail the whole retain.
31966
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
31967
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
31968
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
31969
+ ) : {},
31970
+ observationScopes: resolveObservationScopes(raw.observationScopes),
31971
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
31972
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
31973
+ };
31974
+ }
31975
+ function readRaw(path) {
31976
+ try {
31977
+ return JSON.parse(readFileSync(path, "utf8"));
31978
+ } catch (e) {
31979
+ if (e?.code !== "ENOENT") {
31980
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
31981
+ }
31982
+ return {};
31983
+ }
31984
+ }
31985
+ function mergeRaw(a, b) {
31986
+ const { harnesses: _drop, ...flat } = b;
31987
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
31988
+ }
31989
+ function applyLayer(raw, layer, harness) {
31990
+ let out = mergeRaw(raw, layer);
31991
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
31992
+ if (perHarness) out = mergeRaw(out, perHarness);
31993
+ return out;
31994
+ }
31995
+ var ENV_KEYS = {
31996
+ serverMode: "HINDSIGHT_SERVER_MODE",
31997
+ apiUrl: "HINDSIGHT_API_URL",
31998
+ apiToken: "HINDSIGHT_API_TOKEN",
31999
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
32000
+ // it can carry their existing environment over unchanged.
32001
+ apiPort: "HINDSIGHT_API_PORT",
32002
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
32003
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
32004
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
32005
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
32006
+ bankId: "HINDSIGHT_BANK_ID",
32007
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
32008
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
32009
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
32010
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
32011
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
32012
+ harness: "HINDSIGHT_HARNESS",
32013
+ disabled: "HINDSIGHT_DISABLED",
32014
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
32015
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
32016
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
32017
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
32018
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
32019
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
32020
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
32021
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
32022
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
32023
+ autoSeed: "HINDSIGHT_AUTO_SEED",
32024
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
32025
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
32026
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
32027
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
32028
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
32029
+ logLevel: "HINDSIGHT_LOG_LEVEL",
32030
+ gitIngest: "HINDSIGHT_GIT_INGEST",
32031
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
32032
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
32033
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
32034
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
32035
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
32036
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
32037
+ };
32038
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
32039
+ "dynamicBankId",
32040
+ "resolveWorktrees",
32041
+ "optInOnly",
32042
+ "disabled",
32043
+ "retainSessions",
32044
+ "autoReflect",
32045
+ "autoSeed",
32046
+ "codebaseSurvey"
32047
+ ]);
32048
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
32049
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
32050
+ "apiPort",
32051
+ "daemonIdleTimeout",
32052
+ "maxParallelRetains",
32053
+ "reflectTimeoutMs",
32054
+ "reflectToolTimeoutMs",
32055
+ "pageRefreshEveryTurns",
32056
+ "seedLimit",
32057
+ "surveyBudgetUsd",
32058
+ "surveyRefreshCommits"
32059
+ ]);
32060
+ function readEnvConfig(env = process.env) {
32061
+ const out = {};
32062
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
32063
+ const value = env[name];
32064
+ if (value === void 0 || value.trim() === "") continue;
32065
+ if (ENV_BOOLEANS.has(key)) {
32066
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
32067
+ } else if (ENV_LISTS.has(key)) {
32068
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
32069
+ if (items.length) out[key] = items;
32070
+ } else if (ENV_NUMBERS.has(key)) {
32071
+ const n = Number(value);
32072
+ if (Number.isFinite(n)) out[key] = n;
32073
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
32074
+ } else {
32075
+ out[key] = value;
32076
+ }
32077
+ }
32078
+ return out;
32079
+ }
32080
+ function loadConfig(opts = {}) {
32081
+ const o = typeof opts === "string" ? { path: opts } : opts;
32082
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
32083
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
32084
+ if (!raw.harness && o.harness) raw.harness = o.harness;
32085
+ return resolveConfig(raw);
32086
+ }
32087
+ var BANK_OVERRIDE_EXCLUDED = [
32088
+ "bankId",
32089
+ "bankIdTemplate",
32090
+ "mapPathToBank",
32091
+ "dynamicBankId",
32092
+ "resolveWorktrees",
32093
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
32094
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
32095
+ "optInOnly",
32096
+ "optInPaths",
32097
+ "harness"
32098
+ ];
32099
+ function applyBankConfig(cfg, resolvedId, directory) {
32100
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
32101
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
32102
+ const section = cfg.banks[resolvedId];
32103
+ if (!section) return { cfg, bankId: resolvedId };
32104
+ const safe = { ...section };
32105
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
32106
+ delete safe.banks;
32107
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
32108
+ delete safe.bank;
32109
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
32110
+ }
32111
+ function resolvePartial(cfg, patch) {
32112
+ const full = resolveConfig(patch);
32113
+ const out = {};
32114
+ for (const key of Object.keys(patch)) {
32115
+ if (key in full)
32116
+ out[key] = full[key];
32117
+ }
32118
+ return out;
32119
+ }
32120
+
32121
+ // src/core/host-client.ts
32122
+ function resolveHostConfig(harness, directory) {
32123
+ const cfg0 = loadConfig({ harness });
32124
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
32125
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
32126
+ }
32127
+ function resolveHostMemory(harness, directory) {
32128
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
32129
+ return {
32130
+ cfg,
32131
+ bankId,
32132
+ client: new HindsightClient({
32133
+ apiUrl: cfg.apiUrl,
32134
+ apiToken: cfg.apiToken,
32135
+ bank: bankId,
32136
+ maxParallelRetains: cfg.maxParallelRetains,
32137
+ observationScopes: cfg.observationScopes,
32138
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
32139
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
32140
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
32141
+ // honoured on re-resolution exactly as it was on the first one.
32142
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
32143
+ })
32144
+ };
32145
+ }
32146
+
31903
32147
  // src/core/knowledge-tools.ts
31904
32148
  import { existsSync as existsSync3 } from "fs";
31905
32149
  import { homedir as homedir4 } from "os";
@@ -31943,7 +32187,7 @@ function parsePageList(raw) {
31943
32187
  import { spawn as realSpawn2 } from "child_process";
31944
32188
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
31945
32189
  import { homedir as homedir3 } from "os";
31946
- import { delimiter, dirname as dirname3, join as join4 } from "path";
32190
+ import { delimiter, dirname as dirname4, join as join5 } from "path";
31947
32191
  import { fileURLToPath as fileURLToPath2 } from "url";
31948
32192
  var SURVEY_DOC_IDS = [
31949
32193
  "repository-component-map",
@@ -32011,50 +32255,6 @@ async function syncStatus(client, bank, repoDir) {
32011
32255
  };
32012
32256
  }
32013
32257
 
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
32258
  // src/core/knowledge-tools.ts
32059
32259
  function ok(value) {
32060
32260
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
@@ -32093,7 +32293,11 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32093
32293
  handler: async (_args) => {
32094
32294
  const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
32095
32295
  const harness = opts.harness ?? "unknown";
32096
- const cfg = loadConfig({ harness: opts.harness });
32296
+ const cfg = applyBankConfig(
32297
+ loadConfig({ harness: opts.harness }),
32298
+ bankId,
32299
+ opts.repoDir
32300
+ ).cfg;
32097
32301
  return ok({
32098
32302
  bank_id: bankId,
32099
32303
  harness,
@@ -32105,6 +32309,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32105
32309
  api_token_configured: Boolean(cfg.apiToken),
32106
32310
  disabled: cfg.disabled
32107
32311
  },
32312
+ // What the LIVE client is signing with, which is not the same question as what the file
32313
+ // says. A long-lived host used to keep a credential the config had already replaced, and
32314
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
32315
+ // value is never returned.
32316
+ credential: {
32317
+ api_token_in_use: Boolean(client.apiToken),
32318
+ api_token_matches_config: client.apiToken === cfg.apiToken
32319
+ },
32108
32320
  environment: {
32109
32321
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
32110
32322
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -32153,12 +32365,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32153
32365
  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
32366
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
32155
32367
  handler: guarded(
32156
- async ({ query }) => client.reflect(query, { budget: "high" })
32368
+ async ({ query }) => client.reflect(query, {
32369
+ budget: opts.reflectBudget ?? "high",
32370
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
32371
+ })
32157
32372
  )
32158
32373
  },
32159
32374
  {
32160
32375
  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.",
32376
+ 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
32377
  inputSchema: {
32163
32378
  title: external_exports.string(),
32164
32379
  summary: external_exports.string(),
@@ -32169,7 +32384,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
32169
32384
  title,
32170
32385
  summary,
32171
32386
  relatesToPageId: relates_to_page_id,
32172
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
32387
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
32388
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
32173
32389
  })
32174
32390
  )
32175
32391
  },
@@ -32211,7 +32427,7 @@ function resolversFor(ctx) {
32211
32427
  return {
32212
32428
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
32213
32429
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
32214
- gitProject: () => projectNameOf(ctx.directory),
32430
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
32215
32431
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
32216
32432
  harness: () => ctx.harness,
32217
32433
  bankId: () => ctx.bankId,
@@ -32258,24 +32474,38 @@ function selectTools(cfg, client, bankId, opts = {}) {
32258
32474
  return cfg.disabled ? [] : buildKnowledgeTools(client, bankId, {
32259
32475
  repoDir: cwd,
32260
32476
  harness,
32477
+ pageTrigger: buildPageTrigger(cfg),
32478
+ reflectTimeoutMs: cfg.reflectToolTimeoutMs,
32479
+ reflectBudget: cfg.reflectBudget,
32261
32480
  stampFor: () => buildRetainStamp(cfg, { directory: cwd, harness, bankId })
32262
32481
  });
32263
32482
  }
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
- });
32483
+ function resolveHarness(env = process.env) {
32484
+ const harness = env.HINDSIGHT_MCP_HARNESS;
32485
+ if (!harness) {
32486
+ throw new Error(
32487
+ "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."
32488
+ );
32489
+ }
32490
+ return harness;
32491
+ }
32492
+ function buildMcpServer(tools) {
32275
32493
  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);
32494
+ if (tools.length === 0) {
32495
+ server.server.registerCapabilities({ tools: { listChanged: false } });
32496
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [] }));
32497
+ return server;
32278
32498
  }
32499
+ for (const tool of tools) {
32500
+ server.tool(tool.name, tool.description, tool.inputSchema, tool.handler);
32501
+ }
32502
+ return server;
32503
+ }
32504
+ async function main() {
32505
+ const cwd = process.env.HINDSIGHT_MCP_PROJECT_CWD || process.cwd();
32506
+ const harness = resolveHarness();
32507
+ const { cfg, bankId, client } = resolveHostMemory(harness, cwd);
32508
+ const server = buildMcpServer(selectTools(cfg, client, bankId, { cwd, harness }));
32279
32509
  await server.connect(new StdioServerTransport());
32280
32510
  }
32281
32511
  if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
@@ -32285,5 +32515,7 @@ if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
32285
32515
  });
32286
32516
  }
32287
32517
  export {
32518
+ buildMcpServer,
32519
+ resolveHarness,
32288
32520
  selectTools
32289
32521
  };