@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.
@@ -14518,11 +14518,48 @@ function date4(params) {
14518
14518
  // node_modules/zod/v4/classic/external.js
14519
14519
  config(en_default());
14520
14520
 
14521
+ // src/core/config.ts
14522
+ import { readFileSync } from "fs";
14523
+ import { homedir as homedir2 } from "os";
14524
+ import { join as join4 } from "path";
14525
+
14526
+ // src/core/seed.ts
14527
+ import { spawn as realSpawn } from "child_process";
14528
+ import { dirname, join } from "path";
14529
+ import { fileURLToPath } from "url";
14530
+ var DEFAULT_SEED_LIMIT = 300;
14531
+ function startBackgroundSeed(repoDir, opts = {}) {
14532
+ try {
14533
+ const spawnFn = opts.spawn ?? realSpawn;
14534
+ const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
14535
+ const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
14536
+ const child = spawnFn(
14537
+ "node",
14538
+ [
14539
+ enginePath,
14540
+ "--repo",
14541
+ repoDir,
14542
+ "--gitlog-limit",
14543
+ String(limit),
14544
+ ...opts.harness ? ["--harness", opts.harness] : []
14545
+ ],
14546
+ {
14547
+ detached: true,
14548
+ stdio: "ignore"
14549
+ }
14550
+ );
14551
+ child.on("error", () => {
14552
+ });
14553
+ child.unref();
14554
+ } catch {
14555
+ }
14556
+ }
14557
+
14521
14558
  // src/core/bank.ts
14522
14559
  import { execFileSync } from "child_process";
14523
14560
  import { existsSync } from "fs";
14524
14561
  import { homedir } from "os";
14525
- import { basename, dirname, join, normalize, sep } from "path";
14562
+ import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
14526
14563
 
14527
14564
  // src/core/template.ts
14528
14565
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
@@ -14551,20 +14588,20 @@ function getProjectRootFromGit(directory) {
14551
14588
  { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
14552
14589
  ).trim();
14553
14590
  if (!commonDir) return null;
14554
- return basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
14591
+ return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
14555
14592
  } catch {
14556
14593
  return null;
14557
14594
  }
14558
14595
  }
