Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
25.8 KB
Raw Blame
import { test, expect, beforeEach, afterEach } from "bun:test";
import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { resolveSearchConfig } from "../../../src/core/search/index.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import type { SearchOptions } from "../../../src/core/search/types.ts";
import { configFingerprint } from "../../../src/core/search/pipeline/cache-slot.ts";
import { buildCacheKey } from "../../../src/core/search/query-cache.ts";
import { parseBenchPinnedKnobs } from "../../../src/cli/brain/verbs/bench.ts";

let tmp: string;
let configPath: string;
let origEnv: Record<string, string | undefined>;

const ENV_KEYS = [
  "OPEN_SECOND_BRAIN_SEARCH_DB",
  "OPEN_SECOND_BRAIN_SEARCH_SEMANTIC",
  "OPEN_SECOND_BRAIN_SEARCH_CHUNK_SIZE",
  "OPEN_SECOND_BRAIN_SEARCH_CHUNK_OVERLAP",
  "OPEN_SECOND_BRAIN_SEARCH_CHUNK_MIN_SIZE",
  "OPEN_SECOND_BRAIN_SEARCH_KW_WEIGHT",
  "OPEN_SECOND_BRAIN_SEARCH_SEM_WEIGHT",
  "OPEN_SECOND_BRAIN_SEARCH_IGNORE",
  "OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER",
  "OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL",
  "OPEN_SECOND_BRAIN_EMBEDDING_MODEL",
  "OPEN_SECOND_BRAIN_EMBEDDING_KEY",
  "OPEN_SECOND_BRAIN_EMBEDDING_DIM",
  "OPEN_SECOND_BRAIN_EMBEDDING_TIMEOUT",
  "OPEN_SECOND_BRAIN_EMBEDDING_CONCURRENCY",
  "OPEN_SECOND_BRAIN_EMBEDDING_BATCH",
  "OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES",
  "OPEN_SECOND_BRAIN_SEARCH_RECENCY_SHAPE",
  "OPEN_SECOND_BRAIN_SEARCH_RECENCY_SCALE",
  "OPEN_SECOND_BRAIN_SEARCH_RECENCY_AMPLITUDE",
  "OPEN_SECOND_BRAIN_SEARCH_INTENT_ENABLED",
  "OPEN_SECOND_BRAIN_SEARCH_SYNONYM_ENABLED",
  "OPEN_SECOND_BRAIN_SEARCH_SYNONYM_MAX_TERMS",
  "OPEN_SECOND_BRAIN_SEARCH_CACHE_ENABLED",
  "OPEN_SECOND_BRAIN_SEARCH_CACHE_TTL",
  "OPEN_SECOND_BRAIN_SEARCH_SHUTDOWN_GRACE",
  "OPEN_SECOND_BRAIN_SEARCH_RESUME_REINDEX",
  "OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP",
  "OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP_SCORE",
  "OPEN_SECOND_BRAIN_SEARCH_POOL_MAX_PER_SESSION",
  "OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE",
  "OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE_MODE",
];

beforeEach(() => {
  tmp = mkdtempSync(join(tmpdir(), "osb-cfg-"));
  configPath = join(tmp, "config.yaml");
  origEnv = {};
  for (const k of ENV_KEYS) {
    origEnv[k] = process.env[k];
    delete process.env[k];
  }
});

afterEach(() => {
  for (const k of ENV_KEYS) {
    if (origEnv[k] === undefined) delete process.env[k];
    else process.env[k] = origEnv[k];
  }
  rmSync(tmp, { recursive: true, force: true });
});

