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
26.9 KB
Raw Blame
/**
 * `Brain/active.md` β€” the auto-generated active-preferences digest.
 *
 * The file is a derived view of `Brain/preferences/` (status `confirmed`
 * and `quarantine`) plus the three most recent entries in
 * `Brain/retired/`. It is regenerated at the tail of every `dream`
 * pass and after CLI verbs that mutate preferences directly (pin,
 * unpin, future reject). It is read by:
 *
 *   - the SessionStart / PostCompact hook β†’ injected as
 *     `additionalContext` so the agent sees current rules at the start
 *     of every session and after `/compact`;
 *   - the MCP resource `osb://preferences/active` so MCP-capable hosts
 *     can pull it on demand.
 *
 * Properties:
 *
 *   - **Pure derivation.** No LLM, no network, no clock-dependent
 *     content beyond the `generated_at` stamp. Identical inputs
 *     produce identical *bodies* β€” the function only varies the
 *     frontmatter timestamp.
 *   - **Idempotent write.** The body (everything below the
 *     frontmatter) is compared against the existing file's body
 *     before writing. When equal, the file is left untouched so a
 *     no-op `dream` rerun does not bump mtime or cause Obsidian to
 *     re-render the open tab.
 *   - **Atomic write.** Uses `atomicWriteFileSync` so a crash
 *     mid-render leaves the previous version intact.
 *
 * Anchored in the v0.9.1 plan ("Brain/active.md + SessionStart /
 * PostCompact hook + MCP resources") which closes BRAIN-FUT-006.
 */

import { legacyVaultOf } from "./no-vault.ts";
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, posix } from "node:path";

import { atomicWriteFileSync } from "../fs-atomic.ts";
import { withPrivateShown } from "../store/caller-reach.ts";
import { parseFrontmatter } from "../vault.ts";
import { computeMostApplied, type MostAppliedEntry } from "./most-applied.ts";
import {
  MOST_APPLIED_LIMIT_DEFAULT,
  MOST_APPLIED_WINDOW_DAYS_DEFAULT,
  loadBrainConfig,
  loadGuardrailsConfigSafe,
} from "./policy.ts";
import { isPreferenceVisible } from "./owner-scoped-facts.ts";
import {
  compiledDigestPath,
  digestCachePath,
  digestsRenderedOnDemand,
} from "./compiled-digest-path.ts";
import { legacyMemoryPage, type MemoryPage, storeMemoryPages } from "./memory-pages.ts";
import { withLogReadPass } from "./log-days.ts";
import { parseRetiredMeta } from "./preference.ts";
import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";
import {
  SUPERSEDED_BY_KEY,
  buildChainLookup,
  resolveChainTip,
  type ChainLookup,
} from "./lifecycle/tombstone-read.ts";
import { filterExpired } from "./expiration.ts";
import { chainVerdict } from "../search/correction-coupling.ts";
import { BRAIN_TOMBSTONE_STATUS } from "./types.ts";
import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "./path-constants.ts";
import { brainActivePath, brainDirs, brainDirsOf } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoSecond } from "./time.ts";
import { sortByProvenanceTrust } from "./provenance/trust-order.ts";
import { BRAIN_PREFERENCE_STATUS, type BrainPreference, type BrainRetired } from "./types.ts";

const RECENTLY_RETIRED_COUNT = 3;

const FRONTMATTER_KIND = "brain-active";

export interface RegenerateActiveOptions {
  /** Wall clock for `generated_at`. Defaults to `new Date()`. */
  readonly now?: Date;
}

/**
 * Options for the RENDER, which β€” unlike the write β€” may be narrowed to a
 * single agent's view.
 */
