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
27.0 KB
Raw Blame
/**
 * Brain layer bootstrap.
 *
 * Creates the `<vault>/Brain/` directory tree, drops the default
 * `_brain.yaml`, and renders the operating manual the agent reads each
 * session at `Brain/_BRAIN.md`.
 *
 * Behaviour summary:
 *
 *   - Directory creation is idempotent.
 *   - `Brain/_brain.yaml` and `Brain/_BRAIN.md` are written on first
 *     run; subsequent runs without `force` skip them. `force: true`
 *     overwrites both.
 *   - `<vault>/.gitignore` gains the derived-state guard block
 *     (`/.open-second-brain/`) on first run, merged with any existing
 *     content; later runs skip it when the entries are already present.
 *     The guard is hygiene, not load-bearing: a conflict (malformed
 *     managed-block markers, a later negating line) or a guard file that
 *     cannot be read or written is warned about on stderr and carried in
 *     the result's `guard` field while the bootstrap continues.
 *   - Bootstrap refuses to run if the machine-level plugin config (the
 *     one `o2b init` writes) is missing, since callers must register
 *     the vault before any Brain operation. The error message names
 *     `o2b init` as the fix.
 *   - Every write is routed through {@link atomicWriteFileSync} so an
 *     interrupted run leaves either the prior version or the new one,
 *     never a torn hybrid.
 *   - With no vault (design D14 item 1, task 2.10) the brain is the store:
 *     bootstrap creates the store (`./init-store.ts`) and writes nothing
 *     else. A machine that holds its own switch record writes no legacy
 *     tree either. `.base` files come from the vault adapter
 *     (`../vault-adapter/`), which stamps only the ones this machine may
 *     use.
 */

import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, dirname, join, posix, resolve } from "node:path";
import { fileURLToPath } from "node:url";

import { defaultConfigPath } from "../config.ts";
import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import {
  ensureVaultGitignoreEntries,
  GITIGNORE_GUARD_FILE,
  type GitignoreGuardStatus,
} from "./gitignore-guard.ts";
import {
  BRAIN_ROOT_REL,
  brainConfigPath,
  brainDirs,
  brainManualPath,
  vaultRelative,
} from "./paths.ts";
import { vaultIdentityPath, writeVaultIdentity } from "./vault-identity.ts";
import { formatPrimaryAgentYamlValue } from "./policy.ts";
import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";
import { renderBrainManual } from "./templates.ts";
import { ensureBrainStore, type EnsureBrainStoreResult } from "./init-store.ts";
import { recordFreshInstallSwitch, type FreshSwitchOutcome } from "../store/fresh-switch.ts";
import { storeOnlyMode } from "../store/store-only.ts";
import { stampBaseTemplates } from "../vault-adapter/index.ts";
import { ORIGIN_CHANNEL, ORIGIN_CHANNEL_FIELD } from "../origin-channel.ts";
import { formatFrontmatter, parseFrontmatter } from "../vault.ts";
import type { FrontmatterMap } from "../types.ts";

const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;

const DEFAULT_STARTER_DIR = resolve(
  dirname(fileURLToPath(import.meta.url)),
  "..",
  "..",
  "..",
  "templates",
  "brain-starter",
);

export class BrainStarterError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "BrainStarterError";
  }
}

export interface CopyStarterOptions {
  /** Override the source directory; defaults to the bundled `templates/brain-starter/`. */
  readonly starterPath?: string;
  /**
   * Instant the dropped bundle is aged to; defaults to the wall clock.
   * Passing the bundle's own anchor day reproduces the source bytes
   * exactly, which is what the fixed-`--now` tests rely on.
   */
  readonly now?: Date;
}

const DAY_MS = 86_400_000;
const DATE_RE = /\d{4}-\d{2}-\d{2}/g;