test("defaults are returned when config and env are empty", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.vault).toBe(tmp);
  expect(cfg.dbPath).toBe(join(tmp, ".open-second-brain", "brain.sqlite"));
  expect(cfg.chunkSize).toBe(800);
  expect(cfg.chunkOverlap).toBe(100);
  expect(cfg.chunkMinSize).toBe(100);
  expect(cfg.keywordWeight).toBe(0.6);
  expect(cfg.semanticWeight).toBe(0.4);
  expect(cfg.semantic.enabled).toBe(false);
  expect(cfg.semantic.provider).toBe("openai-compat");
  expect(cfg.semantic.apiKey).toBeNull();
  const ignoreRaws = cfg.scopeRules.ignore.map((r) => r.raw);
  expect(ignoreRaws).toContain(".git");
  expect(ignoreRaws).toContain(".open-second-brain");
  // v0.10.9: the default set folds in `.obsidian` (whole dir) and
  // `Brain/.snapshots`. These come from the shared `vault-scope`
  // defaults, not the legacy `search_ignore_paths` plumbing.
  expect(ignoreRaws).toContain(".obsidian");
  expect(ignoreRaws).toContain("Brain/.snapshots");
});

test("embedding retry budget defaults to 6 and is overridable via env and config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(6);

  writeFileSync(configPath, `vault: "${tmp}"\nembedding_max_retries: "9"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(9);

  process.env["OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES"] = "2";
  expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(2);
});

test("embedding retry budget below 1 is rejected", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nembedding_max_retries: "0"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/embedding_max_retries/);
});

test("recall recency defaults to the Weibull curve params", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.recall.recencyShape).toBe(0.8);
  expect(cfg.recall.recencyScale).toBe(30);
  expect(cfg.recall.recencyAmplitude).toBe(0.05);
});

test("recency curve params are overridable via env and config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_recency_scale: "45"\n`);
  process.env["OPEN_SECOND_BRAIN_SEARCH_RECENCY_SHAPE"] = "1.2";
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.recall.recencyShape).toBe(1.2);
  expect(cfg.recall.recencyScale).toBe(45);
});

test("query-intent classification defaults on and is toggleable", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.intentEnabled).toBe(true);
  process.env["OPEN_SECOND_BRAIN_SEARCH_INTENT_ENABLED"] = "false";
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.intentEnabled).toBe(false);
});

test("synonym expansion defaults off and is toggleable with a term cap", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const def = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(def.synonymEnabled).toBe(false);
  expect(def.synonymMaxTerms).toBe(3);
  process.env["OPEN_SECOND_BRAIN_SEARCH_SYNONYM_ENABLED"] = "true";
  process.env["OPEN_SECOND_BRAIN_SEARCH_SYNONYM_MAX_TERMS"] = "5";
  const on = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(on.synonymEnabled).toBe(true);
  expect(on.synonymMaxTerms).toBe(5);
});

test("query cache defaults off with a 300s TTL and is toggleable", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const def = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(def.cacheEnabled).toBe(false);
  expect(def.cacheTtlSeconds).toBe(300);
  process.env["OPEN_SECOND_BRAIN_SEARCH_CACHE_ENABLED"] = "true";
  process.env["OPEN_SECOND_BRAIN_SEARCH_CACHE_TTL"] = "60";
  const on = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(on.cacheEnabled).toBe(true);
  expect(on.cacheTtlSeconds).toBe(60);
});

test("cross-vault chain-stop defaults off at a 0.8 threshold and is toggleable", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const def = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(def.chainStopEnabled).toBe(false);
  expect(def.chainStopScore).toBe(0.8);
  process.env["OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP"] = "true";
  process.env["OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP_SCORE"] = "0.9";
  const on = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(on.chainStopEnabled).toBe(true);
  expect(on.chainStopScore).toBe(0.9);
});

test("chain-stop score outside [0,1] is rejected", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chain_stop_score: "1.5"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/search_chain_stop_score/);
});

test("non-positive recency scale is rejected", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_recency_scale: "0"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/search_recency_scale/);
});

test("recency amplitude outside [0,1] is rejected", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_recency_amplitude: "2"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/search_recency_amplitude/);
});