export interface RenderActiveOptions extends RegenerateActiveOptions {
  /**
   * Owner scope for delivery isolation (context-integrity-gates, Unit
   * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
   * omitted, or under the default `off`, nothing is filtered and the
   * output is byte-identical to a vault without the gate.
   *
   * Deliberately absent from {@link RegenerateActiveOptions}: `active.md`
   * is ONE file shared by every agent on the vault, injected into every
   * SessionStart by `hooks/active-inject.ts` and regenerated unscoped by
   * the `osb://preferences/active` MCP resource. A per-request visibility
   * filter that reached the write would make the file thrash between
   * narrowed and complete, and an agent could lose its OWN memories from
   * session start because another agent read the vault last.
   */
  readonly agentScope?: string;
  /**
   * `generated_at` stamp for the rendered frontmatter. Defaults to
   * {@link isoSecond} of `now`. A read-time render passes the stamp
   * already on disk so its document describes the same generation the
   * shared file does.
   */
  readonly generatedAt?: string;
  /**
   * May the reader see the record at this vault-relative path? A record
   * it may not is treated as absent: its line, its count and its place in
   * the most-applied list all go, exactly as if the file did not exist.
   * Omitted, nothing is filtered. Like {@link agentScope}, it never
   * reaches the shared write.
   */
  readonly readable?: (rel: string) => boolean;
  /**
   * The reader is below local reach: the most-applied counts leave out
   * events of the store's `private` partition. Never reaches the write.
   */
  readonly withholdsPrivate?: boolean;
}

/** Who is reading the shared digest: the two read-time narrowings. */
export interface ActiveReaderOptions {
  /** See {@link RenderActiveOptions.readable}. */
  readonly readable?: (rel: string) => boolean;
  /** See {@link RenderActiveOptions.agentScope}. */
  readonly agentScope?: string;
  /**
   * The reader arrived below local reach. Such a reader is always handed
   * the in-memory render, never the file: whether a record is withheld
   * from it must not decide between a fresh render and a file that may
   * be stale, or the choice itself tells it the record exists.
   */
  readonly restricted?: boolean;
}

/** A rendered digest that has NOT been written anywhere. */
export interface ActiveRender {
  /** Body only, no frontmatter β€” what the idempotency check compares. */
  readonly body: string;
  /** Frontmatter + body: exactly the bytes a write would store. */
  readonly document: string;
  readonly counts: RegenerateActiveResult["counts"];
}

export interface RegenerateActiveResult {
  /** Absolute path of the written file. */
  readonly path: string;
  /** Whether the rendered body differed from the previous file content. */
  readonly changed: boolean;
  readonly counts: {
    readonly confirmed: number;
    readonly quarantine: number;
    readonly retired_recent: number;
    /**
     * Length of the `Most-applied (30d)` section in this render
     * pass. Zero when no `apply-evidence (result: applied)` events
     * lie inside the trailing 30-day window or no preference still
     * maps to one. `brain_context` echoes this through to MCP
     * clients so they can render a counts ribbon without parsing
     * the markdown body.
     */
    readonly most_applied_30d: number;
  };
}

/**
 * Render the active digest WITHOUT writing it.
 *
 * The read-time half of this module. `active.md` is a single file shared
 * by every agent on the vault, so a scope-narrowed view has to be
 * produced here and delivered to the one caller that asked for it β€”
 * never persisted. {@link regenerateActive} is the write, and it never
 * takes a scope.
 *
 * Errors thrown by individual preference / retired parsers are caught
 * and the offending file is omitted from the render. This does not raise
 * on parse failures because a single corrupted frontmatter must not break
 * the agent's view of every healthy rule. Corruption is the domain of
 * `brain_doctor`; this render's job is to surface what is knowable.
 */
export function renderActive(vault: string | null, opts: RenderActiveOptions = {}): ActiveRender {
  return renderActiveAt(vault, opts);
}