/**
 * The bundle's authored "today": the newest day in its `log/`.
 *
 * Read from the bundle rather than declared next to it, because a
 * constant here is one the next person to extend the log has to
 * remember to move, and nothing would fail if they did not.
 * Returns null for a bundle with no dated log day - a custom
 * `starterPath` in a test, typically - and such a bundle is copied
 * verbatim.
 */
function starterAnchorDay(src: string): string | null {
  let newest: string | null = null;
  let entries: string[];
  try {
    entries = readdirSync(join(src, "log"));
  } catch {
    return null;
  }
  for (const name of entries) {
    const day = /^(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
    if (day !== undefined && (newest === null || day > newest)) newest = day;
  }
  return newest;
}

function shiftDay(day: string, days: number): string {
  const shifted = new Date(`${day}T00:00:00Z`).getTime() + days * DAY_MS;
  return new Date(shifted).toISOString().slice(0, 10);
}

/**
 * Age one copied entry in place, descending into it when it is a
 * directory. The copy above is recursive, so a custom `starterPath` may
 * put a subtree under a starter target and reading it as a file would
 * fail the whole install with `EISDIR`. Only Markdown bodies are
 * rewritten - a starter target holds Brain notes, and a bundle that
 * smuggled a binary in should come back out with its bytes intact.
 */
function ageStarterEntry(abs: string, days: number): void {
  if (statSync(abs).isDirectory()) {
    for (const child of readdirSync(abs)) {
      const childAbs = join(abs, child);
      ageStarterEntry(childAbs, days);
      const moved = child.replace(DATE_RE, (d) => shiftDay(d, days));
      if (moved !== child) renameWithRetry(childAbs, join(abs, moved));
    }
    return;
  }
  if (!abs.endsWith(".md")) return;
  atomicWriteFileSync(
    abs,
    readFileSync(abs, "utf8").replace(DATE_RE, (d) => shiftDay(d, days)),
  );
}

/**
 * Age the copied bundle so its history ends on the day it was dropped.
 *
 * The bundle carries a fictional five-day history with fixed dates, and
 * one of its preferences is `pinned`. Left as authored, that pin passed
 * `stale_evidence_days` ninety days after the bundle was written and
 * every vault initialised after that woke up with a doctor warning on
 * its first run - a bundle that is only clean for one quarter is not a
 * starting point. Every date moves by the same whole number of days, so
 * every interval the bundle demonstrates - the trial window still open,
 * the evidence two days back, the retired entries months behind -
 * survives the move exactly.
 */
function ageStarterCopy(
  vault: string,
  copied: ReadonlyArray<string>,
  days: number,
): ReadonlyArray<string> {
  if (days === 0) return copied;
  const renamed: string[] = [];
  for (const rel of copied) {
    const abs = join(vault, rel);
    ageStarterEntry(abs, days);
    const name = basename(rel);
    const moved = name.replace(DATE_RE, (d) => shiftDay(d, days));
    if (moved === name) {
      renamed.push(rel);
      continue;
    }
    const target = posix.join(dirname(rel), moved);
    renameWithRetry(abs, join(vault, target));
    renamed.push(target);
  }
  return Object.freeze(renamed);
}

export interface StarterBundleResult {
  /** Vault-relative paths newly written. */
  readonly copied: ReadonlyArray<string>;
}

/**
 * Copy the bundled starter set into `<vault>/Brain/`. Refuses when any
 * of `preferences/`, `retired/`, `inbox/`, `log/` already contains a
 * non-dotfile entry — the starter is for fresh vaults.
 *
 * Hidden files (those whose name starts with `.`) are ignored when
 * checking emptiness so a `.gitkeep`-style placeholder does not block
 * the copy.
 */
export function copyStarterBundle(
  vault: string,
  opts: CopyStarterOptions = {},
): StarterBundleResult {
  const src = opts.starterPath ?? DEFAULT_STARTER_DIR;
  try {
    if (!statSync(src).isDirectory()) {
      throw new BrainStarterError(`starter source is not a directory: ${src}`);
    }
  } catch (err) {
    if ((err as NodeJS.ErrnoException).code === "ENOENT") {
      throw new BrainStarterError(`starter source does not exist: ${src}`);
    }
    throw err;
  }
  for (const sub of STARTER_TARGETS) {
    const dir = join(vault, BRAIN_ROOT_REL, sub);
    let entries;
    try {
      // `withFileTypes` returns Dirent objects so we avoid a `statSync`
      // per child entry — one syscall per directory instead of N+1.
      entries = readdirSync(dir, { withFileTypes: true });
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code === "ENOENT") {
        throw new BrainStarterError(
          `Brain/${sub} does not exist — run \`o2b brain init\` (without --starter) first`,
        );
      }
      throw err;
    }
    // "Non-empty" means anything the user (or a prior dream pass)
    // could have left here. The only acceptable non-dotfile entry
    // bootstrap places under a starter target is `inbox/processed/` (and
    // its sibling `inbox/archived/`) — we whitelist those explicitly so a freshly initialised vault
    // does not trip the guard, but any other subdirectory (e.g. a
    // user-created `preferences/custom/`) counts as content and
    // refuses the starter.
    const hasUserContent = entries.some((e) => {
      if (e.name.startsWith(".")) return false;
      if (sub === "inbox" && e.isDirectory() && (e.name === "processed" || e.name === "archived")) {
        return false;
      }
      return true;
    });
    if (hasUserContent) {
      throw new BrainStarterError(
        `Brain/${sub} already has content — \`--starter\` is intended for fresh vaults. ` +
          `Inspect the bundle at ${src} and copy individual files manually if needed.`,
      );
    }
  }
  const copied: string[] = [];
  for (const sub of STARTER_TARGETS) {
    const srcDir = join(src, sub);
    if (!existsSync(srcDir)) continue;
    const destDir = join(vault, BRAIN_ROOT_REL, sub);
    // Single recursive copy per subdir — orders of magnitude fewer
    // syscalls than file-by-file. The filter rejects dotfiles
    // (`.gitkeep`, `.DS_Store`) so the bundle stays focused on
    // Brain content. The pre-check above already guarantees the
    // destination is empty, so collisions are impossible.
    cpSync(srcDir, destDir, {
      recursive: true,
      filter: (p) => !basename(p).startsWith("."),
    });
    // Report from the source listing — bootstrapBrain may have left
    // sibling subdirs in the destination (e.g. `inbox/processed/`)
    // that we did not copy and should not surface as starter entries.
    for (const name of readdirSync(srcDir)) {
      if (name.startsWith(".")) continue;
      // Vault-relative and forward-slash on every host, like every other
      // entry `bootstrapBrain` reports: callers compare these against
      // `Brain/...` prefixes, and a Windows `join` would hand back `Brain\...`.
      copied.push(posix.join(BRAIN_ROOT_REL, sub, name));
    }
  }
  const anchor = starterAnchorDay(src);
  const today = (opts.now ?? new Date()).toISOString().slice(0, 10);
  const days =
    anchor === null
      ? 0
      : Math.round(
          (new Date(`${today}T00:00:00Z`).getTime() - new Date(`${anchor}T00:00:00Z`).getTime()) /
            DAY_MS,
        );
  const placed = ageStarterCopy(vault, copied, days);
  // Only the SHIPPED bundle is operator-seed content this run vouches
  // for. A custom --starter-path copy is third-party text the operator
  // pointed at, so it stays unstamped and fails closed at delivery -
  // the delivery-provenance doctor check names it like every other page
  // whose provenance nothing derives - instead of arriving marked
  // operator-authored.
  if (src === DEFAULT_STARTER_DIR) stampStarterCopy(vault, placed);
  return Object.freeze({ copied: placed });
}