test("OPEN_SECOND_BRAIN_SEARCH_IGNORE has no effect (removed in v0.10.9)", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  process.env["OPEN_SECOND_BRAIN_SEARCH_IGNORE"] = "from-env-1,from-env-2";
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  const raws = cfg.scopeRules.ignore.map((r) => r.raw);
  expect(raws).not.toContain("from-env-1");
  expect(raws).not.toContain("from-env-2");
});

test("search_ignore_paths in config.yaml has no effect (removed in v0.10.9)", () => {
  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_ignore_paths: "from-config-1,from-config-2"\n`,
  );
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  const raws = cfg.scopeRules.ignore.map((r) => r.raw);
  expect(raws).not.toContain("from-config-1");
  expect(raws).not.toContain("from-config-2");
});

test("vault.ignore_paths in Brain/_brain.yaml is the source of truth", () => {
  mkdirSync(join(tmp, "Brain"), { recursive: true });
  writeFileSync(
    join(tmp, "Brain", "_brain.yaml"),
    `schema_version: 1
vault:
  ignore_paths:
    - my-cache
    - Drafts
`,
  );
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.scopeRules.ignore.map((r) => r.raw)).toEqual(["my-cache", "Drafts"]);
  // The path-style entry survives classification.
  const draftsRule = cfg.scopeRules.ignore.find((r) => r.raw === "Drafts");
  expect(draftsRule?.kind).toBe("name");
  // No allowlist declared: null, never an empty array.
  expect(cfg.scopeRules.include).toBeNull();
});

test("vault.include_paths reaches the resolved search config", () => {
  mkdirSync(join(tmp, "Brain"), { recursive: true });
  writeFileSync(
    join(tmp, "Brain", "_brain.yaml"),
    `schema_version: 1
vault:
  include_paths:
    - Brain
    - Notes/Daily
`,
  );
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.scopeRules.include?.map((r) => r.raw)).toEqual(["Brain", "Notes/Daily"]);
  expect(cfg.scopeRules.include?.map((r) => r.kind)).toEqual(["name", "path"]);
  // The built-in exclusions are still in force alongside it.
  expect(cfg.scopeRules.ignore.map((r) => r.raw)).toContain(".git");
});

test("env overrides config which overrides defaults", () => {
  writeFileSync(
    configPath,
    [
      `vault: "${tmp}"`,
      `search_chunk_size: "500"`,
      `search_semantic_enabled: "true"`,
      `embedding_base_url: "https://config.example/v1"`,
      `embedding_model: "config-model"`,
      `embedding_api_key: "cfg-key"`,
    ].join("\n") + "\n",
  );
  process.env["OPEN_SECOND_BRAIN_EMBEDDING_MODEL"] = "env-model";
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.chunkSize).toBe(500);
  expect(cfg.semantic.enabled).toBe(true);
  expect(cfg.semantic.baseUrl).toBe("https://config.example/v1");
  expect(cfg.semantic.model).toBe("env-model");
  expect(cfg.semantic.apiKey).toBe("cfg-key");
});

test("overrides win over both env and config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_size: "500"\n`);
  process.env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"] = "false";
  const cfg = resolveSearchConfig({
    vault: tmp,
    configPath,
    overrides: { keywordWeight: 0.9, semanticWeight: 0.1 },
  });
  expect(cfg.keywordWeight).toBe(0.9);
  expect(cfg.semanticWeight).toBe(0.1);
});

test("overrides can repair invalid configured weight sums", () => {
  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_keyword_weight: "0.7"\nsearch_semantic_weight: "0.5"\n`,
  );
  const cfg = resolveSearchConfig({
    vault: tmp,
    configPath,
    overrides: { keywordWeight: 0.5, semanticWeight: 0.5 },
  });
  expect(cfg.keywordWeight).toBe(0.5);
  expect(cfg.semanticWeight).toBe(0.5);
});

test("invalid numeric value throws INVALID_INPUT", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_size: "not-a-number"\n`);
  let err: SearchError | null = null;
  try {
    resolveSearchConfig({ vault: tmp, configPath });
  } catch (e) {
    err = e as SearchError;
  }
  expect(err).not.toBeNull();
  expect(err?.code).toBe("INVALID_INPUT");
  expect(err?.message).toContain("search_chunk_size");
});