function renderActiveAt(
  vault: string | null,
  opts: RenderActiveOptions,
  expirationNow?: Date,
): ActiveRender {
  const now = opts.now ?? new Date();

  const readable = opts.readable ?? READ_EVERYTHING;
  const preferences = filterExpired(readActivePreferences(vault, opts.agentScope, readable), {
    now: expirationNow ?? now,
  });
  const retiredRecent = readRecentlyRetired(
    vault,
    RECENTLY_RETIRED_COUNT,
    opts.agentScope,
    readable,
  );

  // Confirmed prefs sort by confidence then id. When provenance trust
  // ordering is on, re-rank stated > deduced > inferred as the primary key
  // (stable, so the confidence order is preserved within a trust band). Off
  // by default -> byte-identical.
  const confirmedByConfidence = preferences
    .filter((p) => p.status === BRAIN_PREFERENCE_STATUS.confirmed)
    .toSorted(sortByConfidenceThenId);
  const confirmed = sortByProvenanceTrust(
    confirmedByConfidence,
    loadGuardrailsConfigSafe(vault).provenance_trust_ordering,
  );
  const quarantine = preferences
    .filter((p) => p.status === BRAIN_PREFERENCE_STATUS.quarantine)
    .toSorted(sortByIdAscending);

  // Read window/limit from `_brain.yaml:active.most_applied_*`. The
  // strict loader throws when the file is ABSENT too, and a vault that
  // has never run `brain init` must still get its digest, so that case
  // lands on the defaults here.
  //
  // The catch only ever sees that case: an unreadable `_brain.yaml`
  // already raised out of `loadGuardrailsConfigSafe` above, which is
  // deliberate - a config the operator wrote but broke must not quietly
  // resolve to defaults on a surface the agent reads as its rule set.
  let windowDays = MOST_APPLIED_WINDOW_DAYS_DEFAULT;
  let limit = MOST_APPLIED_LIMIT_DEFAULT;
  try {
    const cfg = loadBrainConfig(vault);
    if (cfg.active?.most_applied) {
      windowDays = cfg.active.most_applied.window_days;
      limit = cfg.active.most_applied.limit;
    }
  } catch {
    // intentional fallback β€” an uninitialised vault has no config to read
  }

  // Most-applied draws from the active candidates (confirmed +
  // quarantine) only β€” retired preferences are reported in their own
  // section below and never resurrected through the hot list.
  const mostApplied = computeMostApplied(vault, [...confirmed, ...quarantine], {
    now,
    windowDays,
    limit,
    withholdsPrivate: opts.withholdsPrivate === true,
  });

  const body = renderBody({
    confirmed,
    quarantine,
    retiredRecent,
    mostApplied,
    windowDays,
  });

  return {
    body,
    document: renderDocument(body, opts.generatedAt ?? isoSecond(now)),
    counts: {
      confirmed: confirmed.length,
      quarantine: quarantine.length,
      retired_recent: retiredRecent.length,
      most_applied_30d: mostApplied.length,
    },
  };
}

/**
 * Must this reader be handed the in-memory render rather than the file?
 *
 * Decided on who is reading, never on what is withheld: an enforced owner
 * scope or a restricted reach always renders, so the answer does not
 * depend on whether a record the reader cannot see exists. The common
 * case - a local reader with no enforced scope - is served the file's own
 * bytes, unchanged.
 */
export function readerNarrowsActive(vault: string | null, opts: ActiveReaderOptions): boolean {
  if (opts.restricted === true) return true;
  return resolveOwnerScopeDelivery(vault, opts.agentScope).enforcedScope !== null;
}

/**
 * The digest as ONE reader may see it, rendered in memory with the
 * `generated_at` stamp already on disk, so the narrowed document names
 * the same generation the shared file does. Nothing is written. Callers
 * ask {@link readerNarrowsActive} first and serve the file otherwise.
 */
