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
30.8 KB
Raw Blame
/**
 * Quiet-window maintenance lane (write-time-integrity-governance,
 * t_166d1226; host pressure and the failure streak, t_992f0c33). Heavy
 * passes (dream, reindex) run through five gates:
 *
 *   1. window   - a configured local-time hour window (tz-aware,
 *                 midnight wrap supported); unconfigured = always open.
 *   2. busy     - recent interactive query-rate from the existing
 *                 recall-telemetry continuity records; a vault without
 *                 telemetry counts as quiet.
 *   3. pressure - the host's normalised run queue, from
 *                 `maintenance.host_pressure_percent`; unconfigured =
 *                 always open. Where the metric is degenerate the gate
 *                 stays open and journals WHY, on its own line, so a
 *                 platform that cannot measure pressure never looks
 *                 like a quiet one.
 *   4. capacity - the vault's own storage forecast, from
 *                 `storage.cap_bytes`; unconfigured (the default) =
 *                 always open and never measured. A measured tier at or
 *                 past the pause line (`storage.pause_percent`, default
 *                 the warn band) pauses the whole lane - background
 *                 production backs off one band before the wall, while
 *                 interactive ingest still works until the critical
 *                 tier refuses it. Where the census is degenerate the
 *                 gate stays open and journals WHY, on its own line,
 *                 for the same reason the pressure gate does.
 *   5. lease    - the expiring SQLite lease; never bypassable, even
 *                 with --force, because two concurrent heavy passes on
 *                 one vault is the exact failure this lane exists to
 *                 prevent.
 *
 * Then, per task, a consecutive-failure streak read off the journal:
 * a task that has failed `maintenance.failure_streak_limit` times in a
 * row is refused by name rather than retried, because nothing here
 * supervises a repeating failure and the lane's stale-first ordering
 * would otherwise hand a permanently broken task the lease first on
 * every pass.
 *
 * ## Two escapes, and why the narrow one exists
 *
 * A refusal is per task and the other tasks still run - but it stands
 * until something clears it, and only a SUCCESS clears it. So there has
 * to be a way to attempt the refused task again.
 *
 * `force` is the wide one: it bypasses the soft gates (window, busy,
 * pressure, capacity) and every streak refusal, for an operator who wants
 * the pass NOW. Making it the only way out was the defect: an operator whose
 * reindex is deterministically broken had to run the whole heavy lane
 * with their own window, busy and host-pressure protection switched off
 * in order to retry one task.
 *
 * {@link RunMaintenanceOptions.retryTasks} is the narrow one: it bypasses
 * the streak refusal for the tasks it NAMES and nothing else. Every gate
 * the operator configured still decides, the lease still decides, and a
 * task it does not name is still refused. It clears no state and writes
 * no row of its own: the attempt's own outcome row is what ends the
 * streak if it succeeds, and what deepens it if it does not, so a retry
 * that keeps failing costs one lane slot per invocation the operator
 * chose to make - not a standing exemption.
 *
 * Tasks run stale-first (least-recently succeeded first, never-run
 * before everything) and every attempt is journaled.
 */

import { listRecallTelemetry } from "../recall-telemetry.ts";
import { capOutput, OPERATION, SafeguardTimeoutError } from "../safeguard.ts";
import { loadMaintenanceConfigSafe, loadStorageConfigSafe } from "../policy/load.ts";
import type { ResolvedBrainStorageConfig } from "../types.ts";
import {
  STORAGE_FORECAST_TIER,
  sampleStorageUsage,
  type StorageForecastTier,
} from "../storage/forecast.ts";
import {
  CAPACITY_GATE_DECISION,
  evaluateCapacityGate,
  type CapacityGateDecision,
} from "../storage/gate.ts";
import { acquireLease, MAINTENANCE_LEASE_NAME, releaseLease } from "./lease.ts";
import {
  appendJournal,
  consecutiveTaskFailures,
  listJournal,
  MAINTENANCE_VERDICT,
  sweepJournal,
  type MaintenanceJournalEntry,
  type MaintenanceSpendReceipt,
  type MaintenanceVerdict,
} from "./journal.ts";
import { HOST_PRESSURE, measureHostPressure, type HostPressureReading } from "./host-pressure.ts";
import type { CustomLaneTask } from "./custom-task-id.ts";

/** The persisted model-spend receipt; defined beside the row it rides. */
export type { MaintenanceSpendReceipt } from "./journal.ts";

