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
67.0 KB
Raw Blame
/**
 * `o2b` CLI entry point. Mirrors `src/open_second_brain/cli.py` from the
 * legacy implementation: same subcommands, same flag names, same exit codes,
 * same error messages (verified by ports of the Python integration tests).
 *
 * Each subcommand resolves its inputs, delegates to `core/*` for business
 * logic, and returns a `0`/`1` exit code. The dispatcher is a small `switch`
 * statement, not a registry β€” keeps the control flow obvious.
 */

import { mkdirSync, statSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

import { recordFreshInstallSwitch } from "../core/store/fresh-switch.ts";

import {
  ConfigReadError,
  configuredVaultKey,
  defaultConfigPath,
  discoverConfig,
  resolveMcpToolProfile,
  resolveVault,
  setConfigValue,
  validateTimezoneName,
} from "../core/config.ts";
import { BrainConfigError } from "../core/brain/policy/errors.ts";
import { EGRESS_OUTCOME, redactForEgress } from "../core/egress/guard.ts";
import { listSecretReferences } from "../core/secret-ref.ts";
import { listNamedSecretAvailability, namedSecretAvailable } from "../core/secret-resolver.ts";
import { BRAIN_INDEX_REL } from "../core/brain/paths.ts";
import { ensureVaultCurrent } from "../core/maintenance/ensure-current.ts";
import { checkSelfHealUpgrade } from "../core/maintenance/self-heal-upgrade-state.ts";
import { doctor } from "../core/doctor.ts";
import { checkHermesResolverParity } from "../core/doctor-hermes-parity.ts";
import {
  runReadinessProbes,
  READINESS_STATUS,
  type ReadinessReport,
  type ReadinessStatus,
} from "../core/doctor-readiness.ts";
import {
  runDoctorSelftest,
  selftestJsonPayload,
  SELFTEST_STAGE_NAMES,
  type SelftestReport,
} from "../core/doctor-selftest.ts";
import { listVaultPages, writeFrontmatter } from "../core/vault.ts";
import { pathIsInside, vaultRelative } from "../core/path-safety.ts";
import { CliError, parseFlags } from "./argparse.ts";
import { describeErrorChain } from "./output.ts";
import { installStdoutEpipeGuard, isEpipeError } from "./stdout-guard.ts";
import { handleAiderSubcommand } from "./aider.ts";
import { handleBrainSubcommand, isBrainImportVerb } from "./brain.ts";
import { ORIGIN_CHANNEL, setOriginChannel, type OriginChannel } from "../core/origin-channel.ts";
import { handleDisciplineSubcommand } from "./discipline.ts";
import { handlePartnerSubcommand } from "./partner.ts";
import { handleSearchSubcommand } from "./search.ts";
import { handleDecisionModelSubcommand } from "./decision-model.ts";
import { handleStateSubcommand } from "./state.ts";
import { handleStoreSubcommand } from "./store.ts";
import { handleViewSubcommand } from "./view.ts";
import { handleTopicSubcommand } from "./topic.ts";
import { installMcpSignalDrain, type McpSignalDrainHandle } from "./mcp-drain.ts";
import { installMcpFaultGuard } from "./mcp-fault-guard.ts";
import { handleVaultSubcommand } from "./vault.ts";
import {
  NoVaultConfiguredError,
  normalizeFlagString,
  requireVault,
  resolveOptionalVault,
  resolveSemanticConfigState,
  sortedReplacer,
} from "./helpers.ts";
import { nextCommandField } from "../core/brain/next-step.ts";
import { emitNextStep, type AdvisoryStream } from "./advisory-rail.ts";
import { renderHelp, renderUsage } from "./help-render.ts";
import { ownsInternalJson, wantsJsonFlag, withJsonFallback } from "./json-helpers.ts";
import {
  installCli,
  renderInstallResult,
  renderUninstallResult,
  uninstallCli,
} from "./install-cli.ts";
import { windowsPathHint } from "./windows-path-hint.ts";
import { cmdUpdate } from "./update.ts";
import { ROOT_VERSION_FLAG_TOKEN, cmdVersion } from "./version.ts";
import { planUninstall, renderPlan } from "./uninstall.ts";
import { cmdBootstrap, handleMcpTokenCommand } from "./bootstrap/index.ts";
import { cmdInstall } from "./install/install.ts";
import { cmdUninstallTarget } from "./install/uninstall-target.ts";
import { cmdInitInteractive } from "./install/init-interactive.ts";
import { ensureBrainStore, type EnsureBrainStoreResult } from "../core/brain/init-store.ts";
import { bindVaultToStore } from "../core/vault-adapter/vault-binding.ts";
import { holdsLegacyBrain } from "../core/store/legacy-tree.ts";
import {
  buildOnboardingChecklist,
  renderOnboardingChecklist,
  searchIndexExists,
} from "./onboarding.ts";
import { CLI_COMMAND_MANIFEST, ROOT_VERSION_FLAG, manifestForJson } from "./command-manifest.ts";
import { COMPLETION_SHELLS, isCompletionShell, renderCompletions } from "./completions.ts";
import { MCPServer } from "../mcp/server.ts";
import { CLI_TRANSPORT_REACH } from "./transport-reach.ts";
import { isLoopbackHost, resolveMcpTokensRequired, startHttp } from "../mcp/http.ts";
import { hasAnyMcpToken } from "../mcp/token-source.ts";
import { serveStdio } from "../mcp/stdio.ts";
import { SERVER_VERSION } from "../mcp/protocol.ts";
import { buildToolTable } from "../mcp/tools.ts";
import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "../mcp/capabilities.ts";
import { resolveToolSurface, toolSurfaceProfileNames } from "../mcp/profiles.ts";
import { TOOL_SCOPE, TOOL_SCOPES, isToolScope, type ToolScope } from "../mcp/tool-contract.ts";
import {
  INSTALL_TARGET_IDS,
  isInstallTargetId,
  type InstallTargetId,
} from "../core/runtime/host-facts.ts";
import { HARNESS_IDS, isHarnessId, type HarnessId } from "../core/brain/scoped-rules.ts";
import { buildStoreStatusBlock } from "../core/store/store-status.ts";
import { storeStatusLine } from "./store-path.ts";

// ── Subcommands ─────────────────────────────────────────────────────────────

/** The vault `o2b status` looks at for the store block: the flag, else the configured one, when it is a directory. */
function statusVault(flag: string | undefined, configPath: string | undefined): string | null {
  let vault: string | null;
  try {
    vault = flag ?? resolveVault(configPath);
  } catch {
    return null;
  }
  return vault !== null && statSync(vault, { throwIfNoEntry: false })?.isDirectory() === true
    ? vault
    : null;
}

async function cmdStatus(argv: string[]): Promise<number> {
  const { flags } = parseFlags(argv, {
    config: { type: "string" },
    vault: { type: "string" },
    json: { type: "boolean" },
  });
  const result = discoverConfig(flags["config"] as string | undefined);
  // v0.10.10 β€” semantic-search hint. Same truthy / key-present logic as
  // `writeSearchInitBlock`; lifted into `resolveSemanticConfigState`
  // so both call sites share a single source of truth.
  const semantic = resolveSemanticConfigState(result.data, process.env);
  // The brain store block `second_brain_status` carries too (design D12).
  // It is extra information: a fault reading it (a locked index or store
  // file) degrades to its error, never a crash of the config report.
  let store: Record<string, unknown>;
  try {
    store = buildStoreStatusBlock({
      vault: statusVault(
        flags["vault"] as string | undefined,
        flags["config"] as string | undefined,
      ),
      configPath: (flags["config"] as string | undefined) ?? null,
    });
  } catch (exc) {
    store = { error: exc instanceof Error ? exc.message : String(exc) };
  }
  if (flags["json"]) {
    const output: Record<string, unknown> = {
      config_path: String(result.path),
      config_exists: result.exists,
      semantic_enabled: semantic.semantic_enabled,
      embedding_key_present: semantic.embedding_key_present,
      semantic_hint: semantic.hint,
    };
    if (Object.keys(result.data).length > 0) {
      output["config_keys"] = Object.keys(result.data).toSorted();
    }
    if (flags["vault"]) output["vault"] = String(flags["vault"]);
    // no-dead-ends, phase 3: the human stream prints this exit as a rail
    // line; the machine stream carried nothing at all until now.
    if (!result.exists) Object.assign(output, nextCommandField("cli-config-absent"));
    output["store"] = store;
    process.stdout.write(JSON.stringify(output, sortedReplacer, 2) + "\n");
  } else {
    process.stdout.write(`config_path: ${result.path}\n`);
    process.stdout.write(`config_exists: ${result.exists ? "true" : "false"}\n`);
    if (Object.keys(result.data).length > 0) {
      process.stdout.write("config_keys:\n");
      for (const key of Object.keys(result.data).toSorted()) {
        process.stdout.write(`- ${key}\n`);
      }
    }
    if (semantic.off && semantic.hint) {
      process.stdout.write(`semantic: off (${semantic.hint})\n`);
    }
    process.stdout.write(`${storeStatusLine(store)}\n`);
  }
  // no-dead-ends, task 7: the terminal-state census found this one. With
  // no configuration file there is nothing else this verb can report and
  // nothing the caller can do with the report, so it names the command
  // that creates one. With a config present it stays byte-identical.
  if (!result.exists) {
    emitNextStep("cli-config-absent", {
      command: "status",
      argv,
      jsonRequested: Boolean(flags["json"]),
    });
  }
  return 0;
}

/**
 * Create the brain store unless it exists, and print the outcome (and the
 * view writer line); `null` after printing the failure.
 */
function ensureStoreAndReport(configPath: string): EnsureBrainStoreResult | null {
  let store: EnsureBrainStoreResult;
  try {
    store = ensureBrainStore({ configPath });
  } catch (exc) {
    process.stderr.write(
      `error: failed to create the brain store: ${(exc as Error).message ?? exc}\n`,
    );
    return null;
  }
  process.stdout.write(
    store.status === "created"
      ? `initialized the brain store: ${store.root}\n`
      : `the brain store already exists: ${store.root}\n`,
  );
  if (store.viewWriter !== null) process.stdout.write(`${store.viewWriter.message}\n`);
  return store;
}

/**
 * The store step of `o2b init --vault`: create the store unless it exists
 * and bind the vault to it. Prints the outcome; false on a failure.
 */
function initBrainStoreForVault(vault: string, configPath: string): boolean {
  const store = ensureStoreAndReport(configPath);
  if (store === null) return false;
  try {
    const bound = bindVaultToStore(vault, {
      configPath,
      store: { root: store.root, storeId: store.storeId },
    });
    if (bound !== null) process.stdout.write("vault bound to the brain store\n");
  } catch (exc) {
    process.stderr.write(
      `error: failed to bind the vault to the brain store: ${(exc as Error).message ?? exc}\n`,
    );
    return false;
  }
  return true;
}

/** `o2b init` with no `--vault` and none configured: machine values, then the store (see `cmdInit`). */
function initWithoutVault(agentName: string | null, timezone: string | null): number {
  let configPath = defaultConfigPath();
  try {
    if (agentName) configPath = setConfigValue("agent_name", agentName);
    if (timezone) configPath = setConfigValue("timezone", timezone);
  } catch (exc) {
    process.stderr.write(
      `error: failed to persist plugin config: ${(exc as Error).message ?? exc}\n`,
    );
    return 1;
  }
  if (ensureStoreAndReport(configPath) === null) return 1;
  recordFreshSwitchQuietly(null, configPath);
  // The onboarding checklist below names the optional vault step and its
  // command, so this line does not repeat it.
  process.stdout.write("no vault configured: the brain works without one\n");
  if (agentName) process.stdout.write(`agent name registered: ${agentName}\n`);
  if (timezone) process.stdout.write(`timezone registered: ${timezone}\n`);
  try {
    process.stdout.write(renderOnboardingChecklist(buildOnboardingChecklist(null, { configPath })));
  } catch {
    // onboarding is advisory; never break init
  }
  return 0;
}

/**
 * A fresh install (no legacy `Brain/` tree in the vault) whose store exists
 * records this device's switch, so a later writer of an older release that
 * creates `Brain/` cannot flip the machine back (design D14 item 1). Never
 * fails the init: with no store yet, `o2b store init` records it.
 */
function recordFreshSwitchQuietly(vault: string | null, configPath: string): void {
  try {
    recordFreshInstallSwitch({ vault, configPath });
  } catch {
    // An unreadable store is reported by doctor; the config write stands.
  }
}

async function cmdInit(argv: string[]): Promise<number> {
  // `--interactive` is its own mode β€” composed of `init` + `brain init` +
  // per-target `install`. The non-interactive path below requires --vault.
  if (argv.includes("--interactive")) {
    return await cmdInitInteractive(argv.filter((a) => a !== "--interactive"));
  }
  const { flags } = parseFlags(argv, {
    vault: { type: "string" },
    name: { type: "string", default: "Second Brain" },
    "agent-name": { type: "string" },
    timezone: { type: "string" },
    force: { type: "boolean" },
  });
  const agentName = (flags["agent-name"] as string | undefined) ?? null;
  const timezone = (flags["timezone"] as string | undefined) ?? null;

  if (timezone) {
    const timezoneValidation = validateTimezoneName(timezone);
    if (!timezoneValidation.ok) {
      process.stderr.write(
        `error: --timezone ${JSON.stringify(timezone)} is not a valid IANA name ` +
          `(${timezoneValidation.error}). ` +
          "Examples: Europe/Belgrade, America/New_York, UTC.\n",
      );
      return 1;
    }
  }

  // An explicit `--vault` must name a path: `resolve("")` is the working
  // directory, which must never become the vault by accident.
  const flagVault =
    flags["vault"] === undefined ? undefined : normalizeFlagString(String(flags["vault"]));
  if (flagVault === null) {
    process.stderr.write("error: --vault must be a non-empty path\n");
    return 1;
  }
  // With no `--vault` the vault already configured is the one this run
  // initializes (a re-run to change the agent name or the timezone); with
  // none configured either, the brain lives in the store alone (design D14
  // item 1): init persists the other values and creates the store. Only
  // the machine config's own `vault` key counts: `VAULT_DIR`, a linked
  // project folder or an active profile name a vault for one session, and
  // must never be written back as the machine's vault.
  let configured: string | null;
  try {
    configured = flagVault === undefined ? configuredVaultKey(defaultConfigPath()) : null;
  } catch (exc) {
    process.stderr.write(
      `error: cannot read the machine config: ${(exc as Error).message ?? exc}\n`,
    );
    return 1;
  }
  const vault = flagVault ?? configured;
  if (vault === null) return initWithoutVault(agentName, timezone);

  // v0.11.0: `o2b init` no longer writes content into the vault.
  // Content scaffolding belongs to `o2b brain init` (the Brain layer).
  // This verb persists machine-local config (vault path, agent name,
  // timezone) so other CLI verbs default to the right vault without
  // a --vault flag.
  void flags["force"]; // accepted for backward CLI compat; unused
  void flags["name"]; // accepted for backward CLI compat; unused
  const resolvedVault = resolve(vault).replace(/\\/g, "/");
  let configPath: string;
  try {
    configPath = setConfigValue("vault", resolvedVault);
    if (agentName) setConfigValue("agent_name", agentName);
    if (timezone) setConfigValue("timezone", timezone);
  } catch (exc) {
    process.stderr.write(
      `error: failed to persist plugin config: ${(exc as Error).message ?? exc}\n`,
    );
    return 1;
  }
  process.stdout.write(`initialized vault: ${resolvedVault}\n`);
  process.stdout.write(`vault path persisted to: ${configPath}\n`);
  // On a fresh vault (no legacy `Brain/` tree) `o2b init` runs `o2b store
  // init` (design D14 item 1) and binds the vault to the store in the
  // device-local state, so the vault is store-only from its first write
  // and the note tools can tell it from a swapped one without a marker
  // file in the vault. A legacy vault gets no store here: a store moves
  // its search index (design D5), and the migration is its way in.
  if (!holdsLegacyBrain(resolvedVault) && !initBrainStoreForVault(resolvedVault, configPath)) {
    return 1;
  }
  // After the store exists: a fresh vault records this device's switch
  // here, so its machine state moves to the device-local state at once.
  recordFreshSwitchQuietly(resolvedVault, configPath);
  if (agentName) {
    process.stdout.write(`agent name registered: ${agentName}\n`);
    process.stdout.write(`agent name persisted to: ${configPath}\n`);
  }
  if (timezone) {
    process.stdout.write(`timezone registered: ${timezone}\n`);
    process.stdout.write(`timezone persisted to: ${configPath}\n`);
  }
  writeSearchInitBlock(resolvedVault, configPath, {
    command: "init",
    argv,
    jsonRequested: flags["json"] === true,
  });
  // Guided first-run onboarding: turn the bare init into a walked-through
  // checklist of state-aware next steps (t_84500f39). Additive - the search
  // block above is unchanged. Best-effort: a checklist failure must never fail
  // the init that already persisted config.
  try {
    const checklist = buildOnboardingChecklist(resolvedVault, { configPath });
    process.stdout.write(renderOnboardingChecklist(checklist));
  } catch {
    // onboarding is advisory; never break init
  }
  return 0;
}

async function cmdOnboarding(argv: string[]): Promise<number> {
  const { flags } = parseFlags(argv, {
    vault: { type: "string" },
    config: { type: "string" },
    json: { type: "boolean" },
  });
  const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
  // With no vault the checklist walks the store (design D14).
  const vault = resolveOptionalVault(flags["vault"] as string | undefined, config);
  const checklist = buildOnboardingChecklist(vault, { configPath: config });
  if (flags["json"]) {
    process.stdout.write(JSON.stringify(checklist, sortedReplacer, 2) + "\n");
    return 0;
  }
  process.stdout.write(renderOnboardingChecklist(checklist));
  return 0;
}

/**
 * Print the post-init search-onboarding block (design Β§10).
 *
 * Advertises `o2b search index` when the vault has no index. When the
 * user has already flipped `search_semantic_enabled` to true but no
 * embedding key is resolvable, the detailed configuration template is
 * appended. The block prints once, only during `o2b init` β€” no nagging
 * on other CLI invocations (the dedicated diagnostic is
 * `o2b search check`).
 */
function writeSearchInitBlock(vault: string, configPath: string, stream: AdvisoryStream): void {
  process.stdout.write("\nSearch:\n");
  // no-dead-ends, phase 3. Two defects at one line. It hand-wrote the
  // rail's own `next: <command>` format, which is the second mechanism
  // the rail exists to prevent; and it advertised the indexer
  // unconditionally, so on a vault that already had an index this block
  // asserted `search-index-missing` two lines above the onboarding
  // checklist reporting that same step as done. One command, two
  // contradictory answers. The predicate is shared with the checklist so
  // they cannot disagree again.
  if (!searchIndexExists(vault, configPath)) emitNextStep("search-index-missing", stream);

  const data = discoverConfig(configPath).data;
  // v0.10.10 β€” share the truthy / key-present logic with `o2b status`
  // through `resolveSemanticConfigState`. We only emit the detailed
  // template when the operator explicitly turned semantic search on
  // but did not configure the key.
  const semantic = resolveSemanticConfigState(data, process.env);
  // Skip the embedding-key prompt when search is explicitly disabled
  // (no point onboarding semantic when the whole layer is off), the
  // semantic flag is off, or the key is already present.
  if (semantic.search_disabled || !semantic.semantic_enabled || semantic.embedding_key_present) {
    return;
  }

  process.stdout.write(
    [
      "",
      "Semantic search is enabled but no embedding key is configured.",
      "",
      "Either set in the config file (printed above), or via env vars:",
      "",
      `  search_semantic_enabled: "true"`,
      `  embedding_base_url:      "https://openrouter.ai/api/v1"`,
      `  embedding_model:         "google/gemini-embedding-2-preview"`,
      `  embedding_api_key:       "<your key>"`,
      "",
      "Env equivalents:",
      "  OPEN_SECOND_BRAIN_SEARCH_SEMANTIC=true",
      "  OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL=...",
      "  OPEN_SECOND_BRAIN_EMBEDDING_MODEL=...",
      "  OPEN_SECOND_BRAIN_EMBEDDING_KEY=...",
      "",
      "Then:",
      "  o2b search check",
      "  o2b search index --embeddings",
      "",
    ].join("\n"),
  );
}

/**
 * Every code `o2b doctor` can return, named once so the returns below and
 * the tests read the same table.
 *
 * `probeIncomplete` carries the value `o2b search check` already spends on
 * a probe that did not complete, so one number means one thing across this
 * CLI; the assertion that they agree lives in the tests. It exists because
 * the other two numbers were both wrong for that finding. A readiness
 * probe whose budget elapsed used to be counted as a failure and exit 1,
 * which made a loaded machine report a healthy installation as broken;
 * classifying it honestly (see `READINESS_STATUS.unknown`) would otherwise
 * have moved it into the 0 that says the opposite. A run that could not
 * find out is neither, and now says so.
 */
export const DOCTOR_EXIT = Object.freeze({
  ok: 0,
  failed: 1,
  probeIncomplete: 6,
} as const);

export type DoctorExit = (typeof DOCTOR_EXIT)[keyof typeof DOCTOR_EXIT];

/**
 * The exit this run earned, from the counts rather than from what was
 * printed.
 *
 * Precedence follows `exitCodeForCheck` in `search/verbs/check.ts`: a
 * PROVED failure keeps the generic code even when a probe also failed to
 * complete, so the specific code never masks the more basic finding.
 */
export function doctorExitCode(
  failedChecks: number,
  readiness: ReadinessReport | null,
): DoctorExit {
  if (failedChecks > 0 || (readiness?.failed ?? 0) > 0) return DOCTOR_EXIT.failed;
  if ((readiness?.unknown ?? 0) > 0) return DOCTOR_EXIT.probeIncomplete;
  return DOCTOR_EXIT.ok;
}

async function cmdDoctor(argv: string[]): Promise<number> {
  const { flags, positional } = parseFlags(argv, {
    vault: { type: "string" },
    config: { type: "string" },
    repo: { type: "string" },
    json: { type: "boolean" },
    readiness: { type: "boolean" },
  });
  // Sub-verbs: `o2b doctor selftest` and nothing else (yet). A positional
  // the doctor grammar does not know is a usage error, not something to
  // silently ignore - plain `doctor` with no positional is untouched.
  if (positional.length > 0) {
    const verb = positional[0]!;
    if (verb !== DOCTOR_SELFTEST_VERB) {
      throw new CliError(`unknown doctor verb: ${verb} (expected "${DOCTOR_SELFTEST_VERB}")`);
    }
    if (positional.length > 1) {
      throw new CliError(`unexpected argument after "${DOCTOR_SELFTEST_VERB}": ${positional[1]}`);
    }
    return cmdDoctorSelftest(flags["json"] === true);
  }
  const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
  const vault = requireVault(flags["vault"] as string | undefined, config);

  let results;
  try {
    const repoRoot = (flags["repo"] as string | undefined) ?? null;
    results = doctor({ vault, config, repoRoot });
    // Appended here rather than inside `doctor()` because it spawns a Python
    // interpreter to run the plugin's own resolver, and `core/doctor.ts` is
    // bundled into the OpenClaw artifact, which refuses a Python reference.
    // See the module docblock: OpenClaw has no Hermes plugin, so the check is
    // meaningless there, and this verb is the surface that owns the question.
    const parity = checkHermesResolverParity({ config, repoRoot });
    if (parity) results.push(parity);
    // Also outside `doctor()`, which is bundled into the OpenClaw artifact.
    results.push(checkSelfHealUpgrade(vault));
  } catch (exc) {
    process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);
    return DOCTOR_EXIT.failed;
  }
  const failed = results.filter((r) => !r.ok).length;

  // Opt-in fail-fast readiness probes (t_cc234ff5). Without `--readiness`
  // this stays null and neither the output nor the exit code changes, so
  // plain `doctor` is byte-identical to before.
  let readiness: ReadinessReport | null = null;
  if (flags["readiness"]) {
    try {
      readiness = await runReadinessProbes({ vault, config, cwd: process.cwd() });
    } catch (exc) {
      process.stderr.write(`error: doctor readiness failed: ${(exc as Error).message ?? exc}\n`);
      // The readiness run itself did not complete, so it established
      // nothing about readiness - but a base check that already failed is a
      // proved fault and outranks it, exactly as inside `doctorExitCode`.
      return failed > 0 ? DOCTOR_EXIT.failed : DOCTOR_EXIT.probeIncomplete;
    }
  }

  /** The terminal tag for one readiness status - probe lines and row lines alike. */
  const READINESS_TAG: Record<ReadinessStatus, string> = {
    [READINESS_STATUS.pass]: "PASS",
    [READINESS_STATUS.fail]: "FAIL",
    [READINESS_STATUS.skipped]: "SKIP",
    [READINESS_STATUS.unknown]: "UNKNOWN",
  };
  const exitCode = doctorExitCode(failed, readiness);

  if (flags["json"]) {
    const payload = {
      // Read off the same exit code the process returns, so the two
      // surfaces of one command cannot give contradictory answers. It is
      // two-valued and so cannot distinguish a proved failure from a run
      // that could not find out - `false` means only "not established as
      // healthy". WHICH of the two it was is in `readiness_summary`, in
      // each probe's own `status`, and in the exit code itself.
      ok: exitCode === DOCTOR_EXIT.ok,
      checks: results.map((r) => ({
        name: r.name,
        ok: r.ok,
        message: r.message,
        ...(r.fix !== undefined ? { fix: r.fix } : {}),
      })),
      ...(readiness
        ? {
            readiness: readiness.probes.map((p) => ({
              name: p.name,
              status: p.status,
              detail: p.detail,
              duration_ms: p.durationMs,
              // `client_versions`' per-target rows - the only probe that
              // sets them (t_8e49ec96). Absent on every other probe, so
              // the payload shape of the existing probes is unchanged.
              ...(p.rows !== undefined
                ? {
                    rows: p.rows.map((row) => ({
                      target: row.target,
                      status: row.status,
                      version: row.version,
                      detail: row.detail,
                    })),
                  }
                : {}),
            })),
            // The counts the human shape has always printed on its summary
            // line, so a caller reading JSON is not the only one who has to
            // reduce the array to learn that something went unmeasured.
            readiness_summary: {
              probes: readiness.probes.length,
              failed: readiness.failed,
              unknown: readiness.unknown,
            },
          }
        : {}),
      summary: { total: results.length, failed },
    };
    process.stdout.write(JSON.stringify(payload, sortedReplacer, 2) + "\n");
    return exitCode;
  }

  for (const r of results) {
    process.stdout.write(`[${r.ok ? "OK" : "FAIL"}] ${r.name}: ${r.message}\n`);
    // Attach the copy-pasteable remediation right under a failing check so an
    // operator can fix it without leaving the doctor output.
    if (!r.ok && r.fix) process.stdout.write(`       fix: ${r.fix}\n`);
  }
  // Scriptable aggregate: a summary line plus the {@link DOCTOR_EXIT} code
  // make `o2b doctor` usable as a setup/CI gate.
  process.stdout.write(`\ndoctor: ${results.length} checks, ${failed} failed\n`);

  if (readiness) {
    process.stdout.write(
      `\nreadiness: ${readiness.probes.length} probes, ${readiness.failed} failed` +
        (readiness.unknown > 0 ? `, ${readiness.unknown} unknown\n` : `\n`),
    );
    for (const p of readiness.probes) {
      // Rendering `unknown` as SKIP would say "not configured" about a probe
      // that found something it could not read, which is the conflation this
      // release is about: the vocabulary grew a fourth member precisely
      // because three could not carry "could not measure" without lying in
      // one direction. Only the new member gets a new tag - the three that
      // already existed keep their exact spelling, so a reader sees a
      // byte-identical line for every outcome it already knew.
      const tag = READINESS_TAG[p.status];
      process.stdout.write(`[${tag}] ${p.name}: ${p.detail}\n`);
      // The per-target rows a probe reports (today, `client_versions`'):
      // one indented line each, so an operator reading the terminal sees
      // WHICH client answered and with what. The probe's own detail is
      // the census only, so this is where each client's answer is named.
      for (const row of p.rows ?? []) {
        process.stdout.write(
          `       ${READINESS_TAG[row.status]} ${row.target}` +
            (row.version !== null ? `: ${row.version}` : "") +
            (row.version === null && row.detail ? ` (${row.detail})` : "") +
            `\n`,
        );
      }
    }
  }
  return exitCode;
}