export function renderActiveForReader(
  vault: string | null,
  opts: ActiveReaderOptions,
): ActiveRender {
  const generatedAt = readGeneratedAt(compiledDigestPath(vault, "active"));
  return renderActive(vault, {
    ...(opts.agentScope !== undefined ? { agentScope: opts.agentScope } : {}),
    ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
    ...(generatedAt !== null ? { generatedAt } : {}),
    withholdsPrivate: opts.restricted === true,
  });
}

/**
 * The bytes of `Brain/active.md` this reader may be handed: the file
 * itself for a local reader with no enforced scope, the reader render
 * otherwise. The file must exist; the caller regenerates it first.
 */
export function readActiveForReader(vault: string | null, opts: ActiveReaderOptions): string {
  return readerNarrowsActive(vault, opts)
    ? renderActiveForReader(vault, opts).document
    : readFileSync(compiledDigestPath(vault, "active"), "utf8");
}

/**
 * The file a reader of the shared digest reads: `Brain/active.md` on an
 * unswitched machine, as it is; on a store-only machine the device-local
 * cache, rendered first (D14 item 7: the digest is rendered on demand,
 * and the cache keeps its generation while the body is unchanged).
 */
export function activeDigestPathForRead(
  vault: string | null,
  opts: RegenerateActiveOptions = {},
): string {
  if (vault !== null && !digestsRenderedOnDemand(vault)) return brainActivePath(vault);
  // The cached generation stands while a render at its own instant still
  // gives its body: what changed since is time alone, as for a vault file
  // the next dream pass has not rewritten yet. A changed input renders now.
  const path = compiledDigestPath(vault, "active");
  const now = opts.now ?? new Date();
  const stamp = readGeneratedAt(path);
  const stampMs = stamp === null ? Number.NaN : Date.parse(stamp);
  // One read pass: the check render and a regeneration share one log read.
  // The cache is a local reader's file: checked with nothing withheld.
  return withPrivateShown(() =>
    withLogReadPass(() => {
      if (stamp !== null && !Number.isNaN(stampMs)) {
        // Keep the log window at the cached generation, but do not keep serving
        // a preference whose explicit expiration has passed since then.
        const atStamp = renderActiveAt(vault, { now: new Date(stampMs) }, now);
        if (readExistingBody(path) === atStamp.body.trim()) return path;
      }
      return regenerateActive(vault, { now }).path;
    }),
  );
}

/**
 * Regenerate `<vault>/Brain/active.md`. Returns whether the body
 * actually changed (callers don't need to skip the call themselves β€”
 * the function makes the right decision internally).
 *
 * The write is ALWAYS unscoped: see {@link RenderActiveOptions.agentScope}
 * for why a per-request visibility filter must not reach this file.
 */
export function regenerateActive(
  vault: string | null,
  opts: RegenerateActiveOptions = {},
): RegenerateActiveResult {
  const now = opts.now ?? new Date();
  const onDemand = digestsRenderedOnDemand(vault);
  if (!onDemand && vault !== null) assertVaultIdentityForWrite(vault);
  const path =
    onDemand || vault === null ? digestCachePath(vault, "active") : brainActivePath(vault);
  // The file is shared with every later reader, so it is rendered with
  // nothing withheld even for a caller below local reach (who is served
  // its own render, `renderActiveForReader`).
  const rendered = withPrivateShown(() => renderActive(vault, { now }));

  // `readExistingBody` returns the trimmed body (parseFrontmatter
  // trims internally), so compare against the trimmed render for an
  // apples-to-apples byte check.
  const existingBody = readExistingBody(path);
  const changed = existingBody === null || existingBody !== rendered.body.trim();
  if (changed) {
    // The device-local cache directory of a store-only machine may not
    // exist yet; the vault's `Brain/` always does when this is reached.
    if (onDemand) mkdirSync(dirname(path), { recursive: true });
    atomicWriteFileSync(path, rendered.document);
  }

  return { path, changed, counts: rendered.counts };
}