/** Default lease TTL: generous enough for a full reindex + dream. */
export const MAINTENANCE_LEASE_TTL_MS = 30 * 60 * 1000;
/** Default busy gate: this many queries in the window means busy. */
export const MAINTENANCE_BUSY_THRESHOLD = 5;
/** Default busy lookback window in minutes. */
export const MAINTENANCE_BUSY_MINUTES = 10;
/**
 * Ceilings for the two busy-gate knobs, beside the defaults they bound
 * rather than in whichever surface first needed them.
 *
 * A day is the longest lookback that still describes "recent interactive
 * use"; past that the gate answers a different question than the one it
 * was built for. Ten thousand queries in that day is well past any real
 * traffic and is the point at which a number stops being a threshold and
 * starts being a typo.
 *
 * They live here because BOTH front doors have to refuse the same
 * values. They were an MCP-only constant, so `--busy-minutes 100000` was
 * accepted on the CLI and refused over MCP - one lane, two contracts.
 */
export const MAINTENANCE_BUSY_MINUTES_MAX = 24 * 60;
export const MAINTENANCE_BUSY_THRESHOLD_MAX = 10_000;

export interface DailyWindow {
  /** Local hour [0..23] the window opens (inclusive). */
  readonly startHour: number;
  /** Local hour [0..23] the window closes (exclusive). */
  readonly endHour: number;
  readonly tz: string;
}

export interface BusyGate {
  readonly minutes: number;
  readonly threshold: number;
}

export interface HostPressureGate {
  /** Skip when the normalised run queue is at or above this percentage. */
  readonly percent: number;
}

/**
 * The storage block the capacity gate decides from. The whole resolved
 * block rather than a narrow slice because the gate is the forecast's
 * tiers: the cap decides WHETHER the gate exists, and the four thresholds
 * decide where warn and critical sit.
 */
export type CapacityGate = ResolvedBrainStorageConfig;

export interface EvaluateGatesOptions {
  readonly now: Date;
  /** Absent = the window gate is always open (neutral default). */
  readonly window?: DailyWindow;
  readonly busy?: BusyGate;
  /**
   * Absent = the host-pressure gate is not configured and never fires.
   * {@link runMaintenance} fills it from the vault's `maintenance:`
   * block when the caller does not name one.
   */
  readonly pressure?: HostPressureGate;
  /** Injectable measurement; defaults to reading this host. */
  readonly readPressure?: () => HostPressureReading;
  /**
   * Absent = the capacity gate is not configured: it never fires and
   * never measures. {@link runMaintenance} fills it from the vault's
   * `storage:` block when the caller does not name one, and only when
   * that block configures `cap_bytes` - an unbounded vault has no gate.
   */
  readonly capacity?: CapacityGate;
  /** Injectable gate decision; defaults to a fresh on-disk census. */
  readonly readCapacity?: (
    vault: string,
    capacity: CapacityGate,
    now: Date,
  ) => CapacityGateDecision;
  /**
   * The explicit machine-config file the caller resolved from, so the
   * default census measures the store a `search_db_path` in it names.
   */
  readonly configPath?: string;
}

/**
 * What the soft gates decided, and what the pressure and capacity gates
 * saw while deciding it.
 *
 * A reading is returned alongside the verdict rather than folded into
 * it because "the host was too loaded" and "this host cannot say how
 * loaded it is" are different facts that the caller must journal on
 * different lines: one is a decision not to run, the other is a gate
 * that did not evaluate while the lane ran anyway. The capacity decision
 * rides the same way - the tier it read, or that it could not read one.
 */
export interface MaintenanceGateDecision {
  readonly verdict: MaintenanceVerdict;
  /** Absent unless the host-pressure gate was reached and configured. */
  readonly pressure?: HostPressureReading;
  /** Absent unless the capacity gate was reached and configured. */
  readonly capacity?: CapacityGateDecision;
}

/** Cap for persisted per-task error strings (journal + results). */
export const LANE_ERROR_MAX_BYTES = 4096;