/**
 * Stamp every dropped page of the SHIPPED bundle with the channel that
 * dropped it.
 *
 * The bootstrap of the bundled starter is an `o2b` CLI run shipping the
 * tree's own seed, so `origin_channel: cli` is the true authorship
 * statement for it: operator-seed content the run itself vouches for,
 * delivered plain at every reach. Without the stamp the delivery-
 * provenance doctor check would name all eighteen pages on every fresh
 * vault's first pass - the warn-on-every-vault-forever outcome the
 * check's system-rendered exclusions exist to prevent, recreated
 * through the seed path. A page that already carries a channel (a
 * bundle page stamped by its author) keeps it, and a bundle page
 * without frontmatter at all is left byte-identical. A custom
 * `--starter-path` copy is deliberately NOT stamped: the run did not
 * author third-party text, and an operator-authored channel on it would
 * deliver it plain at every reach.
 */
function stampStarterCopy(vault: string, placed: ReadonlyArray<string>): void {
  for (const rel of placed) {
    if (!rel.endsWith(".md")) continue;
    const abs = join(vault, rel);
    let metadata: FrontmatterMap;
    let body: string;
    try {
      [metadata, body] = parseFrontmatter(abs);
    } catch {
      continue;
    }
    const keys = Object.keys(metadata);
    if (keys.length === 0 || keys.includes(ORIGIN_CHANNEL_FIELD)) continue;
    // The stamp rides first, which is where a tier-merging rewrite
    // re-emits a user-tier field it preserves - so the dropped bytes
    // are exactly what the next dream pass's no-op pre-flight renders,
    // and the fresh vault's first pass stays a no-op.
    const stamped: FrontmatterMap = { [ORIGIN_CHANNEL_FIELD]: ORIGIN_CHANNEL.cli, ...metadata };
    atomicWriteFileSync(abs, formatFrontmatter(stamped, body));
  }
}