/**
 * Wrapper around {@link regenerateActive} that swallows failures with a
 * stderr warning. Used by `dream` and `setPinned` β€” both treat the
 * digest as a derived view: when its write fails (disk full,
 * permissions, etc.), the real state-changing work is still valid
 * and the next call will retry. We don't want a missing summary file
 * to mask the success of the underlying operation.
 *
 * Exported as the single source of truth for fire-and-warn semantics
 * so the same swallow shape isn't copy-pasted at each call site.
 */
export function regenerateActiveQuiet(
  vault: string | null,
  opts: RegenerateActiveOptions & { legacyOnly?: boolean } = {},
): void {
  try {
    if (opts.legacyOnly && digestsRenderedOnDemand(vault)) return;
    regenerateActive(vault, opts);
  } catch (err) {
    process.stderr.write(`warning: regenerate active.md failed: ${(err as Error).message}\n`);
  }
}

// ----- Scan helpers --------------------------------------------------------

const READ_EVERYTHING = (_rel: string): boolean => true;

/**
 * The `generated_at` stamp of a compiled digest file on disk, or null when
 * absent or unreadable. Shared by the active and lessons reader renders.
 */
export function readGeneratedAt(path: string): string | null {
  if (!existsSync(path)) return null;
  try {
    const [meta] = parseFrontmatter(path);
    const value = meta["generated_at"];
    return typeof value === "string" && value.trim().length > 0 ? value : null;
  } catch {
    // A torn header has no stamp to reuse; the render then stamps its own.
    return null;
  }
}

function readActivePreferences(
  vault: string | null,
  agentScope: string | undefined,
  readable: (rel: string) => boolean,
): BrainPreference[] {
  // With no vault the folders are the store's (design D14).
  const dirs = brainDirsOf(vault);
  // The shared delivery-path walk (context-integrity-gates, Unit A) owns
  // the listing and the parse; a corrupted or status/folder-mismatched
  // file is omitted there, and `brain_doctor` is the surface that flags
  // it. See the module docblock for the rationale.
  const out: BrainPreference[] = [];
  for (const { name, pref } of collectPreferences(dirs.preferences, {
    ownerScope: resolveOwnerScopeDelivery(vault, agentScope),
  }).entries) {
    if (!readable(posix.join(BRAIN_PREFERENCES_REL, name))) continue;
    // Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
    // superseded-non-tip) preference remains on disk for audit but
    // never appears in the active-preferences digest.
    if ((pref.status as string) === BRAIN_TOMBSTONE_STATUS) continue;
    out.push(pref);
  }
  return out;
}

function legacyRetiredPages(vault: string | null): MemoryPage[] {
  const root = legacyVaultOf(vault, "readRecentlyRetired");
  const dir = brainDirs(root).retired;
  if (!existsSync(dir)) return [];
  return readdirSync(dir).map((name) => legacyMemoryPage(root, "retired", name));
}

/**
 * Retirement KEEPS ownership (context-integrity-gates, A7): a retired
 * memory is withdrawn from the active set, never published. The gate
 * verdict is resolved exactly as it is for the active preferences, so a
 * vault with the gate off - or a caller with no scope - sees the same
 * list it always did.
 */