test("weights summing above 1 is rejected", () => {
  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_keyword_weight: "0.7"\nsearch_semantic_weight: "0.5"\n`,
  );
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/sum.*1/);
});

test("non-positive integer knobs are rejected before provider construction", () => {
  for (const key of [
    "search_chunk_size",
    "embedding_dimension",
    "embedding_timeout_ms",
    "embedding_concurrency",
    "embedding_batch_size",
  ]) {
    writeFileSync(configPath, `vault: "${tmp}"\n${key}: "0"\n`);
    expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(key);
  }
});

test("chunk overlap must be non-negative and smaller than chunk size", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_overlap: "-1"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/search_chunk_overlap/);

  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_chunk_size: "100"\nsearch_chunk_overlap: "100"\n`,
  );
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/smaller than/);
});

test("chunk minimum size resolves from config and env overrides config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_min_size: "50"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).chunkMinSize).toBe(50);

  process.env["OPEN_SECOND_BRAIN_SEARCH_CHUNK_MIN_SIZE"] = "75";
  expect(resolveSearchConfig({ vault: tmp, configPath }).chunkMinSize).toBe(75);
});

test("chunk minimum size must be a positive integer not exceeding chunk size", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_min_size: "0"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/search_chunk_min_size/);

  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_chunk_size: "300"\nsearch_chunk_min_size: "400"\n`,
  );
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/exceed/);
});

test("overrides are validated after merging", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  expect(() =>
    resolveSearchConfig({
      vault: tmp,
      configPath,
      overrides: { keywordWeight: Number.NaN },
    }),
  ).toThrow(/search_keyword_weight/);
  expect(() =>
    resolveSearchConfig({
      vault: tmp,
      configPath,
      overrides: { semantic: { batchSize: 0 } },
    }),
  ).toThrow(/embedding_batch_size/);
});

test("a NaN integer override is rejected instead of silently passing range checks", () => {
  // `NaN < min` and `NaN > max` are both false, so an integer-range check
  // that only compares bounds would let a NaN override through unnoticed.
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  expect(() =>
    resolveSearchConfig({
      vault: tmp,
      configPath,
      overrides: { semantic: { concurrency: Number.NaN } },
    }),
  ).toThrow(/embedding_concurrency/);
});

// ── Indexer Durability suite: shutdown grace + resume flag ──────────────────

test("durability keys default to a 5s grace and no resume", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.shutdownGraceMs).toBe(5_000);
  expect(cfg.resumeReindex).toBe(false);
});

test("config keys override the durability defaults", () => {
  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_shutdown_grace_seconds: 12\nsearch_resume_reindex: true\n`,
  );
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.shutdownGraceMs).toBe(12_000);
  expect(cfg.resumeReindex).toBe(true);
});

test("env mirrors override the durability config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_shutdown_grace_seconds: 12\n`);
  process.env["OPEN_SECOND_BRAIN_SEARCH_SHUTDOWN_GRACE"] = "3";
  process.env["OPEN_SECOND_BRAIN_SEARCH_RESUME_REINDEX"] = "true";
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.shutdownGraceMs).toBe(3_000);
  expect(cfg.resumeReindex).toBe(true);
});

test("an invalid grace is rejected loudly (no silent fallback)", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_shutdown_grace_seconds: soon\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(
    /search_shutdown_grace_seconds/,
  );
});

