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
86.9 KB
Raw Blame
/**
 * Configuration discovery and persistence.
 *
 * Mirrors `src/open_second_brain/config.py` from the legacy Python implementation
 * — same lookup chain (env → XDG → ~/.config), same simple `key: value` YAML
 * subset, same atomic write semantics, same redaction policy. Tests pin parity
 * via parallel suites in tests/core/config.test.ts.
 */

import { mkdirSync, readFileSync, statSync, type Stats } from "node:fs";
import { createHmac, randomBytes } from "node:crypto";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";

import lockfile from "proper-lockfile";

import { atomicWriteFileSync, sleepSync } from "./fs-atomic.ts";
import { isSecretReferenceValue, SecretReferenceError } from "./secret-ref.ts";
import { APP_DIR_NAME, configBaseDir } from "./platform-dirs.ts";
import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";
import { resolvePointerVault } from "./brain/portability/pointer.ts";
import { parseBrainYaml } from "./brain/yaml-parse.ts";
import { BrainConfigError } from "./brain/policy/errors.ts";
import { BRAIN_CONFIG_FILE, BRAIN_ROOT_REL } from "./brain/path-constants.ts";
import { resolveSkillRewriteMode, type SkillRewriteMode } from "./brain/skill-rewrite.ts";
import {
  isWikiLinkFormat,
  WIKI_LINK_FORMATS,
  type WikiLinkFormat,
} from "./brain/link-graph/format-wikilink.ts";
import type { LinkOutputFormat } from "./brain/wikilink.ts";
import { STORE_DUAL_WRITE_CONFIG_KEY, STORE_DUAL_WRITE_ENV } from "./store/constants.ts";
import type { ConfigDiscovery } from "./types.ts";

/**
 * The named-secret resolver port (trust-surface-hardening, t_e5807974).
 *
 * A `$secret:` reference in a config value resolves through the vault's
 * custody store, whose own import neighbourhood reaches back into THIS
 * module (store -> audit -> ledger-shards -> config), so a static import
 * of the resolver here closed the six-module cycle config ->
 * secret-resolver -> custody store -> audit -> ledger-shards -> config,
 * whose initialisation order is undefined. Config is the base layer and
 * carries only the PORT; the resolver plane is the adapter and fills it
 * through {@link installNamedSecretResolver} when `secret-resolver.ts`
 * loads - which every production entry (the CLI's `main.ts`, the MCP
 * server, the OpenClaw bridge) does statically at startup, before any
 * command dispatch.
 */
export interface NamedSecretResolver {
  /** Resolve one `$secret:` reference against `vault`'s custody store. */
  resolveNamedSecret(vault: string, value: string): string;
}

let namedSecretResolver: NamedSecretResolver | undefined;

/** Fill the {@link NamedSecretResolver} port; see its docblock for the wiring. */
export function installNamedSecretResolver(resolver: NamedSecretResolver): void {
  namedSecretResolver = resolver;
}

/**
 * Resolve one reference through the installed resolver. The refusal is
 * unreachable in a wired process (see the port's docblock); failing
 * closed by name keeps an unwired one from ever treating a stored
 * reference as literal text - for the installation secret that mistake
 * would self-heal a fresh key right over the reference.
 */
function resolveThroughNamedSecretResolver(vault: string, reference: string): string {
  const resolver = namedSecretResolver;
  if (resolver === undefined) {
    throw new SecretReferenceError(
      "no named-secret resolver is installed in this process; the $secret: reference " +
        "cannot be resolved against the vault's custody store",
      reference,
    );
  }
  return resolver.resolveNamedSecret(vault, reference);
}

const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;

/**
 * Platforms whose per-user configuration root this build cannot derive.
 * Empty since native Windows gained its own layout (`%LOCALAPPDATA%`, see
 * `platform-dirs.ts`); kept as a named list so adding a platform without
 * a layout is a visible decision rather than a silent POSIX fallback.
 */
const UNSUPPORTED_CONFIG_PLATFORMS: ReadonlyArray<string> = Object.freeze([]);

/**
 * Raised when the config path cannot be derived on the running
 * platform. Named and specific because the alternative - a POSIX path on
 * a platform that does not use one - is a plausible-looking answer to a
 * question this build cannot answer. No platform reaches it today; the
 * class stays exported for callers that still distinguish it.
 */
export class UnsupportedPlatformError extends Error {
  readonly platform: string;

  constructor(platform: string) {
    super(
      `open-second-brain has no configuration layout for platform '${platform}': ` +
        "this build does not know where per-user configuration lives there. Set " +
        "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " +
        "to a configuration root, to choose the location yourself.",
    );
    this.name = "UnsupportedPlatformError";
    this.platform = platform;
  }
}

/**
 * Raised when the plugin config file is PRESENT but its contents cannot be
 * obtained: a directory (or any non-regular file) where the file should be,
 * a path that cannot be stat'ed at all (an untraversable parent, a symlink
 * loop), a file that cannot be opened, or bytes that are not UTF-8.
 *
 * Named and specific for the same reason {@link UnsupportedPlatformError}
 * is: the alternative - reporting the file as absent - is a
 * plausible-looking answer to a question this module cannot answer. Absent
 * means "no operator settings, defaults apply"; every gate resolved from
 * this file is default-OFF, so absorbing an unreadable file turns the
 * operator's flags off and leaves the install indistinguishable from one
 * that never set them.
 */
export class ConfigReadError extends Error {
  /** The config file that could not be read. */
  readonly path: string;

  constructor(path: string, reason: string) {
    // The remedy rides in the message rather than in each reporting
    // surface. This error escapes through four channels with nothing in
    // common - the CLI dispatch, an MCP error envelope, a hook's stderr,
    // and a subcommand that wraps it in its own prose - and a remedy
    // rendered per surface would drift between them or be dropped by the
    // wrappers. Long and instructive matches
    // {@link UnsupportedPlatformError}, for the same reason: the whole
    // value of a refusal is telling the operator what to do next.
    super(
      `failed to read plugin config ${path}: ${reason}. The file is present, so its ` +
        "settings are NOT in force and are not read as absent; make it readable " +
        `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`,
    );
    this.name = "ConfigReadError";
    this.path = path;
  }
}

/** Injected view of the environment {@link resolveDefaultConfigPath} reads. */
export interface ConfigPathEnv {
  /** `process.platform` value. */
  readonly platform: string;
  /** `homedir()` value. */
  readonly home: string;
  readonly env: Readonly<Record<string, string | undefined>>;
}

/**
 * Resolve the location of the plugin config file from an injected
 * environment.
 *
 * Order: `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, then the
 * platform default: `%LOCALAPPDATA%\open-second-brain\config.yaml` on
 * Windows, `$HOME/.config/open-second-brain/config.yaml` everywhere else.
 * Only the last step is platform-bound, so an operator on an unsupported
 * platform still has two ways to say where the file lives.
 *
 * @throws {@link UnsupportedPlatformError} on a platform listed in
 *   `UNSUPPORTED_CONFIG_PLATFORMS` (none today).
 */
export function resolveDefaultConfigPath(source: ConfigPathEnv): string {
  const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
  if (override) return expandTilde(override, source.platform, source.home);

  const xdg = source.env["XDG_CONFIG_HOME"];
  if (xdg) return join(expandTilde(xdg, source.platform, source.home), APP_DIR_NAME, "config.yaml");

  if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
    throw new UnsupportedPlatformError(source.platform);
  }
  return join(configBaseDir(source), APP_DIR_NAME, "config.yaml");
}

/**
 * Resolve the location of the plugin config file for this process.
 *
 * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, then the
 * platform default (see {@link resolveDefaultConfigPath}).
 */
export function defaultConfigPath(): string {
  return resolveDefaultConfigPath({
    platform: process.platform,
    home: homedir(),
    env: process.env,
  });
}

/**
 * Parse the simple `key: value` YAML subset used for the plugin config.
 *
 * Intentionally not a real YAML parser — keeping this dependency-free and
 * matching the Python `parse_simple_yaml` exactly so round-trips are stable.
 * Lines that aren't `key: value` (comments, blanks, complex YAML) are skipped.
 */
export function parseSimpleYaml(text: string): Record<string, string> {
  const data: Record<string, string> = {};
  for (const rawLine of text.split(/\r?\n/)) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#")) continue;
    const idx = line.indexOf(":");
    if (idx === -1) continue;
    const key = line.slice(0, idx).trim();
    if (!key) continue;
    let value = line.slice(idx + 1).trim();
    // Strip surrounding quotes (single OR double).
    if (
      value.length >= 2 &&
      ((value.startsWith('"') && value.endsWith('"')) ||
        (value.startsWith("'") && value.endsWith("'")))
    ) {
      value = value.slice(1, -1);
    }
    data[key] = value;
  }
  return data;
}

/**
 * Read and parse the config file, or report it as missing.
 *
 * TWO conditions, not one, and they are kept apart on purpose - the same
 * split `Brain/_brain.yaml` makes in `brain/policy/load.ts`:
 *
 *   - ABSENT - nothing at this path. There are no operator settings to
 *     contradict, so `exists: false` with no data is the correct answer and
 *     every resolver above falls back to its documented default. This is
 *     the common case on any install that has not run `o2b init`.
 *   - PRESENT BUT UNREADABLE - a non-regular file (a directory in the
 *     file's place), a path that cannot be stat'ed, a file that cannot be
 *     opened, or bytes that are not UTF-8. The operator's settings exist
 *     and are NOT the ones in force. Reporting that as absent turned every
 *     default-OFF gate resolved from this file back to `false` and left the
 *     install looking exactly like one that never set a flag;
 *     {@link ConfigReadError} names the file instead.
 *
 * The parse itself has no third condition: {@link parseSimpleYaml} skips
 * whatever it cannot represent (comments, blank lines, nested blocks), and
 * that tolerance is deliberate parity with the legacy Python reader. That
 * tolerance is about SHAPE, not encoding - see {@link readConfigText}.
 */
export function discoverConfig(path?: string): ConfigDiscovery {
  const resolved = path ?? defaultConfigPath();
  const stat = statConfigPath(resolved);
  if (stat === undefined) {
    return { path: resolved, exists: false, data: {} };
  }
  // Ahead of the read rather than letting `readFileSync` raise `EISDIR`,
  // because it also covers the paths a read cannot survive: a FIFO at the
  // config path would block the process forever.
  if (!stat.isFile()) {
    throw new ConfigReadError(resolved, "path exists but is not a regular file");
  }
  return { path: resolved, exists: true, data: parseSimpleYaml(readConfigText(resolved)) };
}