/** The one sub-verb the `doctor` command carries today. */
const DOCTOR_SELFTEST_VERB = "selftest";

/** Column width for the stage-name column of the human rendering. */
const SELFTEST_STAGE_NAME_WIDTH = Math.max(...SELFTEST_STAGE_NAMES.map((name) => name.length));

/**
 * `o2b doctor selftest` - the functional self-test harness (t_c00cc548).
 *
 * Drives a real throwaway store end to end (open + migrate, index pass,
 * direct document roundtrip, keyword/trigram query, concurrent writers
 * through the writer lock, delete, orderly close) and reports one
 * CheckResult-shaped entry per stage. This is a VERB, not a `doctor()`
 * check, for two reasons: a full store roundtrip is the heaviest probe
 * imaginable and would defeat the readiness registry's per-probe budget,
 * and `core/doctor.ts` is bundled into the OpenClaw artifact under import
 * policing, so the harness module is standalone and only this verb imports
 * it.
 *
 * Exit codes reuse {@link DOCTOR_EXIT} - the wave-wide vocabulary, no new
 * numbers: 0 every stage passed; 1 a stage failed (the entry names the
 * fault and the fix); 6 the harness itself could not run (temp storage
 * unavailable), because it then established nothing about the store.
 *
 * The `--json` payload is the harness module's stable projection: no
 * timestamps, no paths, no durations - two healthy runs on one machine
 * stringify byte-identically. Wall-clock timings render in the human
 * surface only.
 */