test("grace of 0 disables the await window", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_shutdown_grace_seconds: 0\n`);
  const cfg = resolveSearchConfig({ vault: tmp, configPath });
  expect(cfg.shutdownGraceMs).toBe(0);
});

// ── Per-source-session pool cap (t_bb6ce095) ─────────────────────────────────

test("the per-session pool cap defaults off and resolves from config and env", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.poolMaxPerSession).toBeUndefined();

  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "4"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.poolMaxPerSession).toBe(4);

  process.env["OPEN_SECOND_BRAIN_SEARCH_POOL_MAX_PER_SESSION"] = "2";
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.poolMaxPerSession).toBe(2);
});

test("a negative per-session pool cap is refused by the resolved-config validation", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "-1"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(
    /search_pool_max_per_session/,
  );
});

test("a non-integer per-session pool cap is refused", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "2.5"\n`);
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(
    /search_pool_max_per_session/,
  );
});

test("the resolved field is absent at the off default and present when positive", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const off = resolveSearchConfig({ vault: tmp, configPath }).recall;
  // Spread-omitted at 0: exact-shape assertions on the resolved config
  // keep holding, exactly like the other opt-in recall fields.
  expect(Object.keys(off)).not.toContain("poolMaxPerSession");

  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "3"\n`);
  const on = resolveSearchConfig({ vault: tmp, configPath }).recall as unknown as Record<
    string,
    unknown
  >;
  expect(on["poolMaxPerSession"]).toBe(3);
});

test("a pool-cap change re-keys the config fingerprint and the per-query cache key", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const off = resolveSearchConfig({ vault: tmp, configPath });
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "2"\n`);
  const on = resolveSearchConfig({ vault: tmp, configPath });

  // A results-affecting knob must invalidate cached rows: the fingerprint
  // string differs, so a cached row computed under the old knob value can
  // never be served under the new one.
  expect(configFingerprint(on)).not.toBe(configFingerprint(off));

  // The per-query override partitions the cache the same way; dropped
  // when absent, so a query that does not set it keys byte-identically
  // to a pre-knob row.
  const base: SearchOptions = { query: "alpha" };
  expect(buildCacheKey({ ...base, poolMaxPerSession: 2 }, "p", "fp")).not.toBe(
    buildCacheKey(base, "p", "fp"),
  );
  // An explicit per-query 0 is a forced off, not the config default.
  expect(buildCacheKey({ ...base, poolMaxPerSession: 0 }, "p", "fp")).not.toBe(
    buildCacheKey(base, "p", "fp"),
  );

  // The review-L4 boundary does NOT mute the folds: a value at or above
  // the query's resolved pool width behaves as off (it cannot drop a row
  // from that pool), but the value still keys both caches, so a change
  // around that boundary can never serve a stale cached row.
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_pool_max_per_session: "10000"\n`);
  const huge = resolveSearchConfig({ vault: tmp, configPath });
  expect(configFingerprint(huge)).not.toBe(configFingerprint(off));
  expect(buildCacheKey({ ...base, poolMaxPerSession: 10_000 }, "p", "fp")).not.toBe(
    buildCacheKey(base, "p", "fp"),
  );
});

test("the bench pin accepts the pool-cap knob name in a recall pin", () => {
  // The measured-decision-note harness pins recall knobs by name, so the
  // new knob must join the pin's known recall keys or every pin naming
  // it is refused.
  const pin = parseBenchPinnedKnobs('{"recall":{"poolMaxPerSession":2}}');
  expect(pin.recall?.poolMaxPerSession).toBe(2);

  // A name outside the list is still refused, by name.
  expect(() => parseBenchPinnedKnobs('{"recall":{"poolCapNonsense":2}}')).toThrow(
    /poolCapNonsense.*not a known knob/,
  );
});

test("the bench pin names the trust gate mode, and the dead legacy field is refused by name", () => {
  // A pin of the legacy field would measure with the gate off without
  // any sign, so it is refused; the mode is the pinnable knob.
  const pin = parseBenchPinnedKnobs('{"recall":{"searchTrustGateMode":"enforce"}}');
  expect(pin.recall?.searchTrustGateMode).toBe("enforce");
  expect(() => parseBenchPinnedKnobs('{"recall":{"retrievalTrustGateEnabled":true}}')).toThrow(
    /retrievalTrustGateEnabled.*not a known knob/,
  );
});

test("an override carrying an invalid trust gate mode is refused by the resolver", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const base = resolveSearchConfig({ vault: tmp, configPath });
  expect(() =>
    resolveSearchConfig({
      vault: tmp,
      configPath,
      overrides: { recall: { ...base.recall, searchTrustGateMode: "measure" as "shadow" } },
    }),
  ).toThrow(/search_trust_gate_mode must be/);
});

// ── Retrieval trust gate mode (session-mining-economy, t_05a0eaa4) ──────────

test("the trust gate mode defaults off and stays absent from the resolved recall config", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const recall = resolveSearchConfig({ vault: tmp, configPath }).recall;
  expect(recall.searchTrustGateMode).toBeUndefined();
  // Spread-omitted at off: exact-shape assertions on the resolved config
  // keep holding, exactly like the other opt-in recall fields.
  expect(Object.keys(recall)).not.toContain("searchTrustGateMode");
});

test("an explicit trust gate mode resolves from config, env winning", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_mode: "shadow"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode).toBe("shadow");

  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_mode: "enforce"\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode).toBe(
    "enforce",
  );

  process.env["OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE_MODE"] = "shadow";
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode).toBe("shadow");
});

test("the legacy boolean maps true to enforce and false to off", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_enabled: true\n`);
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode).toBe(
    "enforce",
  );

  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_enabled: false\n`);
  expect(
    resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode,
  ).toBeUndefined();
});

test("an explicit mode wins over the legacy boolean, including explicit off", () => {
  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_trust_gate_enabled: true\nsearch_trust_gate_mode: "off"\n`,
  );
  expect(
    resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode,
  ).toBeUndefined();

  writeFileSync(
    configPath,
    `vault: "${tmp}"\nsearch_trust_gate_enabled: false\nsearch_trust_gate_mode: "enforce"\n`,
  );
  expect(resolveSearchConfig({ vault: tmp, configPath }).recall.searchTrustGateMode).toBe(
    "enforce",
  );
});