/**
 * Stat of the config path: `undefined` for a genuine absence, {@link Stats}
 * otherwise, {@link ConfigReadError} when the answer is unknowable.
 *
 * This replaces an `existsSync` check, which is not the absent/broken split
 * it looks like: it answers `false` for EVERY stat failure, so a perfectly
 * readable config behind a directory lacking the execute bit (or under a
 * symlink loop, or past a name-too-long component) reported as absent and
 * silently reverted the operator's `vault` and every gate in the file to
 * its default. Only ENOENT on this path is an absence; every other errno is
 * a failure to read it.
 *
 * `throwIfNoEntry: false` is what makes that split free rather than a
 * downgrade: it suppresses ENOENT alone and still raises every other errno,
 * so the common absent case pays one syscall and constructs no error - the
 * same cost `existsSync` had, since it is the same `stat`.
 */
function statConfigPath(resolved: string): Stats | undefined {
  try {
    return statSync(resolved, { throwIfNoEntry: false });
  } catch (err) {
    throw new ConfigReadError(resolved, (err as Error).message ?? String(err));
  }
}

/**
 * Decoded contents of a config file that is known to be a regular file, or
 * a {@link ConfigReadError}.
 *
 * The decode is FATAL, so bytes that are not UTF-8 are the present-but-
 * unreadable condition rather than a lossy parse. `parseSimpleYaml` is
 * tolerant about the SHAPE of a line - that is deliberate parity with the
 * legacy Python reader - but nothing about it licenses accepting bytes we
 * cannot represent: a lossy decode drops whichever keys the undecodable
 * run straddles, which is the same silent revert-to-default as reading the
 * file as absent. It is also destructive, because {@link setConfigValue}
 * merges onto what this returns and would persist the operator's file with
 * every undecodable byte replaced.
 */
function readConfigText(resolved: string): string {
  let bytes: Buffer;
  try {
    bytes = readFileSync(resolved);
  } catch (err) {
    throw new ConfigReadError(resolved, (err as Error).message ?? String(err));
  }
  try {
    return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
  } catch (err) {
    throw new ConfigReadError(
      resolved,
      `not valid UTF-8: ${(err as Error).message ?? String(err)}`,
    );
  }
}

/**
 * Persist a single `key: value` pair into the plugin config file.
 *
 * Atomic: writes to a temp sibling and renames, with fsync on file and parent
 * dir. Rejects values containing characters that would break the simple parser
 * on read-back rather than silently corrupting them.
 */
export function setConfigValue(key: string, value: string, path?: string): string {
  if (typeof value !== "string") {
    throw new TypeError(`config value for ${JSON.stringify(key)} must be a string`);
  }
  for (const bad of CONFIG_VALUE_REJECTED_CHARS) {
    if (value.includes(bad)) {
      throw new Error(
        `config value for ${JSON.stringify(key)} contains a disallowed character ` +
          `(${JSON.stringify(bad)}); reject rather than silently corrupting on read-back`,
      );
    }
  }

  const resolved = path ?? defaultConfigPath();
  const discovery = discoverConfig(resolved);
  const data = { ...discovery.data, [key]: value };
  const body =
    Object.entries(data)
      .map(([k, v]) => `${k}: "${v}"`)
      .join("\n") + "\n";
  atomicWriteFileSync(resolved, body);
  return resolved;
}

export interface TimezoneValidationResult {
  readonly ok: boolean;
  readonly error: string | null;
}

/** Validate an IANA timezone name without normalising or trimming it. */
export function validateTimezoneName(name: string): TimezoneValidationResult {
  try {
    // Constructing the formatter IS the validation - it throws a
    // RangeError on an unknown zone. Called rather than `new`-ed because
    // the instance is discarded either way, and `new` for its side effect
    // reads as an accident.
    Intl.DateTimeFormat("en-US", { timeZone: name });
    return { ok: true, error: null };
  } catch (exc) {
    return { ok: false, error: (exc as Error).message ?? String(exc) };
  }
}

/**
 * Resolve the IANA timezone for stamping Daily entries.
 *
 * Order: `VAULT_TIMEZONE` env → `timezone` field in plugin config → `null`
 * (caller falls back to the host's local clock). Invalid IANA names are silently
 * treated as "not configured" so a typo never breaks logging.
 */
export function resolveTimezone(configPath?: string): string | null {
  let name = process.env["VAULT_TIMEZONE"];
  if (!name) {
    name = discoverConfig(configPath).data["timezone"];
  }
  if (!name) return null;
  return validateTimezoneName(name).ok ? name : null;
}

/**
 * Resolve the vault directory.
 *
 * Order: `VAULT_DIR` env → project pointer walk-up → active profile →
 * `vault` field in plugin config → `null`. Caller decides whether to
 * error out or accept a positional path.
 */
export function resolveVault(configPath?: string, opts: { cwd?: string } = {}): string | null {
  const env = process.env["VAULT_DIR"];
  if (env) return expandTilde(env);
  // Project pointer (Workspace Insight Suite, t_1375e69f): a pointer file
  // in (or above) the working directory is the most specific durable
  // artifact, so it beats the profile pointer. Pointers only exist when
  // the operator linked the directory - without one the chain is
  // byte-identical to before. The walk stops at the filesystem root and
  // reads at most one small JSON per level; malformed pointers and
  // dangling targets fail soft to the next resolution step.
  const pointerVault = resolvePointerVault(opts.cwd ?? process.cwd());
  if (pointerVault !== null) return expandTilde(pointerVault);
  // Multi-vault profiles (v0.22.0): an active named profile overrides the
  // bare `vault` key. With no profiles registry the result is unchanged.
  const discovery = discoverConfig(configPath);
  const profileVault = resolveActiveProfileVault(discovery.path);
  if (profileVault) return expandTilde(profileVault);
  const cfg = discovery.data["vault"];
  if (cfg) return expandTilde(cfg);
  return null;
}

/**
 * The machine config's own `vault` key (`~` expanded), or null when it
 * sets none: unlike {@link resolveVault}, never `VAULT_DIR`, a project
 * pointer or a profile, which name a vault for one session only. For a
 * writer that would persist the answer back as the machine's vault.
 */
export function configuredVaultKey(configPath?: string): string | null {
  const value = discoverConfig(configPath).data["vault"];
  return value ? expandTilde(value) : null;
}

/**
 * The identity every install writes under until one is configured.
 *
 * It is a placeholder, not a name: two unconfigured installs write under
 * the same token, so any surface that folds contributions per agent merges
 * every one of them into a single row that reads as one very busy agent
 * (a-label-is-not-a-boundary, U5). It is exported so the roster can say
 * "unconfigured" instead of repeating the literal in a second place and
 * calling it a name.
 */
export const UNCONFIGURED_AGENT_NAME = "agent";

/**
 * Whether an agent identity was actually chosen by an operator, as opposed
 * to being the placeholder {@link resolveAgentName} falls back to.
 */
export function isConfiguredAgentName(name: string): boolean {
  const trimmed = name.trim();
  return trimmed.length > 0 && trimmed !== UNCONFIGURED_AGENT_NAME;
}

/**
 * Resolve the agent identity used when no explicit `agent` is supplied.
 *
 * Order: `VAULT_AGENT_NAME` env → `agent_name`/`agentName` in plugin config →
 * {@link UNCONFIGURED_AGENT_NAME}. Used by every Brain writer that needs
 * an `agent:` field (signals, evidence rows, log entries) and by the
 * Hermes pre_llm_call hook.
 */
export function resolveAgentName(configPath?: string): string {
  const env = process.env["VAULT_AGENT_NAME"];
  if (env) return env;
  const data = discoverConfig(configPath).data;
  const value = data["agent_name"] ?? data["agentName"];
  if (value) return value;
  return UNCONFIGURED_AGENT_NAME;
}

/**
 * Shared-namespace root from the device config, or null when off
 * (Agent Write Contract Suite, t_936a1a61).
 *
 * Lives here rather than in `brain/shared-namespace.ts` because it is a
 * device-config key resolver like {@link resolveVaultPath} and
 * {@link resolveAgentName}, and because the search-origin enumeration now
 * reads it too: a module on the fan-out path must not have to import the
 * mirror writer - and its signal, log and time dependencies - to learn one
 * config key (a-label-is-not-a-boundary, U5).
 */
export function resolveSharedNamespace(configPath?: string | null): string | null {
  const discovery = discoverConfig(configPath ?? undefined);
  const value = discovery.data[SHARED_NAMESPACE_KEY]?.trim();
  return value ? value : null;
}

/** Device-config key naming the shared vault that remember-writes mirror into. */
const SHARED_NAMESPACE_KEY = "shared_namespace";

/**
 * Stable per-install device identity (Memory Integrity Suite). Keys the
 * per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl`), so
 * it MUST live in the device-local config and never in the synced
 * vault - all devices sharing one id would defeat the sharding.
 *
 * Generated once (8 hex chars) on first use and persisted. An invalid
 * hand-edited value self-heals to a fresh generated id; the
 * `sync-conflict` prefix is reserved so a renamed Syncthing conflict
 * copy can never masquerade as a shard.
 *
 * ## A config that cannot be READ is a refusal, deliberately
 *
 * {@link resolveDeviceId} and {@link resolveInstallationSecret} tolerate a
 * config directory they cannot LOCK - the lock only orders a race, and
 * losing it costs at most a duplicate generation. They do NOT tolerate a
 * config they cannot READ, and {@link ConfigReadError} propagates out of
 * both. The self-heal is the reason: a miss means generate-and-persist,
 * an unreadable file is not a miss, and treating it as one is destructive
 * twice over. {@link setConfigValue} merges onto what it read, so writing
 * a generated id through it would flatten the operator's whole config to
 * that single line; and the value itself is load-bearing - a fresh device
 * id silently re-shards this device's log, a fresh installation secret
 * silently changes every `vault://` reference agents correlate by. There
 * is no neutral answer to fall back to, so the file is named instead.
 *
 * The env overrides are the escape hatch that makes the refusal
 * survivable: `O2B_DEVICE_ID` (and, for tests,
 * {@link INSTALLATION_SECRET_ENV_KEY}) are honoured before the file is
 * opened at all.
 */
export const DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;

/**
 * Names Windows reserves for devices in every path component (`nul`,
 * `con`, `com1`, ...): there a directory under such a name makes writes
 * vanish or reads block. Device ids carry no dot, so the reserved forms
 * with an extension cannot occur.
 */
const WINDOWS_RESERVED_DEVICE_NAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;