function readRecentlyRetired(
  vault: string | null,
  limit: number,
  agentScope: string | undefined,
  readable: (rel: string) => boolean,
): BrainRetired[] {
  // Store pages on a store-only machine; only an unswitched machine
  // resolves (and guards) the legacy folder, so a read never trips the
  // write guard (frozen vault, migration in progress) for a folder it
  // does not read.
  const pages = storeMemoryPages(vault, "retired") ?? legacyRetiredPages(vault);
  const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;
  const out: BrainRetired[] = [];
  // The serve-with-correction chain index, built on the first
  // pointer-bearing record and reused for the rest of the walk: a vault
  // whose retired records carry no pointer never pays for it.
  let chainLookup: ChainLookup | null = null;
  for (const page of pages) {
    const name = page.name;
    // Filtered BEFORE the newest-first cut, so a withheld record never
    // pushes a visible one out of the list either.
    if (!name.endsWith(".md") || !readable(posix.join(BRAIN_RETIRED_REL, name))) continue;
    const full = page.path;
    try {
      const retired = parseRetiredMeta(page.read()[0], full);
      if (scope !== null && !isPreferenceVisible(retired, scope)) continue;
      // Serve-with-correction coupling (truth-correctable-time-aware,
      // contract item 3): a retired record whose frontmatter declares a
      // successor - the serveable-retired regime - is digested only
      // beside its resolved, readable chain-tip correction and is
      // omitted fail-closed otherwise. A record with no pointer is not
      // in the predicate's regime and keeps today's rendering.
      const pointer = retired[SUPERSEDED_BY_KEY];
      if (typeof pointer === "string" && pointer.trim() !== "") {
        chainLookup ??= buildChainLookup(vault, readable);
        const verdict = chainVerdict(
          posix.join(BRAIN_RETIRED_REL, name),
          resolveChainTip(pointer, chainLookup),
        );
        if (verdict.action === "drop") continue;
      }
      out.push(retired);
    } catch {
      // Same rationale as readActivePreferences.
    }
  }
  // Newest first; an unparseable date sorts last, and the id breaks ties so
  // the order never depends on how the folder or the store lists its pages.
  const time = (r: BrainRetired): number => {
    const t = Date.parse(r.retired_at);
    return Number.isNaN(t) ? Number.NEGATIVE_INFINITY : t;
  };
  out.sort((a, b) => {
    const ta = time(a);
    const tb = time(b);
    if (ta !== tb) return tb > ta ? 1 : -1;
    return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
  });
  return out.slice(0, limit);
}

// ----- Render helpers ------------------------------------------------------

interface RenderInput {
  readonly confirmed: ReadonlyArray<BrainPreference>;
  readonly quarantine: ReadonlyArray<BrainPreference>;
  readonly retiredRecent: ReadonlyArray<BrainRetired>;
  readonly mostApplied: ReadonlyArray<MostAppliedEntry>;
  readonly windowDays: number;
}

function renderBody(input: RenderInput): string {
  const out: string[] = [];
  out.push("# Active Brain Preferences");
  out.push("");
  out.push("Auto-generated by `dream`. Do not edit β€” changes will be overwritten.");
  out.push("");

  out.push(`## Confirmed (${input.confirmed.length})`);
  out.push("");
  if (input.confirmed.length === 0) {
    out.push("_No confirmed preferences yet._");
  } else {
    for (const p of input.confirmed) out.push(renderConfirmedLine(p));
  }
  out.push("");

  if (input.mostApplied.length > 0) {
    out.push(`## Most-applied (${input.windowDays}d) (${input.mostApplied.length})`);
    out.push("");
    for (const m of input.mostApplied) out.push(renderMostAppliedLine(m));
    out.push("");
  }

  if (input.quarantine.length > 0) {
    out.push(`## Quarantine (${input.quarantine.length})`);
    out.push("");
    out.push(
      "_Probationary rules β€” still active, but recent evidence is dominantly negative. One further `violated` evidence event retires the rule._",
    );
    out.push("");
    for (const p of input.quarantine) out.push(renderQuarantineLine(p));
    out.push("");
  }

  if (input.retiredRecent.length > 0) {
    out.push(`## Recently retired (last ${input.retiredRecent.length})`);
    out.push("");
    for (const r of input.retiredRecent) out.push(renderRetiredLine(r));
    out.push("");
  }

  // Trim trailing blank line so consecutive renders compare cleanly.
  while (out.length > 0 && out[out.length - 1] === "") out.pop();
  return out.join("\n") + "\n";
}

function renderConfirmedLine(p: BrainPreference): string {
  const tags: string[] = [];
  if (p.scope) tags.push(`scope: ${p.scope}`);
  tags.push(`confidence: ${p.confidence}${formatConfidenceValueTail(p)}`);
  if (p.pinned) tags.push("pinned");
  return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
}