export interface BootstrapBrainOptions {
  /** Overwrite `_brain.yaml` and `_BRAIN.md` if they already exist. */
  readonly force?: boolean;
  /**
   * Injection seam for deterministic tests. The rendered `_brain.yaml`
   * and `_BRAIN.md` carry static text and ignore it; `--starter` ages
   * the dropped bundle to this instant instead of the wall clock.
   */
  readonly now?: Date;
  /**
   * Override path of the machine-level plugin config. When unset, the
   * lookup chain in {@link defaultConfigPath} applies
   * (`OPEN_SECOND_BRAIN_CONFIG` env → XDG → `~/.config`).
   */
  readonly configPath?: string;
  /**
   * Optional primary-agent declaration for the vault. When provided on
   * a fresh init (or with `force`), the value is written into
   * `_brain.yaml.primary_agent`. On a re-run against an already
   * initialised `_brain.yaml` the value is ignored — use
   * `o2b brain set-primary` to mutate an existing config (it is
   * idempotent and won't disturb the rest of the file).
   */
  readonly primaryAgent?: string;
  /**
   * Drop the bundled starter set (8 preferences, 3 retired, 1 inbox
   * signal, 2 log days) into the freshly initialised `Brain/`.
   * Refuses to run if any of those subdirectories is non-empty;
   * `--starter` is for first-init only.
   */
  readonly starter?: boolean;
  /** Override the starter source path (defaults to bundled). */
  readonly starterPath?: string;
}

/**
 * How the step 1c `.gitignore` guard seeding concluded. The four seeder
 * statuses, plus `failed` for the case the seeder cannot report itself:
 * the guard file could not be read or written at all (a chmod-denied or
 * mandatory-locked `.gitignore`, a `.gitignore` that is a directory, a
 * rename the platform refused).
 */
export type BrainInitGuardStatus = GitignoreGuardStatus | "failed";