/**
 * Whether `value` has the shape of a device id. Platform-independent: it
 * judges data that comes from peers (record envelopes, shard listings,
 * folds, digests, log shards), and every machine must accept the same
 * records or their folds and digests stop matching across platforms. A
 * Windows reserved name is a valid id here; choosing this machine's own
 * id is {@link isUsableLocalDeviceId}.
 */
export function isValidDeviceId(value: string): boolean {
  return DEVICE_ID_RE.test(value) && !value.startsWith("sync-conflict");
}

/** Whether `value` is one of the names Windows reserves for devices (`nul`, `con`, ...). */
export function isWindowsReservedDeviceId(value: string): boolean {
  return WINDOWS_RESERVED_DEVICE_NAME_RE.test(value);
}

/**
 * Whether `value` may be THIS machine's device id on `platform`. A new id
 * is never a Windows reserved name on any platform (the generated form
 * cannot be one). An existing configured reserved id is refused only on
 * Windows: a POSIX machine whose id is one of them keeps it, so its log
 * shards and store directories stay under that name.
 */
export function isUsableLocalDeviceId(
  value: string,
  platform: NodeJS.Platform = process.platform,
): boolean {
  return isValidDeviceId(value) && !(platform === "win32" && isWindowsReservedDeviceId(value));
}

/** Environment variable that overrides the machine config's `device_id`. */
export const DEVICE_ID_ENV = "O2B_DEVICE_ID";

/**
 * The device id {@link resolveDeviceId} would answer, read without
 * minting one: null when the env override opts out (the empty string)
 * or when no valid id is configured yet. For readers that must agree
 * with the writers' identity but must never write the machine config.
 */
export function readDeviceId(configPath?: string | null): string | null {
  const env = process.env[DEVICE_ID_ENV];
  if (env === "") return null;
  if (env !== undefined && isUsableLocalDeviceId(env)) return env;
  const value = discoverConfig(configPath ?? defaultConfigPath()).data["device_id"];
  return value !== undefined && isUsableLocalDeviceId(value) ? value : null;
}

export function resolveDeviceId(configPath?: string): string {
  // Env override: a valid id wins outright; the empty string opts out
  // of sharding (legacy single-file log pair). The test preload pins
  // this to "" so the suite stays deterministic; an invalid value
  // falls through to config resolution.
  const env = process.env[DEVICE_ID_ENV];
  if (env !== undefined && (env === "" || isUsableLocalDeviceId(env))) return env;
  const resolved = configPath ?? defaultConfigPath();

  const read = (): string | null => {
    const value = discoverConfig(resolved).data["device_id"];
    return value && isUsableLocalDeviceId(value) ? value : null;
  };

  const existing = read();
  if (existing !== null) return existing;

  // First-use generation, reached only because the config was READ and
  // holds no usable id (see the identity docblock above for why an
  // unreadable one never gets here). Two processes racing could each persist a different
  // id and split one device's logs across two shards, so the
  // read-generate-write sequence holds a directory lock (same
  // bounded-retry shape as the log writer's `acquireLogLock`). A lock
  // failure (read-only config home, exotic fs) falls through to the
  // unlocked path - losing the lock costs at most a duplicate generation,
  // which is not worth failing over.
  const dir = dirname(resolved);
  mkdirSync(dir, { recursive: true });
  let release: (() => void) | undefined;
  try {
    for (let attempt = 0; attempt < 10; attempt++) {
      try {
        release = lockfile.lockSync(dir, { stale: 10_000, realpath: false });
        break;
      } catch (err) {
        if ((err as NodeJS.ErrnoException).code !== "ELOCKED") break;
        sleepSync(50);
      }
    }
    // Re-check under the lock: the racing process may have just won.
    const won = read();
    if (won !== null) return won;
    const generated = randomBytes(4).toString("hex");
    setConfigValue("device_id", generated, resolved);
    return generated;
  } finally {
    release?.();
  }
}

/**
 * Store-hardening escape hatch (D2). Default OFF: MCP responses redact
 * the absolute vault host path to an opaque store reference (see
 * {@link vaultStoreReference}) because those responses land in model
 * context - the exact leak surface this guards. Set
 * `expose_host_paths: true` (or the env twin) to restore the raw path
 * for operators whose tooling depends on it.
 */
export function resolveExposeHostPaths(configPath?: string): boolean {
  return resolveConfigFlag("OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS", "expose_host_paths", configPath);
}

/**
 * Device-local installation secret that keys {@link vaultStoreReference}.
 *
 * Sixteen random bytes (128-bit) rendered as 32 lowercase hex, generated
 * once and persisted beside `device_id` in the same device-local config.
 * Three properties make the store reference unguessable offline:
 *
 *   - it is NEVER synced (device-local config, like `device_id`);
 *   - it is NEVER derived from `device_id`, so the `O2B_DEVICE_ID=""`
 *     sharding opt-out (which makes the device id empty and predictable)
 *     cannot weaken it;
 *   - it has NO empty/predictable escape hatch: the only env override
 *     ({@link INSTALLATION_SECRET_ENV_KEY}, for deterministic tests) is
 *     honoured solely when it is itself a full 32-hex key.
 *
 * A missing or corrupt persisted value self-heals to a fresh key under the
 * same directory lock `resolveDeviceId` uses, so a concurrent first use
 * cannot split into two keys.
 */
export const INSTALLATION_SECRET_CONFIG_KEY = "installation_secret";
/** Test-only env override; honoured ONLY when it is a full 32-hex key. */
export const INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET";
/** Strict shape: 32 lowercase hex = 16 bytes = a 128-bit key. */
export const INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;

export function isValidInstallationSecret(value: string): boolean {
  return INSTALLATION_SECRET_RE.test(value);
}

export function resolveInstallationSecret(configPath?: string, secretsVault?: string): string {
  // Env override exists for deterministic tests only, and is accepted solely
  // as a full 32-hex key so it can never make the secret empty or guessable.
  const env = process.env[INSTALLATION_SECRET_ENV_KEY];
  if (env !== undefined && isValidInstallationSecret(env)) return env;
  const resolved = configPath ?? defaultConfigPath();

  const read = (): string | null => {
    const raw = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
    // A persisted value written as a `$secret:NAME` reference NEVER
    // self-heals. The reference is the operator's stored intent, and the
    // self-heal below would mint a fresh key over it - silently
    // destroying the reference AND rotating the HMAC key, which changes
    // every `vault://` reference agents correlate by, with no error
    // naming anything. So every reference outcome is either the resolved
    // key or a named refusal: unresolvable (the store and the
    // environment cannot answer), locked (the store refuses), resolves
    // but not a 32-hex key (the stored value is not an installation
    // secret), or no vault passed to resolve against. Self-heal only
    // ever mints when NO reference exists - a missing or plain corrupt
    // value, exactly as before.
    if (isSecretReferenceValue(raw)) {
      const reference = String(raw).trim();
      if (secretsVault === undefined) {
        throw new SecretReferenceError(
          "installation_secret is a $secret: reference but no vault was passed to resolve " +
            "it against; pass the vault (or set O2B_INSTALLATION_SECRET to a 32-hex key)",
          reference,
        );
      }
      const resolvedValue = resolveThroughNamedSecretResolver(secretsVault, reference);
      if (!isValidInstallationSecret(resolvedValue)) {
        throw new SecretReferenceError(
          "installation_secret is a $secret: reference that resolves to a value which is " +
            "not a 32-hex installation key; fix the stored value - the reference in the " +
            "device config is never overwritten",
          reference,
        );
      }
      return resolvedValue;
    }
    return raw && isValidInstallationSecret(raw) ? raw : null;
  };

  const existing = read();
  if (existing !== null) return existing;

  // First-use generation under a directory lock, mirroring resolveDeviceId
  // in both halves: a lock failure falls through to the unlocked path,
  // while a config that could not be READ never reaches here at all.
  const dir = dirname(resolved);
  mkdirSync(dir, { recursive: true });
  let release: (() => void) | undefined;
  try {
    for (let attempt = 0; attempt < 10; attempt++) {
      try {
        release = lockfile.lockSync(dir, { stale: 10_000, realpath: false });
        break;
      } catch (err) {
        if ((err as NodeJS.ErrnoException).code !== "ELOCKED") break;
        sleepSync(50);
      }
    }
    const won = read();
    if (won !== null) return won;
    const generated = randomBytes(16).toString("hex");
    setConfigValue(INSTALLATION_SECRET_CONFIG_KEY, generated, resolved);
    return generated;
  } finally {
    release?.();
  }
}

/** Prefix of the opaque store reference emitted in place of a host path. */
export const VAULT_STORE_REF_PREFIX = "vault://";
/** Hex length of the store-reference digest (128 bits of HMAC-SHA256). */
const VAULT_STORE_REF_HEX_LEN = 32;

/**
 * Stable opaque reference for a vault, of the form `vault://<32-hex>`.
 * Computed as HMAC-SHA256, keyed by the device-local
 * {@link resolveInstallationSecret}, over the ABSOLUTE vault path. The key
 * makes the reference unguessable offline (a plain hash of a common host
 * path is trivially reversible), and truncating to 128 bits keeps collisions
 * negligible. It is stable across calls on the same install (agents correlate
 * by it) and never leaks the raw path. Returned by MCP tools in place of the
 * absolute path unless {@link resolveExposeHostPaths} is on.
 *
 * @throws {@link ConfigReadError} when the device-local config holding the
 *   key cannot be read. Propagated, not absorbed: the only fallbacks would
 *   be a fresh key (breaking the stability every consumer correlates by) or
 *   the raw host path (the leak this function exists to prevent). Callers
 *   that render a payload report the condition in the field - see
 *   `vaultPathField` in `src/mcp/tools.ts`.
 */
export function vaultStoreReference(vaultPath: string, configPath?: string): string {
  // The referenced vault's custody store backs a `$secret:` reference in
  // the persisted key; a plain key resolves exactly as before.
  const key = resolveInstallationSecret(configPath, vaultPath);
  const digest = createHmac("sha256", key)
    .update(resolve(vaultPath))
    .digest("hex")
    .slice(0, VAULT_STORE_REF_HEX_LEN);
  return `${VAULT_STORE_REF_PREFIX}${digest}`;
}

export function resolveLinkOutputFormat(configPath?: string): LinkOutputFormat {
  const env = process.env["OBSIDIAN_LINK_FORMAT"]?.trim();
  const data = env ? {} : discoverConfig(configPath).data;
  const raw = env || data["link_output_format"] || data["linkOutputFormat"];
  return raw === "markdown" ? "markdown" : "wikilink";
}

/**
 * Named MCP tool-surface profile (Agent Surface Suite). Returns the raw
 * configured name or null; validation against the known profile set
 * happens in the resolver, which fails open on unknown names.
 */