async function cmdDoctorSelftest(json: boolean): Promise<number> {
  let report: SelftestReport;
  try {
    report = await runDoctorSelftest();
  } catch (exc) {
    // Stage faults are caught inside the harness; a throw here means the
    // harness could not even assemble a report, which is the run-incomplete
    // case, not a proved store fault.
    process.stderr.write(`error: doctor selftest could not run: ${describeErrorChain(exc)}\n`);
    return DOCTOR_EXIT.probeIncomplete;
  }
  const exit: DoctorExit = !report.harnessRan
    ? DOCTOR_EXIT.probeIncomplete
    : report.ok
      ? DOCTOR_EXIT.ok
      : DOCTOR_EXIT.failed;

  if (json) {
    process.stdout.write(JSON.stringify(selftestJsonPayload(report), sortedReplacer, 2) + "\n");
    return exit;
  }

  const tempState =
    report.tempRoot === null ? "not created" : report.tempRemoved ? "removed" : "NOT removed";
  process.stdout.write(
    `doctor selftest: temp vault ${report.tempRoot ?? "(none)"} (${tempState})\n`,
  );
  for (const stage of report.stages) {
    const tag = stage.ok ? "ok" : "FAIL";
    const timing = stage.timingMs
      ? `; p50 ${stage.timingMs.p50Ms}ms / p100 ${stage.timingMs.p100Ms}ms`
      : "";
    process.stdout.write(
      `  ${stage.name.padEnd(SELFTEST_STAGE_NAME_WIDTH)}  ${tag.padEnd(4)}  ` +
        `${stage.message} (${stage.durationMs}ms${timing})\n`,
    );
    for (const warning of stage.warnings) {
      process.stdout.write(`       warning: ${warning}\n`);
    }
    if (!stage.ok && stage.fix) {
      process.stdout.write(`       fix: ${stage.fix}\n`);
    }
  }
  const warnings = report.warnings;
  const warningCount = `${warnings} warning${warnings === 1 ? "" : "s"}`;
  if (!report.harnessRan) {
    const firstFault = report.stages.find((stage) => !stage.ok)?.message ?? "unknown fault";
    process.stdout.write(`doctor selftest: could not run (${firstFault})\n`);
  } else if (report.ok) {
    process.stdout.write(`doctor selftest: ok (${report.stages.length} stages, ${warningCount})\n`);
  } else {
    const failed = report.stages.filter((stage) => !stage.ok).length;
    process.stdout.write(
      `doctor selftest: FAILED (${failed} of ${report.stages.length} stages failed, ${warningCount})\n`,
    );
  }
  return exit;
}