export interface BootstrapBrainResult {
  /** Vault-relative paths newly written. */
  readonly created: ReadonlyArray<string>;
  /** Vault-relative paths whose existing content was replaced. */
  readonly overwritten: ReadonlyArray<string>;
  /** Vault-relative paths left untouched because they already existed. */
  readonly skipped: ReadonlyArray<string>;
  /**
   * How step 1c — the `<vault>/.gitignore` derived-state guard — ended.
   * Always set on a returned result. `created`, `updated` and `skipped`
   * are the clean outcomes; `conflict` (malformed managed-block markers,
   * or a line negating the guard entry, whether the entry was already
   * present or would have landed in a merged block) and `failed` (the
   * file could not be read or written) mark a guard the operator must
   * look at, carry a `detail`, and come with a named warning on stderr.
   * Bootstrap CONTINUES in both cases — the guard is hygiene the
   * doctor's git-tracked-state row reports independently — and machine
   * readers use this field instead of parsing stderr to tell a clean
   * skip from an unresolved guard: the `o2b brain init` verb carries it
   * through to its `--json` payload and names it in the human output.
   */
  readonly guard: {
    readonly status: BrainInitGuardStatus;
    readonly detail?: string;
  };
  /**
   * Whether this run wrote the legacy `Brain/` tree: `false` with no
   * vault, and on a machine that holds its own switch record.
   */
  readonly legacyTree: boolean;
  /** The store step, run when there is no vault; absent otherwise. */
  readonly store?: EnsureBrainStoreResult;
  /**
   * The fresh-install switch step, run with the store step: what
   * `recordFreshInstallSwitch` did, or `error` with the failure's message.
   * It never fails the init; a caller tells the operator when the switch
   * was not recorded (`error`, `no-device`, `no-store`).
   */
  readonly freshSwitch?: {
    readonly outcome: FreshSwitchOutcome | "error";
    readonly detail?: string;
  };
}

/**
 * Bootstrap `<vault>/Brain/` and the legacy-overview replacement.
 *
 * @throws Error when the machine-level plugin config does not exist;
 *   the message names `o2b init` as the fix and the CLI surfaces it
 *   as exit code 1.
 */