export function resolveMcpToolProfile(configPath?: string): string | null {
  const env = process.env["OPEN_SECOND_BRAIN_MCP_TOOL_PROFILE"]?.trim();
  if (env) return env;
  const raw = discoverConfig(configPath).data["mcp_tool_profile"]?.trim();
  return raw ? raw : null;
}

/**
 * Optional skills directory override (Agent Surface Suite). When set,
 * `skills_attach` / `list_skills` / `get_skill` read from this path
 * instead of `<vault>/Brain/skills/`. Supports `~` expansion. A relative
 * value is anchored to the directory of the resolved config file so the
 * skill root is deterministic regardless of the process working
 * directory (a bare `skills_dir: nested/skills` would otherwise resolve
 * against an unpredictable CWD). Falls back to null (use the default
 * vault-local path).
 */
export function resolveSkillsDir(configPath?: string): string | null {
  const discovery = discoverConfig(configPath);
  const env = process.env["OPEN_SECOND_BRAIN_SKILLS_DIR"]?.trim();
  const raw = env || discovery.data["skills_dir"]?.trim();
  if (!raw || raw.length === 0) return null;
  const expanded = expandTilde(raw);
  return isAbsolute(expanded) ? expanded : resolve(dirname(discovery.path), expanded);
}

/**
 * Raw value of one setting: the env override when it is set and non-empty,
 * otherwise the config value, otherwise `undefined`. Env always wins. When
 * `data` is a function it is called only when no env override is set, so
 * an env answer never opens the config file.
 */
function readSetting(
  envKey: string,
  configKey: string,
  data: Record<string, string> | (() => Record<string, string>),
): string | undefined {
  const env = process.env[envKey]?.trim();
  if (env) return env;
  const raw = (typeof data === "function" ? data() : data)[configKey]?.trim();
  return raw ? raw : undefined;
}

/**
 * Name of the setting a rejected value came from: the environment variable
 * when it holds a non-blank value (the one {@link readSetting} answered from),
 * the config key otherwise, so a report points at what the operator set.
 */
function rejectedSettingName(envKey: string, configKey: string): string {
  return process.env[envKey]?.trim() ? envKey : configKey;
}

/**
 * Shared body for a default-OFF boolean config gate: env var (trimmed)
 * wins, falling back to the matching `_brain.yaml`/config key (trimmed);
 * only the literal strings `"true"`/`"1"` are truthy, anything else
 * (including absence) resolves to `false`. Replaces seven copy-pasted
 * resolver bodies that differed only in their env/config key names.
 */
function resolveConfigFlag(envKey: string, configKey: string, configPath?: string): boolean {
  return isFlagOn(readSetting(envKey, configKey, () => discoverConfig(configPath).data));
}

/** The one parse every boolean switch in this file shares. */
function isFlagOn(raw: string | undefined): boolean {
  return raw === "true" || raw === "1";
}

/**
 * Skill-attach triggers gate (Agent Surface Suite). When enabled (default
 * OFF), the `triggers` field from each skill's SKILL.md frontmatter is
 * included in the lexical scorer as a 2x-BM25 tag signal. When disabled
 * or unset, triggers are ignored and scoring is name (3x) + description
 * (1x) only.
 */
export function resolveSkillsAttachTriggers(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_SKILLS_ATTACH_TRIGGERS",
    "skills_attach_triggers",
    configPath,
  );
}

/**
 * Skill auto-attach gate (Agent Surface Suite). Default OFF: the
 * skills_attach tool returns an empty block unless the operator sets
 * `skill_auto_attach: "true"` (or the matching env override), so the
 * default per-turn injection stays bit-identical.
 */
export function resolveSkillAutoAttach(configPath?: string): boolean {
  return resolveConfigFlag("OPEN_SECOND_BRAIN_SKILL_AUTO_ATTACH", "skill_auto_attach", configPath);
}

/**
 * Skill-attach usage-ordering gate (Agent Surface Suite, t_5d1ec8a8).
 * Default OFF: skills_attach ranks purely by the lexical scorer unless
 * `skills_attach_usage_ordering: "true"` (or the matching env override),
 * so the default offer ordering stays byte-identical. When on, observed
 * `skill_invoked` usage reorders lexical near-ties under the bounded
 * composite in `surface/skill-attach.ts`; the continuity read still only
 * happens when the auto-attach gate above is on too.
 */
export function resolveSkillsAttachUsageOrdering(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_SKILLS_ATTACH_USAGE_ORDERING",
    "skills_attach_usage_ordering",
    configPath,
  );
}

/**
 * Context-pack focus wiring gate (Agent Surface Suite, t_5b478e47).
 * Default OFF: brain_context_pack ignores the active search focus
 * unless `search_focus_context_pack: "true"`, keeping the default
 * pack byte-identical.
 */
export function resolveSearchFocusContextPack(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_SEARCH_FOCUS_CONTEXT_PACK",
    "search_focus_context_pack",
    configPath,
  );
}

/**
 * Context-pack density-ranking gate (impact-per-token allocation,
 * t_affa3bd9). Default OFF: brain_context_pack orders purely by tier →
 * recency unless `density_ranking_context_pack: "true"` (or the env
 * override), keeping the default pack byte-identical. When on, a
 * deterministic value-per-token density score breaks within-tier ties
 * (after session focus, before recency).
 */
export function resolveDensityRankingContextPack(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_DENSITY_RANKING_CONTEXT_PACK",
    "density_ranking_context_pack",
    configPath,
  );
}

/**
 * Context-pack entity-facts gate (dated commitments, t_43b0a379). Default
 * OFF: brain_context_pack carries no `entity_facts` section unless
 * `entity_facts_context_pack: "true"` (or the env override), keeping the
 * default pack byte-identical. When on, the report gains a per-entity
 * rollup over candidates the pack already kept.
 */
export function resolveEntityFactsContextPack(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK",
    "entity_facts_context_pack",
    configPath,
  );
}

/**
 * Context-pack score-aware tail-trim gate (delivered-evidence trim,
 * t_cb6a5558). Default OFF: brain_context_pack never trims delivered
 * items after the tier/budget walk unless `tail_trim_context_pack:
 * "true"` (or the env override), keeping the default pack
 * byte-identical. When on, the pack drops the low-scoring tail past its
 * top delivered items and reports the trim in a conditional `tailTrim`
 * report member.
 */
export function resolveTailTrimContextPack(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK",
    "tail_trim_context_pack",
    configPath,
  );
}

/**
 * Counterparty-brief hook gate (dated commitments, t_43b0a379). Default
 * OFF: the UserPromptSubmit hook exits without output unless
 * `counterparty_brief_enabled: "true"` (or the env override), so the
 * hook's stdout stays byte-identical on unchanged installs.
 */
export function resolveCounterpartyBriefEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED",
    "counterparty_brief_enabled",
    configPath,
  );
}

/**
 * Operator-declared trigger vocabulary for the counterparty brief (dated
 * commitments, t_43b0a379): a machine-local main-config list key holding
 * comma-separated tokens in the operator's language; the brief fires only
 * when at least one token occurs in the prompt. Nothing ships a built-in
 * word list (the standing refusal on hardcoded natural-language phrases).
 *
 * Each entry is NFC-normalized and trimmed; empty entries are dropped.
 * ABSENT or MALFORMED answers `[]`, which keeps the brief inert - the
 * safe direction, since a malformed vocabulary silently matching nothing
 * is disclosed in the hooks README. A bracket-shaped value (real YAML
 * list syntax the flat config parser cannot represent) is malformed: its
 * literal text would ship tokens no prompt ever contains.
 */
export function resolveCounterpartyBriefTriggers(configPath?: string): ReadonlyArray<string> {
  const raw = discoverConfig(configPath).data["counterparty_brief_triggers"]?.trim();
  if (raw === undefined || raw === "") return [];
  if (raw.startsWith("[") && raw.endsWith("]")) return [];
  const tokens: string[] = [];
  for (const part of raw.split(",")) {
    const token = part.normalize("NFC").trim();
    if (token.length > 0) tokens.push(token);
  }
  return tokens;
}

/**
 * Post-compaction pinned-anchor survival audit gate
 * (session-lifecycle-capture-durability, t_12c8b256). Default OFF: the
 * `o2b brain post-compact-audit` entry is a no-op unless
 * `post_compact_survival_audit: "true"`, so unchanged installs run no
 * post-compaction re-assertion and stay byte-identical.
 */
export function resolvePostCompactSurvivalAudit(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT",
    "post_compact_survival_audit",
    configPath,
  );
}

/**
 * Post-compaction verbatim recent-turns re-surface gate (C3 / t_92317f91).
 * Default OFF: the bounded last-N-turns buffer is captured and readable on
 * demand, but nothing is auto-surfaced into the post-compaction context
 * unless `recent_turns_resurface: "true"`, so unchanged installs stay
 * byte-identical.
 */
export function resolveRecentTurnsResurface(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_RECENT_TURNS_RESURFACE",
    "recent_turns_resurface",
    configPath,
  );
}

/**
 * Retire-sibling projection gate (near-duplicate defense, t_acab97de).
 * Default OFF: the dream summary, `brain_review_candidates` and
 * `o2b brain reject` carry no `retire_siblings` unless
 * `near_duplicate_retire_siblings_enabled: "true"`, so unchanged installs
 * stay byte-identical.
 */
export function resolveNearDuplicateRetireSiblingsEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_NEAR_DUPLICATE_RETIRE_SIBLINGS_ENABLED",
    "near_duplicate_retire_siblings_enabled",
    configPath,
  );
}

/**
 * Write-receipt near-duplicate widening gate (near-duplicate defense,
 * t_fda66477). Default OFF: the receipt hint compares only pages in the
 * written page's directory unless `near_duplicate_write_widening_enabled:
 * "true"`, which adds keyword-index candidates from other directories.
 */
export function resolveNearDuplicateWriteWideningEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_NEAR_DUPLICATE_WRITE_WIDENING_ENABLED",
    "near_duplicate_write_widening_enabled",
    configPath,
  );
}

/**
 * Brain store dual writes (task 1.11, a phase 1 trial). Default OFF: the
 * legacy writers write only the vault tree. When on, every covered legacy
 * write also appends the equivalent record to the brain store
 * (`src/core/store/dual-write.ts`); a store failure never fails the
 * legacy write. Env twin: `OPEN_SECOND_BRAIN_STORE_DUAL_WRITE`.
 */
export function resolveStoreDualWrite(configPath?: string): boolean {
  return resolveConfigFlag(STORE_DUAL_WRITE_ENV, STORE_DUAL_WRITE_CONFIG_KEY, configPath);
}