/**
 * The heavy passes this lane dispatches.
 *
 * A closed vocabulary rather than four string literals because the names
 * are read on THREE surfaces - the CLI verb's task list, the MCP tool's
 * task list, and `--retry`/`retry_tasks` validation on both - and they
 * were written out by hand on each. Two releases running, the two lists
 * disagreed about what the lane runs, which is the drift a vocabulary
 * exists to make impossible: a fifth task is added here or nowhere.
 *
 * The values come from {@link OPERATION} rather than being retyped, so a
 * lane task is by construction an operation with a safeguard budget and a
 * progress vocabulary of its own. That is not decoration: each surface
 * builds one deadline per task from the task's own name, and a name that
 * was not an operation would resolve a budget nothing reads.
 *
 * One consequence, stated rather than left to be discovered: the
 * tree-wide vocabulary census reads values out of an object LITERAL, so
 * borrowing them here keeps this vocabulary outside its population. The
 * same audit - object, list and guard agree - runs in
 * `tests/mcp/maintenance-parity-census.test.ts`, together with the
 * assertion that every value is still an operation.
 */
export const LANE_TASK = Object.freeze({
  dream: OPERATION.dream,
  reindex: OPERATION.reindex,
  bridges: OPERATION.bridges,
  clusters: OPERATION.clusters,
  relink: OPERATION.relink,
} as const);

export type LaneTask = (typeof LANE_TASK)[keyof typeof LANE_TASK];

/**
 * Membership list for {@link isLaneTask}, in the order the surfaces
 * register their tasks and the order a refusal lists them. The lane
 * itself runs them stale-first, so this is a vocabulary, not a schedule.
 */
export const LANE_TASKS: ReadonlyArray<LaneTask> = Object.freeze([
  LANE_TASK.dream,
  LANE_TASK.reindex,
  LANE_TASK.bridges,
  LANE_TASK.clusters,
  LANE_TASK.relink,
]);

/**
 * Whether `value` names a task this build dispatches. Takes `unknown`
 * because it arrives from a `--retry` argument a person typed or from a
 * `retry_tasks` array a client sent.
 */
export function isLaneTask(value: unknown): value is LaneTask {
  return typeof value === "string" && (LANE_TASKS as ReadonlyArray<string>).includes(value);
}

/**
 * Every identity the lane can run, journal and retry: a built-in
 * {@link LaneTask} or an install-owned `custom:<name>` task declared in
 * the machine config. The built-in vocabulary above is unchanged; a
 * custom identity carries a colon, which no `OPERATION` value does, so
 * the two populations cannot collide.
 */
export type LaneTaskId = LaneTask | CustomLaneTask;

export interface MaintenanceTask {
  readonly name: LaneTaskId;
  /**
   * Run the pass. A pass that spent model budget returns the
   * {@link MaintenanceSpendReceipt} the cost kernel priced for it, and
   * the lane carries the receipt on the attempt's row and its journal
   * line (t_9d155d0e) - per RUN, not per task, because one embedding
   * pass rides one reindex task and the journal row is the audit unit
   * this lane already renders. Returning nothing records no receipt: a
   * pass that spent nothing has nothing to account for. A pass that
   * THROWS records no receipt either, even if it was killed mid-spend -
   * its row carries the named failure, and the receipt's numbers are the
   * kernel's estimate, which only a completed pass can vouch for.
   */
  readonly run: () => Promise<MaintenanceSpendReceipt | void>;
}

export interface RunMaintenanceOptions extends EvaluateGatesOptions {
  readonly holder: string;
  readonly tasks: ReadonlyArray<MaintenanceTask>;
  /**
   * Bypass the window, busy, pressure and capacity gates and every streak
   * refusal - never the lease.
   */
  readonly force?: boolean;
  /**
   * Task names to attempt past their streak refusal, this run only. Every
   * gate still applies; a name that is not a registered task is the
   * caller's to reject, because only the caller knows what it registered.
   */
  readonly retryTasks?: ReadonlyArray<LaneTaskId>;
  readonly leaseTtlMs?: number;
}

export interface MaintenanceTaskResult {
  readonly name: LaneTaskId;
  readonly ok: boolean;
  readonly duration_ms: number;
  readonly error?: string;
  /** True when the task tripped its cooperative safeguard deadline. */
  readonly timed_out?: boolean;
  /** True when the failure streak refused the task instead of running it. */
  readonly refused?: true;
  /** Consecutive journaled failures behind a refusal. */
  readonly failure_streak?: number;
  /** Model spend the task accounted for, when its run returned a receipt. */
  readonly receipt?: MaintenanceSpendReceipt;
}