export function bootstrapBrain(
  vault: string | null,
  opts: BootstrapBrainOptions = {},
): BootstrapBrainResult {
  const force = opts.force ?? false;
  const configPath = opts.configPath ?? defaultConfigPath();

  // Refuse to run before the vault has been registered. The machine
  // config carries the `vault:` field every subsequent `o2b brain *`
  // command relies on; bootstrapping without it would leave the user
  // with a half-wired install that fails on the first invocation
  // with a confusing "vault not configured" error far from the cause.
  if (!existsSync(configPath)) {
    throw new Error(
      `open-second-brain plugin config not found at ${configPath}; ` +
        "run `o2b init` first to register the vault",
    );
  }

  if (vault === null) {
    if (opts.starter === true) {
      throw new Error("--starter drops example pages into a vault, and no vault is configured");
    }
    refusePrimaryAgentWithoutTree(opts.primaryAgent);
    const store = ensureBrainStore({ configPath });
    // The switch record that keeps a fresh install store-only, as `o2b
    // init` writes it. It never fails the init (the store exists, and the
    // next init records the switch), but its outcome is reported, so a
    // switch that was not recorded is never a silent success.
    let freshSwitch: NonNullable<BootstrapBrainResult["freshSwitch"]>;
    try {
      freshSwitch = { outcome: recordFreshInstallSwitch({ vault: null, configPath }) };
    } catch (err) {
      freshSwitch = { outcome: "error", detail: err instanceof Error ? err.message : String(err) };
    }
    return {
      freshSwitch,
      created: [],
      overwritten: [],
      skipped: [],
      guard: { status: "skipped", detail: "no vault is configured" },
      legacyTree: false,
      store,
    };
  }

  const created: string[] = [];
  const overwritten: string[] = [];
  const skipped: string[] = [];

  // 0. A machine that holds its own switch record writes the store only:
  //    no legacy tree, and only the `.base` files the adapter allows. A
  //    vault without `Brain/` on an unswitched machine still gets the tree
  //    here: `brain init` is what creates it.
  const switched = storeOnlyMode({ vault, configPath }).reason === "device-switched";
  if (switched) {
    if (opts.starter === true) {
      throw new Error(
        "--starter drops example pages into the legacy Brain/ tree, which this machine " +
          "no longer writes (it has switched to the store)",
      );
    }
    refusePrimaryAgentWithoutTree(opts.primaryAgent);
    const guard = seedGitignoreGuard(vault, created, overwritten, skipped);
    const bases = stampBaseTemplates(vault, { force, storeOnly: true });
    created.push(...bases.created);
    overwritten.push(...bases.overwritten);
    skipped.push(...bases.skipped);
    return { created, overwritten, skipped, guard, legacyTree: false };
  }

  // 1. Directories. mkdirSync({ recursive: true }) is idempotent and
  //    does not throw on existing paths, so we do not track create
  //    counts for directories — only files end up in the report.
  //
  //    Enumerated from `brainDirs` rather than from a list repeated
  //    here: a hand-written list is how `pending` and `entities` came to
  //    be DECLARED by `brainDirs` and never created (their writers made
  //    them lazily, so a freshly-bootstrapped vault was missing two of
  //    the ten directories it advertises). Iterating the struct makes
  //    "declared but not created" unrepresentable.
  const dirs = brainDirs(vault);
  for (const dir of Object.values(dirs)) {
    mkdirSync(dir, { recursive: true });
  }

  // 1b. `Brain/vault-id.json` — the vault identity marker (Unit J). The
  //     bootstrap path is what legitimately creates a Brain tree, so it
  //     stamps the marker rather than being gated on it. Idempotent: a
  //     vault that already has an identity keeps it, since rotating the
  //     id would make every synced peer look like a different store.
  const identityPath = vaultIdentityPath(vault);
  const identityExisted = existsSync(identityPath);
  writeVaultIdentity(vault);
  if (!identityExisted) created.push(vaultRelative(identityPath, vault));

  // 1c. `<vault>/.gitignore` — the derived-state guard (t_206562ae).
  //     Every derived runtime state lives under `.open-second-brain/`, so
  //     one vault-root-anchored entry covers it; without the seed, a
  //     fresh init in a git repository left brain.sqlite visible to `git
  //     status`. The seeder merges a managed block and never clobbers
  //     user content; a git repository is NOT required (a plain folder
  //     gets the same seed, and git is never consulted here). A created
  //     file reports as created; an existing file that gained the block
  //     reports as overwritten (its bytes changed on disk); a clean skip
  //     or a named conflict leaves the file untouched and reports as
  //     skipped, with `result.guard` distinguishing the two. The step is
  //     guarded, not load-bearing: a `.gitignore` that cannot be read or
  //     written (chmod-denied, mandatory-locked, or a directory) warns on
  //     stderr and degrades to `guard: { status: "failed" }` instead of
  //     aborting — bailing here would leave the half-built tree below
  //     unwritten for a hygiene guard the doctor's git-tracked-state row
  //     reports independently (and in more detail).
  const guard = seedGitignoreGuard(vault, created, overwritten, skipped);

  // 2. `_brain.yaml` — default config (with optional primary_agent).
  const brainYamlPath = brainConfigPath(vault);
  const brainYamlRel = vaultRelative(brainYamlPath, vault);
  const initialYaml = applyPrimaryAgentToYaml(DEFAULT_BRAIN_CONFIG_YAML, opts.primaryAgent);
  if (existsSync(brainYamlPath)) {
    if (force) {
      atomicWriteFileSync(brainYamlPath, initialYaml);
      overwritten.push(brainYamlRel);
    } else {
      skipped.push(brainYamlRel);
    }
  } else {
    atomicWriteFileSync(brainYamlPath, initialYaml);
    created.push(brainYamlRel);
  }

  // 3. `Brain/_BRAIN.md` — operating manual rendered from template.
  const manualPath = brainManualPath(vault);
  const manualRel = vaultRelative(manualPath, vault);
  const manualBody = renderBrainManual(vault);
  if (existsSync(manualPath)) {
    if (force) {
      atomicWriteFileSync(manualPath, manualBody);
      overwritten.push(manualRel);
    } else {
      skipped.push(manualRel);
    }
  } else {
    atomicWriteFileSync(manualPath, manualBody);
    created.push(manualRel);
  }

  // 4. `Brain/bases/*.base` — Obsidian Bases view definitions. Stamped
  //    like the operating manual (always, not opt-in): they are inert
  //    structural scaffolding, not example data. Each file is written
  //    only when absent unless `force` is set.
  const bases = stampBaseTemplates(vault, { force, storeOnly: false });
  created.push(...bases.created);
  overwritten.push(...bases.overwritten);
  skipped.push(...bases.skipped);

  if (opts.starter === true) {
    const starterResult = copyStarterBundle(vault, {
      starterPath: opts.starterPath,
      ...(opts.now !== undefined ? { now: opts.now } : {}),
    });
    created.push(...starterResult.copied);
  }

  return { created, overwritten, skipped, guard, legacyTree: true };
}