14559
- function projectNameOf(directory) {
14560
- return gitProjectName(directory, true);
14596
+ function projectNameOf(directory, sessionRoot) {
14597
+ return gitProjectName(directory, true, sessionRoot);
14561
14598
  }
14562
14599
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
14563
14600
  function nearestExistingDir(directory) {
14564
14601
  let current2 = directory;
14565
14602
  while (current2) {
14566
14603
  if (existsSync(current2)) return current2;
14567
- const parent = dirname(current2);
14604
+ const parent = dirname2(current2);
14568
14605
  if (parent === current2) return "";
14569
14606
  current2 = parent;
14570
14607
  }
@@ -14573,21 +14610,27 @@ function nearestExistingDir(directory) {
14573
14610
  function dirName(directory) {
14574
14611
  return directory && basename(directory) || "unknown";
14575
14612
  }
14576
- function gitProjectName(directory, resolveWorktrees) {
14613
+ function mainWorktreeRoot(directory, sessionRoot = "") {
14614
+ const candidates = [
14615
+ nearestExistingDir(directory),
14616
+ sessionRoot,
14617
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
14618
+ ];
14619
+ for (const candidate of candidates) {
14620
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
14621
+ if (root) return root;
14622
+ }
14623
+ return null;
14624
+ }
14625
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
14577
14626
  if (resolveWorktrees) {
14578
- const candidates = [
14579
- nearestExistingDir(directory),
14580
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
14581
- ];
14582
- for (const candidate of candidates) {
14583
- const root = candidate ? getProjectRootFromGit(candidate) : null;
14584
- if (root) return basename(root);
14585
- }
14627
+ const root = mainWorktreeRoot(directory, sessionRoot);
14628
+ if (root) return basename(root);
14586
14629
  }
14587
- return dirName(directory);
14630
+ return dirName(sessionRoot || directory);
14588
14631
  }
14589
14632
  function configuredDir(dir) {
14590
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
14633
+ const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
14591
14634
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
14592
14635
  }
14593
14636
  function isWithin(directory, configured) {
@@ -14604,320 +14647,89 @@ function mapLookup(map2, directory) {
14604
14647
  }
14605
14648
  return best?.bank;
14606
14649
  }
14650
+ function lookupDirectories(config2, directory, sessionRoot = "") {
14651
+ const directories = [normalize(directory)];
14652
+ if (config2.resolveWorktrees ?? true) {
14653
+ const root = mainWorktreeRoot(directory, sessionRoot);
14654
+ const normalizedRoot = root ? normalize(root) : "";
14655
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
14656
+ }
14657
+ return directories;
14658
+ }
14607
14659
  function isOptedIn(config2, directory) {
14608
14660
  if (!config2.optInOnly) return true;
14609
14661
  if (!directory) return false;
14610
- const cwd = normalize(directory);
14611
- if ((config2.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
14662
+ const directories = lookupDirectories(config2, directory);
14663
+ if (directories.some(
14664
+ (candidate) => (config2.optInPaths ?? []).some(
14665
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
14666
+ )
14667
+ ))
14612
14668
  return true;
14613
- return Boolean(config2.mapPathToBank && mapLookup(config2.mapPathToBank, directory));
14669
+ const pathMap = config2.mapPathToBank;
14670
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
14614
14671
  }
14615
- function deriveBankId(config2, directory, harness = "coding") {
14616
- const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
14672
+ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
14673
+ const pathMap = config2.mapPathToBank;
14674
+ const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
14617
14675
  if (mapped) return mapped;
14618
14676
  const dynamic = config2.dynamicBankId ?? !config2.bankId;
14619
14677
  if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
14620
14678
  const resolvers = {
14621
14679
  harness: () => harness,
14622
14680
  project: () => dirName(directory),
14623
- gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
14681
+ gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot),
14624
14682
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
14625
14683
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
14626
14684
  };
14627
14685
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14628
14686
  }
14629
14687
 
14630
- // src/core/config.ts
14631
- import { readFileSync } from "fs";
14632
- import { homedir as homedir2 } from "os";
14633
- import { join as join3 } from "path";
14634
-
14635
- // src/core/seed.ts
14636
- import { spawn as realSpawn } from "child_process";
14637
- import { dirname as dirname2, join as join2 } from "path";
14638
- import { fileURLToPath } from "url";
14639
- var DEFAULT_SEED_LIMIT = 300;
14640
- function startBackgroundSeed(repoDir, opts = {}) {
14641
- try {
14642
- const spawnFn = opts.spawn ?? realSpawn;
14643
- const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
14644
- const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
14645
- const child = spawnFn(
14646
- "node",
14647
- [
14648
- enginePath,
14649
- "--repo",
14650
- repoDir,
14651
- "--gitlog-limit",
14652
- String(limit),
14653
- ...opts.harness ? ["--harness", opts.harness] : []
14654
- ],
14655
- {
14656
- detached: true,
14657
- stdio: "ignore"
14658
- }
14659
- );
14660
- child.on("error", () => {
14661
- });
14662
- child.unref();
14663
- } catch {
14664
- }
14688
+ // src/core/log.ts
14689
+ import { appendFileSync, mkdirSync } from "fs";
14690
+ import { tmpdir } from "os";
14691
+ import { dirname as dirname3, join as join3 } from "path";
14692
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14693
+ var current = ["debug", "info", "warn", "error"].find(
14694
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14695
+ ) ?? "info";
14696
+ function setLogLevel(level) {
14697
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14665
14698
  }
14666
-
14667
- // src/core/config.ts
14668
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
14669
- var DEFAULT_DAEMON_PORT = 9077;
14670
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
14671
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
14672
- function resolveConfig(raw = {}) {
14673
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
14674
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
14675
- return {
14676
- serverMode,
14677
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
14678
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
14679
- // daemon needs no plumbing through eight separate constructors.
14680
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
14681
- apiToken: raw.apiToken || void 0,
14682
- apiPort,
14683
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
14684
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
14685
- embedVersion: raw.embedVersion || void 0,
14686
- embedPackagePath: raw.embedPackagePath || void 0,
14687
- bankId: raw.bankId,
14688
- dynamicBankId: raw.dynamicBankId,
14689
- bankIdTemplate: raw.bankIdTemplate,
14690
- mapPathToBank: raw.mapPathToBank,
14691
- resolveWorktrees: raw.resolveWorktrees,
14692
- optInOnly: raw.optInOnly ?? false,
14693
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
14694
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
14695
- harness: raw.harness ?? "opencode",
14696
- disabled: raw.disabled ?? false,
14697
- retainSessions: raw.retainSessions ?? true,
14698
- // opencode: write back by default (parity with hook-harness Stop)
14699
- maxParallelRetains: raw.maxParallelRetains || 10,
14700
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
14701
- autoReflect: raw.autoReflect ?? true,
14702
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
14703
- autoSeed: raw.autoSeed ?? true,
14704
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
14705
- codebaseSurvey: raw.codebaseSurvey ?? true,
14706
- surveyModel: raw.surveyModel || "haiku",
14707
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
14708
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
14709
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
14710
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
14711
- // nested object cannot reach the API as a tag and fail the whole retain.
14712
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
14713
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
14714
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
14715
- ) : {},
14716
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
14717
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
14718
- };
14699
+ function logFilePath() {
14700
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
14719
14701
  }
14720
- function readRaw(path) {
14702
+ function write(level, scope, msg, extra) {
14703
+ if (WEIGHT[level] < WEIGHT[current]) return;
14721
14704
  try {
14722
- return JSON.parse(readFileSync(path, "utf8"));
14723
- } catch (e) {
14724
- if (e?.code !== "ENOENT") {
14725
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
14726
- }
14727
- return {};
14705
+ const file2 = logFilePath();
14706
+ mkdirSync(dirname3(file2), { recursive: true });
14707
+ appendFileSync(
14708
+ file2,
14709
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14710
+ );
14711
+ } catch {
14728
14712
  }
14729
14713
  }
14730
- function mergeRaw(a, b) {
14731
- const { harnesses: _drop, ...flat } = b;
14732
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
14733
- }
14734
- function applyLayer(raw, layer, harness) {
14735
- let out = mergeRaw(raw, layer);
14736
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
14737
- if (perHarness) out = mergeRaw(out, perHarness);
14738
- return out;
14739
- }
14740
- var ENV_KEYS = {
14741
- serverMode: "HINDSIGHT_SERVER_MODE",
14742
- apiUrl: "HINDSIGHT_API_URL",
14743
- apiToken: "HINDSIGHT_API_TOKEN",
14744
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
14745
- // it can carry their existing environment over unchanged.
14746
- apiPort: "HINDSIGHT_API_PORT",
14747
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
14748
- embedVersion: "HINDSIGHT_EMBED_VERSION",
14749
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
14750
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
14751
- bankId: "HINDSIGHT_BANK_ID",
14752
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
14753
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
14754
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
14755
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
14756
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
14757
- harness: "HINDSIGHT_HARNESS",
14758
- disabled: "HINDSIGHT_DISABLED",
14759
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
14760
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
14761
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
14762
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
14763
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
14764
- autoSeed: "HINDSIGHT_AUTO_SEED",
14765
- seedLimit: "HINDSIGHT_SEED_LIMIT",
14766
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
14767
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
14768
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
14769
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
14770
- logLevel: "HINDSIGHT_LOG_LEVEL",
14771
- gitIngest: "HINDSIGHT_GIT_INGEST",
14772
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
14773
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
14774
- retainTags: "HINDSIGHT_RETAIN_TAGS"
14714
+ var log = {
14715
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14716
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
14717
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14718
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
14775
14719
  };
14776
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
14777
- "dynamicBankId",
14778
- "resolveWorktrees",
14779
- "optInOnly",
14780
- "disabled",
14781
- "retainSessions",
14782
- "autoReflect",
14783
- "autoSeed",
14784
- "codebaseSurvey"
14785
- ]);
14786
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
14787
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
14788
- "apiPort",
14789
- "daemonIdleTimeout",
14790
- "maxParallelRetains",
14791
- "reflectTimeoutMs",
14792
- "pageRefreshEveryTurns",
14793
- "seedLimit",
14794
- "surveyBudgetUsd",
14795
- "surveyRefreshCommits"
14796
- ]);
14797
- function readEnvConfig(env = process.env) {
14798
- const out = {};
14799
- for (const [key, name] of Object.entries(ENV_KEYS)) {
14800
- const value = env[name];
14801
- if (value === void 0 || value.trim() === "") continue;
14802
- if (ENV_BOOLEANS.has(key)) {
14803
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
14804
- } else if (ENV_LISTS.has(key)) {
14805
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
14806
- if (items.length) out[key] = items;
14807
- } else if (ENV_NUMBERS.has(key)) {
14808
- const n = Number(value);
14809
- if (Number.isFinite(n)) out[key] = n;
14810
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
14811
- } else {
14812
- out[key] = value;
14813
- }
14814
- }
14815
- return out;
14816
- }
14817
- function loadConfig(opts = {}) {
14818
- const o = typeof opts === "string" ? { path: opts } : opts;
14819
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
14820
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
14821
- if (!raw.harness && o.harness) raw.harness = o.harness;
14822
- return resolveConfig(raw);
14823
- }
14824
- var BANK_OVERRIDE_EXCLUDED = [
14825
- "bankId",
14826
- "bankIdTemplate",
14827
- "mapPathToBank",
14828
- "dynamicBankId",
14829
- "resolveWorktrees",
14830
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
14831
- // only ever arrive too late to matter — strip them rather than let them read as effective.
14832
- "optInOnly",
14833
- "optInPaths",
14834
- "harness"
14835
- ];
14836
- function applyBankConfig(cfg, resolvedId, directory) {
14837
- if (directory !== void 0 && !isOptedIn(cfg, directory))
14838
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
14839
- const section = cfg.banks[resolvedId];
14840
- if (!section) return { cfg, bankId: resolvedId };
14841
- const safe = { ...section };
14842
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
14843
- delete safe.banks;
14844
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
14845
- delete safe.bank;
14846
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
14847
- }
14848
- function resolvePartial(cfg, patch) {
14849
- const full = resolveConfig(patch);
14850
- const out = {};
14851
- for (const key of Object.keys(patch)) {
14852
- if (key in full)
14853
- out[key] = full[key];
14854
- }
14855
- return out;
14856
- }
14857
-
14858
- // src/core/diag.ts
14859
- import { appendFileSync as appendFileSync2 } from "fs";
14860
-
14861
- // src/core/log.ts
14862
- import { appendFileSync, mkdirSync } from "fs";
14863
- import { tmpdir } from "os";
14864
- import { dirname as dirname3, join as join4 } from "path";
14865
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14866
- var current = ["debug", "info", "warn", "error"].find(
14867
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14868
- ) ?? "info";
14869
- function setLogLevel(level) {
14870
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14871
- }
14872
- function logFilePath() {
14873
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
14874
- }
14875
- function write(level, scope, msg, extra) {
14876
- if (WEIGHT[level] < WEIGHT[current]) return;
14877
- try {
14878
- const file2 = logFilePath();
14879
- mkdirSync(dirname3(file2), { recursive: true });
14880
- appendFileSync(
14881
- file2,
14882
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14883
- );
14884
- } catch {
14885
- }
14886
- }
14887
- var log = {
14888
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14889
- info: (scope, msg, extra) => write("info", scope, msg, extra),
14890
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14891
- error: (scope, msg, extra) => write("error", scope, msg, extra)
14892
- };
14893
- function describeError(value, maxChars = 200) {
14894
- const parts = [];
14895
- const seen = /* @__PURE__ */ new Set();
14896
- let current2 = value;
14897
- while (current2 && !seen.has(current2)) {
14898
- seen.add(current2);
14899
- const error51 = current2;
14900
- const text = typeof error51.message === "string" ? error51.message : String(current2);
14901
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
14902
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
14903
- current2 = error51.cause;
14904
- }
14905
- return (parts.join(": ") || String(value)).slice(0, maxChars);
14906
- }
14907
-
14908
- // src/core/diag.ts
14909
- function diagFilePath() {
14910
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
14911
- }
14912
- function diag(harness, event, extra = {}) {
14913
- log.debug(harness, `diag:${event}`, extra);
14914
- try {
14915
- appendFileSync2(
14916
- diagFilePath(),
14917
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
14918
- );
14919
- } catch {
14720
+ function describeError(value, maxChars = 200) {
14721
+ const parts = [];
14722
+ const seen = /* @__PURE__ */ new Set();
14723
+ let current2 = value;
14724
+ while (current2 && !seen.has(current2)) {
14725
+ seen.add(current2);
14726
+ const error51 = current2;
14727
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
14728
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
14729
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
14730
+ current2 = error51.cause;
14920
14731
  }
14732
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
14921
14733
  }
14922
14734
 
14923
14735
  // src/core/missions.ts
@@ -14995,7 +14807,10 @@ var KNOWLEDGE_LABELS = {
14995
14807
  }
14996
14808
  ]
14997
14809
  };
14998
- var PAGES = [
14810
+ function pageScopeRule(project) {
14811
+ 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.`;
14812
+ }
14813
+ var PAGE_TAXONOMY = [
14999
14814
  {
15000
14815
  name: "Component map",
15001
14816
  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.",
@@ -15018,15 +14833,28 @@ var PAGES = [
15018
14833
  },
15019
14834
  {
15020
14835
  name: "Initiatives and enhancements",
15021
- 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.",
14836
+ 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.",
15022
14837
  tags: ["knowledge:feature-work"]
15023
14838
  }
15024
14839
  ];
14840
+ function pagesFor(project) {
14841
+ const scope = pageScopeRule(project);
14842
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
14843
+ }
15025
14844
  var PAGE_MAX_TOKENS = 4096;
15026
- var PAGE_TRIGGER = {
15027
- fact_types: ["world", "experience", "observation"],
15028
- refresh_after_consolidation: true
15029
- };
14845
+ var PAGE_TAGS_MATCH = "all";
14846
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
14847
+ function buildPageTrigger(cfg = {}) {
14848
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
14849
+ switch (cfg.pageTriggerType) {
14850
+ case "cron":
14851
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
14852
+ case "manual":
14853
+ return { ...base, refresh_after_consolidation: false };
14854
+ default:
14855
+ return { ...base, refresh_after_consolidation: true };
14856
+ }
14857
+ }
15030
14858
  var CODING_BANK_TEMPLATE = {
15031
14859
  version: "1",
15032
14860
  bank: {
@@ -15081,6 +14909,7 @@ async function pool(items, n, fn, onError, onProgress) {
15081
14909
  }
15082
14910
 
15083
14911
  // src/core/hindsight.ts
14912
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
15084
14913
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
15085
14914
  var RateLimitedError = class extends Error {
15086
14915
  constructor(retryAfterMs2) {
@@ -15113,8 +14942,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
15113
14942
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
15114
14943
  var HindsightClient = class {
15115
14944
  apiUrl;
15116
- apiToken;
14945
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
14946
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
14947
+ token;
14948
+ tokenProvider;
15117
14949
  bank;
14950
+ project;
15118
14951
  opIds = [];
15119
14952
  // async operation ids collected by retain(), for drain()
15120
14953
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -15123,34 +14956,81 @@ var HindsightClient = class {
15123
14956
  idempotentRetain;
15124
14957
  log;
15125
14958
  maxParallelRetains;
14959
+ observationScopes;
15126
14960
  constructor(o) {
15127
14961
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
15128
- this.apiToken = o.apiToken;
14962
+ this.token = o.apiToken;
14963
+ this.tokenProvider = o.tokenProvider;
15129
14964
  this.bank = o.bank;
14965
+ this.project = o.project;
15130
14966
  this.log = o.log ?? (() => {
15131
14967
  });
15132
14968
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
14969
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
14970
+ }
14971
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
14972
+ get apiToken() {
14973
+ return this.token;
15133
14974
  }
15134
14975
  headers() {
15135
14976
  const h = { "Content-Type": "application/json" };
15136
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
14977
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
15137
14978
  return h;
15138
14979
  }
14980
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
14981
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
14982
+ * doubling every failing request. */
14983
+ refreshToken() {
14984
+ if (!this.tokenProvider) return false;
14985
+ let next;
14986
+ try {
14987
+ next = this.tokenProvider();
14988
+ } catch {
14989
+ return false;
14990
+ }
14991
+ if (next === this.token) return false;
14992
+ this.token = next;
14993
+ return true;
14994
+ }
14995
+ /**
14996
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
14997
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
14998
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
14999
+ * not.
15000
+ *
15001
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
15002
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
15003
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
15004
+ * bounds the whole call.
15005
+ */
15006
+ async fetchWithAuth(url2, init) {
15007
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
15008
+ const r = await send();
15009
+ if (r.status !== 401 || !this.refreshToken()) return r;
15010
+ return send();
15011
+ }
15012
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
15013
+ * server answers identically for both — only the client knows which it sent. */
15014
+ authHint(status) {
15015
+ if (status !== 401) return "";
15016
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
15017
+ }
15139
15018
  bankUrl(suffix = "") {
15140
15019
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15141
15020
  }
15142
15021
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15143
15022
  async req(method, url2, body, tolerate = []) {
15144
- const r = await fetch(url2, {
15023
+ const r = await this.fetchWithAuth(url2, {
15145
15024
  method,
15146
- headers: this.headers(),
15147
15025
  body: body ? JSON.stringify(body) : void 0,
15148
15026
  signal: AbortSignal.timeout(15e3)
15149
15027
  });
15150
15028
  if (r.status === 429 && !tolerate.includes(429))
15151
15029
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
15152
15030
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
15153
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
15031
+ throw new Error(
15032
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
15033
+ );
15154
15034
  return r;
15155
15035
  }
15156
15036
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -15161,7 +15041,11 @@ var HindsightClient = class {
15161
15041
  context,
15162
15042
  document_id: documentId,
15163
15043
  tags,
15164
- strategy
15044
+ strategy,
15045
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
15046
+ // observations were built under is a property of the write rather than of whichever server
15047
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
15048
+ observation_scopes: this.observationScopes
15165
15049
  };
15166
15050
  if (opts.timestamp) item.timestamp = opts.timestamp;
15167
15051
  if (opts.metadata) item.metadata = opts.metadata;
@@ -15240,7 +15124,7 @@ var HindsightClient = class {
15240
15124
  this.log(
15241
15125
  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}`
15242
15126
  );
15243
- await this.seedPages();
15127
+ await this.seedPages(opts.pageTrigger);
15244
15128
  }
15245
15129
  /**
15246
15130
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -15298,7 +15182,7 @@ var HindsightClient = class {
15298
15182
  let backoffMs = POLL_CYCLE_MS;
15299
15183
  await pool([...pending], this.maxParallelRetains, async (id) => {
15300
15184
  try {
15301
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
15185
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
15302
15186
  if (r.status === 429) {
15303
15187
  backoffMs = Math.min(
15304
15188
  RETRY_AFTER_CEILING_MS,
@@ -15324,247 +15208,654 @@ var HindsightClient = class {
15324
15208
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
15325
15209
  );
15326
15210
  }
15327
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
15328
- async reflect(query, opts = {}) {
15329
- const ctrl = new AbortController();
15330
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
15331
- try {
15332
- const resp = await fetch(this.bankUrl("/reflect"), {
15333
- method: "POST",
15334
- headers: this.headers(),
15335
- body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
15336
- signal: ctrl.signal
15337
- });
15338
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
15339
- const data = await resp.json();
15340
- return (data.text || "").trim();
15341
- } finally {
15342
- clearTimeout(timer);
15343
- }
15211
+ /**
15212
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15213
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15214
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15215
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15216
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15217
+ */
15218
+ async reflect(query, opts) {
15219
+ const ctrl = new AbortController();
15220
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
15221
+ try {
15222
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
15223
+ method: "POST",
15224
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
15225
+ signal: ctrl.signal
15226
+ });
15227
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
15228
+ const data = await resp.json();
15229
+ return (data.text || "").trim();
15230
+ } finally {
15231
+ clearTimeout(timer);
15232
+ }
15233
+ }
15234
+ /**
15235
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15236
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
15237
+ */
15238
+ async tree() {
15239
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15240
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
15241
+ if ([404, 405, 501].includes(r.status)) {
15242
+ this.knowledgePagesSupported = false;
15243
+ throw new KnowledgePagesUnavailableError();
15244
+ }
15245
+ this.knowledgePagesSupported = true;
15246
+ try {
15247
+ return (await r.json()).roots ?? [];
15248
+ } catch {
15249
+ return [];
15250
+ }
15251
+ }
15252
+ /**
15253
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
15254
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
15255
+ * to read, and a caller enumerating pages wants leaves, not structure.
15256
+ *
15257
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
15258
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
15259
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
15260
+ */
15261
+ async listPages() {
15262
+ const items = [];
15263
+ const walk = (nodes, folder) => {
15264
+ for (const n of nodes) {
15265
+ if (!n?.id || !n?.name) continue;
15266
+ if (n.kind === "page") {
15267
+ items.push({
15268
+ id: n.id,
15269
+ name: n.name,
15270
+ ...n.description ? { description: n.description } : {},
15271
+ ...folder ? { folder } : {}
15272
+ });
15273
+ }
15274
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
15275
+ }
15276
+ };
15277
+ walk(await this.tree());
15278
+ return { items };
15279
+ }
15280
+ /**
15281
+ * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
15282
+ * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
15283
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15284
+ * token cap.
15285
+ */
15286
+ async getPage(pageId) {
15287
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15288
+ const r = await this.req(
15289
+ "GET",
15290
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15291
+ );
15292
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15293
+ return await r.json();
15294
+ }
15295
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15296
+ * Returns page-level hits with a relevance snippet — the real search behind
15297
+ * hindsight_search_knowledge_pages. */
15298
+ async searchKnowledgePages(query, limit = 3) {
15299
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15300
+ const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15301
+ const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15302
+ const j = await r.json();
15303
+ return (j.results ?? []).map((x) => ({
15304
+ id: x.id,
15305
+ name: x.name,
15306
+ snippet: x.snippet ?? "",
15307
+ score: x.score ?? 0
15308
+ }));
15309
+ }
15310
+ /**
15311
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
15312
+ *
15313
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
15314
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
15315
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
15316
+ *
15317
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
15318
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
15319
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
15320
+ */
15321
+ async seedPages(pageTrigger = buildPageTrigger()) {
15322
+ const pages = pagesFor(this.project ?? this.bank);
15323
+ const existing = /* @__PURE__ */ new Map();
15324
+ let roots;
15325
+ try {
15326
+ roots = await this.tree();
15327
+ } catch (e) {
15328
+ if (e instanceof KnowledgePagesUnavailableError) {
15329
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
15330
+ return;
15331
+ }
15332
+ throw e;
15333
+ }
15334
+ for (const n of roots) {
15335
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
15336
+ }
15337
+ let created = 0;
15338
+ let updated = 0;
15339
+ for (const page of pages) {
15340
+ const hit = existing.get(page.name.toLowerCase());
15341
+ const body = {
15342
+ name: page.name,
15343
+ source_query: page.source_query,
15344
+ tags: page.tags,
15345
+ max_tokens: PAGE_MAX_TOKENS,
15346
+ trigger: pageTrigger
15347
+ };
15348
+ if (!hit) {
15349
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
15350
+ if ([404, 405, 501].includes(r.status)) {
15351
+ this.knowledgePagesSupported = false;
15352
+ this.log(
15353
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15354
+ );
15355
+ return;
15356
+ }
15357
+ if (r.status !== 409) created++;
15358
+ } else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
15359
+ const patch = {
15360
+ trigger: pageTrigger
15361
+ };
15362
+ if (hit.description !== page.source_query) {
15363
+ patch.source_query = page.source_query;
15364
+ patch.tags = page.tags;
15365
+ }
15366
+ const r = await this.req(
15367
+ "PATCH",
15368
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
15369
+ patch
15370
+ );
15371
+ if ([404, 405, 501].includes(r.status)) {
15372
+ this.knowledgePagesSupported = false;
15373
+ this.log(
15374
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15375
+ );
15376
+ return;
15377
+ }
15378
+ updated++;
15379
+ }
15380
+ }
15381
+ this.log(
15382
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
15383
+ );
15384
+ }
15385
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
15386
+ slugify(s) {
15387
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
15388
+ }
15389
+ /**
15390
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
15391
+ * New initiative → creates a page under the Initiatives folder.
15392
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
15393
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
15394
+ *
15395
+ * The marker carries its page id in two places, neither of them a tag (#3641):
15396
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
15397
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
15398
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
15399
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
15400
+ * vocabulary that exists to be matched with exact set-ops.
15401
+ */
15402
+ async captureInitiative(args) {
15403
+ let pageId = args.relatesToPageId;
15404
+ if (!pageId) {
15405
+ const folderId = await this.ensureFolder("Initiatives");
15406
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
15407
+ name: args.title,
15408
+ 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.`,
15409
+ parent_id: folderId,
15410
+ tags: ["knowledge:feature-work"],
15411
+ trigger: args.pageTrigger ?? buildPageTrigger()
15412
+ });
15413
+ try {
15414
+ const j = await r.json();
15415
+ pageId = j.page_id ?? j.id;
15416
+ } catch {
15417
+ }
15418
+ pageId ||= `initiative-${this.slugify(args.title)}`;
15419
+ }
15420
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
15421
+ const content = `${verb}: ${args.title}. ${args.summary}`;
15422
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
15423
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
15424
+ const context = `initiative marker for [[page:${pageId}]]`;
15425
+ await this.retain(content, context, markerId, tags, "document", {
15426
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
15427
+ });
15428
+ return { page_id: pageId };
15429
+ }
15430
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
15431
+ async ensureFolder(name) {
15432
+ try {
15433
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
15434
+ const hit = (tree.roots || []).find(
15435
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
15436
+ );
15437
+ if (hit?.id) return hit.id;
15438
+ } catch {
15439
+ }
15440
+ try {
15441
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
15442
+ return (await r.json()).id;
15443
+ } catch {
15444
+ return void 0;
15445
+ }
15446
+ }
15447
+ };
15448
+
15449
+ // src/core/config.ts
15450
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
15451
+ var DEFAULT_DAEMON_PORT = 9077;
15452
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
15453
+ function resolvePageTriggerType(raw) {
15454
+ if (raw.pageTriggerType === "manual") return "manual";
15455
+ if (raw.pageTriggerType === "cron") {
15456
+ if (raw.pageTriggerCron?.trim()) return "cron";
15457
+ log.warn(
15458
+ "config",
15459
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
15460
+ );
15461
+ }
15462
+ return "auto-refresh";
15463
+ }
15464
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
15465
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
15466
+ function resolveReflectBudget(raw) {
15467
+ const value = raw.reflectBudget;
15468
+ if (value === void 0) return "high";
15469
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
15470
+ return value;
15471
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
15472
+ return "high";
15473
+ }
15474
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
15475
+ function resolveObservationScopes(raw) {
15476
+ const value = raw;
15477
+ if (typeof value === "string")
15478
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
15479
+ if (Array.isArray(value)) {
15480
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
15481
+ if (scopes.length) return scopes;
15482
+ }
15483
+ return DEFAULT_OBSERVATION_SCOPES;
15484
+ }
15485
+ function resolveConfig(raw = {}) {
15486
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
15487
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
15488
+ return {
15489
+ serverMode,
15490
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
15491
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
15492
+ // daemon needs no plumbing through eight separate constructors.
15493
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
15494
+ apiToken: raw.apiToken || void 0,
15495
+ apiPort,
15496
+ daemonIdleTimeout: raw.daemonIdleTimeout,
15497
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
15498
+ embedVersion: raw.embedVersion || void 0,
15499
+ embedPackagePath: raw.embedPackagePath || void 0,
15500
+ bankId: raw.bankId,
15501
+ dynamicBankId: raw.dynamicBankId,
15502
+ bankIdTemplate: raw.bankIdTemplate,
15503
+ mapPathToBank: raw.mapPathToBank,
15504
+ resolveWorktrees: raw.resolveWorktrees,
15505
+ optInOnly: raw.optInOnly ?? false,
15506
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
15507
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
15508
+ harness: raw.harness ?? "opencode",
15509
+ disabled: raw.disabled ?? false,
15510
+ retainSessions: raw.retainSessions ?? true,
15511
+ // write sessions back by default, every harness
15512
+ maxParallelRetains: raw.maxParallelRetains || 10,
15513
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
15514
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
15515
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
15516
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
15517
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
15518
+ reflectBudget: resolveReflectBudget(raw),
15519
+ autoReflect: raw.autoReflect ?? true,
15520
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
15521
+ pageTriggerType: resolvePageTriggerType(raw),
15522
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
15523
+ autoSeed: raw.autoSeed ?? true,
15524
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
15525
+ codebaseSurvey: raw.codebaseSurvey ?? true,
15526
+ surveyModel: raw.surveyModel || "haiku",
15527
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
15528
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
15529
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
15530
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
15531
+ // nested object cannot reach the API as a tag and fail the whole retain.
15532
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
15533
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
15534
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
15535
+ ) : {},
15536
+ observationScopes: resolveObservationScopes(raw.observationScopes),
15537
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
15538
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
15539
+ };
15540
+ }
15541
+ function readRaw(path) {
15542
+ try {
15543
+ return JSON.parse(readFileSync(path, "utf8"));
15544
+ } catch (e) {
15545
+ if (e?.code !== "ENOENT") {
15546
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
15547
+ }
15548
+ return {};
15549
+ }
15550
+ }
15551
+ function mergeRaw(a, b) {
15552
+ const { harnesses: _drop, ...flat } = b;
15553
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
15554
+ }
15555
+ function applyLayer(raw, layer, harness) {
15556
+ let out = mergeRaw(raw, layer);
15557
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
15558
+ if (perHarness) out = mergeRaw(out, perHarness);
15559
+ return out;
15560
+ }
15561
+ var ENV_KEYS = {
15562
+ serverMode: "HINDSIGHT_SERVER_MODE",
15563
+ apiUrl: "HINDSIGHT_API_URL",
15564
+ apiToken: "HINDSIGHT_API_TOKEN",
15565
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
15566
+ // it can carry their existing environment over unchanged.
15567
+ apiPort: "HINDSIGHT_API_PORT",
15568
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
15569
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
15570
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
15571
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
15572
+ bankId: "HINDSIGHT_BANK_ID",
15573
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
15574
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
15575
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
15576
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
15577
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
15578
+ harness: "HINDSIGHT_HARNESS",
15579
+ disabled: "HINDSIGHT_DISABLED",
15580
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
15581
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
15582
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
15583
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
15584
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
15585
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
15586
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
15587
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
15588
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
15589
+ autoSeed: "HINDSIGHT_AUTO_SEED",
15590
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
15591
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
15592
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
15593
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
15594
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
15595
+ logLevel: "HINDSIGHT_LOG_LEVEL",
15596
+ gitIngest: "HINDSIGHT_GIT_INGEST",
15597
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
15598
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
15599
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
15600
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
15601
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
15602
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
15603
+ };
15604
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
15605
+ "dynamicBankId",
15606
+ "resolveWorktrees",
15607
+ "optInOnly",
15608
+ "disabled",
15609
+ "retainSessions",
15610
+ "autoReflect",
15611
+ "autoSeed",
15612
+ "codebaseSurvey"
15613
+ ]);
15614
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
15615
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
15616
+ "apiPort",
15617
+ "daemonIdleTimeout",
15618
+ "maxParallelRetains",
15619
+ "reflectTimeoutMs",
15620
+ "reflectToolTimeoutMs",
15621
+ "pageRefreshEveryTurns",
15622
+ "seedLimit",
15623
+ "surveyBudgetUsd",
15624
+ "surveyRefreshCommits"
15625
+ ]);
15626
+ function readEnvConfig(env = process.env) {
15627
+ const out = {};
15628
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
15629
+ const value = env[name];
15630
+ if (value === void 0 || value.trim() === "") continue;
15631
+ if (ENV_BOOLEANS.has(key)) {
15632
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
15633
+ } else if (ENV_LISTS.has(key)) {
15634
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
15635
+ if (items.length) out[key] = items;
15636
+ } else if (ENV_NUMBERS.has(key)) {
15637
+ const n = Number(value);
15638
+ if (Number.isFinite(n)) out[key] = n;
15639
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
15640
+ } else {
15641
+ out[key] = value;
15642
+ }
15643
+ }
15644
+ return out;
15645
+ }
15646
+ function loadConfig(opts = {}) {
15647
+ const o = typeof opts === "string" ? { path: opts } : opts;
15648
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
15649
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
15650
+ if (!raw.harness && o.harness) raw.harness = o.harness;
15651
+ return resolveConfig(raw);
15652
+ }
15653
+ var BANK_OVERRIDE_EXCLUDED = [
15654
+ "bankId",
15655
+ "bankIdTemplate",
15656
+ "mapPathToBank",
15657
+ "dynamicBankId",
15658
+ "resolveWorktrees",
15659
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
15660
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
15661
+ "optInOnly",
15662
+ "optInPaths",
15663
+ "harness"
15664
+ ];
15665
+ function applyBankConfig(cfg, resolvedId, directory) {
15666
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
15667
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
15668
+ const section = cfg.banks[resolvedId];
15669
+ if (!section) return { cfg, bankId: resolvedId };
15670
+ const safe = { ...section };
15671
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
15672
+ delete safe.banks;
15673
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
15674
+ delete safe.bank;
15675
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
15676
+ }
15677
+ function resolvePartial(cfg, patch) {
15678
+ const full = resolveConfig(patch);
15679
+ const out = {};
15680
+ for (const key of Object.keys(patch)) {
15681
+ if (key in full)
15682
+ out[key] = full[key];
15683
+ }
15684
+ return out;
15685
+ }
15686
+
15687
+ // src/core/host-client.ts
15688
+ function resolveHostConfig(harness, directory) {
15689
+ const cfg0 = loadConfig({ harness });
15690
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
15691
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
15692
+ }
15693
+ function resolveHostMemory(harness, directory) {
15694
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
15695
+ return {
15696
+ cfg,
15697
+ bankId,
15698
+ client: new HindsightClient({
15699
+ apiUrl: cfg.apiUrl,
15700
+ apiToken: cfg.apiToken,
15701
+ bank: bankId,
15702
+ maxParallelRetains: cfg.maxParallelRetains,
15703
+ observationScopes: cfg.observationScopes,
15704
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
15705
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
15706
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
15707
+ // honoured on re-resolution exactly as it was on the first one.
15708
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
15709
+ })
15710
+ };
15711
+ }
15712
+
15713
+ // src/core/diag.ts
15714
+ import { appendFileSync as appendFileSync2 } from "fs";
15715
+ function diagFilePath() {
15716
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
15717
+ }
15718
+ function diag(harness, event, extra = {}) {
15719
+ log.debug(harness, `diag:${event}`, extra);
15720
+ try {
15721
+ appendFileSync2(
15722
+ diagFilePath(),
15723
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
15724
+ );
15725
+ } catch {
15726
+ }
15727
+ }
15728
+
15729
+ // src/core/daemon.ts
15730
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
15731
+ import { dirname as dirname4, join as join5 } from "path";
15732
+ import { fileURLToPath as fileURLToPath2 } from "url";
15733
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
15734
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
15735
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
15736
+ try {
15737
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
15738
+ return res.ok;
15739
+ } catch {
15740
+ return false;
15344
15741
  }
15345
- /**
15346
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15347
- * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
15348
- */
15349
- async tree() {
15350
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15351
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
15352
- if ([404, 405, 501].includes(r.status)) {
15353
- this.knowledgePagesSupported = false;
15354
- throw new KnowledgePagesUnavailableError();
15355
- }
15356
- this.knowledgePagesSupported = true;
15357
- try {
15358
- return (await r.json()).roots ?? [];
15359
- } catch {
15360
- return [];
15361
- }
15742
+ }
15743
+ function hasRustToolchain() {
15744
+ if (process.platform !== "darwin") return true;
15745
+ try {
15746
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
15747
+ return true;
15748
+ } catch {
15749
+ return false;
15362
15750
  }
15363
- /**
15364
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
15365
- * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
15366
- * to read, and a caller enumerating pages wants leaves, not structure.
15367
- *
15368
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
15369
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
15370
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
15371
- */
15372
- async listPages() {
15373
- const items = [];
15374
- const walk = (nodes, folder) => {
15375
- for (const n of nodes) {
15376
- if (!n?.id || !n?.name) continue;
15377
- if (n.kind === "page") {
15378
- items.push({
15379
- id: n.id,
15380
- name: n.name,
15381
- ...n.description ? { description: n.description } : {},
15382
- ...folder ? { folder } : {}
15383
- });
15384
- }
15385
- if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
15386
- }
15751
+ }
15752
+ function hasUvx() {
15753
+ try {
15754
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
15755
+ return true;
15756
+ } catch {
15757
+ return false;
15758
+ }
15759
+ }
15760
+ var PROVIDER_PROBES = [
15761
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
15762
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
15763
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
15764
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
15765
+ ];
15766
+ function detectLlm(env = process.env) {
15767
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
15768
+ if (explicit) {
15769
+ return {
15770
+ provider: explicit,
15771
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
15772
+ source: "HINDSIGHT_API_LLM_PROVIDER"
15387
15773
  };
15388
- walk(await this.tree());
15389
- return { items };
15390
15774
  }
15391
- /**
15392
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
15393
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
15394
- * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15395
- * token cap.
15396
- */
15397
- async getPage(pageId) {
15398
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15399
- const r = await this.req(
15400
- "GET",
15401
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15402
- );
15403
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15404
- return await r.json();
15775
+ for (const probe of PROVIDER_PROBES) {
15776
+ const key = env[probe.keyEnv]?.trim();
15777
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
15405
15778
  }
15406
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15407
- * Returns page-level hits with a relevance snippet — the real search behind
15408
- * hindsight_search_knowledge_pages. */
15409
- async searchKnowledgePages(query, limit = 3) {
15410
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15411
- const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15412
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15413
- const j = await r.json();
15414
- return (j.results ?? []).map((x) => ({
15415
- id: x.id,
15416
- name: x.name,
15417
- snippet: x.snippet ?? "",
15418
- score: x.score ?? 0
15419
- }));
15779
+ if (onPath("claude")) {
15780
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
15420
15781
  }
15421
- /**
15422
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
15423
- *
15424
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
15425
- * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
15426
- * off a slug). Names are unique per folder server-side, which makes them a sound key.
15427
- *
15428
- * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
15429
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
15430
- */
15431
- async seedPages() {
15432
- const existing = /* @__PURE__ */ new Map();
15433
- let roots;
15434
- try {
15435
- roots = await this.tree();
15436
- } catch (e) {
15437
- if (e instanceof KnowledgePagesUnavailableError) {
15438
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
15439
- return;
15440
- }
15441
- throw e;
15442
- }
15443
- for (const n of roots) {
15444
- if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
15445
- }
15446
- let created = 0;
15447
- let updated = 0;
15448
- for (const page of PAGES) {
15449
- const hit = existing.get(page.name.toLowerCase());
15450
- const body = {
15451
- name: page.name,
15452
- source_query: page.source_query,
15453
- tags: page.tags,
15454
- max_tokens: PAGE_MAX_TOKENS,
15455
- trigger: PAGE_TRIGGER
15456
- };
15457
- if (!hit) {
15458
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
15459
- if ([404, 405, 501].includes(r.status)) {
15460
- this.knowledgePagesSupported = false;
15461
- this.log(
15462
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15463
- );
15464
- return;
15465
- }
15466
- if (r.status !== 409) created++;
15467
- } else if (hit.description !== page.source_query) {
15468
- const r = await this.req(
15469
- "PATCH",
15470
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
15471
- { source_query: page.source_query, tags: page.tags }
15472
- );
15473
- if ([404, 405, 501].includes(r.status)) {
15474
- this.knowledgePagesSupported = false;
15475
- this.log(
15476
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15477
- );
15478
- return;
15479
- }
15480
- updated++;
15481
- }
15482
- }
15483
- this.log(
15484
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
15485
- );
15782
+ return void 0;
15783
+ }
15784
+ function onPath(bin) {
15785
+ try {
15786
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
15787
+ return true;
15788
+ } catch {
15789
+ return false;
15486
15790
  }
15487
- /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
15488
- slugify(s) {
15489
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
15791
+ }
15792
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
15793
+ try {
15794
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
15795
+ const child = spawnFn("node", [starter, "--harness", harness], {
15796
+ detached: true,
15797
+ stdio: "ignore"
15798
+ });
15799
+ child.on("error", () => {
15800
+ });
15801
+ child.unref();
15802
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
15803
+ } catch {
15490
15804
  }
15491
- /**
15492
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
15493
- * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
15494
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
15495
- */
15496
- async captureInitiative(args) {
15497
- let pageId = args.relatesToPageId;
15498
- if (!pageId) {
15499
- const folderId = await this.ensureFolder("Initiatives");
15500
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
15501
- name: args.title,
15502
- 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.`,
15503
- parent_id: folderId,
15504
- tags: ["knowledge:feature-work"],
15505
- trigger: {
15506
- fact_types: ["world", "experience", "observation"],
15507
- refresh_after_consolidation: true
15508
- }
15509
- });
15510
- try {
15511
- const j = await r.json();
15512
- pageId = j.page_id ?? j.id;
15513
- } catch {
15514
- }
15515
- pageId ||= `initiative-${this.slugify(args.title)}`;
15516
- }
15517
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
15518
- const content = `${verb}: ${args.title}. ${args.summary}`;
15519
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
15520
- const tags = [
15521
- .../* @__PURE__ */ new Set([
15522
- ...args.stamp?.tags ?? [],
15523
- "knowledge:feature-work",
15524
- `relatedPageId:${pageId}`
15525
- ])
15526
- ];
15527
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
15528
- await this.retain(content, "initiative marker", markerId, tags, "document", {
15529
- metadata: args.stamp?.metadata
15530
- });
15531
- } else {
15532
- await this.retain(content, "initiative marker", markerId, tags, "document");
15533
- }
15534
- return { page_id: pageId };
15805
+ }
15806
+ async function ensureDaemon(cfg, harness, opts = {}) {
15807
+ if (cfg.serverMode !== "daemon") return;
15808
+ if (await isServerHealthy(cfg.apiUrl)) return;
15809
+ if (!preflightDaemon(cfg, harness)) return;
15810
+ startDaemonDetached(cfg, harness, opts.spawnFn);
15811
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
15812
+ }
15813
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
15814
+ const deadline = Date.now() + budgetMs;
15815
+ while (Date.now() < deadline) {
15816
+ await new Promise((r) => setTimeout(r, pollMs));
15817
+ if (await isServerHealthy(baseUrl)) return true;
15535
15818
  }