function renderMostAppliedLine(m: MostAppliedEntry): string {
  const p = m.preference;
  const tags: string[] = [];
  if (p.scope) tags.push(`scope: ${p.scope}`);
  // Display label is window-agnostic; the actual window length is in the
  // `## Most-applied (Nd)` section header. The struct field
  // (`MostAppliedEntry.applied_30d`) keeps its v0.10.10 name so internal
  // consumers (MCP counts, e2e tests) don't break.
  tags.push(`applied_in_window: ${m.applied_30d}`);
  // One-liner by design (token-diet): every most-applied preference is
  // confirmed or quarantined, so its principle text is already rendered
  // verbatim in the section above - repeating it here duplicated ~31%
  // of the injected bytes on a real vault.
  return `- \`${p.id}\` (${tags.join(", ")})`;
}

function renderQuarantineLine(p: BrainPreference): string {
  const tags: string[] = [];
  if (p.scope) tags.push(`scope: ${p.scope}`);
  tags.push(`applied: ${p.applied_count} / violated: ${p.violated_count}`);
  if (p.confidence_value !== null) {
    tags.push(`conf: ${p.confidence_value.toFixed(2)}`);
  }
  if (p.pinned) tags.push("pinned");
  return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
}

/**
 * Tail rendered next to the confidence band in the `confidence:`
 * metadata. When a commitment tier is set (Belief lifecycle suite, B3),
 * the tier label is rendered in place of the raw confidence float; the
 * band itself is unchanged. When no tier is set, the numeric
 * `confidence_value` is rendered as before (empty when it is `null`, e.g.
 * a legacy preference written before v0.10.3). Unset commitment therefore
 * keeps the output byte-identical to today.
 */
function formatConfidenceValueTail(p: BrainPreference): string {
  if (p.commitment !== undefined) return ` (${p.commitment})`;
  if (p.confidence_value === null) return "";
  return ` (${p.confidence_value.toFixed(2)})`;
}

function renderRetiredLine(r: BrainRetired): string {
  const date = r.retired_at.slice(0, 10);
  return `- \`${r.id}\` β€” ${r.retired_reason} on ${date}`;
}

function renderDocument(body: string, generatedAt: string): string {
  const lines: string[] = [
    "---",
    `kind: ${FRONTMATTER_KIND}`,
    `generated_at: ${generatedAt}`,
    "---",
    "",
    body.trimEnd(),
    "",
  ];
  return lines.join("\n");
}

/** Find an existing stale vault digest using the same body comparison as regeneration. */
export function legacyActiveIsStale(vault: string, path: string, now: Date): boolean {
  if (!existsSync(path) || digestsRenderedOnDemand(vault, undefined, { persistSwitch: false })) {
    return false;
  }
  return readExistingBody(path) !== renderActive(vault, { now }).body.trim();
}

function readExistingBody(path: string): string | null {
  if (!existsSync(path)) return null;
  try {
    const [, body] = parseFrontmatter(path);
    // `parseFrontmatter` returns the body already stripped of the
    // frontmatter block and leading separator newline. We compare
    // against `renderBody`'s output, which also lacks frontmatter β€”
    // both sides go through the same trim semantics so the
    // idempotency check is byte-correct without bespoke regex work.
    return body;
  } catch {
    return null;
  }
}

function sortByConfidenceThenId(a: BrainPreference, b: BrainPreference): number {
  const order = { high: 0, medium: 1, low: 2 } as const;
  const ca = order[a.confidence];
  const cb = order[b.confidence];
  if (ca !== cb) return ca - cb;
  return a.id.localeCompare(b.id);
}

function sortByIdAscending(a: BrainPreference, b: BrainPreference): number {
  return a.id.localeCompare(b.id);
}