/**
 * `o2b export-config --output <file>` - the machine-config snapshot an
 * operator hands to someone else when reporting a problem, which is
 * exactly why it is an egress path (registry entry `config-export`).
 *
 * It used to redact through a private copy in `config.ts` that matched
 * five substrings against KEY NAMES and never inspected a value, so a
 * credential stored under a name that copy did not recognise was written
 * out in full. Both halves now come from the shared redactor, and a value
 * the redactor could only partially scan refuses the write instead of
 * producing a file that claims to be clean.
 */
async function cmdExportConfig(argv: string[]): Promise<number> {
  const { flags } = parseFlags(argv, {
    config: { type: "string" },
    output: { type: "string", required: true },
  });
  const result = discoverConfig(flags["config"] as string | undefined);
  const verdict = redactForEgress("config-export", {
    config_path: String(result.path),
    config_exists: result.exists,
    config: result.data as Record<string, unknown>,
  });
  if (verdict.outcome !== EGRESS_OUTCOME.released) {
    process.stderr.write(`error: ${verdict.detail}\n`);
    return 1;
  }
  const output = String(flags["output"]);
  try {
    mkdirSync(resolve(output, ".."), { recursive: true });
    writeFileSync(output, JSON.stringify(verdict.payload, sortedReplacer, 2) + "\n", "utf8");
  } catch (exc) {
    process.stderr.write(`error: failed to export config: ${(exc as Error).message ?? exc}\n`);
    return 1;
  }
  process.stdout.write(`exported: ${output}\n`);
  return 0;
}