/**
 * Step 1c: seed the `<vault>/.gitignore` derived-state guard, record the
 * file in the created/overwritten/skipped lists, and answer the guard
 * outcome the result carries. The guard is always answered — the seeder
 * deliberately propagates I/O errors, and here they stop being fatal:
 * report on stderr, degrade to `guard: { status: "failed" }`, continue.
 */
function seedGitignoreGuard(
  vault: string,
  created: string[],
  overwritten: string[],
  skipped: string[],
): BootstrapBrainResult["guard"] {
  try {
    const gitignore = ensureVaultGitignoreEntries(vault);
    if (gitignore.status === "created") {
      created.push(gitignore.file);
    } else if (gitignore.status === "updated") {
      overwritten.push(gitignore.file);
    } else {
      skipped.push(gitignore.file);
    }
    return {
      status: gitignore.status,
      ...(gitignore.detail !== undefined ? { detail: gitignore.detail } : {}),
    };
  } catch (err) {
    const detail = err instanceof Error ? err.message : String(err);
    process.stderr.write(
      `warning: brain init could not seed the ${GITIGNORE_GUARD_FILE} derived-state guard ` +
        `(derived brain state stays visible to git; \`o2b brain doctor\` reports the row): ` +
        `${detail}\n`,
    );
    skipped.push(GITIGNORE_GUARD_FILE);
    return { status: "failed", detail };
  }
}

/**
 * `--primary-agent` is written into `_brain.yaml`, which a store-only
 * machine never writes: refuse it, naming the store-side setting, rather
 * than report a success that persisted nothing.
 */
function refusePrimaryAgentWithoutTree(primaryAgent: string | undefined): void {
  if (primaryAgent === undefined) return;
  throw new Error(
    "--primary-agent writes _brain.yaml, which this machine does not keep (its brain lives in " +
      "the store); set it with `o2b brain settings set primary_agent <name>`",
  );
}

/**
 * Replace the `primary_agent: null` line in the default `_brain.yaml`
 * body with the operator-supplied value, when provided. Trimmed,
 * empty-string-rejecting (the validator would catch that at load time,
 * but we fail loud here so an init that intended to declare a primary
 * does not silently fall back to `null`).
 *
 * The substitution is anchored on the literal `^primary_agent:` line
 * so re-running the helper against an already-customised YAML stays
 * idempotent for the relevant slot.
 */
function applyPrimaryAgentToYaml(yamlBody: string, primaryAgent: string | undefined): string {
  if (primaryAgent === undefined) return yamlBody;
  const line = `primary_agent: ${formatPrimaryAgentYamlValue(primaryAgent)}`;
  return yamlBody.replace(/^primary_agent:.*$/m, line);
}