/**
 * SessionEnd handoff-note gate (Agent Surface Suite, t_28afa4d2).
 * Default OFF: lifecycle capture writes no handoff note unless
 * `session_handoff: "true"`.
 */
export function resolveSessionHandoff(configPath?: string): boolean {
  return resolveConfigFlag("OPEN_SECOND_BRAIN_SESSION_HANDOFF", "session_handoff", configPath);
}

/**
 * Rated-decision recall config keys (Belief lifecycle suite, B5,
 * t_5712fa39). Both are OPTIONAL and default-OFF: when neither the env
 * nor the config key is set, {@link resolveDecisionRecallMaxPerSession}
 * returns `null`, which disables rated-decision recall entirely so the
 * session-injection output is byte-identical to today.
 */
export const DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session";
export const DECISION_RECALL_MAX_PER_SESSION_ENV_KEY =
  "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION";
export const DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns";
export const DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY =
  "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS";

/**
 * Environment twin of the lessons promotion scope list (operator-approved
 * lesson promotion, t_1e952e43). The flat machine-config key itself is
 * `lessons.promotion.scopes`, declared beside its resolver in
 * `src/core/brain/policy/blocks/lessons.ts` so the brain module owns its
 * own key vocabulary. Comma-separated scope names; the same parsing rules
 * as `resolveCounterpartyBriefTriggers` apply (entries NFC-normalized and
 * trimmed, empty entries dropped, bracket-shaped values malformed). Absent
 * or empty disables promotion entirely.
 */
export const LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";

/**
 * Shared body for a non-negative-integer config value: env var (trimmed)
 * wins, falling back to the config key (trimmed). Returns `null` when
 * unset, blank, or not a non-negative integer, so an unconfigured value
 * leaves the caller's default behaviour intact.
 */
function resolveConfigNonNegativeInt(
  envKey: string,
  configKey: string,
  configPath?: string,
): number | null {
  const env = process.env[envKey]?.trim();
  const raw = env || discoverConfig(configPath).data[configKey]?.trim();
  if (!raw || raw.length === 0) return null;
  const n = Number(raw);
  if (!Number.isInteger(n) || n < 0) return null;
  return n;
}

/**
 * Max rated-decision recalls per session. `null` (the default) disables
 * the feature entirely - injection stays byte-identical.
 */
export function resolveDecisionRecallMaxPerSession(configPath?: string): number | null {
  return resolveConfigNonNegativeInt(
    DECISION_RECALL_MAX_PER_SESSION_ENV_KEY,
    DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY,
    configPath,
  );
}

/**
 * Minimum turns between two rated-decision recalls. `null` (unset)
 * resolves to `0` (no spacing) at the call site.
 */
export function resolveDecisionRecallMinSpacingTurns(configPath?: string): number | null {
  return resolveConfigNonNegativeInt(
    DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY,
    DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY,
    configPath,
  );
}

/**
 * Wikilink output format (Workspace Insight Suite, t_5f31b5f1).
 * Default `preserve` keeps every generated/normalized link exactly as
 * typed - byte-identical to pre-suite behaviour. `full` and `short`
 * select the rewrite mode for `o2b brain links normalize` and for
 * generators that adopt the kernel. An unknown value fails fast: a
 * typo must never silently rewrite links in the wrong mode.
 */
export function resolveWikiLinkFormat(configPath?: string): WikiLinkFormat {
  const env = process.env["OPEN_SECOND_BRAIN_WIKI_LINK_FORMAT"]?.trim();
  const raw = env || discoverConfig(configPath).data["wiki_link_format"]?.trim();
  if (raw === undefined || raw === "") return "preserve";
  if (!isWikiLinkFormat(raw)) {
    throw new Error(
      `wiki_link_format must be one of ${WIKI_LINK_FORMATS.join(", ")}; got '${raw}'`,
    );
  }
  return raw;
}

/**
 * Trigger cooldown window in days (Workspace Insight Suite,
 * t_cd1fee79): how long a dismissed/acted trigger blocks recreation
 * and how long a delivered trigger stays out of the morning brief.
 * Default 7. An invalid value fails fast.
 */
export function resolveTriggerCooldownDays(configPath?: string): number {
  const env = process.env["OPEN_SECOND_BRAIN_TRIGGER_COOLDOWN_DAYS"]?.trim();
  const raw = env || discoverConfig(configPath).data["trigger_cooldown_days"]?.trim();
  if (raw === undefined || raw === "") return 7;
  const days = Number(raw);
  if (!Number.isInteger(days) || days < 0) {
    throw new Error(`trigger_cooldown_days must be a non-negative integer; got '${raw}'`);
  }
  return days;
}

/**
 * Recall-gate telemetry gate (Workspace Insight Suite, t_65036e02).
 * Default OFF: brain_recall_gate stays a pure diagnostic unless
 * `recall_gate_telemetry: "true"`, when every decision lands as a
 * gate_telemetry continuity record (prompt hash only, never the
 * prompt).
 */
export function resolveRecallGateTelemetry(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY",
    "recall_gate_telemetry",
    configPath,
  );
}

/**
 * Recall adequacy thresholds (retrieval-precision-quality-loop,
 * t_b8f66fec). Configurable floors that drive the sufficient / weak /
 * insufficient verdict. Defaults mirror
 * DEFAULT_RECALL_ADEQUACY_THRESHOLDS (0.6 / 0.3 / 1). Invalid values fail
 * fast rather than silently reverting to a default.
 *
 * What these floors are compared against CHANGED in
 * a-label-is-not-a-boundary, and the numbers kept their values while
 * their meaning moved. They used to bound a recall attempt's top
 * relevance SCORE, which could not work: the keyword lane is min-max
 * normalised inside the candidate set, so the top row of any recall with
 * a non-empty keyword lane scored at or above the configured
 * `search_keyword_weight` whatever it matched - shipped at 0.6, identical
 * to `recall_adequacy_sufficient`, and 0.65 as measured end to end on a
 * freshly written keyword-only vault, where the freshness prior is added
 * on top of the normalised lane. Every keyword recall in the product
 * therefore graded `sufficient / proceed`, `weak` and `insufficient` were
 * unreachable, and a hundredth of a point on either key would have
 * inverted the verdict for every query at once.
 *
 * They now bound MATCH QUALITY: the share of the query's IDF mass the
 * retrieved material covers. That share is absolute where a score was
 * relative - it does not move with rank position, lane magnitude or
 * fusion mode - though it is measured over the rows a search delivers, so
 * a narrower `limit` reports less of it. An operator who tuned these keys
 * against the old quantity was tuning something that never varied, so no
 * setting is being silently reinterpreted - but the keys do decide
 * something now, and 0.6 means "covers at least three fifths of what was
 * asked" rather than "something was returned".
 */
export function resolveRecallAdequacyThresholds(configPath?: string): {
  sufficient: number;
  weak: number;
  minResults: number;
} {
  const data = discoverConfig(configPath).data;
  const sufficient = resolveAdequacyFloor(
    "recall_adequacy_sufficient",
    process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_SUFFICIENT"],
    data["recall_adequacy_sufficient"],
    0.6,
  );
  const weak = resolveAdequacyFloor(
    "recall_adequacy_weak",
    process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_WEAK"],
    data["recall_adequacy_weak"],
    0.3,
  );
  if (weak > sufficient) {
    throw new Error(
      `recall_adequacy_weak (${weak}) must not exceed recall_adequacy_sufficient (${sufficient})`,
    );
  }
  const minResults = resolveAdequacyMinResults(
    process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_MIN_RESULTS"],
    data["recall_adequacy_min_results"],
  );
  return { sufficient, weak, minResults };
}

function resolveAdequacyFloor(
  key: string,
  env: string | undefined,
  fileValue: string | undefined,
  fallback: number,
): number {
  const raw = (env?.trim() || fileValue?.trim()) ?? "";
  if (raw === "") return fallback;
  const value = Number(raw);
  if (!Number.isFinite(value) || value < 0 || value > 1) {
    throw new Error(`${key} must be a number in [0,1]; got '${raw}'`);
  }
  return value;
}

function resolveAdequacyMinResults(env: string | undefined, fileValue: string | undefined): number {
  const raw = (env?.trim() || fileValue?.trim()) ?? "";
  if (raw === "") return 1;
  const value = Number(raw);
  if (!Number.isInteger(value) || value < 1) {
    throw new Error(`recall_adequacy_min_results must be a positive integer; got '${raw}'`);
  }
  return value;
}

/**
 * Operator-declared model context window, environment channel
 * (t_a567cc12). The vault-side channel is the `context:` block of
 * `Brain/_brain.yaml`, and the BLOCK wins over a value here: the
 * resolver's deliberate precedence (plan B1) is operator config >
 * operator env > declared table > `1m` suffix > default, and an
 * explicit per-call argument wins over both operator channels. The
 * precedence lives with the resolver that consumes the parsed values,
 * exactly as the recall-adequacy floors above hand theirs to their
 * consumer.
 *
 * A well-formed positive integer is returned as-is: like every
 * first-hand declaration it passes through the resolver unclamped - the
 * declaration exists to state the true window. Any other value fails
 * fast, mirroring the trio above - a window that silently ignored its
 * operator would mis-size every pack.
 */
export const MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW";

/** Parse {@link MODEL_CONTEXT_WINDOW_ENV_KEY}; `undefined` when unset or blank. */
export function resolveModelContextWindowEnvTokens(): number | undefined {
  const raw = process.env[MODEL_CONTEXT_WINDOW_ENV_KEY]?.trim() ?? "";
  if (raw === "") return undefined;
  const value = Number(raw);
  if (!Number.isInteger(value) || value <= 0) {
    throw new Error(`${MODEL_CONTEXT_WINDOW_ENV_KEY} must be a positive integer; got '${raw}'`);
  }
  return value;
}

/**
 * Generation-report tracing gate (Hindsight brain-loop ops, t_281c3edc).
 * Default OFF: the inbound `generation_report` continuity path stays
 * dormant unless `generation_trace_enabled: "true"`, when an agent's
 * post-handoff usage report lands as a continuity record (prompt hash
 * and counts only, never the prompt). A per-call option can still enable
 * a single report when the config gate is off.
 */
export function resolveGenerationTraceEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_GENERATION_TRACE_ENABLED",
    "generation_trace_enabled",
    configPath,
  );
}