export interface RunMaintenanceResult {
  readonly verdict: MaintenanceVerdict;
  readonly tasks: ReadonlyArray<MaintenanceTaskResult>;
  /**
   * The capacity report, when the run was skipped for storage capacity:
   * the tier the gate measured, the reading behind it, and the remedy an
   * operator (or an agent relaying to one) can act on. Both front doors
   * attach it verbatim, so the two surfaces cannot disagree about what a
   * skip says.
   */
  readonly capacity?: MaintenanceCapacityReport;
}

/**
 * What an operator does about a lane the capacity gate skipped. The
 * reclamation verbs are the remedy, then a re-run; raising the cap is
 * the operator's own decision and names the file only they should edit.
 *
 * The remedy also names pruning the recovery points, because both
 * reclamation verbs archive all of `Brain/` into `Brain/.snapshots/`
 * before they free anything - a compressed copy of the vault lands in a
 * COUNTED surface first - and a remedy that can grow the vault while it
 * shrinks the ledger is not one an operator can follow blind at 96
 * percent.
 */
export const MAINTENANCE_CAPACITY_REMEDY =
  "free space by running receipt compaction or retiring near-duplicate copies, " +
  "then prune the recovery points both write into Brain/.snapshots " +
  "(snapshots.retention_count bounds them), or raise storage.cap_bytes in " +
  "Brain/_brain.yaml, then re-run";

/** The capacity block both lane front doors attach to a skipped run. */
export interface MaintenanceCapacityReport {
  readonly tier: StorageForecastTier;
  readonly remedy: string;
  /**
   * The reading behind the tier, mirroring the pressure reading's ride
   * through the journal: the percent of the cap the gate measured, and
   * the measured bytes and configured cap it is a percent of. Null when
   * the gate decision carried no reading - a skip is always a measured
   * one in production, so null names a decision supplied from outside
   * the gate, never a tier the gate guessed at.
   */
  readonly capacity_percent: number | null;
  readonly measured_bytes: number | null;
  readonly cap_bytes: number | null;
  /**
   * The pause line the lane decided on (`storage.pause_percent`), when
   * the gate carried one. A tier of `ok` beside a skip names this line
   * as what closed the lane; a null names a decision with no pause line
   * in force, skipped on the critical tier alone.
   */
  readonly pause_percent: number | null;
}

/** The report for the gate decision that skipped a run. */
export function capacityReport(decision: CapacityGateDecision): MaintenanceCapacityReport {
  const reading = decision.reading;
  return {
    tier: decision.tier,
    remedy: MAINTENANCE_CAPACITY_REMEDY,
    capacity_percent: reading?.percentUsed ?? null,
    measured_bytes: reading?.measuredBytes ?? null,
    cap_bytes: reading?.capBytes ?? null,
    pause_percent: decision.pausePercent ?? null,
  };
}

/** True when `now` falls inside the local-time window (wrap-aware). */
export function dailyWindowContains(now: Date, window: DailyWindow): boolean {
  const hour = Number(
    new Intl.DateTimeFormat("en-CA", {
      timeZone: window.tz,
      hour: "2-digit",
      hourCycle: "h23",
    }).format(now),
  );
  if (window.startHour === window.endHour) return true; // degenerate: always open
  if (window.startHour < window.endHour) {
    return hour >= window.startHour && hour < window.endHour;
  }
  // Midnight wrap: 22-04 means [22..24) plus [0..4).
  return hour >= window.startHour || hour < window.endHour;
}

/**
 * Evaluate the soft gates; the lease is checked at run time.
 *
 * The gates are ordered cheapest-first and, more importantly,
 * least-surprising-first: window and busy decide exactly as they did
 * before the pressure gate existed, the host is only probed once both
 * have let the pass through, and the capacity gate - the most expensive,
 * a byte walk over the whole vault - is probed last. A closed earlier
 * gate therefore leaves no pressure reading and no capacity decision,
 * which is honest - nothing was measured.
 */