async function cmdSecrets(argv: string[]): Promise<number> {
  if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
    // The one clarification the two surfaces cannot state inline: without
    // --vault the fallback reads the reference name itself, so a store
    // name and its env-var spelling can disagree without either lying.
    process.stdout.write(
      "usage: o2b secrets list|status [args...]\n" +
        "Without --vault, the env fallback reads the reference name verbatim, case-sensitively.\n",
    );
    return argv.length === 0 ? 2 : 0;
  }
  const verb = argv[0]!;
  const rest = argv.slice(1);
  switch (verb) {
    case "list":
      return cmdSecretsList(rest);
    case "status":
      return cmdSecretsStatus(rest);
    default:
      process.stderr.write(`error: unknown secrets verb: ${verb}\n`);
      return 2;
  }
}

function cmdSecretsList(argv: string[]): number {
  const { flags, positional } = parseFlags(argv, {
    config: { type: "string" },
    json: { type: "boolean" },
    vault: { type: "string" },
  });
  if (positional.length > 0) {
    process.stderr.write(
      `error: secrets list does not accept positional arguments: ${positional.join(" ")}\n`,
    );
    return 2;
  }
  const discovery = discoverConfig(flags["config"] as string | undefined);
  // With `--vault`, availability joins the vault's custody store (metadata
  // only - a locked envelope still counts); without it, the env-only
  // lookup exactly as before.
  const vault = normalizeFlagString(flags["vault"]);
  const refs =
    vault !== null
      ? listNamedSecretAvailability(vault, discovery.data)
      : listSecretReferences(discovery.data, process.env);
  if (flags["json"]) {
    process.stdout.write(
      JSON.stringify(
        {
          config_path: discovery.path,
          config_exists: discovery.exists,
          secrets: refs.map((ref) => ({
            config_key: ref.configKey,
            name: ref.name,
            available: ref.available,
            // Present only on a reference the grammar cannot spell - a
            // value that refuses at use time no matter what the store or
            // the environment holds (additive-only row shape).
            ...(ref.invalid === true ? { invalid: true } : {}),
          })),
        },
        null,
        2,
      ) + "\n",
    );
    return 0;
  }
  for (const ref of refs) {
    const state =
      ref.invalid === true ? "invalid reference" : ref.available ? "available" : "missing";
    process.stdout.write(`${ref.configKey}: ${ref.name} (${state})\n`);
  }
  return 0;
}

function cmdSecretsStatus(argv: string[]): number {
  const { flags, positional } = parseFlags(argv, {
    config: { type: "string" },
    json: { type: "boolean" },
    vault: { type: "string" },
  });
  if (positional.length !== 1) {
    process.stderr.write("error: secrets status requires exactly one secret name\n");
    return 2;
  }
  void flags["config"];
  const name = positional[0]!;
  // With `--vault`, a store-held name counts as available from metadata
  // alone (a locked envelope still counts, no decrypt); without it, the
  // env-only lookup exactly as before. The exit-code contract is
  // unchanged: available exits 0, missing exits 1.
  const vault = normalizeFlagString(flags["vault"]);
  const available = vault !== null ? namedSecretAvailable(vault, name) : Boolean(process.env[name]);
  if (flags["json"]) {
    process.stdout.write(JSON.stringify({ name, available }, null, 2) + "\n");
  } else {
    process.stdout.write(`${name}: ${available ? "available" : "missing"}\n`);
  }
  return available ? 0 : 1;
}

async function cmdIndex(argv: string[]): Promise<number> {
  const { flags } = parseFlags(argv, { vault: { type: "string" } });
  const vault = requireVault(flags["vault"] as string | undefined, defaultConfigPath());
  let pages;
  try {
    pages = listVaultPages(vault, { reach: CLI_TRANSPORT_REACH });
  } catch (exc) {
    process.stderr.write(`error: failed to list vault pages: ${(exc as Error).message ?? exc}\n`);
    return 1;
  }
  if (pages.length === 0) {
    process.stdout.write(`no markdown pages found in vault: ${vault}\n`);
    return 0;
  }
  const lines: string[] = [
    `# Vault Index`,
    "",
    `Auto-generated index of ${pages.length} pages.`,
    "",
  ];
  for (const p of pages) {
    // `vaultRelative`, not a prefix strip: slicing off `vault` and a
    // leading `/` left `\notes\a.md` on Windows, where the separator
    // is a backslash and the listing wants the vault's POSIX form.
    const rel = pathIsInside(p.path, vault) ? vaultRelative(p.path, vault) : p.path;
    lines.push(`- [[${p.title}]]  \`${rel}\``);
  }
  const indexPath = resolve(vault, BRAIN_INDEX_REL);
  try {
    writeFrontmatter(indexPath, { title: "Index", type: "index" }, lines.join("\n"));
  } catch (exc) {
    process.stderr.write(`error: failed to write index: ${(exc as Error).message ?? exc}\n`);
    return 1;
  }
  process.stdout.write(`index regenerated: ${indexPath} (${pages.length} pages)\n`);
  return 0;
}

/** The C1 control range, which `JSON.stringify` leaves as raw characters. */
const C1_CONTROL_RE = /[\u0080-\u009f]/g;

/**
 * A refused argv value as it is echoed to stderr: JSON-quoted, which
 * escapes the C0 controls, with the C1 controls (the 8-bit CSI U+009B
 * among them) escaped as `\uXXXX` too, so no terminal control sequence
 * reaches the operator's screen.
 */