/**
 * Route-level MCP latency metrics gate (context-pack-economics-
 * observability suite). Default OFF: the `mcp_route_latency` continuity
 * path stays dormant unless `mcp_route_metrics_enabled: "true"`, when the
 * MCP server records one payload-safe latency record per tool call (tool
 * name, scope, status, duration, and argument key names only - never
 * argument values). Fail-open: a failed record never fails the call.
 */
export function resolveMcpRouteMetricsEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_MCP_ROUTE_METRICS_ENABLED",
    "mcp_route_metrics_enabled",
    configPath,
  );
}

/**
 * Token-impact + context-pack-quality ledger gate (context-pack-economics-
 * observability suite). Default OFF: the `token_impact` / `token_impact_outcome`
 * continuity paths stay dormant unless `token_impact_ledger_enabled: "true"`,
 * when opt-in `record`/`outcome` posts to `brain_token_impact` persist the
 * tokenizer-exact prompt-token delta (baseline vs packed, method-labelled)
 * and modeled inference-avoidance calibration. Payload-safe: counts and an
 * opaque pack id only, never raw prompts or recalled text. Fail-open: a
 * failed write never fails the caller. Read paths (list/summary) ignore the
 * gate so historical aggregates stay inspectable after it is turned off.
 */
export function resolveTokenImpactLedgerEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_TOKEN_IMPACT_LEDGER_ENABLED",
    "token_impact_ledger_enabled",
    configPath,
  );
}

/**
 * Agent-operable context-pack outcome-loop gate (context-pack-economics-
 * observability suite, C5). Default OFF: the `context_pack_outcome`
 * continuity path (and its composed `token_impact_outcome` calibration
 * write) stays dormant unless `context_pack_outcome_enabled: "true"`, when
 * an opt-in `post` to `brain_context_pack_outcome` records one compact
 * outcome row - first-pass/repair/retry counters plus the three strictly
 * separate token signals (exact / modeled / observed) - correlated to a
 * carried context-pack quality-sample id. Payload-safe: counts and an
 * opaque sample id only, never raw prompts, completions, or recalled text.
 * Fail-open: a failed write never fails the caller. Read paths (list/
 * summary) ignore the gate so historical aggregates stay inspectable.
 */
export function resolveContextPackOutcomeEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_CONTEXT_PACK_OUTCOME_ENABLED",
    "context_pack_outcome_enabled",
    configPath,
  );
}

/**
 * Prompt-time bounded recall-inject gate (recall-trust-and-write-surface,
 * A2 / t_2ce46130). Default OFF: the opt-in UserPromptSubmit recall-inject
 * hook stays a no-op unless `recall_inject_enabled: "true"` (or the matching
 * env override), when each user prompt relevance-recalls a small bounded,
 * clip-safe brief of vault notes and injects it as additionalContext. The
 * hook is fail-closed (any error or timeout injects nothing) and audited
 * (every inject/abstain/error decision writes one line). Flag off keeps the
 * prompt preamble byte-identical.
 */
export function resolveRecallInjectEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED",
    "recall_inject_enabled",
    configPath,
  );
}

/**
 * The per-phase answer-time quote-check modes (answer-trust wave, Lane A).
 *
 * Three keys - `quote_check.recall`, `quote_check.active`,
 * `quote_check.subagent` - live in the `quote_check` block of
 * `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow`, each
 * with its own resolver and no second reader. The shape follows the
 * decision-model per-use mode switch
 * (`src/core/decision-model/contract.ts`, `DECISION_MODEL_MODES`).
 *
 * Channel honesty: the Stop hook's annotation renders on Claude Code
 * only. The other registered runtimes render no Stop annotation - and
 * grok ships no `transcript_path` at all - so there the check is
 * silently inert, and a non-`off` mode promises findings that only a
 * Claude Code session (or the `enforce` Brain-log trail, where a
 * transcript is read at all) delivers.
 */
export const ANSWER_QUOTE_CHECK_MODES = Object.freeze(["off", "shadow", "enforce"] as const);

/** Closed union over {@link ANSWER_QUOTE_CHECK_MODES}. */
export type AnswerQuoteCheckMode = (typeof ANSWER_QUOTE_CHECK_MODES)[number];

/** Narrow a mode read back off a payload or a fixture. */
export function isAnswerQuoteCheckMode(value: unknown): value is AnswerQuoteCheckMode {
  return (
    typeof value === "string" && (ANSWER_QUOTE_CHECK_MODES as ReadonlyArray<string>).includes(value)
  );
}

/** The `_brain.yaml` block the three keys live in, and its phase keys. */
const QUOTE_CHECK_BLOCK = "quote_check";

/** The phases the quote check runs on, in their pinned listing order. */
export const ANSWER_QUOTE_CHECK_PHASES = Object.freeze(["recall", "active", "subagent"] as const);

/** Closed union over {@link ANSWER_QUOTE_CHECK_PHASES}. */
export type AnswerQuoteCheckPhase = (typeof ANSWER_QUOTE_CHECK_PHASES)[number];

/** The mode every phase resolves to when nothing is configured. */
const QUOTE_CHECK_DEFAULT: AnswerQuoteCheckMode = "shadow";

/** Paths and keys whose unknown-field warning already fired in this process. */
const quoteCheckWarnedUnknownKeys = new Set<string>();

/**
 * The `quote_check` block parsed off `path`, or `null` when the file or
 * the block is absent - the one condition resolved to defaults, because
 * there are no operator settings to contradict. A file (or block) that
 * EXISTS but cannot be honored raises by name instead: read like
 * `loadBrainConfig`'s absent/present split, so a typo can never silently
 * turn a configured `enforce` into the default.
 */
function readQuoteCheckBlock(path: string): Record<string, unknown> | null {
  let stat: Stats;
  try {
    const probed = statSync(path, { throwIfNoEntry: false });
    if (probed === undefined) return null;
    stat = probed;
  } catch (err) {
    throw new BrainConfigError(
      `failed to stat: ${(err as Error).message}`,
      QUOTE_CHECK_BLOCK,
      path,
    );
  }
  if (!stat.isFile()) {
    throw new BrainConfigError(
      "path exists but is not a regular file; its settings are not in force and are not read as absent",
      QUOTE_CHECK_BLOCK,
      path,
    );
  }
  let parsed: Record<string, unknown>;
  try {
    parsed = parseBrainYaml(
      new TextDecoder("utf-8", { fatal: true }).decode(readFileSync(path)),
    ) as Record<string, unknown>;
  } catch (err) {
    throw new BrainConfigError(
      `failed to parse: ${(err as Error).message}`,
      QUOTE_CHECK_BLOCK,
      path,
    );
  }
  const block = parsed[QUOTE_CHECK_BLOCK];
  if (block === undefined) return null;
  if (typeof block !== "object" || block === null || Array.isArray(block)) {
    throw new BrainConfigError(
      `expected a block of per-phase modes, got ${Array.isArray(block) ? "an array" : typeof block}`,
      QUOTE_CHECK_BLOCK,
      path,
    );
  }
  return block as Record<string, unknown>;
}

/**
 * Unknown keys inside the `quote_check` block warn per the strict-block
 * convention (`warnUnknownKeys` in the policy validator), once per key
 * per process on stderr - the audit channel every consumer of these
 * resolvers (the Stop hook) already keeps. A warning never changes the
 * resolved mode.
 */
function warnUnknownQuoteCheckKeys(path: string, block: Record<string, unknown>): void {
  for (const key of Object.keys(block)) {
    if ((ANSWER_QUOTE_CHECK_PHASES as ReadonlyArray<string>).includes(key)) continue;
    const stamp = `${path}\0${key}`;
    if (quoteCheckWarnedUnknownKeys.has(stamp)) continue;
    quoteCheckWarnedUnknownKeys.add(stamp);
    process.stderr.write(`${QUOTE_CHECK_BLOCK}.${key}: unknown field ignored (forward-compat)\n`);
  }
}

/** One phase's mode off the block; every exported resolver is this read. */
function resolveAnswerQuoteCheckPhase(
  phase: AnswerQuoteCheckPhase,
  path: string | null,
): AnswerQuoteCheckMode {
  if (path === null) return QUOTE_CHECK_DEFAULT;
  const block = readQuoteCheckBlock(path);
  if (block === null) return QUOTE_CHECK_DEFAULT;
  warnUnknownQuoteCheckKeys(path, block);
  const raw = block[phase];
  if (raw === undefined) return QUOTE_CHECK_DEFAULT;
  if (!isAnswerQuoteCheckMode(raw)) {
    throw new BrainConfigError(
      `unsupported value ${JSON.stringify(raw)}; expected one of ${ANSWER_QUOTE_CHECK_MODES.join(
        ", ",
      )}`,
      `${QUOTE_CHECK_BLOCK}.${phase}`,
      path,
    );
  }
  return raw;
}

/**
 * The brain config file the resolvers read when the caller names none:
 * the standard vault's `Brain/_brain.yaml`. `null` when no vault
 * resolves, which leaves every phase at its default - a vaultless install
 * has no operator settings to contradict.
 */
function defaultAnswerQuoteCheckConfigPath(): string | null {
  const vault = resolveVault();
  return vault === null ? null : join(vault, BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);
}

/**
 * Mode of `quote_check.recall` (answer-trust wave, Lane A): whether the
 * Stop hook checks quoted spans against recall-injected notes, and what
 * it may do about them. See {@link resolveAnswerQuoteCheckPhase} for the
 * shared semantics; the hook additionally gates this phase on
 * {@link resolveRecallInjectEnabled}.
 */
export function resolveAnswerQuoteCheckRecall(configPath?: string): AnswerQuoteCheckMode {
  return resolveAnswerQuoteCheckPhase("recall", configPath ?? defaultAnswerQuoteCheckConfigPath());
}

/**
 * Mode of `quote_check.active`: the same check over the notes the
 * SessionStart active digest emitted. The hook gates this phase on a live
 * active-injection ledger (`osb.active_inject.emitted`).
 */
export function resolveAnswerQuoteCheckActive(configPath?: string): AnswerQuoteCheckMode {
  return resolveAnswerQuoteCheckPhase("active", configPath ?? defaultAnswerQuoteCheckConfigPath());
}

/**
 * Mode of `quote_check.subagent`: the same check over the context the
 * sub-agent carrier delivered. The hook gates this phase on a live
 * sub-agent delivery ledger.
 */
export function resolveAnswerQuoteCheckSubagent(configPath?: string): AnswerQuoteCheckMode {
  return resolveAnswerQuoteCheckPhase(
    "subagent",
    configPath ?? defaultAnswerQuoteCheckConfigPath(),
  );
}