export function evaluateGates(vault: string, opts: EvaluateGatesOptions): MaintenanceGateDecision {
  if (opts.window !== undefined && !dailyWindowContains(opts.now, opts.window)) {
    return { verdict: MAINTENANCE_VERDICT.skippedWindow };
  }
  const busy = opts.busy ?? {
    minutes: MAINTENANCE_BUSY_MINUTES,
    threshold: MAINTENANCE_BUSY_THRESHOLD,
  };
  const since = new Date(opts.now.getTime() - busy.minutes * 60_000).toISOString();
  const recent = listRecallTelemetry(vault, { since });
  if (recent.length >= busy.threshold) return { verdict: MAINTENANCE_VERDICT.skippedBusy };

  let pressure: HostPressureReading | undefined;
  if (opts.pressure !== undefined) {
    pressure = (opts.readPressure ?? measureHostPressure)();
    // Unmeasurable leaves the gate OPEN. Closing it would stop this vault
    // being maintained at all wherever the metric is degenerate, and
    // treating the degenerate reading as a number would report a loaded
    // host as an idle one - which is the failure the reading exists to
    // make impossible. The caller journals the reason.
    if (pressure.state === HOST_PRESSURE.measured && pressure.percent >= opts.pressure.percent) {
      return { verdict: MAINTENANCE_VERDICT.skippedPressure, pressure };
    }
  }

  const capacity = readCapacityDecision(vault, opts);
  if (capacity?.decision === CAPACITY_GATE_DECISION.skip) {
    return {
      verdict: MAINTENANCE_VERDICT.skippedCapacity,
      ...(pressure !== undefined ? { pressure } : {}),
      capacity,
    };
  }
  return {
    verdict: MAINTENANCE_VERDICT.run,
    ...(pressure !== undefined ? { pressure } : {}),
    ...(capacity !== undefined ? { capacity } : {}),
  };
}

/**
 * The capacity gate's decision, or `undefined` when the gate is not
 * configured: an unconfigured gate never measures, exactly like an
 * unconfigured pressure gate.
 */
function readCapacityDecision(
  vault: string,
  opts: EvaluateGatesOptions,
): CapacityGateDecision | undefined {
  if (opts.capacity === undefined) return undefined;
  if (opts.readCapacity !== undefined) return opts.readCapacity(vault, opts.capacity, opts.now);
  return evaluateStorageCapacityGate(vault, opts.capacity, opts.now, opts.configPath);
}

/** The gate decision from a fresh on-disk census, never the stored aggregate. */
function evaluateStorageCapacityGate(
  vault: string,
  capacity: CapacityGate,
  now: Date,
  configPath: string | undefined,
): CapacityGateDecision {
  return evaluateCapacityGate(vault, {
    now,
    ...(configPath !== undefined ? { configPath } : {}),
    capBytes: capacity.cap_bytes,
    warnPercent: capacity.warn_percent,
    criticalPercent: capacity.critical_percent,
    // The lane's own pause line: background production backs off one
    // band before the wall the ingest refusal keeps.
    pausePercent: capacity.pause_percent,
    warnDays: capacity.warn_days,
    criticalDays: capacity.critical_days,
  });
}

/**
 * Run the registered heavy tasks through the gates. Tasks execute
 * stale-first: least-recently succeeded first (from the journal),
 * never-run before everything, so a task that keeps failing or got
 * starved naturally floats to the front.
 */