function quoteRefusedValue(value: string): string {
  return JSON.stringify(value).replace(
    C1_CONTROL_RE,
    (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,
  );
}

async function cmdMcp(argv: string[]): Promise<number> {
  // `o2b mcp token` is a management sub-dispatcher, not the server: it
  // mints, rotates, revokes and lists the named per-agent tokens in the
  // vault's store. Routed before any flag parsing - the server's schema
  // would read `token` as a stray positional and start serving - and it
  // is dispatched through the same switch-case-visible `mcp` command, so
  // the manifest census stays untouched.
  if (argv[0] === "token") return handleMcpTokenCommand(argv.slice(1));
  const { flags } = parseFlags(argv, {
    vault: { type: "string" },
    config: { type: "string" },
    repo: { type: "string" },
    scope: { type: "string" },
    "writer-only": { type: "boolean" },
    "tool-profile": { type: "string" },
    "host-target": { type: "string" },
    harness: { type: "string" },
    probe: { type: "boolean" },
    json: { type: "boolean" },
    transport: { type: "string", default: "stdio" },
    host: { type: "string", default: "127.0.0.1" },
    port: { type: "string", default: "0" },
    "api-key": { type: "string" },
    "allow-tool": { type: "string-array" },
    "disable-tool": { type: "string-array" },
    "max-tools": { type: "string" },
  });

  // `--writer-only` is an alias for `--scope writer`. The two flags
  // are mutually consistent; if the user passes both, `--writer-only`
  // wins only when `--scope` is absent or already "writer". A
  // contradictory pair (e.g. `--scope full --writer-only`) is
  // rejected to avoid silent surprises.
  const writerOnly = Boolean(flags["writer-only"]);
  const explicitScope =
    (flags["scope"] as string | undefined) ?? (writerOnly ? TOOL_SCOPE.writer : undefined);
  if (explicitScope !== undefined && !isToolScope(explicitScope)) {
    process.stderr.write(
      `o2b mcp: invalid --scope value: ${explicitScope}; expected one of: ${TOOL_SCOPES.join(", ")}\n`,
    );
    return 2;
  }
  if (writerOnly && explicitScope !== TOOL_SCOPE.writer) {
    process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${explicitScope}\n`);
    return 2;
  }

  // Which runtime launched this server. Written into the generated
  // registration by the install adapter, and read back only by the
  // capability report, which cites that host's published tool ceiling.
  // An unrecognised value is refused rather than dropped: silently
  // ignoring it would report the ceiling as unchecked on a host that
  // publishes one, which is the exact silence this flag exists to end.
  // The refused value is echoed quoted and escaped (quoteRefusedValue),
  // so a control character in it reaches stderr escaped.
  const hostTargetFlag = flags["host-target"] as string | undefined;
  if (hostTargetFlag !== undefined && !isInstallTargetId(hostTargetFlag)) {
    process.stderr.write(
      `o2b mcp: invalid --host-target value: ${quoteRefusedValue(hostTargetFlag)}; ` +
        `expected one of: ${INSTALL_TARGET_IDS.join(", ")}\n`,
    );
    return 2;
  }
  const hostTarget = hostTargetFlag as InstallTargetId | undefined;

  // Which harness launched this server, for the scoped standing rules
  // (`Brain/standing-rules/harness/<id>.md`). Written by the packager into
  // the plugin registration (Claude Code) or the bridge argv (Hermes);
  // absent falls back to `--host-target`. Refused when unknown for the
  // same reason `--host-target` is: a typo would silently match no file.
  const harnessFlag = flags["harness"] as string | undefined;
  if (harnessFlag !== undefined && !isHarnessId(harnessFlag)) {
    process.stderr.write(
      `o2b mcp: invalid --harness value: ${quoteRefusedValue(harnessFlag)}; ` +
        `expected one of: ${HARNESS_IDS.join(", ")}\n`,
    );
    return 2;
  }
  const harness = harnessFlag as HarnessId | undefined;
  // Captured once, at launch: the project scope is the directory the
  // runtime started this server in, not wherever a later chdir points.
  const workspaceDir = process.cwd();

  const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
  const transport = flags["transport"] as string;
  if (transport !== "stdio" && transport !== "http") {
    process.stderr.write(
      `o2b mcp: invalid --transport value: ${transport}; expected one of: stdio, http\n`,
    );
    return 2;
  }
  const rawPort = flags["port"] as string;
  const port = Number(rawPort);
  if (!Number.isInteger(port) || port < 0 || port > 65535) {
    process.stderr.write(`o2b mcp: --port must be an integer from 0 to 65535\n`);
    return 2;
  }
  const host = flags["host"] as string;
  // An argv flag is visible in every process listing on the host, so the
  // key can arrive through the environment instead. The flag wins when
  // both are set - an explicit argument is the operator's most recent
  // word.
  const apiKey =
    (flags["api-key"] as string | undefined) ??
    process.env["OPEN_SECOND_BRAIN_MCP_API_KEY"] ??
    undefined;
  // Bearer is optional on a loopback bind (the loopback bind + Host/Origin
  // rebinding guard are the baseline defence) but a credential source is
  // mandatory on a non-loopback host, which would otherwise expose the Brain
  // unauthenticated on the network: the shared key, or a non-empty per-agent
  // token map (write-side-trust, Task 7). The vault resolves without
  // throwing here so the pre-check keeps its answer (and its exit code) on
  // a machine with no vault at all.
  // An explicit blank `--vault` names no vault (it is refused below); it
  // must not resolve the token file against the working directory.
  const mapVault =
    normalizeFlagString(flags["vault"] as string | undefined) ?? resolveVault(config) ?? null;
  const mintedTokens = hasAnyMcpToken({ vault: mapVault, configPath: config });
  if (
    transport === "http" &&
    !isLoopbackHost(host) &&
    (apiKey === undefined || apiKey === "") &&
    !mintedTokens
  ) {
    process.stderr.write(
      "o2b mcp: --api-key (or OPEN_SECOND_BRAIN_MCP_API_KEY) or at least one minted agent token " +
        "is required when --transport http binds a non-loopback --host\n",
    );
    return 2;
  }

  // Named tool-surface profile: flag wins over the config key. An unknown
  // name FAILS CLOSED (audit L5): a profile is how an operator narrows
  // what an agent may call, and a typo that silently widened it to the
  // full surface would grant exactly the tools the profile withheld.
  const profileName =
    (flags["tool-profile"] as string | undefined) ?? resolveMcpToolProfile(config);
  const explicitWindow = parseCapabilityWindow(flags);
  const surface = resolveToolSurface({
    profileName,
    ...(explicitScope !== undefined ? { explicitScope } : {}),
    ...(explicitWindow !== undefined ? { explicitWindow } : {}),
  });
  if (surface.unknownProfile !== undefined) {
    process.stderr.write(
      `o2b mcp: unknown tool profile "${surface.unknownProfile}" ` +
        `(from ${flags["tool-profile"] !== undefined ? "--tool-profile" : "mcp_tool_profile / OPEN_SECOND_BRAIN_MCP_TOOL_PROFILE"}); ` +
        `refusing to start rather than serve the full surface ` +
        `(known: ${toolSurfaceProfileNames().join(", ")})\n`,
    );
    return 2;
  }
  const scope = surface.scope;
  const serverName = scope === "writer" ? "open-second-brain-writer" : "open-second-brain";
  const capabilityWindow = surface.window;

  if (flags["probe"]) {
    return await runMcpProbe({
      vault: flags["vault"] as string | undefined,
      config,
      scope,
      serverName,
      json: Boolean(flags["json"]),
      capabilityWindow,
      hostTarget,
    });
  }

  // The vault is optional (design D14): a server with none starts, answers
  // `second_brain_status` and the store tools, and refuses each
  // vault-adapter tool by name.
  const vault = resolveOptionalVault(flags["vault"] as string | undefined, config);
  const vaultLabel = vault ?? "none";
  const repoRoot = (flags["repo"] as string | undefined) ?? null;

  // A served transport outlives every other verb, so it is the one place
  // a stray rejection from core can end the process mid-session, and
  // Claude Code and Codex never restart a dead MCP server. Installed
  // before the background vault refresh (its detached work is the first
  // that could reject) and released before the verb returns, so the
  // top-level `main().catch` still fails loudly once the server stops.
  // The probe above returns before this point: a one-shot check should
  // crash loudly. See `mcp-fault-guard.ts`.
  const faults = installMcpFaultGuard();
  try {
    // Hands-off post-upgrade maintenance: if the vault's on-disk state lags the
    // running version (stale Brain managed files, stale/missing search index),
    // bring it current with no user action. Fire-and-forget, full scope only
    // (the writer server skips it), never blocks or fails server start; a needed
    // reindex runs detached in the background.
    if (scope === "full" && vault !== null) {
      void ensureVaultCurrent(vault, { background: true, configPath: config }).catch(() => {
        // best-effort; the server must come up regardless
      });
    }

    if (transport === "http") {
      // Enforcement needs both halves: the operator key AND a map to
      // enforce against. With the key on but nothing minted yet the server
      // starts and only says so - an outage would be the wrong answer for
      // an operator one mint away from the posture they asked for.
      if (resolveMcpTokensRequired(config) && !hasAnyMcpToken({ vault, configPath: config })) {
        process.stderr.write(
          "o2b mcp: mcp_tokens_required is on, but no agent token is minted for this server yet; " +
            "credential-less requests are not refused until one exists " +
            "(mint one with `o2b mcp token mint --agent <name>`)\n",
        );
      }
      const handle = await startHttp(
        { vault, configPath: config, repoRoot },
        { host, port, apiKey, faultCounts: () => faults.counts() },
        { scope, serverName, capabilityWindow, hostTarget, harness, workspaceDir },
      );
      // Log the actually-bound endpoint. With the default --port 0 the OS
      // assigns an ephemeral port, so the requested `port` value ("0") would
      // advertise the wrong URL. handle.url carries the real bound port.
      process.stderr.write(
        `[mcp] ${serverName} ${SERVER_VERSION} listening on ${handle.url} (vault=${vaultLabel})\n`,
      );
      // A served transport outlives every other verb in this CLI, so it is
      // the one place a shutdown signal has work to do: stop accepting,
      // finish what is running, then let the registered `exit` hooks
      // checkpoint the index and release the locks. Released in a `finally`
      // because the listeners are process-global.
      const signals = installMcpSignalDrain({ close: () => handle.close() });
      try {
        // `closed` rather than `resolve`: this module imports `resolve` from
        // `node:path`, and shadowing it here hid that import inside the closure.
        await new Promise<void>((closed) => handle.server.once("close", closed));
      } finally {
        signals.release();
      }
      return signals.exitCode() ?? 0;
    }

    process.stderr.write(
      `[mcp] ${serverName} ${SERVER_VERSION} listening on stdio (vault=${vaultLabel})\n`,
    );
    // A holder rather than a `let`, because the assignment happens inside a
    // callback: the compiler cannot see that it ran and would narrow a bare
    // binding to `null` at both reads below.
    const stdio: { signals: McpSignalDrainHandle | null } = { signals: null };
    try {
      const code = await serveStdio(
        { vault, configPath: config, repoRoot },
        {
          onStart: (live) => {
            stdio.signals = installMcpSignalDrain({ close: () => live.close() });
          },
        },
        { scope, serverName, capabilityWindow, hostTarget, harness, workspaceDir },
      );
      return stdio.signals?.exitCode() ?? code;
    } finally {
      stdio.signals?.release();
    }
  } finally {
    faults.release();
  }
}

function parseCapabilityWindow(
  flags: Record<string, string | boolean | string[] | undefined>,
): RuntimeCapabilityWindow | undefined {
  const allowedTools = flags["allow-tool"] as string[] | undefined;
  const disabledTools = flags["disable-tool"] as string[] | undefined;
  const rawMaxTools = flags["max-tools"] as string | undefined;
  let maxTools: number | undefined;
  if (rawMaxTools !== undefined) {
    const parsed = Number(rawMaxTools);
    if (!Number.isInteger(parsed) || parsed < 1) {
      throw new CliError("--max-tools must be a positive integer");
    }
    maxTools = parsed;
  }
  if (!allowedTools && !disabledTools && maxTools === undefined) return undefined;
  return {
    ...(allowedTools ? { allowedTools } : {}),
    ...(disabledTools ? { disabledTools } : {}),
    ...(maxTools !== undefined ? { maxTools } : {}),
  };
}

async function runMcpProbe(args: {
  vault: string | undefined;
  config: string;
  scope: ToolScope;
  serverName: string;
  json: boolean;
  capabilityWindow: RuntimeCapabilityWindow | undefined;
  hostTarget: InstallTargetId | undefined;
}): Promise<number> {
  // The probe is an in-process MCP handshake: it counts the tools the
  // server would advertise and exits. Used by `o2b install --check`
  // to verify the server starts cleanly.
  let vault: string | null;
  try {
    vault = resolveOptionalVault(args.vault, args.config);
  } catch (e) {
    process.stdout.write(`mcp probe FAIL: vault not configured (${(e as Error).message})\n`);
    return 1;
  }
  try {
    const evaluated = evaluateToolCapabilities(buildToolTable(args.scope), {
      scope: args.scope,
      serverName: args.serverName,
      window: args.capabilityWindow,
      hostTarget: args.hostTarget,
    });
    if (args.json) {
      process.stdout.write(
        JSON.stringify(
          {
            ok: true,
            server_name: args.serverName,
            vault,
            capabilities: evaluated.report,
          },
          null,
          2,
        ) + "\n",
      );
      return 0;
    }
    const tools = evaluated.tools;
    process.stdout.write(
      `mcp probe ok: ${args.serverName} (${tools.length} tools, vault=${vault ?? "none"})\n`,
    );
    return 0;
  } catch (e) {
    process.stdout.write(`mcp probe FAIL: ${(e as Error).message}\n`);
    return 1;
  }
}

async function cmdInstallCli(argv: string[]): Promise<number> {
  const { flags } = parseFlags(argv, { bindir: { type: "string" } });
  const result = installCli(flags["bindir"] as string | undefined);
  process.stdout.write(renderInstallResult(result));
  const pathHint = windowsPathHint(result.bindir);
  if (pathHint !== null) process.stdout.write(pathHint);
  return result.errors.length > 0 ? 1 : 0;
}

async function cmdUninstall(argv: string[]): Promise<number> {
  // `--target X` (and the `--target=X` form) is its own mode β€”
  // per-runtime uninstall, distinct from the legacy `--apply-local`
  // config-removal path.
  if (argv.some((a) => a === "--target" || a.startsWith("--target="))) {
    return await cmdUninstallTarget(argv);
  }
  const { flags } = parseFlags(argv, {
    config: { type: "string" },
    "apply-local": { type: "boolean" },
    "remove-cli": { type: "boolean" },
  });
  const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
  const plan = planUninstall({
    configPath: config,
    applyLocal: Boolean(flags["apply-local"]),
  });
  process.stdout.write(renderPlan(plan));
  let returnCode = 0;
  if (flags["remove-cli"]) {
    const result = uninstallCli();
    process.stdout.write("\n" + renderUninstallResult(result));
    if (result.errors.length > 0) returnCode = 1;
  }
  if (plan.errors.length > 0) returnCode = 1;
  return returnCode;
}

async function cmdToolCall(argv: string[]): Promise<number> {
  const { flags, positional } = parseFlags(argv, {
    vault: { type: "string" },
    "tool-arg": { type: "string-array" },
  });
  if (positional.length < 1) {
    process.stderr.write("error: tool-call requires a tool name argument\n");
    return 2;
  }
  const toolName = positional[0]!;
  const config = defaultConfigPath();
  const vault = resolveOptionalVault(flags["vault"] as string | undefined, config);

  const args: Record<string, unknown> = {};
  for (const pair of (flags["tool-arg"] as string[] | undefined) ?? []) {
    const eq = pair.indexOf("=");
    if (eq === -1) {
      // Argument-shape error: align with the dispatcher convention
      // (CliError β†’ exit 2). Tool execution failures keep using exit 1.
      process.stderr.write(`error: --tool-arg must be key=value, got: ${pair}\n`);
      return 2;
    }
    const k = pair.slice(0, eq);
    const v = pair.slice(eq + 1);
    try {
      args[k] = JSON.parse(v);
    } catch {
      args[k] = v;
    }
  }
  // The CLI tool-call bridge runs in the operator's own shell against
  // the operator's own vault, so it establishes the same reach stdio
  // does - and for the same reason: filesystem-equivalent access is
  // already held before the first argument is parsed.
  const server = new MCPServer({ vault, configPath: config }, { reach: CLI_TRANSPORT_REACH });
  try {
    const result = await server.callTool(toolName, args);
    process.stdout.write(JSON.stringify(result, null, 2) + "\n");
    return 0;
  } catch (exc) {
    process.stderr.write(`error: ${(exc as Error).message ?? exc}\n`);
    return 1;
  }
}

function cmdHelp(argv: ReadonlyArray<string>): number {
  const { flags, positional } = parseFlags(argv, {});
  if (positional.length > 0) {
    process.stderr.write(
      `error: help does not accept positional arguments: ${positional.join(" ")}\n`,
    );
    return 2;
  }
  if (flags["json"]) {
    process.stdout.write(JSON.stringify(manifestForJson(), null, 2) + "\n");
  } else {
    process.stdout.write(renderHelp());
  }
  return 0;
}

function cmdCompletions(argv: ReadonlyArray<string>): number {
  const { positional } = parseFlags(argv, {});
  if (positional.length !== 1) {
    process.stderr.write(
      `error: completions requires one shell (${COMPLETION_SHELLS.join("|")})\n`,
    );
    return 2;
  }
  const shell = positional[0]!;
  if (!isCompletionShell(shell)) {
    process.stderr.write(`error: unsupported completion shell: ${shell}\n`);
    return 2;
  }
  process.stdout.write(renderCompletions(shell, CLI_COMMAND_MANIFEST));
  return 0;
}

/** The command that hands this process over to the MCP transport. */
const MCP_COMMAND = "mcp";

/**
 * The verb the root `--version` flag is a synonym of.
 *
 * Read off the flag declaration rather than spelled again, because the
 * synonym is only a synonym while the two words agree. The dispatcher
 * case itself stays a string literal, for the reason given there; that
 * the two reach the same verb is what `tests/cli/version.test.ts` pins.
 */
const VERSION_COMMAND = ROOT_VERSION_FLAG.name;

/**
 * Which origin channel this invocation is, derived from the command line
 * and from nothing else (Unit C, `src/core/origin-channel.ts`).
 *
 * Deriving it HERE, in the dispatcher, is the point: there is no flag
 * that names the channel and no way to reach {@link setOriginChannel}
 * from a tool argument, so a record's channel is a fact about how the
 * process was started rather than a claim anyone made.
 *
 * `o2b tool-call` stays `cli` deliberately. It invokes an MCP tool
 * HANDLER, but the channel names the transport that carried the request,
 * and that transport was a shell.
 */
function originChannelForArgv(command: string, rest: ReadonlyArray<string>): OriginChannel {
  if (command === MCP_COMMAND) return ORIGIN_CHANNEL.mcpTool;
  if (command === "brain" && isBrainImportVerb(rest)) return ORIGIN_CHANNEL.import;
  return ORIGIN_CHANNEL.cli;
}

export async function main(argv: ReadonlyArray<string>): Promise<number> {
  if (argv.length === 0) {
    // No command named: the terse banner, not the complete index. The
    // index is two hundred lines and would bury the fact that nothing
    // was asked for; the banner names where the index is.
    process.stdout.write(renderUsage());
    return 2;
  }
  if (argv[0] === "-h" || argv[0] === "--help") {
    process.stdout.write(renderHelp());
    return 0;
  }
  // The synonym of `o2b version`, REWRITTEN to the verb rather than
  // handled beside it. Routing it through the one dispatcher is what
  // makes the two spellings answer identically: an arm of its own also
  // skipped the `CliError` handler below, so `o2b version latest` said
  // "error: version takes no positional arguments" and exited 2 while
  // `o2b --version latest` printed a stack trace and exited 1.
  const command = argv[0] === ROOT_VERSION_FLAG_TOKEN ? VERSION_COMMAND : argv[0]!;
  const rest = argv.slice(1);

  // Claim the origin channel for this process before anything can write.
  // The two help arms above return without writing, so they need none.
  setOriginChannel(originChannelForArgv(command, rest));

  // Per-command --help support: print the dedicated help line plus generic.
  // The `brain` subcommand has its own dispatcher with per-verb help, so we
  // skip the generic shortcut and hand control over directly.
  if (
    rest.length === 1 &&
    (rest[0] === "-h" || rest[0] === "--help") &&
    command !== "aider" &&
    command !== "brain" &&
    command !== "vault" &&
    command !== "topic" &&
    // `secrets` has its own two-line help (the env fallback's name read
    // is spelled there), so the generic URL stub would only bury it.
    command !== "secrets"
  ) {
    process.stdout.write(`${command}: see https://github.com/itechmeat/open-second-brain\n`);
    if (command === "uninstall") {
      process.stdout.write(
        "Read-only by default. Prints the Hermes commands you must run yourself " +
          "(this tool never touches ~/.hermes/config.yaml or the installed plugin). " +
          "With --apply-local it may remove the machine-local Open Second Brain " +
          "config directory only. Your vault and Markdown notes are never removed. " +
          "With --remove-cli it also removes the o2b/vault-log " +
          "symlinks created by 'o2b install-cli'.\n",
      );
    }
    return 0;
  }

  const run = () => dispatchCommand(command, rest);
  if (wantsJsonFlag(rest) && !ownsInternalJson(command, rest)) {
    return await withJsonFallback(command, run);
  }
  return await run();
}

async function dispatchCommand(command: string, rest: string[]): Promise<number> {
  try {
    switch (command) {
      case "status":
        return await cmdStatus(rest);
      case "init":
        return await cmdInit(rest);
      case "doctor":
        return await cmdDoctor(rest);
      case "onboarding":
        return await cmdOnboarding(rest);
      case "export-config":
        return await cmdExportConfig(rest);
      case "index":
        return await cmdIndex(rest);
      case "mcp":
        return await cmdMcp(rest);
      case "install-cli":
        return await cmdInstallCli(rest);
      case "install":
        return await cmdInstall(rest);
      case "bootstrap":
        return await cmdBootstrap(rest);
      case "update":
        return await cmdUpdate(rest);
      case "uninstall":
        return await cmdUninstall(rest);
      case "tool-call":
        return await cmdToolCall(rest);
      case "secrets":
        return await cmdSecrets(rest);
      case "help":
        return cmdHelp(rest);
      case "completions":
        return cmdCompletions(rest);
      // A string literal like every sibling case, and not the constant
      // above: `tests/cli/manifest-completeness.test.ts` reads this
      // switch with `case "([^"]+)":`, so a case named through a
      // constant is a case that census cannot see.
      case "version":
        return cmdVersion(rest);
      case "aider":
        return await handleAiderSubcommand(rest);
      case "brain":
        return await handleBrainSubcommand(rest);
      case "discipline":
        return await handleDisciplineSubcommand(rest);
      case "search":
        return await handleSearchSubcommand(rest);
      case "state":
        return await handleStateSubcommand(rest);
      case "store":
        return await handleStoreSubcommand(rest);
      case "view":
        return await handleViewSubcommand(rest);
      case "topic":
        return await handleTopicSubcommand(rest);
      case "vault":
        return await handleVaultSubcommand(rest);
      case "partner":
        return await handlePartnerSubcommand(rest);
      case "decision-model":
        return await handleDecisionModelSubcommand(rest);
      default:
        process.stderr.write(`error: unknown command: ${command}\n`);
        process.stderr.write(renderUsage());
        return 2;
    }
  } catch (exc) {
    if (exc instanceof CliError) {
      process.stderr.write(`error: ${exc.message}\n`);
      return 2;
    }
    if (exc instanceof NoVaultConfiguredError) {
      process.stderr.write(exc.message + "\n");
      return 1;
    }
    if (exc instanceof ConfigReadError) {
      return reportConfigReadError(exc, command, rest);
    }
    if (exc instanceof BrainConfigError) {
      // Joins `NoVaultConfiguredError` on exit 1 for the reason stated at
      // {@link reportConfigReadError}: nothing is wrong with the argv, the
      // machine cannot answer. The message already names the file and the
      // field, because {@link BrainConfigError} composes both.
      //
      // Reached from `o2b install` and `o2b update`, where the settings
      // ladder reads `<vault>/Brain/_brain.yaml` and REFUSES an unreadable
      // one rather than regenerating a default the operator never chose.
      // The refusal is right; printing it as a stack trace was not, and it
      // took every other target's status down with it - `detectAll` walks
      // ten adapters and one of them reads that file.
      process.stderr.write(`error: ${exc.message}\n`);
      return 1;
    }
    throw exc;
  }
}

/**
 * Refusal for a plugin config that is present but unreadable.
 *
 * Exit 1, joining `NoVaultConfiguredError` rather than `CliError`: this
 * command line reserves 2 for a mistake in the argv and 1 for a machine
 * that cannot answer the question. Nothing about the invocation is wrong
 * here - the same argv works the moment the file mode does.
 *
 * The message needs no assembly. {@link ConfigReadError} carries its own
 * remedy so that every surface it escapes through (here, an MCP error
 * envelope, a subcommand's own wrapper) says the same thing.
 *
 * A `--json` caller additionally gets a parseable object on stdout. For
 * every other command the {@link withJsonFallback} envelope already carries
 * the refusal - it could not before, because a THROWN error escaped the
 * envelope entirely and left stdout empty. A command that renders its own
 * JSON is not wrapped, so it would still be the one surface where a machine
 * consumer sees a non-zero exit and nothing to parse. The keys are the ones
 * `o2b status --json` and its MCP twin already use for this condition.
 */
function reportConfigReadError(exc: ConfigReadError, command: string, rest: string[]): number {
  process.stderr.write(`error: ${exc.message}\n`);
  if (wantsJsonFlag(rest) && ownsInternalJson(command, rest)) {
    process.stdout.write(
      JSON.stringify({ config_path: exc.path, error: exc.message }, sortedReplacer, 2) + "\n",
    );
  }
  return 1;
}

if (import.meta.main) {
  // O1 (t_2ed754d1): an early-closed stdout pipe (`o2b <listing> | head -1`)
  // must exit clean. The listener catches Bun's asynchronous closed-pipe
  // `error` event; the `.catch` covers a synchronous EPIPE throw. Every other
  // error keeps its existing loud failure.
  installStdoutEpipeGuard();
  main(process.argv.slice(2))
    .then((code) => process.exit(code))
    .catch((err: unknown) => {
      if (isEpipeError(err)) process.exit(0);
      throw err;
    });
}