/** Recall-inject cap overrides that passed validation (absent = hook default). */
export interface RecallInjectCapsResolution {
  readonly caps: {
    readonly maxNotes?: number;
    readonly maxChars?: number;
    readonly timeBudgetMs?: number;
    readonly confidenceFloor?: number;
  };
  /** Config key names whose value was rejected, in resolution order. */
  readonly invalid: ReadonlyArray<string>;
}

/** `raw` as a number within `[min, max]` (an integer when asked), else `undefined`. */
function parseBounded(raw: string, min: number, max: number, integer: boolean): number | undefined {
  const value = Number(raw);
  if (!Number.isFinite(value) || (integer && !Number.isInteger(value))) return undefined;
  if (value < min || value > max) return undefined;
  return value;
}

/** One recall-inject cap: its field, env override, config key and range. */
const RECALL_INJECT_CAP_SPECS = [
  {
    field: "maxNotes",
    env: "OPEN_SECOND_BRAIN_RECALL_INJECT_MAX_NOTES",
    key: "recall_inject_max_notes",
    min: 1,
    max: 10,
    integer: true,
  },
  {
    field: "maxChars",
    env: "OPEN_SECOND_BRAIN_RECALL_INJECT_MAX_CHARS",
    key: "recall_inject_max_chars",
    min: 200,
    max: 8000,
    integer: true,
  },
  {
    field: "timeBudgetMs",
    env: "OPEN_SECOND_BRAIN_RECALL_INJECT_TIME_BUDGET_MS",
    key: "recall_inject_time_budget_ms",
    min: 250,
    max: 6000,
    integer: true,
  },
  {
    field: "confidenceFloor",
    env: "OPEN_SECOND_BRAIN_RECALL_INJECT_CONFIDENCE_FLOOR",
    key: "recall_inject_confidence_floor",
    min: 0,
    max: 1,
    integer: false,
  },
] as const;

/**
 * Operator overrides of the recall-inject caps (note count, brief size, time
 * budget, confidence floor). Each key resolves env first, then config. A value
 * out of range, non-numeric or (for the integer caps) fractional is left out
 * of `caps` and named in `invalid`, so the hook keeps its built-in default and
 * can audit the rejection. Unset keys contribute nothing, so a default install
 * resolves to empty caps.
 */
export function resolveRecallInjectCaps(configPath?: string): RecallInjectCapsResolution {
  const data = discoverConfig(configPath).data;
  const caps: Record<string, number> = {};
  const invalid: string[] = [];
  for (const spec of RECALL_INJECT_CAP_SPECS) {
    const raw = readSetting(spec.env, spec.key, data);
    if (raw === undefined) continue;
    const value = parseBounded(raw, spec.min, spec.max, spec.integer);
    if (value === undefined) invalid.push(rejectedSettingName(spec.env, spec.key));
    else caps[spec.field] = value;
  }
  return { caps: caps as RecallInjectCapsResolution["caps"], invalid };
}

/**
 * Recall-inject per-session dedupe. Default ON: a note already injected this
 * session is not injected again. Only an explicit falsy literal (`"false"` or
 * `"0"`, env first, then config) turns it off.
 */
export function resolveRecallInjectDedupe(configPath?: string): boolean {
  const raw = readSetting(
    "OPEN_SECOND_BRAIN_RECALL_INJECT_DEDUPE",
    "recall_inject_dedupe",
    discoverConfig(configPath).data,
  );
  return raw !== "false" && raw !== "0";
}

/**
 * Active-digest re-delivery gate. Default OFF: the SessionStart digest is
 * emitted as one payload, byte-identical to today, unless
 * `reground_parts_enabled: "true"` (or the matching env override), when an
 * over-ceiling digest is split and parts 2..n are re-delivered on later events.
 */
export function resolveRegroundPartsEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_REGROUND_PARTS_ENABLED",
    "reground_parts_enabled",
    configPath,
  );
}

/**
 * Default per-part ceiling of a split digest, in UTF-16 code units: the
 * observed Claude Code 10,000-unit persistence threshold less 10%.
 */
export const REGROUND_PART_CHARS_DEFAULT = 9000;

/** The per-part ceiling that applies, and the keys whose value was rejected on the way. */
export interface RegroundPartCharsResolution {
  readonly chars: number;
  /**
   * Names of the settings whose value was out of range or not an integer, in
   * precedence order: the environment variable when the value came from it,
   * the config key otherwise.
   */
  readonly invalid: ReadonlyArray<string>;
}

/**
 * Per-part ceiling of a split digest for one host runtime. Precedence:
 * `reground_part_chars_<runtime>`, then `reground_part_chars`, then
 * {@link REGROUND_PART_CHARS_DEFAULT}; each level reads env first, then
 * config. A value outside the integer range 2000..100000 falls through to the
 * next level and is named in `invalid` by the source it came from, so the
 * caller can report it.
 */
export function resolveRegroundPartChars(
  runtime: "claudecode" | "codex",
  configPath?: string,
): RegroundPartCharsResolution {
  const data = discoverConfig(configPath).data;
  const levels = [
    [
      `OPEN_SECOND_BRAIN_REGROUND_PART_CHARS_${runtime.toUpperCase()}`,
      `reground_part_chars_${runtime}`,
    ],
    ["OPEN_SECOND_BRAIN_REGROUND_PART_CHARS", "reground_part_chars"],
  ] as const;
  const invalid: string[] = [];
  for (const [envKey, configKey] of levels) {
    const raw = readSetting(envKey, configKey, data);
    if (raw === undefined) continue;
    const value = parseBounded(raw, 2000, 100_000, true);
    if (value !== undefined) return { chars: value, invalid };
    invalid.push(rejectedSettingName(envKey, configKey));
  }
  return { chars: REGROUND_PART_CHARS_DEFAULT, invalid };
}

/**
 * End-of-turn hygiene digest gate (context-injection-pipeline). Default
 * OFF: the Stop hook stays a silent no-op unless `hygiene_digest_enabled`
 * is `"true"` (or the matching env override). Resolved BEFORE the vault so
 * the off path costs one config read - the hook fires after every turn on
 * every install, and the detectors and search index load only after this
 * gate passes.
 */
export function resolveHygieneDigestEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_HYGIENE_DIGEST_ENABLED",
    "hygiene_digest_enabled",
    configPath,
  );
}

/**
 * Tiered context-injection nav tier gate (retrieval-quality-and-context-delivery,
 * D1 / t_2d4f34d7). Default OFF: the additive navigation/map tier stays a
 * no-op unless `nav_tier_enabled: "true"` (or the matching env override). The
 * always-on kernel (active-inject / recall-inject) is untouched either way, so
 * flag off keeps the session preamble byte-identical; flag on injects a
 * structural navmap only on cadence or first-turn trigger.
 */
export function resolveNavTierEnabled(configPath?: string): boolean {
  return resolveConfigFlag("OPEN_SECOND_BRAIN_NAV_TIER_ENABLED", "nav_tier_enabled", configPath);
}

/**
 * Optional nav-tier cadence window override in minutes (D1). A valid positive
 * integer (env first, then config) wins; anything else returns undefined so
 * the caller falls back to the named-constant default. The cadence window is
 * the interval during which a fresh nav-tier stamp suppresses re-injection.
 */
export function resolveNavTierCadenceMinutes(configPath?: string): number | undefined {
  const env = process.env["OPEN_SECOND_BRAIN_NAV_TIER_CADENCE_MINUTES"]?.trim();
  const raw = env || discoverConfig(configPath).data["nav_tier_cadence_minutes"]?.trim();
  if (!raw) return undefined;
  const value = Number(raw);
  if (!Number.isInteger(value) || value < 1) return undefined;
  return value;
}

/**
 * Strict PreToolUse read-block gate (retrieval-quality-and-context-delivery,
 * D2 / t_36b0fd8d). Default OFF: the opt-in PreToolUse hook stays permissive
 * (emits nothing, byte-identical to today) unless `hook_strict_enabled:
 * "true"` (or the matching env override). Flag on denies the FIRST raw
 * vault-file read of a session with a redirect to the brain search surface,
 * then downgrades to a soft nudge; every failure path fails open.
 */
export function resolveHookStrictEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_HOOK_STRICT_ENABLED",
    "hook_strict_enabled",
    configPath,
  );
}

/**
 * PreToolUse host-settings backup hook (t_f4555087). Default OFF: the
 * opt-in hook stays a byte-identical no-op unless `host_settings_backup:
 * "true"` (or the matching env override). Flag on, a file-tool call
 * targeting a Claude settings file gets its current content backed up -
 * into a timestamped folder beside the target, with one audit receipt -
 * before the write is allowed; a backup that cannot be taken denies the
 * call via stdout. The hook wrapper restates the flag read stdlib-only;
 * this resolver is the canonical definition the wrapper's twin must
 * agree with (pinned by the hook tests).
 */
export function resolveHostSettingsBackupEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_HOST_SETTINGS_BACKUP",
    "host_settings_backup",
    configPath,
  );
}

/**
 * Env var and config key of the maintenance lane's embedding opt-in.
 * Named because the lane quotes them back: a run that skipped the
 * embedding phase says which switch would turn it on.
 */
export const MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS";
export const MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings";

/**
 * Whether the unattended maintenance lane (`o2b brain maintenance run`
 * and `brain_maintenance`) may run the embedding phase of its reindex
 * pass. Default OFF: a cron that runs the lane stays keyword-only and
 * contacts no provider unless the operator opts in, because provider
 * spend only happens behind an explicit gate. When on, the embedding
 * cost gate (`embedding_cost_gate_usd`) still applies to every pass.
 */
export function resolveMaintenanceEmbeddings(configPath?: string): boolean {
  return resolveConfigFlag(
    MAINTENANCE_EMBEDDINGS_ENV,
    MAINTENANCE_EMBEDDINGS_CONFIG_KEY,
    configPath,
  );
}

/**
 * Env var and config key of the maintenance lane's custom-task master
 * switch. Named because the lane quotes them back: `status` says which
 * of the two turned declared custom tasks off.
 */
export const MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS";
export const MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks";

/** Which source decided a boolean switch: the env override, the config key, or neither. */
export type MaintenanceSwitchSource = "env" | "config" | "unset";

/**
 * Whether the maintenance lane may run the install-owned custom tasks
 * declared as `maintenance_custom_<name>` keys in this config file, and
 * the source that decided it, so `status` can name the env override when
 * that is what turned the declared tasks off. Default OFF: a declared
 * command is operator-authored shell, so it runs only behind an explicit
 * opt-in, and `..._CUSTOM_TASKS=0` in the env turns it off on one host
 * without editing the shared file. The commands themselves are read from
 * this machine config only, never from the vault. Same parse as every
 * other flag in this file. A caller that already parsed the config passes
 * its `data`, so the switch and the declarations come from one snapshot.
 */