export async function runMaintenance(
  vault: string,
  opts: RunMaintenanceOptions,
): Promise<RunMaintenanceResult> {
  const nowIso = opts.now.toISOString();
  // Vault-side policy: the pressure threshold the caller did not name, the
  // storage block the capacity gate decides from, and the streak limit. An
  // unreadable `_brain.yaml` raises here rather than resolving to defaults
  // - every one of these knobs decides whether heavy work starts or a
  // write is refused, so a silent revert would run a pass the operator had
  // gated.
  const policy = loadMaintenanceConfigSafe(vault);
  const storage = loadStorageConfigSafe(vault);
  if (opts.force !== true) {
    const gate: EvaluateGatesOptions = {
      now: opts.now,
      ...(opts.window !== undefined ? { window: opts.window } : {}),
      ...(opts.busy !== undefined ? { busy: opts.busy } : {}),
      ...(opts.readPressure !== undefined ? { readPressure: opts.readPressure } : {}),
      ...(opts.readCapacity !== undefined ? { readCapacity: opts.readCapacity } : {}),
      ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
      ...resolvePressureGate(opts.pressure, policy.host_pressure_percent),
      ...resolveCapacityGate(opts.capacity, storage),
    };
    const decision = evaluateGates(vault, gate);
    // Two lines, never one: a gate that could not evaluate is its own
    // row, so the journal never leaves an operator to infer from a
    // running lane that the pressure gate was open because the host was
    // quiet.
    if (decision.pressure?.state === HOST_PRESSURE.unmeasurable) {
      appendJournal(vault, {
        ts: nowIso,
        holder: opts.holder,
        verdict: MAINTENANCE_VERDICT.pressureUnmeasurable,
        pressure_reason: decision.pressure.reason,
      });
    }
    // The capacity gate's own notice line, for the same reason: an
    // unmeasurable store ran, and the journal has to say its gate was
    // open because nothing could be read - not because the vault is
    // healthy.
    if (
      decision.capacity !== undefined &&
      decision.capacity.tier === STORAGE_FORECAST_TIER.unmeasurable
    ) {
      appendJournal(vault, {
        ts: nowIso,
        holder: opts.holder,
        verdict: MAINTENANCE_VERDICT.capacityUnmeasurable,
        ...(decision.capacity.reason !== undefined
          ? { capacity_reason: decision.capacity.reason }
          : {}),
      });
    }
    // The gate evaluated, so its census is a sample - on a SKIP and on a
    // RUN alike. The M5 blind spot was sampling skips only: on a vault
    // where nobody runs the storage report, no sample was ever recorded,
    // no trend existed and the day-based tiers could never fire. The
    // decision already walked the vault, so recording its census costs
    // one walk and never two; day-bucketing in the forecast keeps the
    // extra rows cheap. Fail-soft by contract; a sample that cannot be
    // written never turns a run into a crash.
    if (decision.capacity?.census !== undefined) {
      sampleStorageUsage(vault, {
        now: opts.now,
        usage: decision.capacity.census,
      });
    }
    if (decision.verdict !== MAINTENANCE_VERDICT.run) {
      // One report serves every skip surface below: the journal row and
      // both front doors read the same numbers, so they cannot disagree
      // about what a skip measured.
      const capacity =
        decision.verdict === MAINTENANCE_VERDICT.skippedCapacity && decision.capacity !== undefined
          ? capacityReport(decision.capacity)
          : undefined;
      appendJournal(vault, {
        ts: nowIso,
        holder: opts.holder,
        verdict: decision.verdict,
        ...(decision.pressure?.state === HOST_PRESSURE.measured
          ? { pressure_percent: decision.pressure.percent }
          : {}),
        ...(capacity !== undefined
          ? {
              capacity_tier: capacity.tier,
              // The reading rides the row the way the pressure percent
              // does - written together, only when the gate took one.
              // All three figures come from one reading, so the guard
              // names each field it writes: the journal entry carries no
              // null reading, only an absent one.
              ...(capacity.measured_bytes !== null &&
              capacity.capacity_percent !== null &&
              capacity.cap_bytes !== null
                ? {
                    capacity_percent: capacity.capacity_percent,
                    capacity_measured_bytes: capacity.measured_bytes,
                    capacity_cap_bytes: capacity.cap_bytes,
                  }
                : {}),
            }
          : {}),
      });
      return {
        verdict: decision.verdict,
        tasks: [],
        ...(capacity !== undefined ? { capacity } : {}),
      };
    }
  }

  const ttl = opts.leaseTtlMs ?? MAINTENANCE_LEASE_TTL_MS;
  if (!acquireLease(vault, { holder: opts.holder, ttlMs: ttl, now: opts.now })) {
    appendJournal(vault, {
      ts: nowIso,
      holder: opts.holder,
      verdict: MAINTENANCE_VERDICT.skippedLease,
    });
    return { verdict: MAINTENANCE_VERDICT.skippedLease, tasks: [] };
  }

  try {
    const ordered = orderStaleFirst(vault, opts.tasks);
    const retry = new Set(opts.retryTasks ?? []);
    const results: MaintenanceTaskResult[] = [];
    for (const task of ordered) {
      const refusal =
        opts.force === true || retry.has(task.name)
          ? undefined
          : refuseOnStreak(vault, task.name, policy.failure_streak_limit);
      if (refusal !== undefined) {
        results.push(refusal.result);
        appendJournal(vault, { ts: nowIso, holder: opts.holder, ...refusal.entry });
        continue;
      }
      const startedAt = Date.now();
      let ok = true;
      let error: string | undefined;
      let timedOut = false;
      let receipt: MaintenanceSpendReceipt | undefined;
      try {
        // Sequential by design: the lane exists to serialize heavy work.
        // eslint-disable-next-line no-await-in-loop
        const produced = await task.run();
        // A `void`-returning task records no receipt; truthiness narrows
        // it - a receipt is always an object.
        if (produced) receipt = produced;
      } catch (exc) {
        ok = false;
        timedOut = exc instanceof SafeguardTimeoutError;
        // Caps keep a pathological error string from flooding the
        // journal and every status render downstream.
        error = capOutput(
          exc instanceof Error ? exc.message : String(exc),
          LANE_ERROR_MAX_BYTES,
        ).text;
      }
      const duration = Date.now() - startedAt;
      results.push({
        name: task.name,
        ok,
        duration_ms: duration,
        ...(error ? { error } : {}),
        ...(timedOut ? { timed_out: true } : {}),
        ...(receipt ? { receipt } : {}),
      });
      appendJournal(vault, {
        ts: nowIso,
        holder: opts.holder,
        verdict: MAINTENANCE_VERDICT.run,
        task: task.name,
        ok,
        duration_ms: duration,
        ...(error ? { error } : {}),
        ...(timedOut ? { timed_out: true } : {}),
        ...(receipt ? { receipt } : {}),
      });
    }
    // The cap rewrite happens only here, while the lease is held -
    // the one point where no other writer can race the journal.
    sweepJournal(vault);
    return { verdict: MAINTENANCE_VERDICT.run, tasks: results };
  } finally {
    releaseLease(vault, { holder: opts.holder, name: MAINTENANCE_LEASE_NAME });
  }
}