test("an invalid trust gate mode is refused naming the key in force", () => {
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_mode: "measure"\n`);
  let err: SearchError | null = null;
  try {
    resolveSearchConfig({ vault: tmp, configPath });
  } catch (e) {
    err = e as SearchError;
  }
  expect(err?.code).toBe("INVALID_INPUT");
  expect(err?.message).toContain("search_trust_gate_mode");
  expect(err?.message).toContain("measure");

  // Env in force: the refusal names the env var, never the config key
  // that lost the precedence race.
  process.env["OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE_MODE"] = "maybe";
  let envMessage = "";
  try {
    resolveSearchConfig({ vault: tmp, configPath });
  } catch (e) {
    envMessage = (e as Error).message;
  }
  expect(envMessage).toContain("OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE_MODE");
  expect(envMessage).not.toContain("search_trust_gate_mode must");
});

test("an invalid legacy trust gate boolean from the env names the env var", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  process.env["OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE"] = "yes";
  expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(
    "OPEN_SECOND_BRAIN_SEARCH_TRUST_GATE must be",
  );
});

test("a trust gate mode change re-keys the config fingerprint", () => {
  writeFileSync(configPath, `vault: "${tmp}"\n`);
  const off = resolveSearchConfig({ vault: tmp, configPath });
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_mode: "shadow"\n`);
  const shadow = resolveSearchConfig({ vault: tmp, configPath });
  writeFileSync(configPath, `vault: "${tmp}"\nsearch_trust_gate_mode: "enforce"\n`);
  const enforce = resolveSearchConfig({ vault: tmp, configPath });

  // The mode decides whether the gate excludes, so a change must
  // invalidate cached rows; the legacy boolean entry already re-keyed,
  // and the mode adds its own dimension on top.
  expect(configFingerprint(shadow)).not.toBe(configFingerprint(off));
  expect(configFingerprint(enforce)).not.toBe(configFingerprint(shadow));
  expect(configFingerprint(enforce)).not.toBe(configFingerprint(off));
});