export function resolveMaintenanceCustomTasksSwitch(
  configPath?: string,
  data: Readonly<Record<string, string>> = discoverConfig(configPath).data,
): {
  readonly enabled: boolean;
  readonly source: MaintenanceSwitchSource;
} {
  const env = process.env[MAINTENANCE_CUSTOM_TASKS_ENV]?.trim();
  const fromConfig = data[MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY]?.trim();
  return {
    enabled: isFlagOn(env || fromConfig),
    source: env ? "env" : fromConfig ? "config" : "unset",
  };
}

/**
 * Env var and config key of the codegraph partner-check switch. Named
 * rather than inlined because the doctor QUOTES them: the line it prints
 * for a check it did not run has to tell the operator which switch turned
 * it off, and a hand-copied spelling there would drift from the one that
 * is actually read.
 */
export const PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";
export const PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";

/**
 * Codegraph partner-check switch (nothing-runs-unwatched, U12). Default
 * OFF, so `o2b doctor` consults the partner exactly as it always has.
 *
 * It is an env var plus a config key - the shape every other boolean gate
 * in this file takes - rather than a CLI flag, for two reasons. The
 * property being expressed belongs to a MACHINE ("the partner CLI is
 * installed here and asking it costs seconds against a cold HOME"), not to
 * one invocation, so it wants a place to be written down once. And
 * `doctor()` has three callers - the CLI, the MCP `vault_health` tool and
 * the OpenClaw extension - of which a flag would reach one; the other two
 * take no arguments an operator controls.
 *
 * The switch gates the DOCTOR's automatic consultation only. `o2b partner
 * codegraph report` is the operator asking the partner directly, and an
 * answer they asked for is never suppressed by a switch about background
 * cost.
 */
export function resolvePartnerCodegraphDisabled(configPath?: string): boolean {
  return resolveConfigFlag(
    PARTNER_CODEGRAPH_DISABLED_ENV,
    PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY,
    configPath,
  );
}

/**
 * Knowledge-gap loop gate (recall-trust-and-write-surface, A3 /
 * t_67d38036). Default OFF: the opt-in session-start gap agenda and
 * session-end gap promotion/auto-close stay dormant unless
 * `gap_loop_enabled: "true"` (or the matching env override). Flag off keeps
 * the session preamble byte-identical and writes no gap-task notes.
 */
export function resolveGapLoopEnabled(configPath?: string): boolean {
  return resolveConfigFlag("OPEN_SECOND_BRAIN_GAP_LOOP_ENABLED", "gap_loop_enabled", configPath);
}

/**
 * Session-start backlog nudge gate (session-mining-economy, t_0358af42).
 * Default OFF: the SessionStart hook that reports the undistilled-session
 * count stays dormant unless `backlog_nudge_enabled: "true"` (or the
 * matching env override). Flag off keeps the session preamble
 * byte-identical and writes no throttle state.
 */
export function resolveBacklogNudgeEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_BACKLOG_NUDGE_ENABLED",
    "backlog_nudge_enabled",
    configPath,
  );
}

/**
 * Session-start cross-agent log catch-up gate (t_3b44cd9a). Default OFF:
 * the SessionStart hook that replays the `Brain/log` lines other agents
 * appended stays dormant unless `log_catchup_enabled: "true"` (or the
 * matching env override). Flag off keeps the session preamble
 * byte-identical and writes no cursor state.
 */
export function resolveLogCatchupEnabled(configPath?: string): boolean {
  return resolveConfigFlag(
    "OPEN_SECOND_BRAIN_LOG_CATCHUP_ENABLED",
    "log_catchup_enabled",
    configPath,
  );
}

/**
 * Optional gap-loop recurrence threshold override (A3). A valid positive
 * integer (env first, then config) wins; anything else returns undefined so
 * the caller falls back to the named-constant default. Env-overridable so an
 * operator can tune how often a gap must recur before it promotes to a task.
 */
export function resolveGapLoopThreshold(configPath?: string): number | undefined {
  const env = process.env["OPEN_SECOND_BRAIN_GAP_LOOP_THRESHOLD"]?.trim();
  const raw = env || discoverConfig(configPath).data["gap_loop_threshold"]?.trim();
  if (!raw) return undefined;
  const value = Number(raw);
  if (!Number.isInteger(value) || value < 1) return undefined;
  return value;
}

/**
 * Optional external judge command for the memory benchmark (Memory
 * Observability Suite, t_882c396a). Unset (the default) means the
 * judge phase is skipped - the harness itself never calls an LLM.
 */
export function resolveBenchJudgeCmd(configPath?: string): string | undefined {
  const env = process.env["OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD"]?.trim();
  const raw = env || discoverConfig(configPath).data["bench_judge_cmd"]?.trim();
  return raw !== undefined && raw !== "" ? raw : undefined;
}

export const SESSION_CAPTURE_ROLES = ["user", "assistant", "system", "tool", "meta"] as const;

export type SessionCaptureRole = (typeof SESSION_CAPTURE_ROLES)[number];

function isSessionCaptureRole(value: string): value is SessionCaptureRole {
  return (SESSION_CAPTURE_ROLES as ReadonlyArray<string>).includes(value);
}

/**
 * Config-level default for session-capture role filtering (Agent
 * Surface Suite, t_e2346fe9). `session_capture_roles` is a
 * comma-separated subset of user/assistant/system/tool/meta; absent or
 * empty means "capture every role" (null = no filter, bit-identical to
 * the pre-key behaviour). An unknown role name fails fast - a silent
 * typo here would silently drop memory.
 */
export function resolveSessionCaptureRoles(configPath?: string): SessionCaptureRole[] | null {
  const env = process.env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_ROLES"]?.trim();
  const raw = env || discoverConfig(configPath).data["session_capture_roles"]?.trim();
  if (!raw) return null;
  const roles: SessionCaptureRole[] = [];
  for (const part of raw.split(",")) {
    const role = part.trim().toLowerCase();
    if (role.length === 0) continue;
    if (!isSessionCaptureRole(role)) {
      throw new Error(
        `session_capture_roles: unknown role "${role}" (expected a subset of ${SESSION_CAPTURE_ROLES.join(", ")})`,
      );
    }
    if (!roles.includes(role)) roles.push(role);
  }
  return roles.length > 0 ? roles : null;
}

/**
 * Inbound Telegram capture bot token (Knowledge intake suite, t_f8f5ef6a).
 * Order: `TELEGRAM_BOT_TOKEN` env -> `telegram_bot_token` config -> null.
 * A value written as a `$secret:NAME` reference resolves through the passed
 * vault's custody store. The key contains "token", so `redactConfigMapping`
 * (src/core/egress) redacts it from any config snapshot. `null` (the
 * default) means the capture runner exits with a typed error rather than
 * starting; nothing runs without an explicit token.
 */
export function resolveTelegramBotToken(configPath?: string, secretsVault?: string): string | null {
  const env = process.env["TELEGRAM_BOT_TOKEN"]?.trim();
  const raw = env || discoverConfig(configPath).data["telegram_bot_token"]?.trim();
  if (raw === undefined || raw.length === 0) return null;
  // A token written as a `$secret:NAME` reference resolves through the
  // vault's custody store (read-only); without the vault the value is
  // taken as-is, exactly as before the resolver routing existed.
  if (secretsVault !== undefined && isSecretReferenceValue(raw)) {
    return resolveThroughNamedSecretResolver(secretsVault, raw);
  }
  return raw;
}

/**
 * Allowlisted Telegram chat ids for the capture bot (Knowledge intake
 * suite, t_f8f5ef6a). Order: `TELEGRAM_CHAT_ALLOWLIST` env ->
 * `telegram_chat_allowlist` config, comma-separated. Empty (the default)
 * accepts no chats - the allowlist is structural and must be explicit, so a
 * misconfigured bot captures nothing rather than everything.
 */
export function resolveTelegramCaptureAllowlist(configPath?: string): string[] {
  const env = process.env["TELEGRAM_CHAT_ALLOWLIST"]?.trim();
  const raw = env || discoverConfig(configPath).data["telegram_chat_allowlist"]?.trim();
  if (!raw) return [];
  const ids: string[] = [];
  for (const part of raw.split(",")) {
    const id = part.trim();
    if (id.length > 0 && !ids.includes(id)) ids.push(id);
  }
  return ids;
}

/**
 * Rewrite-gate mode for benchmark-gated skill rewrites (agent-presence,
 * Lane A). `gated` (the default) runs one candidate per gate round;
 * `iterative` is accepted and currently behaves exactly like `gated` -
 * one candidate per round - because the bounded edit loop it reserves is
 * not implemented yet; the value is carried so operators can opt in
 * without a config migration when the loop ships. The flat
 * machine-config key is `skill_rewrite.mode`; an unknown value is a named
 * error from the kernel's own resolver, never a silent fallback to the
 * default.
 */
export const SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode";
export const SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE";

/** Resolve the rewrite mode: env twin first, then the config file's flat key. */
export function resolveSkillRewriteModeConfig(configPath?: string): SkillRewriteMode {
  const env = process.env[SKILL_REWRITE_MODE_ENV_KEY]?.trim();
  const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_MODE_CONFIG_KEY]?.trim();
  return resolveSkillRewriteMode(raw);
}

/**
 * Optional advisory judge command for rewrite gate rounds (agent-presence,
 * Lane A). Same contract as `bench_judge_cmd` (t_882c396a): unset (the
 * default) means the judge phase is skipped, and when set the judge is
 * advisory only - it never moves the `tasks_passed_rate` metric the gate
 * decides on. The deterministic scorer stays canonical in every message.
 */
export const SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd";
export const SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";

/** Resolve the advisory rewrite judge: env twin first, then the config file. */
export function resolveSkillRewriteJudgeCmd(configPath?: string): string | undefined {
  const env = process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY]?.trim();
  const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY]?.trim();
  return raw !== undefined && raw !== "" ? raw : undefined;
}

/**
 * `~` and `~/x` (and `~\x` on Windows) against `home`. The platform and
 * home default to the running process; the injected-environment resolvers
 * pass their own so a test for one platform does not read another's.
 */
function expandTilde(
  p: string,
  platform: string = process.platform,
  home: string = homedir(),
): string {
  if (p === "~") return home;
  if (p.startsWith("~/")) return join(home, p.slice(2));
  // Windows users write `~\vault` as naturally as `~/vault`.
  if (platform === "win32" && p.startsWith("~\\")) return join(home, p.slice(2));
  return p;
}