/**
 * The pressure gate to evaluate: the caller's, else the vault's, else
 * none. There is deliberately no third source and no default number - an
 * unconfigured gate never fires.
 */
function resolvePressureGate(
  named: HostPressureGate | undefined,
  configured: number | null,
): { pressure?: HostPressureGate } {
  if (named !== undefined) return { pressure: named };
  if (configured !== null) return { pressure: { percent: configured } };
  return {};
}

/**
 * The capacity gate to evaluate: the caller's, else the vault's, and the
 * vault's only when its storage block configures `cap_bytes`. No cap is
 * the documented default and means unbounded: no gate, no byte walk, no
 * refusal - an operator who never asked for a capacity gate never gets
 * one, on any tier.
 */
function resolveCapacityGate(
  named: CapacityGate | undefined,
  configured: ResolvedBrainStorageConfig,
): { capacity?: CapacityGate } {
  if (named !== undefined) return { capacity: named };
  if (configured.cap_bytes !== null) return { capacity: configured };
  return {};
}

/** The task-result and journal rows of a streak refusal, or `undefined` to run. */
function refuseOnStreak(
  vault: string,
  task: LaneTaskId,
  limit: number,
):
  | { result: MaintenanceTaskResult; entry: Omit<MaintenanceJournalEntry, "ts" | "holder"> }
  | undefined {
  const streak = consecutiveTaskFailures(vault, task);
  if (streak < limit) return undefined;
  // The number is in the message because the journal row and the task
  // result are read on different surfaces, and an operator who sees only
  // one of them still has to know how deep the hole is and how to climb
  // out of it.
  //
  // Both spellings of the narrow escape are named, because the message is
  // read on both surfaces and naming only the CLI flag made the refusal a
  // dead end for an MCP caller: it prescribed a remedy that surface did
  // not have. It has `retry_tasks` now, and the sentence says so.
  const error =
    `refused: ${streak} consecutive journaled failures reached the ` +
    `maintenance.failure_streak_limit of ${limit}; fix the cause, then re-run with ` +
    `--retry ${task} (retry_tasks: ["${task}"] over MCP) to attempt this task alone with ` +
    `every other gate still in force, or --force to run the whole lane past every soft gate`;
  return {
    result: { name: task, ok: false, duration_ms: 0, error, refused: true, failure_streak: streak },
    // No `ok` on the row: a refusal is not an attempt, and recording one
    // as a failed attempt would deepen the very streak it reports until
    // no success could ever clear it.
    entry: { verdict: MAINTENANCE_VERDICT.refusedStreak, task, streak, error },
  };
}

function orderStaleFirst(vault: string, tasks: ReadonlyArray<MaintenanceTask>): MaintenanceTask[] {
  const lastSuccess = new Map<string, string>();
  for (const entry of listJournal(vault)) {
    if (entry.task === undefined || entry.ok !== true) continue;
    if (!lastSuccess.has(entry.task)) lastSuccess.set(entry.task, entry.ts); // newest-first list
  }
  return [...tasks].toSorted((a, b) => {
    const aTs = lastSuccess.get(a.name) ?? "";
    const bTs = lastSuccess.get(b.name) ?? "";
    return aTs.localeCompare(bTs);
  });
}