15536
- /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
15537
- async ensureFolder(name) {
15538
- try {
15539
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
15540
- const hit = (tree.roots || []).find(
15541
- (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
15542
- );
15543
- if (hit?.id) return hit.id;
15544
- } catch {
15545
- }
15546
- try {
15547
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
15548
- return (await r.json()).id;
15549
- } catch {
15550
- return void 0;
15551
- }
15819
+ return false;
15820
+ }
15821
+ function preflightDaemon(cfg, harness) {
15822
+ if (!hasUvx()) {
15823
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
15824
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
15825
+ return false;
15552
15826
  }
15553
- };
15827
+ if (!hasRustToolchain()) {
15828
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
15829
+ log.warn(
15830
+ harness,
15831
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
15832
+ );
15833
+ return false;
15834
+ }
15835
+ if (!detectLlm()) {
15836
+ diag(harness, "daemon_no_llm", {});
15837
+ log.warn(
15838
+ harness,
15839
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
15840
+ );
15841
+ return false;
15842
+ }
15843
+ return true;
15844
+ }
15554
15845
 
15555
15846
  // src/core/knowledge-tools.ts
15556
15847
  import { existsSync as existsSync3 } from "fs";
15557
15848
  import { homedir as homedir4 } from "os";
15558
- import { join as join6 } from "path";
15849
+ import { join as join7 } from "path";
15559
15850
 
15560
15851
  // src/core/status.ts
15561
- import { execFileSync as execFileSync3 } from "child_process";
15852
+ import { execFileSync as execFileSync4 } from "child_process";
15562
15853
 
15563
15854
  // src/core/git.ts
15564
- import { execFileSync as execFileSync2 } from "child_process";
15855
+ import { execFileSync as execFileSync3 } from "child_process";
15565
15856
  import { resolve } from "path";
15566
15857
  function git(repo, ...args) {
15567
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15858
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15568
15859
  }
15569
15860
  function repoNameOf(repo) {
15570
15861
  return projectNameOf(resolve(repo));
@@ -15610,7 +15901,7 @@ function roster(pages) {
15610
15901
  var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP for any question the project's accumulated knowledge might answer (components, conventions, past decisions, initiatives): search the knowledge pages and credit results visibly with a markdown blockquote so it renders as a callout, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>".
15611
15902
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
15612
15903
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
15613
- - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this ONCE to record it as a tracked page. Skip bug fixes, small tweaks, and chores.
15904
+ - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this to record it as a tracked page; then call it AGAIN with relates_to_page_id set to that page whenever the goal, scope, or rationale materially changes mid-work, so the page tracks the current plan and not the opening one. Skip bug fixes, small tweaks, chores, and trivial course-corrections.
15614
15905
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
15615
15906
  var REFLECT_ON_GOALS = "- The user just set a NEW task or goal \u2192 call hindsight_reflect with that goal FIRST, before planning: no memory is injected automatically in this configuration, so this call is the only way past decisions, constraints, and failed attempts relevant to the goal reach you.\n";
15616
15907
  function toolGuide(opts) {
@@ -15637,11 +15928,11 @@ ${toolGuide(opts)}
15637
15928
  }
15638
15929
 
15639
15930
  // src/core/survey.ts
15640
- import { spawn as realSpawn2 } from "child_process";
15931
+ import { spawn as realSpawn3 } from "child_process";
15641
15932
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15642
15933
  import { homedir as homedir3 } from "os";
15643
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15644
- import { fileURLToPath as fileURLToPath2 } from "url";
15934
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15935
+ import { fileURLToPath as fileURLToPath3 } from "url";
15645
15936
  var SURVEY_DOC_IDS = [
15646
15937
  "repository-component-map",
15647
15938
  "repository-core-concepts",
@@ -15651,7 +15942,7 @@ var SURVEY_DOC_IDS = [
15651
15942
  function resolveClaudeBin(explicit) {
15652
15943
  if (explicit) return explicit;
15653
15944
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15654
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15945
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15655
15946
  try {
15656
15947
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15657
15948
  } catch {
@@ -15680,7 +15971,7 @@ function binExists(bin) {
15680
15971
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15681
15972
  if (!dir) continue;
15682
15973
  try {
15683
- accessSync(join5(dir, bin), constants.X_OK);
15974
+ accessSync(join6(dir, bin), constants.X_OK);
15684
15975
  return true;
15685
15976
  } catch {
15686
15977
  }
@@ -15724,7 +16015,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15724
16015
  hindsight: {
15725
16016
  command: "node",
15726
16017
  args: [opts.mcpServerPath],
15727
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16018
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16019
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16020
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16021
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16022
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15728
16023
  }
15729
16024
  }
15730
16025
  });
@@ -15764,6 +16059,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15764
16059
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15765
16060
  "-c",
15766
16061
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16062
+ "-c",
16063
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15767
16064
  SURVEY_PROMPT
15768
16065
  ],
15769
16066
  env
@@ -15787,9 +16084,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15787
16084
  }
15788
16085
  function startCodebaseSurvey(repoDir, opts = {}) {
15789
16086
  try {
15790
- const spawnFn = opts.spawn ?? realSpawn2;
16087
+ const spawnFn = opts.spawn ?? realSpawn3;
15791
16088
  const exists = opts.exists ?? binExists;
15792
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16089
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15793
16090
  const preferred = opts.harness ?? "claude-code";
15794
16091
  const order = [
15795
16092
  preferred,
@@ -15828,7 +16125,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15828
16125
  var DEEPEN_DIFF_TARGET = 300;
15829
16126
  function commitCount(repoDir) {
15830
16127
  try {
15831
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16128
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15832
16129
  encoding: "utf8"
15833
16130
  });
15834
16131
  return Number(out.trim()) || 0;
@@ -15919,9 +16216,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15919
16216
  description: "Report safe Hindsight runtime diagnostics for this coding-agent session: resolved bank, workspace, harness, config location, API endpoint, and non-secret environment overrides. Use this when memory, hooks, MCP tools, or configuration appear not to work. Tokens and other secret values are never returned.",
15920
16217
  inputSchema: {},
15921
16218
  handler: async (_args) => {
15922
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16219
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15923
16220
  const harness = opts.harness ?? "unknown";
15924
- const cfg = loadConfig({ harness: opts.harness });
16221
+ const cfg = applyBankConfig(
16222
+ loadConfig({ harness: opts.harness }),
16223
+ bankId,
16224
+ opts.repoDir
16225
+ ).cfg;
15925
16226
  return ok({
15926
16227
  bank_id: bankId,
15927
16228
  harness,
@@ -15933,6 +16234,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15933
16234
  api_token_configured: Boolean(cfg.apiToken),
15934
16235
  disabled: cfg.disabled
15935
16236
  },
16237
+ // What the LIVE client is signing with, which is not the same question as what the file
16238
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16239
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16240
+ // value is never returned.
16241
+ credential: {
16242
+ api_token_in_use: Boolean(client.apiToken),
16243
+ api_token_matches_config: client.apiToken === cfg.apiToken
16244
+ },
15936
16245
  environment: {
15937
16246
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15938
16247
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15981,12 +16290,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15981
16290
  description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
15982
16291
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15983
16292
  handler: guarded(
15984
- async ({ query }) => client.reflect(query, { budget: "high" })
16293
+ async ({ query }) => client.reflect(query, {
16294
+ budget: opts.reflectBudget ?? "high",
16295
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16296
+ })
15985
16297
  )
15986
16298
  },
15987
16299
  {
15988
16300
  name: "hindsight_capture_initiative",
15989
- description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it.\n\nWHEN TO CALL: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Call it ONCE, EARLY.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, and chores are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat').\n- summary: 2-3 sentences on what you're building and why (the intent, not a code diff).\n- relates_to_page_id: leave empty for a new initiative. Set it only to attach to an initiative that already has a page \u2014 pass that page's id from hindsight_list_knowledge_pages.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
16301
+ description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_knowledge_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
15990
16302
  inputSchema: {
15991
16303
  title: external_exports.string(),
15992
16304
  summary: external_exports.string(),
@@ -15997,7 +16309,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15997
16309
  title,
15998
16310
  summary,
15999
16311
  relatesToPageId: relates_to_page_id,
16000
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16312
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16313
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
16001
16314
  })
16002
16315
  )
16003
16316
  },
@@ -16204,7 +16517,7 @@ function resolversFor(ctx) {
16204
16517
  return {
16205
16518
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16206
16519
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16207
- gitProject: () => projectNameOf(ctx.directory),
16520
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16208
16521
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16209
16522
  harness: () => ctx.harness,
16210
16523
  bankId: () => ctx.bankId,
@@ -16250,11 +16563,6 @@ import { readFileSync as readFileSync4 } from "fs";
16250
16563
  // src/core/skill-sync.ts
16251
16564
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16252
16565
  import { homedir as homedir5 } from "os";
16253
- import { dirname as dirname5, join as join7 } from "path";
16254
- import { fileURLToPath as fileURLToPath3 } from "url";
16255
-
16256
- // src/core/daemon.ts
16257
- import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
16258
16566
  import { dirname as dirname6, join as join8 } from "path";
16259
16567
  import { fileURLToPath as fileURLToPath4 } from "url";
16260
16568
 
@@ -16345,7 +16653,7 @@ async function buildSessionStartContext(args) {
16345
16653
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16346
16654
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16347
16655
  const countCommitsSince = args.commitsSince ?? commitsSince;
16348
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16656
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16349
16657
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16350
16658
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16351
16659
  const recordSurveyBaseline = (sha) => {
@@ -16621,6 +16929,9 @@ var RuntimeCore = class {
16621
16929
  return buildKnowledgeTools(this.client, this.bankId, {
16622
16930
  repoDir: this.projectDir,
16623
16931
  harness: this.harness,
16932
+ pageTrigger: buildPageTrigger(this.cfg),
16933
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16934
+ reflectBudget: this.cfg.reflectBudget,
16624
16935
  stampFor: () => buildRetainStamp(this.cfg, {
16625
16936
  directory: this.projectDir,
16626
16937
  harness: this.harness,
@@ -16639,6 +16950,7 @@ var RuntimeCore = class {
16639
16950
  */
16640
16951
  async seedIfCold(repoPath) {
16641
16952
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16953
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16642
16954
  try {
16643
16955
  const out = await buildSessionStartContext({
16644
16956
  cwd: repoPath || process.cwd(),
@@ -16762,15 +17074,17 @@ var RuntimeCore = class {
16762
17074
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16763
17075
  retain(sessionId, turns, startTs, trigger = "turn") {
16764
17076
  const t0 = Date.now();
16765
- void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16766
- cursors: this.cursors,
16767
- stamp: buildRetainStamp(this.cfg, {
16768
- directory: this.projectDir,
16769
- harness: this.harness,
16770
- bankId: this.bankId,
16771
- sessionId
17077
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17078
+ () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
17079
+ cursors: this.cursors,
17080
+ stamp: buildRetainStamp(this.cfg, {
17081
+ directory: this.projectDir,
17082
+ harness: this.harness,
17083
+ bankId: this.bankId,
17084
+ sessionId
17085
+ })
16772
17086
  })
16773
- }).then(
17087
+ ).then(
16774
17088
  () => diag(this.harness, "retain_ok", {
16775
17089
  ms: Date.now() - t0,
16776
17090
  turns: turns.length,
@@ -16898,17 +17212,9 @@ ${injection}` };
16898
17212
  };
16899
17213
  }
16900
17214
  function createRuntime(repoPath) {
16901
- let cfg = loadConfig({ harness: HARNESS2 });
17215
+ const { cfg, bankId, client } = resolveHostMemory(HARNESS2, repoPath);
16902
17216
  if (cfg.disabled) return void 0;
16903
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, repoPath, HARNESS2), repoPath);
16904
- cfg = resolved.cfg;
16905
- if (cfg.disabled) return void 0;
16906
- const client = new HindsightClient({
16907
- apiUrl: cfg.apiUrl,
16908
- apiToken: cfg.apiToken,
16909
- bank: resolved.bankId
16910
- });
16911
- return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, repoPath);
17217
+ return new RuntimeCore(client, bankId, cfg, HARNESS2, repoPath);
16912
17218
  }
16913
17219
  var extension = (pi) => {
16914
17220
  const repoPath = process.cwd();