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

feat: unattended maintenance recipes, install-owned lane tasks and an MCP fault guard (v1.65.0) (#224)

Serg Eroshea1ecfe7be173
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 75edd05b..6756b0d0 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.64.0",
+ "version": "1.65.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 55f02c09..08113c9a 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.64.0",
+ "version": "1.65.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd4dfa18..22dbee99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,30 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.65.0] - 2026-10-01
+
+The maintenance lane becomes something an unattended host can schedule and extend, and the MCP server survives the background faults that used to end it: `o2b brain maintenance run --cron-template` prints the recipe that schedules the lane, every recipe can be printed as a systemd user timer, an install can put its own upkeep commands under the lane's gates as `custom:<name>` tasks, and a served `o2b mcp` names and counts a stray promise rejection instead of dying on it, while an uncaught exception still exits, through the hooks that checkpoint the index and release the locks.
+
+### Added
+
+- **`o2b brain maintenance run --cron-template` prints the lane's schedule.** The lane was designed as the cron entry point and had no recipe of its own. `run --cron-template [--interval <N>m|h|d] [--format cron|systemd] [--window H-H --tz ZONE]` prints a script (`~/.local/bin/osb-maintenance-<hash>.sh`, where `<hash>` is the first 8 hex characters of the SHA-256 of the resolved vault path, so each vault gets its own script, Hermes job and systemd units) and its scheduler lines, default interval `1h`: the lane's window, busy, pressure and lease gates decide whether work happens and a gate skip exits 0, so an hourly schedule plus `--window` is the intended pattern. The script embeds the resolved vault, single-quote escaped, because cron runs without the operator's environment; it runs `o2b brain maintenance run --vault '<vault>' --json`, stays silent on exit 0 and prints the captured JSON and keeps the exit code on any other exit, so cron mail or a Hermes job surfaces a failure, a timeout (6) or a refusal (7). It prints and installs nothing: it returns before the lease, the gates, the journal and the metrics. The window and the zone are pasted into the script's command line, so the renderer itself refuses a window that is not `H-H` with hours 0..23 and a zone that is not a plain zone name, rather than printing shell text; it also refuses a zone `Intl` does not know and a vault path with a line break, by name, and its verify line names the vault. A bad interval, window or format, `--interval` or `--format` without `--cron-template`, and `status --cron-template` exit with the lane's usage code 2.
+- **Every recipe prints a systemd user timer with `--format systemd`.** `o2b search reindex --cron-template`, `o2b partner codegraph resync --cron-template` and the new maintenance recipe take `--format cron|systemd` (default `cron`, whose output is byte-identical to before). `systemd` prints the same script section plus a `.service`/`.timer` pair to save under `~/.config/systemd/user/` (`OnBootSec=`, `OnUnitActiveSec=<N><unit>`; no `Persistent=`, which systemd ignores on a monotonic timer), the `systemctl --user daemon-reload` and `enable --now` commands, the `loginctl enable-linger` note and the same verify footer. One spec feeds both renderers, so a recipe cannot say one thing in cron and another in systemd; an interval the cron grammar refuses is refused with the same message in both formats, and an unknown format is refused naming `cron` and `systemd`.
+- **Install-owned custom lane tasks.** An install can declare its own upkeep commands in the machine config file: `maintenance_custom_<name>: <command>`, with optional `maintenance_custom_<name>_cwd` (default the running user's home directory, never the vault unless named) and `maintenance_custom_<name>_timeout_seconds` (default 120, a whole number from 1 to 1200); the declared timeouts together stay within 1200 s, leaving 600 s of the 30-minute lease for the built-in tasks, and a task over that budget is refused by name. They run only with the master switch `maintenance_custom_tasks: true` (env `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`, default off, `0` turns it off on one host), after the four built-in tasks, under the same window, busy, pressure, lease and streak gates, and they journal as `custom:<name>`. A task runs through `sh -c` (`cmd.exe /d /s /c` on Windows) with `O2B_VAULT` set, stdin closed, stdout discarded and every variable whose name declares a credential dropped from its environment; a `_cwd` that does not exist or is not a directory fails the task by name before anything is spawned; a non-zero exit fails the task as `exit <N>` with the redacted tail of its stderr, capped at 4096 bytes, and the outcome is the shell's exit status: background processes the command leaves are killed with its process group (POSIX) at its timeout or when the o2b process exits. A custom task makes no model call and records no spend receipt. Commands are never read from the vault, which syncs between devices and is writable through the MCP write tools, and no MCP parameter can add, edit or read one. `--retry custom:<name>` and `retry_tasks` accept a declared task; at most 8 can be declared.
+- **`/health` on the HTTP transport carries the server's fault counts.** A `faults` block (`unhandled_rejection`, `uncaught_exception`, `last_fault_at`) joins the drain fields, so a supervisor can see a server that is surviving rejections before an operator reads its log.
+
+### Changed
+
+- **A served `o2b mcp` survives an unhandled promise rejection.** Both served transports install a fault guard: a rejection nobody awaited is logged by name on stderr (`[mcp] unhandled_rejection #N: <reason> (server keeps serving)` with the first stack frame, a non-Error reason named too, tokens and URL credentials masked in every line the guard writes), rate-limited to 5 full lines per 60 seconds and then one summary line, counted, and the server goes on answering. An uncaught exception is logged by name and exits **70**: the process state is unknown after one, so the server does not keep serving, and it exits rather than dying so the `exit` hooks still checkpoint the search index and release the locks. It does not drain first, because a drain would keep serving from that unknown state. `o2b mcp --probe` installs no guard.
+- **One task builder serves both maintenance surfaces.** The CLI verb and `brain_maintenance` used two hand-kept copies of the dream, reindex, bridges and clusters task bodies; both now build their tasks, including declared custom tasks, from one shared builder, so the two surfaces cannot drift apart again. `--retry` and `retry_tasks` validate against the tasks this install actually registered, and a request longer than that is refused with the count; the `retry_tasks` schema `maxItems` advertises the built-ins plus the custom-task cap.
+- **`brain_maintenance` returns `custom_task_errors`.** A refused custom declaration (a bad name, an empty command, an out-of-range timeout, a relative `_cwd`, a `_cwd` or `_timeout_seconds` key without its command, a ninth task, a timeout over the budget) is named there, and on the CLI as `custom task refused: <reason>` on stderr; the valid tasks still run. `status` says `custom tasks declared but maintenance_custom_tasks is off` when keys are declared and the switch is off, and names `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS` when the environment turned it off.
+- **A timeout counts toward a custom task's failure streak.** A built-in task keeps the rule that a safeguard timeout neither counts toward nor resets its streak, because its budget is per operation and a slow vault is not a broken task; a custom command that always hangs would otherwise never be refused and would spend its whole timeout of lease time on every pass.
+- **Docs:** `docs/cli-reference.md` documents the maintenance recipe, `--format cron|systemd` on every recipe, custom lane tasks, the Hermes jobs path and exit code 70 of `o2b mcp`; `docs/mcp.md` gains a "Background faults" section and documents custom tasks on `brain_maintenance`; `docs/updating.md` names the new opt-ins; `docs/hermes-cron.md` points at the maintenance recipe and the systemd format; the README names this release.
+
+### Fixed
+
+- **The codegraph resync recipe single-quotes the project path.** `o2b partner codegraph resync --cron-template` now quotes the repository path like the other recipe arguments.
+- **`o2b discipline install` works on hosts where Hermes does not run as root.** The default jobs file was fixed at `/root/.hermes/cron/jobs.json`; it is now `~/.hermes/cron/jobs.json` of the running user, still overridden by `OSB_HERMES_JOBS`, and a home directory that cannot be resolved is a named error that points at `OSB_HERMES_JOBS`. Root hosts see no change. An empty `OSB_HERMES_JOBS` now reads as unset instead of as a path.
+
## [1.64.0] - 2026-10-01
Search ranks by what the operator marked and remembers when things happened, diagnostics prove that this machine can still act instead of only that its files look right, and the write path names the residue it lands: the index persists each document's resolved event-time window and `pinned` flag (schema v13), a bounded pinned boost joins ranking beside two opt-in guards and one wall-clock deadline over the composite hybrid path, `o2b doctor selftest` drives a throwaway store end to end, `--readiness` probes the commands the installer registered and the write-back contract the workspace instruction files carry, the maintenance lane distinguishes a pass that failed from one that did not finish and, once opted in, announces and receipts its embedding spend, and write receipts name near-duplicate bodies while hygiene scans report slug-collision residue and inline-tag drift.
@@ -7900,6 +7924,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.65.0]: https://github.com/itechmeat/open-second-brain/compare/v1.64.0...v1.65.0
[1.64.0]: https://github.com/itechmeat/open-second-brain/compare/v1.63.0...v1.64.0
[1.63.0]: https://github.com/itechmeat/open-second-brain/compare/v1.62.0...v1.63.0
[1.62.0]: https://github.com/itechmeat/open-second-brain/compare/v1.61.0...v1.62.0
diff --git a/README.md b/README.md
index 6382e4a4..02153f4d 100644
--- a/README.md
+++ b/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.64.0 teaches search what the operator marked and when things happened (persisted per-document event-time windows, a bounded pinned boost, opt-in rerank and metadata-boost guards, one hybrid-path deadline), teaches diagnostics to prove function instead of only inspecting state (`o2b doctor selftest`, probes for the installer's registered commands and the workspace write-back contract, honest maintenance timeouts with announced and receipted embedding spend), and names residue where it lands (near-duplicate write advisories, slug-collision and inline-tag hygiene findings, hub candidates staged at inbox drain). Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.65.0 makes the maintenance lane something an unattended host can schedule and extend (a cron recipe of its own, a systemd user timer for every recipe, install-owned `custom:<name>` upkeep tasks under the lane's gates) and keeps a served `o2b mcp` alive through a stray promise rejection, naming and counting it on stderr and in `/health`, while an uncaught exception still exits through the hooks that checkpoint the index and release the locks. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/claude.md b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/claude.md
new file mode 100644
index 00000000..1a2bf943
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/claude.md
@@ -0,0 +1,122 @@
+### Item 1 / Variant 1: Dedicated spec module beside the other two consumers
+- **Approach**: Add `src/cli/brain/maintenance-cron-template.ts` exporting a `CronRecipeSpec` (title, `cronName` `osb-maintenance`, `operatorScriptPath`, script body that runs `o2b brain maintenance run --vault <resolved> [--window H-H --tz ZONE]`, verify command `o2b brain maintenance status`), mirroring `search-cron-template.ts` and `partner-codegraph-cron.ts`. The verb gains `--cron-template [--interval]`, prints the rendered recipe before any vault or lease work, and maps `CronTemplateError` to usage exit 2. The Hermes jobs default becomes `join(homedir(), ".hermes", "cron", "jobs.json")` with an optional `HERMES_HOME` override.
+- **Trade-offs**:
+ - Pro: identical shape to the two existing consumers, so the lane owner touches only the verb, one new file and the manifest.
+ - Pro: spec body is unit-testable without the lane; existing reindex fixtures untouched.
+ - Con: a third near-identical spec file; the three consumers still share nothing beyond the kernel.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 1 / Variant 2: Spec inlined in the maintenance verb
+- **Approach**: Build the `CronRecipeSpec` inline inside `src/cli/brain/verbs/maintenance.ts` where the resolved vault, `--window` and `--tz` are already parsed, and call `renderCronRecipe` directly. Same Hermes path fix.
+- **Trade-offs**:
+ - Pro: fewest files; the recipe body sits next to the flags it embeds.
+ - Con: the verb file is already large and owns exit-code logic; recipe text mixed in hurts readability and the byte-pinned fixture test would import the verb.
+ - Con: breaks the one-consumer-one-module pattern the other two recipes established.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 1 / Variant 3: Generic self-recipe helper on the kernel
+- **Approach**: Extend `cron-recipe.ts` with `specFromCommand({cronName, argv, verify})` that turns any `o2b` argv into a spec, then have all three consumers call it. Maintenance passes its own argv (vault, window, tz).
+- **Trade-offs**:
+ - Pro: removes future duplication for any verb that wants a recipe.
+ - Con: refactoring the two existing consumers risks the byte-pinned search fixtures and widens the lane's file ownership into files other lanes may touch (item 4 also edits the kernel).
+ - Con: over-general for a wave whose kernel is already being changed by item 4.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 1 / Recommended: Variant 1
+**Rationale**: It matches the proven consumer pattern exactly, keeps the byte-pinned search fixtures out of the diff, and stays inside files only this lane owns. Variant 3 collides with item 4's kernel edits in the same worktree; Variant 2 buries operator-facing text in an already dense verb file.
+
+### Item 2 / Variant 1: Fault state in `src/mcp`, installer in `src/cli`, mirroring the drain split
+- **Approach**: Add `src/mcp/fault-state.ts` with a small `FaultCounter` (rejections survived, suppressed-by-rate-limit count, last fault summary) that `http.ts` reads into the `/health` body as `faults: {rejections, suppressed}`. Add `src/cli/mcp-fault-guard.ts` with `installMcpFaultGuard({counter, stderr, exit})`: `unhandledRejection` logs one named line (`o2b mcp: unhandled rejection survived: <message>`), rate-limited to N per minute with a periodic "suppressed K more" line; `uncaughtException` logs and calls `exit(EXIT_FAULT = 70)` so WAL checkpoint and lock unlink hooks run. `cmdMcp` installs it next to `installMcpSignalDrain` and uninstalls on normal close. Tests: in-process with injected stderr/exit; spawned-process test runs a tiny Bun script that imports the installer and throws asynchronously, asserting exit 70 and the stderr line (no production inject seam).
+- **Trade-offs**:
+ - Pro: respects `src/mcp` never importing `src/cli` while letting `/health` see the count; same seam style as `mcp-drain.ts`.
+ - Pro: exit via `process.exit` keeps the existing exit-hook ordering guarantee.
+ - Con: two small modules and a shared counter object to thread through `serveHttp`.
+ - Con: rate-limit window and cap are new constants to name and document.
+- **Complexity**: medium
+- **Risk**: low
+
+### Item 2 / Variant 2: Everything inside `src/mcp/fault-guard.ts`
+- **Approach**: One module in `src/mcp` owns the counter, the handlers and the exit call; `cmdMcp` calls `installFaultGuard()` and `http.ts` imports the counter from the same module.
+- **Trade-offs**:
+ - Pro: single file, trivial `/health` wiring.
+ - Con: a transport-layer module registering process-global handlers is exactly the "two signal conventions" smell `mcp-drain.ts` documents avoiding; exit codes would be defined outside `src/cli/interrupt.ts` where the project's exit vocabulary lives.
+ - Con: harder to inject `exit` from a CLI-side test without exporting the seam from `src/mcp`.
+- **Complexity**: small
+- **Risk**: medium
+
+### Item 2 / Variant 3: Extend `installMcpSignalDrain` to cover faults
+- **Approach**: Widen `McpSignalDrainOptions` with fault handling so one installer registers signals, `unhandledRejection` and `uncaughtException`; on uncaught exception it runs the same drain-then-exit path with code 70.
+- **Trade-offs**:
+ - Pro: one install/uninstall call site, and an uncaught exception could drain in-flight requests before exiting.
+ - Con: draining after an uncaught exception runs code in a possibly corrupted process; the premise asks for log-and-exit, not drain.
+ - Con: couples two unrelated concerns in a module whose docblock is precise about its narrow job; existing drain tests must be revisited.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 2 / Recommended: Variant 1
+**Rationale**: It reproduces the architecture the project already chose for signals, keeps the import direction rule intact, and gives `/health` the count through a plain shared object. It also avoids draining inside a process that just threw, which is the one behaviour Variant 3 would add that the premise explicitly does not want.
+
+### Item 3 / Variant 1: Prefix keys in the install-owned config, shared task builder
+- **Approach**: Declare custom tasks as `maintenance_task_<name>: <shell command>` in the flat config file (XDG config dir, never the vault), with the existing `safeguard_timeout_<name>_seconds` convention supplying the per-task deadline. Add `src/core/brain/maintenance/tasks.ts` with `buildLaneTasks(vault, config)` returning built-ins plus custom tasks, used by both the CLI verb and the MCP tool; widen `LaneTask` to `string` (keep `BUILTIN_LANE_TASK` for the four), validate `--retry`/`retry_tasks` against the built list and cap at its length. Custom tasks run via `shellArgv` with the vault path in env, captured output capped and redacted, non-zero exit or timeout recorded as a named failure.
+- **Trade-offs**:
+ - Pro: reuses the per-operation timeout key pattern and `discoverConfig` that already returns every key; no new file, no new parser.
+ - Pro: removes the CLI/MCP duplication as a side effect.
+ - Con: name validation (`^[a-z][a-z0-9_-]{0,31}$`, no collision with built-ins) and key scanning need tests; a reserved prefix in a flat namespace is slightly implicit.
+ - Con: MCP tool description must be trimmed to mention custom tasks within 300 characters.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 3 / Variant 2: Separate install-owned tasks file
+- **Approach**: Read `maintenance-tasks.yaml` from the same config directory, one `name: command` line per task through the existing flat parser; the rest (shared builder, widened `LaneTask`, retry validation) as in Variant 1.
+- **Trade-offs**:
+ - Pro: clean separation from the main config; the file's sole purpose is obvious to an operator and to `doctor`.
+ - Con: a second discovery path to document, test for env/XDG precedence, and surface in `doctor`; more lane-owned files touched (config discovery).
+ - Con: the per-task timeout still has to live in the main config or grow a second syntax.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 3 / Variant 3: CLI-only custom tasks, MCP keeps built-ins
+- **Approach**: Same prefix-key declaration and shared builder, but the MCP tool passes `customTasks: false` so `brain_maintenance` runs and retries only the four built-ins; the cron lane via CLI is the only runner of operator commands.
+- **Trade-offs**:
+ - Pro: no MCP description change; operator commands never run from an agent-triggered call.
+ - Con: the two surfaces disagree on what the lane is, and a streak refusal visible in the journal cannot be retried from MCP.
+ - Con: security gain is nominal since the command source is the install-owned config either way.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 3 / Recommended: Variant 1
+**Rationale**: It satisfies the security constraint by construction (commands come only from the install-owned config, never from vault or tool arguments) while reusing two existing conventions, the flat config and the per-operation timeout key. Variant 2 adds a discovery surface for little gain, and Variant 3 leaves the two lane surfaces inconsistent.
+
+### Item 4 / Variant 1: Sibling renderer sharing the spec
+- **Approach**: Add `renderSystemdRecipe(spec, interval, opts)` beside `renderCronRecipe` in `cron-recipe.ts`, reusing the same `CronRecipeSpec`, the heredoc script section and `parseInterval`'s human label, but emitting `~/.config/systemd/user/<cronName>.service` and `.timer` heredocs (`OnBootSec`/`OnUnitActiveSec=<interval>`, `Persistent=true`) plus `systemctl --user daemon-reload && enable --now`. A `--format cron|systemd` flag on the three recipe verbs dispatches between the two; default `cron`, unknown value exits with the verb's usage code.
+- **Trade-offs**:
+ - Pro: `renderCronRecipe` is not edited, so the byte-pinned search fixtures stay identical by construction.
+ - Pro: `OnUnitActiveSec` takes `<N>m|h|d` directly, so the day-bound refusal in `parseInterval` is still honoured for consistency without any cron expression math.
+ - Con: the shared script section is extracted into a helper, a small refactor of the existing renderer body.
+ - Con: three verbs each gain a flag plus a manifest entry; item 1's new verb must adopt it too.
+- **Complexity**: medium
+- **Risk**: low
+
+### Item 4 / Variant 2: Format parameter on `renderCronRecipe`
+- **Approach**: Add an optional `format` argument to `renderCronRecipe`; when `systemd`, swap the crontab and Hermes sections for unit-file sections. Verbs pass the parsed `--format`.
+- **Trade-offs**:
+ - Pro: one entry point, minimal call-site change.
+ - Con: branching inside the renderer that the byte-pinned fixtures cover; any slip in the default path breaks them.
+ - Con: the name `renderCronRecipe` becomes misleading.
+- **Complexity**: small
+- **Risk**: medium
+
+### Item 4 / Variant 3: Format-agnostic section table
+- **Approach**: Rework the kernel into `renderRecipe(spec, interval, {format})` with a per-format table of section builders (`cron`, `systemd`), and re-express today's output as the `cron` entry.
+- **Trade-offs**:
+ - Pro: adding a future format (launchd) is one table entry.
+ - Con: a wholesale rewrite of the renderer with byte-identical output as the acceptance test, in the same wave where item 1 adds a consumer.
+ - Con: nothing in scope needs a third format.
+- **Complexity**: large
+- **Risk**: medium
+
+### Item 4 / Recommended: Variant 1
+**Rationale**: It leaves the existing renderer path untouched, which is the only way to guarantee the byte-pinned fixtures without a careful diff, and it reuses the spec so each consumer declares nothing new. Variant 2 saves little code while putting the fixtures at risk, and Variant 3 is a rewrite for a format count of two.
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/prompt.md b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/prompt.md
new file mode 100644
index 00000000..5ee017e5
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/prompt.md
@@ -0,0 +1,58 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Release wave "Unattended maintenance and MCP fault guards" for Open Second Brain (target v1.65.0). Four items ship in one pull request. Each item below is the verified premise (the original upstream-inspired card corrected against the live source), not the raw card.
+
+## Item 1: Cron recipe for the maintenance lane
+
+`o2b brain maintenance run` is documented as "the cron entry point" (it runs dream, reindex, bridges and clusters under a lease and a `--window H-H --tz ZONE` gate) but has no `--cron-template`. A shared print-never-install kernel already exists in `src/cli/cron-recipe.ts` (`CronRecipeSpec`, `parseInterval` for `<N>m|h|d`, `renderCronRecipe` printing a watchdog script, a native crontab line and a `hermes cron create` line, `operatorScriptPath`). Two verbs consume it: `search reindex --cron-template` (default 30m) and `partner codegraph resync --cron-template` (default 6h). Add `--cron-template [--interval <N>m|h|d]` to `brain maintenance run`, default interval 1h, embedding the resolved vault and the optional `--window/--tz`; a bad interval exits with the lane's usage code 2. Also fix `src/cli/discipline-install.ts`, whose default Hermes jobs file is hardcoded to `/root/.hermes/cron/jobs.json`: derive it from the home directory. No installer, no `--scheduler` flag.
+
+## Item 2: Process-level fault guard for the MCP server
+
+Nothing registers `unhandledRejection` or `uncaughtException`, so a stray rejection kills `o2b mcp` with the runtime default and no named line; Claude Code and Codex never restart a dead MCP server mid-session (the Hermes bridge restarts once). Signal draining already lives CLI-side in `src/cli/mcp-drain.ts` (`installMcpSignalDrain`, injected `stderr`/`exit`). Exit hooks exist: WAL checkpoint (`src/core/search/store-exit.ts`), lock unlink (`src/core/brain/sync-lockfile.ts`). HTTP transport has a `/health` endpoint that reports drain state. Desired: rejections are survived (rate-limited named stderr log, counted), an uncaught exception logs and exits with a distinct code (70) through the normal exit hooks, the fault count is visible on `/health`, with an in-process test and a spawned-process regression test.
+
+## Item 3: Install-owned custom tasks in the maintenance lane
+
+The lane kernel `runMaintenance` (src/core/brain/maintenance/lane.ts) already runs whatever task array the caller passes; the journal and streak logic key on plain strings. Blockers: the CLI verb (src/cli/brain/verbs/maintenance.ts) and the MCP tool (src/mcp/brain/admin-tools.ts) each build the four built-in tasks inline (duplicated); `--retry`/`retry_tasks` validate with `isLaneTask` and cap at four; each built-in task's safeguard timeout is keyed by an `OPERATION` member; the MCP tool description is 295 of 300 allowed characters. Config is a flat `key: value` machine file (no nested lists). Precedent for operator-configured shell commands exists (`bench_judge_cmd`, shared `shellArgv` in src/core/reliability/command-bridge.ts) and an output redactor exists. Desired: an operator declares their own recurring command so it runs under the lane's window, busy, pressure, lease and streak gates. Security constraint: the vault is synced and writable by MCP write tools, so commands must never come from the vault.
+
+## Item 4: Repository-declared schedules (narrowed)
+
+Upstream lets a repository declare background schedules that the tool discovers. Open Second Brain has no per-repository config convention, and a discovery verb fed by repository content would carry foreign shell commands into a printed recipe. The orchestrator has already refused the discovery part. What survives: a systemd user timer rendering (`.service` + `.timer`) in the shared recipe kernel, offered as `--format cron|systemd` on the recipe surfaces.
+
+# Project context
+
+Open Second Brain: TypeScript on Bun (CI pins Bun 1.4.0), CLI `o2b` plus an MCP server (stdio and HTTP), Obsidian-compatible Markdown vault, SQLite index.
+Recent commits:
+4499698c feat: search that honours pins and event time, diagnostics that prove action, writes that name their residue (v1.64.0) (#223)
+a0b3c2e0 feat: exactly-one binding for mentions and imports, once-only write receipts, selectable search breadth and per-device ledgers (v1.63.0) (#222)
+f4f9e3e6 feat: silent failures surface by name in redaction, receipts, ingest, search store, doctor (v1.62.0) (#220)
+Related files:
+src/cli/cron-recipe.ts, src/cli/search-cron-template.ts, src/cli/partner-codegraph-cron.ts, src/cli/discipline-install.ts, src/cli/brain/verbs/maintenance.ts, src/cli/command-manifest.ts, src/cli/main.ts (cmdMcp), src/cli/mcp-drain.ts, src/mcp/http.ts, src/core/brain/maintenance/lane.ts, src/core/brain/maintenance/journal.ts, src/core/config.ts (maintenance_embeddings flag pattern), src/core/reliability/command-bridge.ts, src/mcp/brain/admin-tools.ts, src/mcp/registry-guard.ts
+Conventions:
+- Recipes print and never install; the operator copies them into their scheduler.
+- Errors surface by name; no silent skips. Every flag declared in the command manifest (a completeness test enforces it).
+- MCP tool descriptions capped at 300 characters, property descriptions at 160.
+- `src/mcp` imports nothing from `src/cli`.
+- Version bump and CHANGELOG ride inside the feature PR.
+Constraints:
+- No new dependencies. No plugin system. All user-facing strings English.
+- Existing byte-pinned recipe fixtures (search reindex) must stay byte-identical.
+- Implementation runs as four parallel lanes with disjoint file ownership in one worktree.
+
+# Required output format
+
+For EACH of the four items produce 2 or 3 distinct variants (fewer than the usual three is fine where the space is narrow). For each variant:
+
+### Item K / Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the variants of each item, add exactly one recommendation for that item:
+
+### Item K / Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-fault-handlers.txt b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-fault-handlers.txt
new file mode 100644
index 00000000..63bc8d2a
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-fault-handlers.txt
@@ -0,0 +1,15 @@
+Scanning files...
+Preparing local/potion-code-16m-v2
+query groups (1):
+Q1 [primary]: process unhandledRejection uncaughtException handler
+hits: 10
+
+#1 matchedBy=fts+vector src/cli/mcp-drain.ts:64-82
+64 interface McpSignalDrainHandle {
+
+#2 matchedBy=fts+vector docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/prompt.md:11-14
+heading: Item 2: Process-level fault guard for the MCP server
+heading_level: 2
+scope: Task
+11 ## Item 2: Process-level fault guard for the MCP server
+
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-isLaneTask.txt b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-isLaneTask.txt
new file mode 100644
index 00000000..6ed7b4c3
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-isLaneTask.txt
@@ -0,0 +1,17 @@
+src/mcp/brain/admin-tools.ts
+ 46: isLaneTask,
+ 355-468 [function toolBrainMaintenance]
+ 423: const unknownRetries = requestedRetries.filter((name) => !isLaneTask(name));
+ 431: const retryTasks: ReadonlyArray<LaneTask> = requestedRetries.filter(isLaneTask);
+tests/mcp/maintenance-parity-census.test.ts
+ 55: isLaneTask,
+ 225: expect(`${task} is a lane task: ${isLaneTask(task)}`).toBe(`${task} is a lane task: true`);
+ 232: expect(`${outsider} is a lane task: ${isLaneTask(outsider)}`).toBe(
+src/cli/brain/verbs/maintenance.ts
+ 42: isLaneTask,
+ 331-417 [function cmdBrainMaintenance]
+ 379: const unknownRetries = requested.filter((name) => !isLaneTask(name));
+ 390: const retryTasks = requested.filter(isLaneTask);
+src/core/brain/maintenance/lane.ts
+ 182: * Membership list for {@link isLaneTask}, in the order the surfaces
+ 198: export function isLaneTask(value: unknown): value is LaneTask {
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-renderCronRecipe.txt b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-renderCronRecipe.txt
new file mode 100644
index 00000000..f4483e31
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-renderCronRecipe.txt
@@ -0,0 +1,20 @@
+src/cli/search-cron-template.ts
+ 25: renderCronRecipe,
+ 54-56 [function renderCronTemplate] 55: return renderCronRecipe(SEARCH_REINDEX_RECIPE, interval, opts);
+src/cli/cron-recipe.ts
+ 161: * {@link renderCronRecipe} from a single source.
+ 229: export function renderCronRecipe<TOptions extends CronRecipeOptions>(
+src/cli/partner-codegraph-cron.ts
+ 35: renderCronRecipe,
+ 209-215 [function renderCodegraphResyncTemplate] 214: return renderCronRecipe(CODEGRAPH_RESYNC_RECIPE, interval, { ...opts, projectPath });
+tests/cli/cron-recipe.test.ts
+ 22: renderCronRecipe,
+ 53: describe("renderCronRecipe", () => {
+ 55: const out = renderCronRecipe(SPEC, "30m", {});
+ 70: const out = renderCronRecipe(SPEC, "30m", {});
+ 81: const out = renderCronRecipe(SPEC, "30m", {});
+ 96: const out = renderCronRecipe(SPEC, "6h", {});
+ 105: const out = renderCronRecipe(SPEC, "30m", {});
+ 111: const out = renderCronRecipe(SPEC, "30m", { o2bBin: "/opt/probe/o2b" });
+ 117: expect(() => renderCronRecipe(SPEC, "90m", {})).toThrow(CronTemplateError);
+ 118: expect(() => renderCronRecipe(SPEC, "nonsense", {})).toThrow(CronTemplateError);
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-systemd.txt b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-systemd.txt
new file mode 100644
index 00000000..c4463ed4
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/cli-output/zg-systemd.txt
@@ -0,0 +1,15 @@
+Scanning files...
+Preparing local/potion-code-16m-v2
+query groups (1):
+Q1 [primary]: systemd timer unit OnUnitActiveSec render
+hits: 10
+
+#1 matchedBy=fts+vector docs/brainstorm/release-1-0-stability-trust/cli-output/claude.md:1-11
+heading: Variant 1: Independent vertical slices
+heading_level: 3
+1 ### Variant 1: Independent vertical slices
+
+#2 matchedBy=fts+vector docs/brainstorm/release-1-0-stability-trust/variants.md:7-18
+heading: Variant 1: Independent vertical slices (consultant verbatim)
+heading_level: 2
+scope: Release 1.0.0 - Stability & Trust - variant audit trail
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/design.md b/docs/brainstorm/unattended-maintenance-mcp-guards/design.md
new file mode 100644
index 00000000..d4c64edb
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/design.md
@@ -0,0 +1,126 @@
+# Unattended maintenance and MCP fault guards - scheduler recipes for the lane, install-owned lane tasks, and an MCP server that survives a stray rejection
+
+**Status:** draft
+**Author:** release orchestrator (via feature-release-playbook)
+**Audience:** implementation
+**Target release:** 1.65.0 (the `package.json` bump happens in PR preparation, not in implementation)
+
+## Problem statement
+
+Open Second Brain has an unattended maintenance lane (`o2b brain maintenance run`) whose own docblock calls it the cron entry point, yet the CLI prints a scheduler recipe for `search reindex` and `partner codegraph resync` but not for the lane, and the only verb that writes a schedule (`o2b discipline install`) hardcodes a Hermes jobs file under `/root`. The lane runs a fixed set of four built-in tasks, so an install cannot put its own upkeep under the lane's window, busy, pressure, lease and streak gates. Separately, the `o2b mcp` server registers no process-level fault handler: one stray promise rejection anywhere in core ends the server with the runtime default and no named line, and Claude Code and Codex never restart a dead MCP server mid-session.
+
+## Premise verification
+
+Every card was checked against the live source at `4499698c` (v1.64.0) before the brainstorm. Two of the four premises were corrected, one was confirmed, one was narrowed.
+
+| Card | Verdict | Correction that shapes this design |
+|---|---|---|
+| portable cron/systemd scheduling | partly false | A print-never-install recipe kernel already exists (`src/cli/cron-recipe.ts`, `renderCronRecipe`) with a native crontab path and two consumers. The real gap is that `brain maintenance run` (the cron entry point, `src/cli/brain/verbs/maintenance.ts:15-17`) has no `--cron-template`. Dream is a lane task and needs no separate recipe. An installer and `--scheduler` contradict the print-never-install rule. The `/root` default jobs path (`src/cli/discipline-install.ts:17`) is real. |
+| MCP fault guards | confirmed | Zero `unhandledRejection`/`uncaughtException` listeners in `src`, `hooks`, `plugins`, `scripts`, `bin`. Anchor `src/mcp/server.ts:294` is stale (the cited function is at `:418`). The trigger is a rejection escaping tool handlers or core, not a specific server loop (`src/mcp/stdio.ts` already catches per line). The Hermes bridge restarts the child once; Claude Code and Codex do not. |
+| deployment-owned lane routines | partly false | The lane kernel is not a fixed pipeline: `runMaintenance` (`src/core/brain/maintenance/lane.ts:313`) runs whatever tasks the caller passes, and the journal keys on plain strings. The blockers are the duplicated inline task lists (CLI `maintenance.ts:306-375`, MCP `admin-tools.ts:476-545`), `isLaneTask` validation and the four-entry cap on `--retry`/`retry_tasks`, the `OPERATION`-keyed safeguard, and a 295 of 300 character MCP description. "Max retries" in the card is `failure_streak_limit`. |
+| branch-local schedule discovery | narrowed, discovery refused | The kernel renders intervals only and has no systemd form. Open Second Brain has no per-repository config convention, and the kernel's script body is consumer-authored shell, so a discovery verb would carry repository-authored commands into a recipe the operator pastes. Only the systemd timer rendering survives (see the refusal below). |
+
+Spot checks repeated during design (all confirmed at HEAD): `DEFAULT_JOBS_FILE` at `discipline-install.ts:17`; `renderCronRecipe` at `cron-recipe.ts:229` and `ParsedInterval` carrying only `cron`, `human`, `hermesSchedule`; the timeout rule in `consecutiveTaskFailures` (`journal.ts:271`, a timed-out row neither counts nor ends a streak); `resolveMaintenanceEmbeddings` via `resolveConfigFlag` (`config.ts:1102-1119`, `:669`); `shellArgv` private at `command-bridge.ts:38`; `MAINTENANCE_LEASE_TTL_MS = 30 min` (`lane.ts:75`); `installMcpSignalDrain` call sites in `cmdMcp` (`main.ts:880`, `:903`); `HEALTH_PATH` at `http.ts:166`; the current `brain_maintenance` description measures 295 characters. zg queries for systemd rendering and process fault handlers returned no source hits (`cli-output/zg-*.txt`).
+
+## Scope
+
+1. **Maintenance lane cron recipe.** `o2b brain maintenance run --cron-template [--interval <N>m|h|d] [--window H-H --tz ZONE] [--format cron|systemd]` prints a recipe and writes nothing. Backed by a new `src/cli/maintenance-cron.ts` (`MAINTENANCE_CRON_NAME = "osb-maintenance"`, `DEFAULT_MAINTENANCE_INTERVAL = "1h"`, `MAINTENANCE_RECIPE`, `renderMaintenanceCronTemplate`). The script body runs `o2b brain maintenance run --vault '<vault>' [--window H-H --tz ZONE] --json`, keeps the exit code, stays silent on exit 0 and prints the JSON on any other exit so cron mail or a Hermes job surfaces it. A bad interval, a bad window, a bad format, or `--cron-template` on `status` exits with the lane's usage code 2. Flags are declared in the command manifest.
+2. **Hermes jobs path from the home directory.** `discipline-install.ts` derives the default jobs file from `homedir()` joined with `.hermes/cron/jobs.json`; `OSB_HERMES_JOBS` still overrides. When the home directory cannot be resolved (empty `homedir()`), the verb fails with a named error naming `OSB_HERMES_JOBS` as the way out.
+3. **systemd user timer rendering.** A shared `renderSystemdTimer(spec, interval, opts)` in `src/cli/cron-recipe.ts`, a sibling of `renderCronRecipe` that takes the same `CronRecipeSpec`, so a recipe cannot say one thing in cron and another in systemd. `renderCronRecipe` keeps its output byte for byte; the only edit to it is extracting the header and the script section into a private helper both renderers call. `--format cron|systemd` (default `cron`) selects the renderer. `systemd` prints the same watchdog script section plus a `.service`/`.timer` pair (`OnBootSec=`, `OnUnitActiveSec=<N><unit>`, `Persistent=true`) to save under `~/.config/systemd/user/`, the `systemctl --user daemon-reload` and `enable --now` commands, the `loginctl enable-linger` note, and the same verify footer. Offered on all three recipe surfaces: the new maintenance recipe, `search reindex --cron-template` and `partner codegraph resync --cron-template` (a small change: each consumer exports a format-aware render function and its verb forwards one flag).
+4. **MCP fault guard.** New `src/cli/mcp-fault-guard.ts` with `installMcpFaultGuard`, `EXIT_INTERNAL_FAULT = 70`, `FAULT_KIND`, rate-limited logging (`REJECTION_LOG_BURST = 5` full lines per `REJECTION_LOG_WINDOW_MS = 60_000`, then one summary line per window). An unhandled rejection is logged by name with its first stack frame, counted, and the server keeps serving. An uncaught exception is logged by name and exits 70 through `process.exit`, so the existing exit hooks (WAL checkpoint, lock unlink) run; no drain is attempted. Installed in `cmdMcp` next to both drain installs and released in the same `finally` blocks; probe mode does not install it. The HTTP `/health` response carries `faults: { unhandled_rejection, uncaught_exception, last_fault_at }` through a getter injected from the CLI, so `src/mcp` still imports nothing from `src/cli`.
+5. **Install-owned custom lane tasks.** Declared in the machine config file only, as flat keys: `maintenance_custom_<name>: <command>`, optional `maintenance_custom_<name>_cwd` and `maintenance_custom_<name>_timeout_seconds`. Master switch `maintenance_custom_tasks` (default off) with env override `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`, the `maintenance_embeddings` pattern. Identity `custom:<name>`, `<name>` matching `^[a-z][a-z0-9-]{0,31}$`. A custom task spawns the command through the shared `shellArgv` form, with cwd defaulting to the vault, stdin closed, `O2B_VAULT` set, a default timeout of 600 s, and a non-zero exit reported as `exit <N>: <redacted, capped stderr tail>`. It never calls the model and records no spend receipt. A timeout of a custom task counts toward its failure streak.
+6. **One shared lane task builder.** `src/core/brain/maintenance/lane-tasks.ts` builds the four built-in tasks plus the declared custom tasks once, used by both the CLI verb and the MCP tool. The two duplicated inline lists are removed. `--retry`/`retry_tasks` accept custom identities and validate against the registered task names; the cap becomes the number of declared tasks.
+7. Tests, docs (`docs/cli-reference.md`, `docs/mcp.md`, `docs/updating.md`, `docs/hermes-cron.md`) and a `CHANGELOG.md` entry under `## [1.65.0] - 2026-10-01`.
+
+## Out of scope
+
+- Any installer: no verb writes a crontab, a systemd unit, a launchd plist or a Task Scheduler entry. No `--scheduler` flag.
+- A recipe for `discipline report`: its value is the Hermes `deliver` field, which a plain crontab cannot reproduce. Hermes stays its only installer.
+- A time-of-day field in the recipe kernel (`--at HH:MM`): `--window` already gives time-of-day semantics, and widening `parseInterval` risks the byte-pinned reindex fixture.
+- Persisting MCP fault counts for `o2b doctor`: writing to the vault from a fault handler risks the lock the guard protects. stderr plus `/health` only.
+- Giving up after N rejections per minute: count and expose them; revisit only if a real loop shows up.
+- A plugin system, a JSON protocol for custom tasks, or custom tasks declared in the vault `_brain.yaml`.
+- Repository-declared schedules and a discovery verb (refused, see below).
+
+## Refusal: repository-declared schedules and the discovery verb
+
+The card asked for project branches or worktrees to declare background schedules (an upstream `.daemon/schedule.json` pattern) that Open Second Brain discovers and surfaces as proposals. This wave refuses that part, for three reasons:
+
+1. **No per-repository config convention exists.** Open Second Brain reads no project file of its own today: configuration lives in the vault and in the machine config, and cross-project wiring is a managed block the operator pastes into the project's agent instructions. A `.o2b/schedule.json` would be a new public file format that the stability policy then binds the project to supporting indefinitely, on the strength of one upstream release and no user signal.
+2. **A print-only verb fed by repository content would carry foreign shell commands.** A recipe's script body is shell the operator pastes into a scheduler. Feeding it from a file in a repository the operator merely checked out turns "print only" into a copy-paste path for code someone else wrote. An allowlist of Open Second Brain verbs would make it safe, but then every allowed job already has its own `--cron-template` (the reindex, codegraph and, from this release, the maintenance lane recipes), so the discovery verb would add a file format without adding a capability.
+3. **The kernel could not render the upstream schedule anyway.** The upstream example is a calendar slot ("Sunday 04:00"); the kernel renders intervals only, and calendar slots are out of scope for the reason given above.
+
+What survives is the part with standalone value: the systemd user timer rendering (`renderSystemdTimer` and `--format cron|systemd`), shared by every recipe surface. A future card can revisit discovery if users ask for it, starting from the allowlist design recorded in the premise report.
+
+## Chosen approach
+
+The consultant's recommended variant was taken for every item, with three overrides where an orchestrator decision binds the detail (recorded in `variants.md`): the maintenance spec lives at `src/cli/maintenance-cron.ts`, not under `src/cli/brain/`; the custom task keys are `maintenance_custom_<name>` with their own `_timeout_seconds` and a `custom:<name>` identity, not `maintenance_task_<name>` with the `OPERATION` timeout key and a widened `string` type; and the `/health` fault count reaches `src/mcp/http.ts` through an injected getter typed in `src/mcp`, not through a new shared counter module. In prose:
+
+- **Recipes** extend the existing kernel instead of adding a second one: the maintenance lane becomes a third `CronRecipeSpec` consumer, and systemd is a second renderer over the same spec (same script body, same verify footer), so a recipe can never say one thing in cron and another in systemd.
+- **The fault guard** is a CLI-side sibling of `mcp-drain.ts` with the same injection shape (`stderr`, `exit`, `now`), installed only by the two served transports of `o2b mcp`. Foreground verbs keep failing loudly.
+- **Custom tasks** reuse the lane kernel untouched except for widened identity types and one journal rule; the new code is a config resolver, a spawning task factory and the shared builder that both front doors call.
+
+## Design decisions
+
+Orchestrator decisions (binding, recorded here as decided before the brainstorm):
+
+- **D1. Four cards, four features, one pull request, version 1.65.0.** The bump is done during PR preparation, not during implementation.
+- **D2. No new dependencies, no plugin system, errors by name, no silent skips, English user-facing strings.**
+- **D3. The recipe lives on `brain maintenance run`, not a new verb.** Default interval `1h`: the lane's window, busy and lease gates decide whether work happens and a gate skip exits 0, so hourly plus `--window` is the intended pattern. Bad interval exits 2 (`MAINTENANCE_EXIT.usage`), unlike the other two recipe surfaces whose `1` predates the lane's exit vocabulary; in the lane `1` means "attempted and failed".
+- **D4. The Hermes jobs path is derived from the home directory**, with a named error when it cannot be resolved. Root hosts see no change; non-root hosts, which today write to `/root` and fail, start working. Named in the CHANGELOG.
+- **D5. Fault guard semantics:** rejections survived, logged by name with rate limiting, counted; uncaught exceptions logged and exit 70 through the existing exit hooks; count on `/health`; in-process tests plus one spawned-process test; a section in `docs/mcp.md`.
+- **D6. Custom tasks are machine config, never vault config.** The vault syncs between devices and is writable through MCP write tools, so a command stored there would let an agent or a synced edit plant code the lane then runs. No MCP parameter can add, edit or read a command.
+- **D7. Master switch `maintenance_custom_tasks`, default off, env override.** A declared task runs only when the switch is on; `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS=0` turns it off on one host.
+- **D8. Identity `custom:<name>`, `<name>` matching `^[a-z][a-z0-9-]{0,31}$`.** A colon never occurs in an `OPERATION` value, so a custom identity cannot collide with a built-in one, and underscores are banned in `<name>` so the `_cwd` and `_timeout_seconds` suffixes are unambiguous. `LANE_TASK`, `LANE_TASKS`, `isLaneTask` and `OPERATION` stay unchanged.
+- **D9. One shared task builder used by both the CLI verb and the MCP tool**; `--retry`/`retry_tasks` accept custom identities; the retry cap is the number of declared tasks.
+- **D10. A timeout of a custom task counts toward its failure streak.** The premise report named the risk: a command that always hangs would otherwise never be streak-refused and would cost its full timeout of lease time on every pass. Built-in tasks keep today's rule (a timeout neither counts nor ends a streak), because their budgets are per-operation and a slow vault is not a broken task.
+- **D11. The MCP tool description stays under 300 characters, measured in a test.** Proposed text (263 characters): "Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters and declared custom:<name> tasks behind window, busy, pressure and streak gates; status renders lease and journal. Reindex embeds only with config maintenance_embeddings." The `retry_tasks` property description names the built-ins plus "custom:<name>" and never the configured names (they vary per install and the property cap is 160); proposed text measures 159 characters.
+- **D12. Repository-declared schedule discovery is refused this wave**; only `renderSystemdTimer` and `--format` ship (see the refusal section).
+- **D13. Parallel implementation in four lanes with disjoint file ownership** (see `plan.md`). Shared files have exactly one owner.
+
+Design choices made here:
+
+- **systemd is a sibling renderer over the same spec, not a branch inside `renderCronRecipe`** (consultant item 4, Variant 1). The default path stays the code the byte-pinned fixtures cover. `renderSystemdTimer` validates the interval with `parseInterval` (so the same refusals apply: seconds, 60 minutes or more, 24 hours or more, 28 days or more) and renders `OnUnitActiveSec=` from the normalised `<N><unit>` (systemd reads `m`, `h`, `d` natively). An unknown `--format` value throws `CronTemplateError` (`unknown recipe format "<x>": expected cron or systemd`), which every consumer already maps to its usage exit. The kernel exports `RECIPE_FORMATS = ["cron", "systemd"]` and `parseRecipeFormat(raw)`.
+- **The maintenance recipe embeds the resolved vault**, single-quote escaped the way `discipline-install.ts` does: cron runs without the operator's environment. The `--cron-template` branch resolves the vault as `run` does and fails with usage when none is configured, rather than printing a recipe that cannot run. It returns before the lease, the gates, the journal and the metrics, and a test asserts the journal and the lease stay empty.
+- **The custom task timeout is enforced by the task itself**, not by the `OPERATION`-keyed safeguard (a custom identity is not an operation): the factory kills the child on `timeout_seconds` and throws `SafeguardTimeoutError`, so the journal row carries `timed_out: true` exactly as for built-ins. The journal's streak rule then counts a timed-out row when its task is a custom identity (`isCustomLaneTask(entry.task)`), which keeps the verdict honest on the row and changes nothing for built-in rows. The timeout must stay below `MAINTENANCE_LEASE_TTL_MS` (30 min); a declared value at or above 1800 s is a named config error.
+- **Config errors are named, never dropped.** A bad name, an empty command, a non-integer or out-of-range timeout, a `_cwd`/`_timeout_seconds` key without its command, or more than `CUSTOM_TASK_MAX = 8` tasks each produce an error string. The CLI prints each on stderr as `custom task refused: <reason>`; the MCP tool returns them in a `custom_task_errors` field. A refused declaration journals nothing; valid declarations still run. With the master switch off, declared keys are reported once as `custom tasks declared but maintenance_custom_tasks is off` in `status`, never run.
+- **The shared builder lives in core** (`src/core/brain/maintenance/lane-tasks.ts`) and takes the surface-specific parts by injection: `safeguardFor(op)`, `signal`, `progress`, `onBanner`, `forceCost`. Its output is `{ tasks, reindex, taskNames, customErrors }`. The metrics writes and store handling move unchanged from the two inline lists.
+- **Fault guard listeners use `process.on`, not `once`**: with `once`, a second rejection would fall back to the default handler and kill the process. A throw inside the exception handler goes straight to `exit`. Every stderr write is wrapped in try/catch (a closed stderr must not turn the guard into a crash). The guard is released before `cmdMcp` returns, so the top-level `main().catch` still crashes loudly once the server has stopped.
+- **`EXIT_INTERNAL_FAULT = 70` lives in the guard module** (sysexits `EX_SOFTWARE`), distinct from 1 (generic CLI error) and 130/143 (signals), so a wrapper can tell a crash from a stop.
+
+## File changes
+
+New files:
+- `src/cli/maintenance-cron.ts`
+- `src/cli/mcp-fault-guard.ts`
+- `src/core/brain/maintenance/custom-tasks.ts`
+- `src/core/brain/maintenance/lane-tasks.ts`
+- `tests/cli/maintenance-cron.test.ts`
+- `tests/cli/mcp-fault-guard.test.ts`
+- `tests/cli/mcp-fault-guard-spawn.test.ts`
+- `tests/fixtures/mcp-fault-guard/serve-with-rejection.ts`, `tests/fixtures/mcp-fault-guard/serve-with-throw.ts`
+- `tests/mcp/http-health-faults.test.ts`
+- `tests/core/brain/maintenance/custom-tasks.test.ts`
+- `tests/core/brain/maintenance/lane-tasks.test.ts`
+
+Modified files:
+- `src/cli/cron-recipe.ts`, `src/cli/search-cron-template.ts`, `src/cli/partner-codegraph-cron.ts`, `src/cli/search/verbs/indexing.ts`, `src/cli/partner.ts`, `src/cli/discipline-install.ts`
+- `src/cli/main.ts` (`cmdMcp` only), `src/mcp/http.ts`
+- `src/core/brain/maintenance/lane.ts` (identity types), `src/core/brain/maintenance/journal.ts` (custom timeout rule), `src/core/config.ts`, `src/core/reliability/command-bridge.ts` (export `shellArgv`)
+- `src/cli/brain/verbs/maintenance.ts`, `src/mcp/brain/admin-tools.ts`, `src/cli/command-manifest.ts`
+- Tests: `tests/cli/cron-recipe.test.ts`, `tests/cli/search-cron-template.test.ts`, `tests/cli/partner-codegraph-resync.test.ts`, `tests/cli/discipline-install.test.ts`, `tests/core/brain/maintenance/maintenance.test.ts`, `tests/cli/brain-maintenance.test.ts`, `tests/mcp/maintenance-parity-census.test.ts`, `tests/cli/manifest-completeness.test.ts`
+- Docs: `docs/cli-reference.md`, `docs/mcp.md`, `docs/updating.md`, `docs/hermes-cron.md`, `CHANGELOG.md`
+
+No skill or `hooks/hooks.json` change, so `sync-plugin-mirrors` has nothing to regenerate.
+
+## Risks and open questions
+
+- **Byte drift in existing recipes.** Mitigation: the `cron` format path is the existing code path unchanged; the byte-pinned search fixture and the codegraph resync tests must pass unedited.
+- **Process-global listeners in the shared test runner.** Every guard test releases in `finally` and asserts `process.listenerCount` before and after; the spawned-process test proves the real behaviour.
+- **Bun 1.4.0 semantics.** Assumed: registering `unhandledRejection` suppresses the default exit as in Node. The spawned-process test fails if the process dies, so the assumption is checked, not trusted. If Bun differs, the implementer reports it rather than adding an env seam.
+- **Swallowed rejections hiding bugs.** Each is named on stderr with its first stack frame, counted, and visible on `/health`.
+- **Arbitrary command execution through an agent-triggered `brain_maintenance run`.** Mitigated by the machine-config-only source, the master switch (default off), the pattern-checked name, and no MCP input reaching a command line. The docs say the lane cannot police spend or side effects inside an operator's own command.
+- **Secrets in a custom task's stderr reaching the journal.** `redactRawOutput` runs before `capOutput`.
+- **Journal volume.** Up to eight more rows per pass against the 500-row cap shortens how far back built-in history reaches; the streak refusal row already preserves counts.
+- **Lane 4 depends on exports from lanes 1 and 3.** The plan pins the exported signatures so lane 4 can write its tests first and wire last; integration is the last task of lane 4.
+- **Open question for implementation:** whether `o2b doctor` should list declared custom tasks and their errors. Recommendation: not in this release; `status` reports them.
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/plan.md b/docs/brainstorm/unattended-maintenance-mcp-guards/plan.md
new file mode 100644
index 00000000..cc94c760
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/plan.md
@@ -0,0 +1,266 @@
+# Unattended maintenance and MCP fault guards - implementation plan
+
+Feature branch: `feat/unattended-maintenance-mcp-guards` (already checked out; never create or switch branches). Target release 1.65.0; the `package.json` bump and `sync-version.ts` run during PR preparation, not here.
+
+Four lanes run in parallel in one worktree, one implementer each. File ownership is disjoint: a lane edits only the files listed under its "Owns" line. When a lane needs a line in a file it does not own, it hands the exact text to the owner through the "Hands to lane 4" list below, and the owner applies it. Shared files (`src/cli/main.ts`, `src/cli/command-manifest.ts`, every doc, `CHANGELOG.md`) have exactly one owner.
+
+Rules for every lane:
+- TDD: write the test file and its cases first, watch them fail for the right reason, then implement.
+- `git add` by file name only, format only your own files (`bunx biome format --write <your files>` or the project formatter via `bun run fmt` restricted to your paths), retry on `index.lock`. One commit per task, English conventional subject, no AI markers, no card ids.
+- Test runs set `TMPDIR` to the wave scratch directory. Gates use the CI Bun 1.4.0 binary when present.
+- `bun run typecheck` is global. An error in a file you do not own is reported to its lane owner, not fixed by you.
+- Errors surface by name; no silent skips. All user-facing strings English.
+
+## Lane contracts (pinned so lanes can test against them before they land)
+
+Lane 1 exports from `src/cli/cron-recipe.ts`:
+```ts
+export const RECIPE_FORMATS: readonly ["cron", "systemd"];
+export type RecipeFormat = (typeof RECIPE_FORMATS)[number];
+export function parseRecipeFormat(raw: string | undefined): RecipeFormat; // undefined -> "cron"; unknown -> CronTemplateError
+export function renderSystemdTimer<T extends CronRecipeOptions>(spec: CronRecipeSpec<T>, interval: string, opts: T): string;
+```
+Lane 1 exports from `src/cli/maintenance-cron.ts`:
+```ts
+export const MAINTENANCE_CRON_NAME = "osb-maintenance";
+export const DEFAULT_MAINTENANCE_INTERVAL = "1h";
+export interface MaintenanceCronOptions extends CronRecipeOptions { readonly vault: string; readonly window?: string; readonly tz?: string; }
+export const MAINTENANCE_RECIPE: CronRecipeSpec<MaintenanceCronOptions>;
+export function renderMaintenanceCronTemplate(interval: string, opts: MaintenanceCronOptions & { readonly format?: RecipeFormat }): string; // throws CronTemplateError
+```
+
+Lane 2 exports from `src/mcp/http.ts`:
+```ts
+export interface McpFaultCounts { readonly unhandled_rejection: number; readonly uncaught_exception: number; readonly last_fault_at: string | null; }
+// ServeHttpOptions gains: readonly faultCounts?: () => McpFaultCounts; /health then carries `faults`
+```
+and from `src/cli/mcp-fault-guard.ts`: `EXIT_INTERNAL_FAULT = 70`, `FAULT_KIND`, `REJECTION_LOG_BURST = 5`, `REJECTION_LOG_WINDOW_MS = 60_000`, `installMcpFaultGuard(opts?: { stderr?; exit?; now? }): { counts(): McpFaultCounts; release(): void }`.
+
+Lane 3 exports from `src/core/brain/maintenance/custom-tasks.ts`:
+```ts
+export const CUSTOM_TASK_PREFIX = "custom:";
+export const CUSTOM_TASK_NAME_PATTERN: RegExp; // ^[a-z][a-z0-9-]{0,31}$
+export const CUSTOM_TASK_MAX = 8;
+export const CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS = 600;
+export type CustomLaneTask = `custom:${string}`;
+export function isCustomLaneTask(value: unknown): value is CustomLaneTask;
+export interface CustomTaskSpec { readonly name: string; readonly id: CustomLaneTask; readonly command: string; readonly cwd?: string; readonly timeoutSeconds: number; }
+export interface CustomTaskResolution { readonly enabled: boolean; readonly specs: ReadonlyArray<CustomTaskSpec>; readonly errors: ReadonlyArray<string>; readonly declared: number; }
+export function resolveCustomTasks(configPath?: string): CustomTaskResolution;
+export function createCustomLaneTask(spec: CustomTaskSpec, ctx: { vault: string; signal?: AbortSignal }): MaintenanceTask;
+```
+from `src/core/brain/maintenance/lane.ts`: `export type LaneTaskId = LaneTask | CustomLaneTask;` and `isLaneTaskId(value)`; `MaintenanceTask.name`, `RunMaintenanceOptions.retryTasks`, `MaintenanceTaskResult.name` widened to `LaneTaskId`.
+from `src/core/brain/maintenance/lane-tasks.ts`:
+```ts
+export interface LaneTaskBuildOptions {
+ readonly vault: string; readonly configPath?: string; readonly searchConfig: SearchConfig; readonly now: Date;
+ readonly forceCost: boolean; readonly safeguardFor: (operation: LaneTask) => Safeguard;
+ readonly signal?: AbortSignal; readonly onProgress?: ProgressSink;
+ readonly onBanner?: (preview: EmbeddingSpendPreview) => void;
+}
+export interface LaneTaskSet {
+ readonly tasks: ReadonlyArray<MaintenanceTask>; readonly reindex: LaneReindex;
+ readonly taskNames: ReadonlyArray<LaneTaskId>; readonly custom: CustomTaskResolution;
+}
+export function buildLaneTasks(opts: LaneTaskBuildOptions): LaneTaskSet;
+```
+from `src/core/config.ts`: `MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS"`, `MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks"`, `resolveMaintenanceCustomTasks(configPath?)`.
+
+## Lane 1: recipes, systemd timer, Hermes jobs path
+
+**Owns**: `src/cli/cron-recipe.ts`, `src/cli/maintenance-cron.ts` (new), `src/cli/search-cron-template.ts`, `src/cli/partner-codegraph-cron.ts`, `src/cli/search/verbs/indexing.ts`, `src/cli/partner.ts`, `src/cli/discipline-install.ts`, `tests/cli/cron-recipe.test.ts`, `tests/cli/maintenance-cron.test.ts` (new), `tests/cli/search-cron-template.test.ts`, `tests/cli/partner-codegraph-resync.test.ts`, `tests/cli/discipline-install.test.ts`.
+
+**Gate**: `bun test tests/cli/cron-recipe.test.ts tests/cli/maintenance-cron.test.ts tests/cli/search-cron-template.test.ts tests/cli/partner-codegraph-resync.test.ts tests/cli/discipline-install.test.ts && bun run typecheck`
+
+### Task 1.1: `renderSystemdTimer` and recipe formats in the kernel
+- **Tests first** (`tests/cli/cron-recipe.test.ts`, new cases; existing cases unchanged):
+ - `renderSystemdTimer(SPEC, "30m", {})` contains the same script heredoc as `renderCronRecipe(SPEC, "30m", {})` (extract the section between the markers and compare).
+ - It contains `~/.config/systemd/user/<cronName>.service` and `.timer`, `OnUnitActiveSec=30m`, `OnBootSec=`, `Persistent=true`, `systemctl --user daemon-reload`, `systemctl --user enable --now <cronName>.timer`, the `loginctl enable-linger` note and the spec's verify command.
+ - It contains no crontab line and no `hermes cron create`.
+ - `"6h"` gives `OnUnitActiveSec=6h`; `"1d"` gives `OnUnitActiveSec=1d`; `"90m"`, `"30s"`, `"24h"`, `"28d"`, `"nonsense"` throw `CronTemplateError` with the same messages as `renderCronRecipe`.
+ - `parseRecipeFormat(undefined)` is `"cron"`, `"systemd"` passes, `"launchd"` throws `CronTemplateError` naming `cron` and `systemd`.
+ - `renderCronRecipe` output for the synthetic spec is byte-identical to a snapshot taken before the refactor (pin it in the test).
+- **Implementation**: extract the header and script section of `renderCronRecipe` into a private helper; add `renderSystemdTimer`, `RECIPE_FORMATS`, `RecipeFormat`, `parseRecipeFormat`. Update the module docblock: systemd output is also print-only.
+- **Acceptance**: new cases green; `tests/cli/search-cron-template.test.ts` (byte-pinned) green without edits.
+- **Depends on**: none
+
+### Task 1.2: maintenance lane recipe spec
+- **Tests first** (`tests/cli/maintenance-cron.test.ts`, new):
+ - `renderMaintenanceCronTemplate("1h", { vault: "/v" })` renders `0 */1 * * *` and the script path `~/.local/bin/osb-maintenance.sh`.
+ - The body runs `o2b brain maintenance run --vault '/v' --json`; `--window 3-5 --tz Europe/Berlin` appear only when given.
+ - A vault containing a single quote is escaped the way `discipline-install.ts` escapes it.
+ - The body keeps the exit code: silent on 0, prints the captured JSON and exits with the same code otherwise (assert the shell text).
+ - The verify footer reads `o2b brain maintenance status`.
+ - `format: "systemd"` yields `OnUnitActiveSec=1h` and the same script body.
+ - `"30s"` throws `CronTemplateError`.
+ - Rendering writes nothing: a temp vault tree listing is unchanged before and after.
+- **Implementation**: `src/cli/maintenance-cron.ts` per the lane contract, `operatorScriptPath(MAINTENANCE_CRON_NAME)`, scheduler note "(when Hermes owns the schedule)" in the same style as the reindex recipe.
+- **Acceptance**: tests green.
+- **Depends on**: Task 1.1
+
+### Task 1.3: `--format` on the two existing recipe verbs
+- **Tests first**:
+ - `tests/cli/search-cron-template.test.ts`: `renderCronTemplate("30m", { format: "systemd" })` contains `OnUnitActiveSec=30m`; the existing byte-pinned fixture case stays as it is.
+ - `tests/cli/partner-codegraph-resync.test.ts`: `resync --cron-template --format systemd` prints a timer pair; `--format launchd` exits `EXIT_INTERVAL_REFUSED` (1) with the named message; no `--format` prints today's output.
+ - Same two checks through `o2b search reindex --cron-template --format ...` in whichever existing CLI test drives that verb (`search-cron-template.test.ts`).
+- **Implementation**: `renderCronTemplate` and `renderCodegraphResyncTemplate` accept an optional `format` and dispatch to `renderCronRecipe` or `renderSystemdTimer`; `indexing.ts` and `partner.ts` add `format: { type: "string" }` to their flag schemas, call `parseRecipeFormat`, and keep their existing exit code (1) for a `CronTemplateError`. Usage strings mention `[--format cron|systemd]`.
+- **Acceptance**: tests green; byte-pinned fixture unchanged.
+- **Depends on**: Task 1.1
+
+### Task 1.4: Hermes jobs path from the home directory
+- **Tests first** (`tests/cli/discipline-install.test.ts`): export a pure `resolveJobsFilePath(env, home)`; with `OSB_HERMES_JOBS` unset and `home = "/home/op"` it returns `/home/op/.hermes/cron/jobs.json`; with `OSB_HERMES_JOBS` set it returns that value; with `home = ""` it throws a named error whose message mentions `OSB_HERMES_JOBS`. Never touch the live jobs file.
+- **Implementation**: replace `DEFAULT_JOBS_FILE` with `join(homedir(), ".hermes", "cron", "jobs.json")` resolved at call time through `resolveJobsFilePath(process.env, homedir())`; the verb maps the named error to its existing error exit with the message on stderr.
+- **Acceptance**: tests green; existing discipline-install cases green.
+- **Depends on**: none
+
+**Hands to lane 4**:
+- Manifest: under `search reindex` add `flag("format", "string")`; under `partner codegraph resync` add `flag("format", "string")`.
+- `docs/cli-reference.md`: `search reindex` and `partner codegraph resync` rows gain `[--format cron|systemd]`; the discipline install row says the default jobs file is `~/.hermes/cron/jobs.json` of the running user, `OSB_HERMES_JOBS` overrides.
+- `docs/hermes-cron.md`: one paragraph that `o2b brain maintenance run --cron-template` is the alternative to a hand-chained dream job, and that every recipe also prints a systemd user timer with `--format systemd`.
+- `CHANGELOG.md` lines: systemd timer format on all recipes; maintenance recipe; Hermes jobs path fix (non-root Hermes hosts now work; root hosts see no change).
+
+## Lane 2: MCP fault guard
+
+**Owns**: `src/cli/mcp-fault-guard.ts` (new), `src/cli/main.ts`, `src/mcp/http.ts`, `tests/cli/mcp-fault-guard.test.ts` (new), `tests/cli/mcp-fault-guard-spawn.test.ts` (new), `tests/fixtures/mcp-fault-guard/serve-with-rejection.ts` (new), `tests/fixtures/mcp-fault-guard/serve-with-throw.ts` (new), `tests/mcp/http-health-faults.test.ts` (new).
+
+**Gate**: `bun test tests/cli/mcp-fault-guard.test.ts tests/cli/mcp-fault-guard-spawn.test.ts tests/mcp/http-health-faults.test.ts tests/mcp/http-drain.test.ts tests/mcp/http-transport.test.ts tests/cli/o2b-mcp-launcher.test.ts && bun run typecheck`
+
+### Task 2.1: the guard module
+- **Tests first** (`tests/cli/mcp-fault-guard.test.ts`, in-process, injected `stderr`/`exit`/`now`, `release()` in every `finally`):
+ - An unhandled `Promise.reject(new Error("probe"))`: wait until `counts().unhandled_rejection === 1`; the stderr line is `[mcp] unhandled_rejection #1: Error: probe (server keeps serving)` plus the first stack frame; `exit` not called.
+ - A non-Error rejection reason (a string, `undefined`) is still named (`non-error reason: "x"`).
+ - Rate limit: 8 rejections in one window give 5 full lines and one summary line `[mcp] unhandled_rejection: 3 more suppressed in the last 60000ms`; advancing `now` past the window logs in full again; the count is 8 either way.
+ - `process.emit("uncaughtException", new Error("boom"))` gives `exits == [70]` and a line naming `uncaught_exception: Error: boom` and the exit code.
+ - A throwing `stderr.write` does not escape the handler (rejection still counted, exception still exits 70).
+ - `release()` restores `process.listenerCount("unhandledRejection")` and `("uncaughtException")` to their values before install; a second `release()` is a no-op.
+ - `last_fault_at` is the ISO time from `now` of the latest fault, `null` before any.
+- **Implementation**: `src/cli/mcp-fault-guard.ts` per the lane contract, reusing `DrainReportStream` from `mcp-drain.ts`; `process.on` (not `once`); re-entrant throw in the exception handler goes straight to `exit`; no drain on an uncaught exception. Docblock explains why the guard lives CLI-side and why an exception exits.
+- **Acceptance**: tests green; no listener leaks.
+- **Depends on**: none
+
+### Task 2.2: `/health` carries the fault counts
+- **Tests first** (`tests/mcp/http-health-faults.test.ts`): start the HTTP transport on port 0 with a `faultCounts` getter returning fixed counts; `GET /health` JSON has `faults` equal to them; without the getter, `faults` is absent (existing clients unaffected); the drain fields are unchanged.
+- **Implementation**: `McpFaultCounts` type and the optional `faultCounts` option in `src/mcp/http.ts`; the health body adds `faults` only when the getter is present.
+- **Acceptance**: tests green; `tests/mcp/http-drain.test.ts` and `tests/mcp/http-transport.test.ts` green unedited.
+- **Depends on**: none
+
+### Task 2.3: wiring in `cmdMcp` and the spawned-process regression
+- **Tests first** (`tests/cli/mcp-fault-guard-spawn.test.ts`, modelled on `tests/cli/o2b-mcp-launcher.test.ts`, temp vault under `TMPDIR`):
+ - Fixture `serve-with-rejection.ts` imports `installMcpFaultGuard` and `serveStdio`, installs the guard, rejects a detached promise after `onStart`, then serves. Send `initialize`, `tools/call brain_context`, then `tools/list`: both later responses arrive, stderr contains `unhandled_rejection #1`, the process is still alive, then close stdin and expect exit 0.
+ - Fixture `serve-with-throw.ts` acquires a sync lock through the real lock module, then throws from `setTimeout`: exit code 70, stderr names `uncaught_exception`, and the lock file is gone (proves the exit hooks ran). Skip on win32 if exit hooks differ there, with the reason in the skip message.
+- **Implementation**: in `src/cli/main.ts` `cmdMcp`, install the guard before `startHttp` (passing `faultCounts: () => guard.counts()`) and before `serveStdio`, release it in the same `finally` blocks as the signal drain; `runMcpProbe` does not install it.
+- **Acceptance**: tests green; launcher test green unedited.
+- **Depends on**: Tasks 2.1, 2.2
+
+**Hands to lane 4**:
+- `docs/mcp.md`: new section `## Background faults (since v1.65.0)` after "Shutdown and draining": rejections survived, named, rate-limited (5 lines per 60 s, then one summary line), counted; an uncaught exception logs and exits 70 so the exit hooks checkpoint the index and release locks; no drain on an exception and why; `/health` `faults` fields; the Hermes bridge restarts the server once, Claude Code and Codex do not; guard only on the served transports.
+- `docs/cli-reference.md`: exit code 70 in the `o2b mcp` exit list.
+- `CHANGELOG.md` lines for the guard and the `/health` field.
+
+## Lane 3: custom lane tasks core, config, shared builder
+
+**Owns**: `src/core/brain/maintenance/custom-tasks.ts` (new), `src/core/brain/maintenance/lane-tasks.ts` (new), `src/core/brain/maintenance/lane.ts`, `src/core/brain/maintenance/journal.ts`, `src/core/config.ts`, `src/core/reliability/command-bridge.ts`, `tests/core/brain/maintenance/custom-tasks.test.ts` (new), `tests/core/brain/maintenance/lane-tasks.test.ts` (new), `tests/core/brain/maintenance/maintenance.test.ts`.
+
+**Gate**: `bun test tests/core/brain/maintenance tests/core/reliability && bun run typecheck`
+
+### Task 3.1: master switch and config resolution
+- **Tests first** (`tests/core/brain/maintenance/custom-tasks.test.ts`, temp config file):
+ - `resolveMaintenanceCustomTasks` is false by default, true with `maintenance_custom_tasks: true`, and the env `0` overrides config `true`.
+ - `resolveCustomTasks` reads `maintenance_custom_tidy: ./tidy.sh`, `maintenance_custom_tidy_cwd: /srv/x`, `maintenance_custom_tidy_timeout_seconds: 120` into one spec with id `custom:tidy`; sorted by name.
+ - Each of these is a named error and the others still resolve: name `Bad`, name with `_` (`maintenance_custom_a_b` without a matching command reads as a dangling suffix or a bad name, named either way), an empty command, timeout `0`, `abc`, `1800` or above (`MAINTENANCE_LEASE_TTL_MS`), a `_cwd` key without its command, more than 8 tasks (the ninth onward named).
+ - Switch off with keys declared: `enabled: false`, `specs` empty, `declared` counts them.
+- **Implementation**: config constants and resolver in `src/core/config.ts` next to `maintenance_embeddings`; `resolveCustomTasks` in `custom-tasks.ts` reading the flat config through the existing config loader.
+- **Acceptance**: tests green.
+- **Depends on**: none
+
+### Task 3.2: the custom task runner
+- **Tests first** (same file):
+ - Exit 0: task resolves; cwd defaults to the vault; `O2B_VAULT` is set in the child env; stdin is closed.
+ - Exit 3: throws `Error` whose message starts `exit 3:` and carries the stderr tail, redacted (a fake token in stderr is masked) and capped at 4096 bytes.
+ - A command that sleeps past `timeoutSeconds` (use 1 s) is killed and throws `SafeguardTimeoutError`.
+ - An aborted `signal` kills the child and rejects.
+ - The shell form comes from the exported `shellArgv` (Windows form covered by the existing command-bridge tests).
+- **Implementation**: export `shellArgv` from `command-bridge.ts`; `createCustomLaneTask` with async `spawn`, `redactRawOutput` before `capOutput`, no receipt, no model call.
+- **Acceptance**: tests green.
+- **Depends on**: Task 3.1
+
+### Task 3.3: identity widening and the custom timeout streak rule
+- **Tests first** (`tests/core/brain/maintenance/maintenance.test.ts`, extended):
+ - A `custom:x` task that fails `failure_streak_limit` times is refused by name while the built-in tasks still run.
+ - A `custom:x` task that times out `failure_streak_limit` times is refused (timeout counts for custom identities).
+ - A built-in task that times out the same number of times is still not refused (rule unchanged).
+ - `retryTasks: ["custom:x"]` passes the refusal; stale-first ordering includes custom ids.
+- **Implementation**: `LaneTaskId`, `isLaneTaskId` and the widened signatures in `lane.ts` (`LANE_TASK`, `LANE_TASKS`, `isLaneTask` unchanged); in `journal.ts` `consecutiveTaskFailures`, a `timed_out` row counts when `isCustomLaneTask(entry.task)`; update the comment that describes the rule.
+- **Acceptance**: tests green; existing maintenance tests green.
+- **Depends on**: Task 3.1
+
+### Task 3.4: one shared lane task builder
+- **Tests first** (`tests/core/brain/maintenance/lane-tasks.test.ts`):
+ - With the switch off, `taskNames` is exactly `LANE_TASKS` in order.
+ - With two declared custom tasks and the switch on, `taskNames` is the four built-ins followed by `custom:a`, `custom:b`; `custom.errors` passes through.
+ - `safeguardFor` is called lazily with the operation of the task being run, once per run.
+ - Running the built `custom:a` task executes its command (fixture script) and returns no spend receipt (`reindex.spendBlock` ignores it).
+- **Implementation**: `buildLaneTasks` per the lane contract; move the dream, bridges and clusters bodies (including the metrics writes) from the two surfaces into it unchanged.
+- **Acceptance**: tests green.
+- **Depends on**: Tasks 3.2, 3.3
+
+**Hands to lane 4**:
+- `docs/cli-reference.md` paragraph after the v1.64.0 lane paragraph: the keys, the master switch and env override, the identity pattern, cwd default, timeout default and cap, the no-spend rule (the lane cannot police spend inside an operator's command), that a timeout counts toward a custom task's streak, and that commands are never read from the vault.
+- `docs/updating.md` near the maintenance section: new opt-in, existing installs see no change.
+- `CHANGELOG.md` lines for custom tasks and the shared builder.
+
+## Lane 4: CLI and MCP surfaces, command manifest, docs and CHANGELOG
+
+**Owns**: `src/cli/brain/verbs/maintenance.ts`, `src/mcp/brain/admin-tools.ts`, `src/cli/command-manifest.ts`, `tests/cli/brain-maintenance.test.ts`, `tests/cli/brain-maintenance-progress.test.ts` (only if the refactor requires it), `tests/mcp/maintenance-parity-census.test.ts`, `tests/cli/manifest-completeness.test.ts`, `docs/cli-reference.md`, `docs/mcp.md`, `docs/updating.md`, `docs/hermes-cron.md`, `CHANGELOG.md`.
+
+Lane 4 writes its tests first against the pinned contracts and wires each surface once the exporting lane has committed (Task 4.2 after lane 1 Task 1.2; Tasks 4.3 and 4.4 after lane 3 Task 3.4).
+
+**Gate**: `bun test tests/cli/brain-maintenance.test.ts tests/cli/brain-maintenance-progress.test.ts tests/mcp/maintenance-parity-census.test.ts tests/cli/manifest-completeness.test.ts tests/mcp/brain-tools-parity.test.ts && bun run typecheck`
+
+### Task 4.1: command manifest
+- **Tests first** (`tests/cli/manifest-completeness.test.ts`): the completion token list gains `--format`; a new case asserts `brain maintenance` declares `run` and `status` with `run` carrying `cron-template`, `interval`, `format`, `window`, `tz`, `retry`, `force`, `force-cost`.
+- **Implementation**: declare the maintenance subcommands and flags in `command-manifest.ts:306`; apply lane 1's two `format` flags.
+- **Acceptance**: tests green.
+- **Depends on**: none
+
+### Task 4.2: `brain maintenance run --cron-template`
+- **Tests first** (`tests/cli/brain-maintenance.test.ts`):
+ - `run --cron-template` exits 0, prints a recipe naming `osb-maintenance` and the vault, and leaves the lease (`currentLease` null) and the journal empty.
+ - `--interval 30s` and `--interval 90d` exit 2 with the kernel message; `--format launchd` exits 2.
+ - `--window 25-3 --cron-template` exits 2; `--window 3-5 --tz Europe/Berlin` appear in the printed body.
+ - `status --cron-template` exits 2.
+ - `--format systemd` prints `OnUnitActiveSec=1h`.
+- **Implementation**: add `cron-template`, `interval`, `format` to the flag schema; under `op === "run"` branch before the lease and gates, call `renderMaintenanceCronTemplate`, map `CronTemplateError` to `MAINTENANCE_EXIT.usage`; extend `USAGE`.
+- **Acceptance**: tests green.
+- **Depends on**: lane 1 Task 1.2, Task 4.1
+
+### Task 4.3: CLI verb on the shared builder, custom retries
+- **Tests first** (`tests/cli/brain-maintenance.test.ts`, temp config with a fixture command):
+ - With the switch on, `run --json` reports a `custom:tidy` row; `--retry custom:tidy` passes its streak refusal; `--retry custom:nope` exits 2 naming the registered tasks.
+ - A bad declaration prints `custom task refused: <reason>` on stderr, the valid tasks still run, and the exit code is the lane's verdict code.
+ - `status` shows custom journal rows and, with the switch off but keys declared, the line `custom tasks declared but maintenance_custom_tasks is off`.
+- **Implementation**: replace the inline task list with `buildLaneTasks`; `--retry` validates against `taskNames`; usage says `--retry <task|custom:name>`.
+- **Acceptance**: tests green; `brain-maintenance-progress.test.ts` green.
+- **Depends on**: lane 3 Task 3.4, Task 4.2
+
+### Task 4.4: MCP tool on the shared builder, description budget
+- **Tests first** (`tests/mcp/maintenance-parity-census.test.ts`):
+ - `retry_tasks` accepts a declared custom name on both surfaces; an undeclared `custom:nope` is refused on both by name.
+ - More entries than declared tasks is refused with the declared count in the message; the schema `maxItems` is `LANE_TASKS.length + CUSTOM_TASK_MAX`.
+ - The tool description is under 300 characters and the `retry_tasks` property description under 160 (measured); the description mentions `custom:<name>` and names no configured task.
+ - The "neither surface spells a lane task by hand" check still passes; config errors surface as `custom_task_errors` in the MCP result.
+- **Implementation**: `toolBrainMaintenance` uses `buildLaneTasks`; retry checks against `taskNames`; description per design decision D11; property description reads "Tasks to retry past their streak refusal, this run only; gates still apply. Known: ${LANE_TASKS.join(", ")}, custom:<name>. Unknown names are refused." (159 characters, measured).
+- **Acceptance**: tests green; `tests/mcp/brain-tools-parity.test.ts` green.
+- **Depends on**: lane 3 Task 3.4
+
+### Task 4.5: docs and CHANGELOG for all lanes
+- **Files**: `docs/cli-reference.md` (maintenance synopsis at the lane row: `run --cron-template [--interval N] [--format cron|systemd]`, prints and installs nothing; "usually cron'd" points at the recipe; plus every line handed over by lanes 1, 2, 3), `docs/mcp.md` (lane 2 section; long-running table row "the four built-ins plus declared custom tasks"; bullet near the maintenance tool section), `docs/updating.md`, `docs/hermes-cron.md`, `CHANGELOG.md` under a new `## [1.65.0] - 2026-10-01` heading with `### Added`, `### Changed`, `### Fixed` as needed and the `[1.65.0]: https://github.com/itechmeat/open-second-brain/compare/v1.64.0...v1.65.0` link reference at the bottom. No `package.json` change.
+- **Acceptance**: `bun run check:paths` and `bun run fmt:check` green on the changed docs; no exclamation marks, no card ids, no machine paths, "Open Second Brain" spelled out.
+- **Depends on**: hand-overs from lanes 1, 2, 3
+
+## Integration (after all lanes)
+
+### Task 5.1: full gate
+- **Commands**: `bun run typecheck`, `bun run lint`, `bun run fmt:check`, `bun run sync-plugin-mirrors:check`, `bun test` (the known `dedup-index-cache` flake on an ext4 `TMPDIR` is the only accepted failure).
+- **Acceptance**: all green; `git status --short` clean after the lane commits.
+- **Depends on**: every task above
diff --git a/docs/brainstorm/unattended-maintenance-mcp-guards/variants.md b/docs/brainstorm/unattended-maintenance-mcp-guards/variants.md
new file mode 100644
index 00000000..289409ba
--- /dev/null
+++ b/docs/brainstorm/unattended-maintenance-mcp-guards/variants.md
@@ -0,0 +1,141 @@
+# Unattended maintenance and MCP fault guards - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), primary path, exit 0, parseable variants for all four items (3 per item). Fallback (Codex) not needed. Prompt: `cli-output/prompt.md`, raw output: `cli-output/claude.md`. Reconnaissance queries: `cli-output/zg-*.txt`.
+
+The prompt carried the verified premises, not the raw cards, and stated that repository-declared schedule discovery was already refused, so item 4 covers only the systemd rendering.
+
+## Variants (consultant verbatim)
+
+### Item 1 / Variant 1: Dedicated spec module beside the other two consumers
+- **Approach**: Add `src/cli/brain/maintenance-cron-template.ts` exporting a `CronRecipeSpec` (title, `cronName` `osb-maintenance`, `operatorScriptPath`, script body that runs `o2b brain maintenance run --vault <resolved> [--window H-H --tz ZONE]`, verify command `o2b brain maintenance status`), mirroring `search-cron-template.ts` and `partner-codegraph-cron.ts`. The verb gains `--cron-template [--interval]`, prints the rendered recipe before any vault or lease work, and maps `CronTemplateError` to usage exit 2. The Hermes jobs default becomes `join(homedir(), ".hermes", "cron", "jobs.json")` with an optional `HERMES_HOME` override.
+- **Trade-offs**:
+ - Pro: identical shape to the two existing consumers, so the lane owner touches only the verb, one new file and the manifest.
+ - Pro: spec body is unit-testable without the lane; existing reindex fixtures untouched.
+ - Con: a third near-identical spec file; the three consumers still share nothing beyond the kernel.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 1 / Variant 2: Spec inlined in the maintenance verb
+- **Approach**: Build the `CronRecipeSpec` inline inside `src/cli/brain/verbs/maintenance.ts` where the resolved vault, `--window` and `--tz` are already parsed, and call `renderCronRecipe` directly. Same Hermes path fix.
+- **Trade-offs**:
+ - Pro: fewest files; the recipe body sits next to the flags it embeds.
+ - Con: the verb file is already large and owns exit-code logic; recipe text mixed in hurts readability and the byte-pinned fixture test would import the verb.
+ - Con: breaks the one-consumer-one-module pattern the other two recipes established.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 1 / Variant 3: Generic self-recipe helper on the kernel
+- **Approach**: Extend `cron-recipe.ts` with `specFromCommand({cronName, argv, verify})` that turns any `o2b` argv into a spec, then have all three consumers call it. Maintenance passes its own argv (vault, window, tz).
+- **Trade-offs**:
+ - Pro: removes future duplication for any verb that wants a recipe.
+ - Con: refactoring the two existing consumers risks the byte-pinned search fixtures and widens the lane's file ownership into files other lanes may touch (item 4 also edits the kernel).
+ - Con: over-general for a wave whose kernel is already being changed by item 4.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 1 / Recommended: Variant 1
+**Rationale**: It matches the proven consumer pattern exactly, keeps the byte-pinned search fixtures out of the diff, and stays inside files only this lane owns. Variant 3 collides with item 4's kernel edits in the same worktree; Variant 2 buries operator-facing text in an already dense verb file.
+
+### Item 2 / Variant 1: Fault state in `src/mcp`, installer in `src/cli`, mirroring the drain split
+- **Approach**: Add `src/mcp/fault-state.ts` with a small `FaultCounter` (rejections survived, suppressed-by-rate-limit count, last fault summary) that `http.ts` reads into the `/health` body as `faults: {rejections, suppressed}`. Add `src/cli/mcp-fault-guard.ts` with `installMcpFaultGuard({counter, stderr, exit})`: `unhandledRejection` logs one named line (`o2b mcp: unhandled rejection survived: <message>`), rate-limited to N per minute with a periodic "suppressed K more" line; `uncaughtException` logs and calls `exit(EXIT_FAULT = 70)` so WAL checkpoint and lock unlink hooks run. `cmdMcp` installs it next to `installMcpSignalDrain` and uninstalls on normal close. Tests: in-process with injected stderr/exit; spawned-process test runs a tiny Bun script that imports the installer and throws asynchronously, asserting exit 70 and the stderr line (no production inject seam).
+- **Trade-offs**:
+ - Pro: respects `src/mcp` never importing `src/cli` while letting `/health` see the count; same seam style as `mcp-drain.ts`.
+ - Pro: exit via `process.exit` keeps the existing exit-hook ordering guarantee.
+ - Con: two small modules and a shared counter object to thread through `serveHttp`.
+ - Con: rate-limit window and cap are new constants to name and document.
+- **Complexity**: medium
+- **Risk**: low
+
+### Item 2 / Variant 2: Everything inside `src/mcp/fault-guard.ts`
+- **Approach**: One module in `src/mcp` owns the counter, the handlers and the exit call; `cmdMcp` calls `installFaultGuard()` and `http.ts` imports the counter from the same module.
+- **Trade-offs**:
+ - Pro: single file, trivial `/health` wiring.
+ - Con: a transport-layer module registering process-global handlers is exactly the "two signal conventions" smell `mcp-drain.ts` documents avoiding; exit codes would be defined outside `src/cli/interrupt.ts` where the project's exit vocabulary lives.
+ - Con: harder to inject `exit` from a CLI-side test without exporting the seam from `src/mcp`.
+- **Complexity**: small
+- **Risk**: medium
+
+### Item 2 / Variant 3: Extend `installMcpSignalDrain` to cover faults
+- **Approach**: Widen `McpSignalDrainOptions` with fault handling so one installer registers signals, `unhandledRejection` and `uncaughtException`; on uncaught exception it runs the same drain-then-exit path with code 70.
+- **Trade-offs**:
+ - Pro: one install/uninstall call site, and an uncaught exception could drain in-flight requests before exiting.
+ - Con: draining after an uncaught exception runs code in a possibly corrupted process; the premise asks for log-and-exit, not drain.
+ - Con: couples two unrelated concerns in a module whose docblock is precise about its narrow job; existing drain tests must be revisited.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 2 / Recommended: Variant 1
+**Rationale**: It reproduces the architecture the project already chose for signals, keeps the import direction rule intact, and gives `/health` the count through a plain shared object. It also avoids draining inside a process that just threw, which is the one behaviour Variant 3 would add that the premise explicitly does not want.
+
+### Item 3 / Variant 1: Prefix keys in the install-owned config, shared task builder
+- **Approach**: Declare custom tasks as `maintenance_task_<name>: <shell command>` in the flat config file (XDG config dir, never the vault), with the existing `safeguard_timeout_<name>_seconds` convention supplying the per-task deadline. Add `src/core/brain/maintenance/tasks.ts` with `buildLaneTasks(vault, config)` returning built-ins plus custom tasks, used by both the CLI verb and the MCP tool; widen `LaneTask` to `string` (keep `BUILTIN_LANE_TASK` for the four), validate `--retry`/`retry_tasks` against the built list and cap at its length. Custom tasks run via `shellArgv` with the vault path in env, captured output capped and redacted, non-zero exit or timeout recorded as a named failure.
+- **Trade-offs**:
+ - Pro: reuses the per-operation timeout key pattern and `discoverConfig` that already returns every key; no new file, no new parser.
+ - Pro: removes the CLI/MCP duplication as a side effect.
+ - Con: name validation (`^[a-z][a-z0-9_-]{0,31}$`, no collision with built-ins) and key scanning need tests; a reserved prefix in a flat namespace is slightly implicit.
+ - Con: MCP tool description must be trimmed to mention custom tasks within 300 characters.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 3 / Variant 2: Separate install-owned tasks file
+- **Approach**: Read `maintenance-tasks.yaml` from the same config directory, one `name: command` line per task through the existing flat parser; the rest (shared builder, widened `LaneTask`, retry validation) as in Variant 1.
+- **Trade-offs**:
+ - Pro: clean separation from the main config; the file's sole purpose is obvious to an operator and to `doctor`.
+ - Con: a second discovery path to document, test for env/XDG precedence, and surface in `doctor`; more lane-owned files touched (config discovery).
+ - Con: the per-task timeout still has to live in the main config or grow a second syntax.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Item 3 / Variant 3: CLI-only custom tasks, MCP keeps built-ins
+- **Approach**: Same prefix-key declaration and shared builder, but the MCP tool passes `customTasks: false` so `brain_maintenance` runs and retries only the four built-ins; the cron lane via CLI is the only runner of operator commands.
+- **Trade-offs**:
+ - Pro: no MCP description change; operator commands never run from an agent-triggered call.
+ - Con: the two surfaces disagree on what the lane is, and a streak refusal visible in the journal cannot be retried from MCP.
+ - Con: security gain is nominal since the command source is the install-owned config either way.
+- **Complexity**: small
+- **Risk**: low
+
+### Item 3 / Recommended: Variant 1
+**Rationale**: It satisfies the security constraint by construction (commands come only from the install-owned config, never from vault or tool arguments) while reusing two existing conventions, the flat config and the per-operation timeout key. Variant 2 adds a discovery surface for little gain, and Variant 3 leaves the two lane surfaces inconsistent.
+
+### Item 4 / Variant 1: Sibling renderer sharing the spec
+- **Approach**: Add `renderSystemdRecipe(spec, interval, opts)` beside `renderCronRecipe` in `cron-recipe.ts`, reusing the same `CronRecipeSpec`, the heredoc script section and `parseInterval`'s human label, but emitting `~/.config/systemd/user/<cronName>.service` and `.timer` heredocs (`OnBootSec`/`OnUnitActiveSec=<interval>`, `Persistent=true`) plus `systemctl --user daemon-reload && enable --now`. A `--format cron|systemd` flag on the three recipe verbs dispatches between the two; default `cron`, unknown value exits with the verb's usage code.
+- **Trade-offs**:
+ - Pro: `renderCronRecipe` is not edited, so the byte-pinned search fixtures stay identical by construction.
+ - Pro: `OnUnitActiveSec` takes `<N>m|h|d` directly, so the day-bound refusal in `parseInterval` is still honoured for consistency without any cron expression math.
+ - Con: the shared script section is extracted into a helper, a small refactor of the existing renderer body.
+ - Con: three verbs each gain a flag plus a manifest entry; item 1's new verb must adopt it too.
+- **Complexity**: medium
+- **Risk**: low
+
+### Item 4 / Variant 2: Format parameter on `renderCronRecipe`
+- **Approach**: Add an optional `format` argument to `renderCronRecipe`; when `systemd`, swap the crontab and Hermes sections for unit-file sections. Verbs pass the parsed `--format`.
+- **Trade-offs**:
+ - Pro: one entry point, minimal call-site change.
+ - Con: branching inside the renderer that the byte-pinned fixtures cover; any slip in the default path breaks them.
+ - Con: the name `renderCronRecipe` becomes misleading.
+- **Complexity**: small
+- **Risk**: medium
+
+### Item 4 / Variant 3: Format-agnostic section table
+- **Approach**: Rework the kernel into `renderRecipe(spec, interval, {format})` with a per-format table of section builders (`cron`, `systemd`), and re-express today's output as the `cron` entry.
+- **Trade-offs**:
+ - Pro: adding a future format (launchd) is one table entry.
+ - Con: a wholesale rewrite of the renderer with byte-identical output as the acceptance test, in the same wave where item 1 adds a consumer.
+ - Con: nothing in scope needs a third format.
+- **Complexity**: large
+- **Risk**: medium
+
+### Item 4 / Recommended: Variant 1
+**Rationale**: It leaves the existing renderer path untouched, which is the only way to guarantee the byte-pinned fixtures without a careful diff, and it reuses the spec so each consumer declares nothing new. Variant 2 saves little code while putting the fixtures at risk, and Variant 3 is a rewrite for a format count of two.
+
+## Final decision
+
+| Item | Consultant pick | Orchestrator decision | Override |
+|---|---|---|---|
+| 1. Maintenance lane recipe | Variant 1 (dedicated spec module) | Variant 1 | Path is `src/cli/maintenance-cron.ts` (binding decision), not `src/cli/brain/maintenance-cron-template.ts`. The optional `HERMES_HOME` override is dropped: the binding decision names only the home directory and `OSB_HERMES_JOBS`, and a second override would be a new public knob nobody asked for. |
+| 2. MCP fault guard | Variant 1 (state in `src/mcp`, installer in `src/cli`) | Variant 1, simplified | No new `src/mcp/fault-state.ts`. `src/mcp/http.ts` declares a `McpFaultCounts` type and an optional `faultCounts` getter in its options; the guard in `src/cli` satisfies the type. Same import direction, one fewer module and no shared mutable object. `EXIT_INTERNAL_FAULT = 70` lives in `src/cli/mcp-fault-guard.ts` (binding decision), not `interrupt.ts`. |
+| 3. Custom lane tasks | Variant 1 (prefix keys in machine config, shared builder) | Variant 1, with the binding details | Keys `maintenance_custom_<name>` plus `_cwd` and `_timeout_seconds`, not `maintenance_task_<name>` with `safeguard_timeout_<name>_seconds`: a custom identity is not an `OPERATION`, and reusing the operation key namespace would let a custom name shadow a built-in budget key. Identity `custom:<name>` with `^[a-z][a-z0-9-]{0,31}$` (no underscore, so the suffixes are unambiguous) instead of widening `LaneTask` to `string`, which would lose the compile-time check on built-in names. Master switch `maintenance_custom_tasks`, default off. A custom task timeout counts toward its streak. |
+| 4. systemd rendering | Variant 1 (sibling renderer over the same spec) | Variant 1 | None. Named `renderSystemdTimer` (binding decision). Offered on all three recipe surfaces, because each consumer change is one forwarded flag. |
+
+Rationale in short: the consultant's picks match the project's established seams (one module per recipe consumer, CLI-side process handlers, core-side lane kernel), and every override narrows a detail to a binding orchestrator decision without changing the architecture. The refusal of repository-declared schedule discovery, with its reasons, is recorded in `design.md`.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 4b140be1..b1b8ef89 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -367,7 +367,7 @@ because it is a report and generates nothing.
```text
o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set
o2b brain feedback Record one taste signal (--topic, --signal, --principle, --scope, ...); --scope is optional and falls back to feedback.default_scope from _brain.yaml when set
-o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
+o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd - `o2b brain maintenance run --cron-template` prints a schedule that runs it inside the maintenance lane)
o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback; Markdown links follow link_output_format / OBSIDIAN_LINK_FORMAT
@@ -601,7 +601,8 @@ o2b brain label <path> --suggest [--dimensions a,b] - read-only ad
o2b brain attr <path> <field>=<value> | --remove <field> | --show - per-type attribute fields; an undeclared field error lists the declared fields WITH descriptions
o2b brain tiers check | restore <path> [--field F] --apply | accept <path> [--field F] - staged repair for identity-tier frontmatter hand-edits
o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> - capability-gated custody; the value enters via stdin, never argv
-o2b brain maintenance run [--force] [--retry <task>] [--force-cost] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream + reindex
+o2b brain maintenance run [--force] [--retry <task|custom:name>] [--force-cost] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream, reindex, bridges, clusters and declared custom tasks
+o2b brain maintenance run --cron-template [--interval N] [--format cron|systemd] [--window H-H --tz ZONE] - print the cron or systemd recipe that schedules the lane (default interval 1h); prints and installs nothing
```
The schema pack gains four additive ontology fields (`labels`, `link_constraints`, `attributes`, `frontmatter_tiers`) with audited mutations through `o2b brain schema apply`. Link constraints enforce at index materialization: a typed edge whose endpoint page types violate the declared pairs falls back to an untyped link, `o2b brain schema lint` lists each violation, and removing the constraint restores the edges on the next index run. Tier drift detection rides the same index pass - the snapshot keeps the expected value, so reindexes never absorb a hand-edit, and `brain_doctor` warns with the open count. Filter labelled recall with `o2b search <q> --property labels=<dim>/<value>`. Secrets protect against context leakage and vault sync exposure, not against root; every custody operation lands a no-values record in `Brain/log/secret-custody/`. A maintenance gate skip exits 0 so cron never alarms on a quiet hour.
@@ -610,6 +611,10 @@ The lane's two vault-side knobs live in `Brain/_brain.yaml` under `maintenance:`
Since v1.64.0 the lane's timeouts are honest and its embedding spend is named. A task killed at its safeguard deadline exits **6** (`probeIncomplete`), keyed on `timed_out` rows alone: the only proved fact is that the pass did not finish, which is not the same as a task failing; a proved failure (1) outranks a timeout, a timeout outranks a refusal (7), and the render says TIMED OUT with the safeguard detail. The reindex task stays keyword-only unless `maintenance_embeddings: true` (env `OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS`, default `false`) opts it in; then it requests the embedding phase whenever the resolved semantic config can reach a provider, announces the pending-spend estimate before the pass, and journals the phase's own cost-gate result as the per-run receipt - model, tokens, estimated cost, and whether a bypass fired - on the task row, the journal line and the `maintenance_spend` metrics surface; the preview is an estimate by position, the receipt prices what the completed pass embedded, and a run killed mid-spend receipts nothing. `--force-cost` (MCP `force_cost`) bypasses a positive `embedding_cost_gate_usd` for this run, recorded on the receipt when it overrode a gate that would have refused. A safeguard timeout is journaled as `timed_out` and neither counts toward nor resets the failure streak that refuses a task.
+Since v1.65.0 the lane prints its own schedule and can carry an install's own upkeep. `o2b brain maintenance run --cron-template` prints a script (`~/.local/bin/osb-maintenance-<hash>.sh`, where `<hash>` is the first 8 hex characters of the SHA-256 of the resolved vault path, so each vault gets its own script, Hermes job and systemd units and re-rendering for the same vault keeps the name) and its scheduler lines - a crontab line and the Hermes form by default, a systemd user timer with `--format systemd` - with `--interval <N>m|h|d` defaulting to `1h`: the gates decide whether work happens and a gate skip exits 0, so an hourly schedule plus `--window` is the intended pattern. The script embeds the resolved vault, runs `o2b brain maintenance run --vault '<vault>' --json`, stays silent on exit 0 and prints the captured JSON and keeps the exit code otherwise. The rendered script calls `o2b` by name, so it expects `o2b` on the scheduler's PATH: cron jobs and systemd user services start with a minimal PATH, so add the install directory (usually `~/.local/bin`) to that PATH. The verb returns before the lease, the gates, the journal and the metrics, so printing a recipe leaves no trace. A bad interval, window or format, `--interval` or `--format` without `--cron-template`, a lane-run flag (`--force`, `--retry`, `--force-cost`, `--busy-minutes`, `--busy-threshold`, `--agent`, `--progress`, `--json`) beside `--cron-template`, and `status --cron-template` exit 2.
+
+Custom lane tasks (since v1.65.0) put an install's own upkeep under the lane's window, busy, pressure, lease and streak gates. They are declared in the machine config file, never in the vault: `maintenance_custom_<name>: <command>`, optionally `maintenance_custom_<name>_cwd: <absolute dir>` (default the running user's home directory; the vault is allowed when named) and `maintenance_custom_<name>_timeout_seconds: <N>` (default 120; a whole number from 1 to 1200). The lease is taken once per pass for 30 minutes, so the declared custom timeouts together stay within 1200 s, which leaves 600 s for the built-in tasks; in name order, a task whose timeout would take the sum past 1200 s is refused by name, and the full 8 tasks fit at the default. Declared tasks run only with the master switch `maintenance_custom_tasks: true` (env `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`, default off; `0` turns it off on one host). Each runs as `custom:<name>`, where `<name>` matches `^[a-z][a-z0-9-]{0,31}$` (no underscores, so the suffixes stay unambiguous, and no task can be named `tasks`), after the four built-in tasks and stale-first with them; at most 8 are declared. The command runs through `sh -c` (`cmd.exe /d /s /c` on Windows) with stdin closed, stdout discarded and `O2B_VAULT` set. Its environment is this process's minus every variable whose name declares a credential (`*_API_KEY`, `*_TOKEN`, `*_SECRET`, `*PASSWORD*` and the other names the redactor treats as secrets); `PATH`, `HOME`, `LANG`, `LC_*`, `TZ`, `TMPDIR` and `O2B_VAULT` are always kept, and a command that needs a key reads it from its own configuration. The default working directory is not the vault because the vault syncs and is writable through the MCP write tools, and on Windows a bare command name resolves in the working directory first; use absolute executable paths. A `_cwd` that does not exist fails the task as `custom task <name>: cwd does not exist: <path>`. A non-zero exit is reported as `exit <N>: <stderr tail>`, redacted and capped at 4096 bytes. The task's outcome is its shell's exit status: it does not wait for processes the command left in the background, but those still belong to the task, and on POSIX the command's whole process group is killed (SIGTERM, then SIGKILL a second later) when the timeout elapses or the o2b process exits, whichever is first, also after the shell has exited (on Windows `taskkill /T /F` kills the tree while the shell runs). Past its timeout the run is journaled as timed out, and unlike a built-in task, a custom task's timeout counts toward its `failure_streak_limit` and exits 1 rather than 6, so a command that always hangs is refused like one that always fails. A shell that exits before its timeout keeps its exit status even when a background process still holds its stderr at the deadline. `--retry custom:<name>` (MCP `retry_tasks`) attempts a refused custom task alone; an undeclared name is refused with the registered list. A bad declaration (a bad name, an empty command, an out-of-range timeout, a relative `_cwd`, a suffix key without its command, a ninth task, a timeout over the budget) is named on stderr as `custom task refused: <reason>` (MCP `custom_task_errors`) and the valid ones still run; `status` says `custom tasks declared but maintenance_custom_tasks is off` while the switch is off, or `custom tasks declared but OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS turns them off` when the env override did it. A custom task never calls a model on the lane's behalf and records no spend receipt, and the lane cannot police spend or side effects inside an operator's own command. No MCP parameter can add, edit or read a command. The config reader strips one pair of matching surrounding quotes from a value, so a command that starts and ends with the same quote character loses them; wrap such a command in single quotes (`maintenance_custom_tidy: '"/opt/my tool" --flag "x"'`).
+
### Link and recall intelligence (since v0.45.0)
```text
@@ -1238,6 +1243,8 @@ Which emitters those verbs actually have is not taken on trust. `tests/cli/progr
| `o2b search watch` | Exits **0**, unchanged: stopping is how that command ends. |
| `o2b mcp` (both transports, since v1.50.0) | Stops accepting new requests, waits for the in-flight ones to a bounded deadline, closes, and exits **130** / **143**. It is the one verb here that calls `process.exit` rather than re-raising, because two `exit` hooks - the search-store WAL checkpoint and the lock release - do not run when a process dies by signal. See "Shutdown and draining" in [`mcp.md`](mcp.md). |
+`o2b mcp` exits **70** on an uncaught exception (since v1.65.0) after naming it on stderr: the served transports install a fault guard that survives, names, rate-limits and counts unhandled promise rejections, but an exception leaves the process state unknown, so the server exits - through `process.exit`, for the same two `exit` hooks - without draining. See "Background faults" in [`mcp.md`](mcp.md).
+
For the two verbs that do hold a handle, a second interrupt is not intercepted and falls through to the default handler, so a wedged run is always killable by pressing the key twice. And an interrupt that arrives while such a verb is in a region with no checkpoint - opening a store, writing a report - is not swallowed: the verb prints `interrupted: SIGINT arrived while … stopping now` and ends with the signal's code rather than returning 0. A run the operator stopped never exits 0.
## Lock and cache overrides (since v1.61.0)
@@ -1483,7 +1490,7 @@ five files exits `1` even though everything it DID do succeeded, because
```text
o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime/vault activity plus complexity-to-thinking ratio); status ok | info | alert
-o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digest
+o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digest. The jobs file is `~/.hermes/cron/jobs.json` of the running user (since v1.65.0; before, always under the root user's home); `OSB_HERMES_JOBS` overrides it
o2b discipline uninstall Remove the cron job; --weekly removes only the weekly digest, without flag removes both
```
@@ -1495,7 +1502,7 @@ Reports on external code-project partners. Strictly read-only: never installs, i
```text
o2b partner codegraph report Resolve the in-scope code project and report the codegraph index state (no_project | absent | not_indexed | indexed with node/file/edge counts | error) plus a structural Cargo.toml workspace-member list. When indexed, runs a read-only, non-blocking graph-health gate (index.health) that flags empty-graph, collapsed-edges, dangling-references, self-loops, and cache-root-mismatch before labeling/import/recall trust the graph. Non-Rust projects report cargo_workspace: null with a reason. --vault sharpens the scan scope; --json emits the schema-versioned report; --fail-on-health exits 1 unless the index is present AND its health gate is clean, so a scheduled job can branch on it (without the flag the exit stays 0 whatever the report says)
-o2b partner codegraph resync Print a cron recipe that re-indexes the in-scope code project whenever its commit moves. --cron-template is REQUIRED (there is nothing else this verb does, and it never runs an indexer); --interval accepts <N>m|h|d and defaults to 6h; --project names the repository instead of resolving it from the scan; --vault sharpens that scan. Output is text on stdout and nothing else: the emitted script aborts on a cache-root-mismatch health warning, aborts when jq is missing rather than matching the report loosely, skips quietly when the commit is unchanged, invokes codegraph itself, and records the commit in a stamp under ${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain only after a --fail-on-health check passes
+o2b partner codegraph resync Print a cron recipe that re-indexes the in-scope code project whenever its commit moves. --cron-template is REQUIRED (there is nothing else this verb does, and it never runs an indexer); --interval accepts <N>m|h|d and defaults to 6h; --format cron|systemd (default cron, since v1.65.0) prints the crontab line or a systemd user timer pair; --project names the repository instead of resolving it from the scan; --vault sharpens that scan. Output is text on stdout and nothing else: the emitted script aborts on a cache-root-mismatch health warning, aborts when jq is missing rather than matching the report loosely, skips quietly when the commit is unchanged, invokes codegraph itself, and records the commit in a stamp under ${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain only after a --fail-on-health check passes
```
Every write in the resync recipe is a shell command the operator's own
@@ -1550,6 +1557,9 @@ o2b search reindex Rebuild the SQLite + FTS5 index from scratch
--interval <N>m|h|d sets that recipe's cadence, default 30m; an interval
cron cannot express (seconds, 60m+, 24h+, 28d+) is refused with the
reason rather than rendered as a schedule that means something else
+ --format cron|systemd selects the recipe's scheduler (default cron;
+ systemd prints a user .service/.timer pair, since v1.65.0);
+ --interval or --format without --cron-template exits 2 and runs no reindex
--self-heal <run-id> records this run's terminal outcome (or its
failure, by name) on the self_heal_reindex metrics surface under that
id; set by the detached post-upgrade rebuild, whose streams are all
diff --git a/docs/hermes-cron.md b/docs/hermes-cron.md
index d6f42db8..da2841ad 100644
--- a/docs/hermes-cron.md
+++ b/docs/hermes-cron.md
@@ -78,11 +78,13 @@ When `--silent-if-empty` is set and the window has no changes, the command write
`dream` is itself idempotent — running it on top of an unchanged Brain is a no-op (no log entry written, no snapshot taken). The chained form is safe at any cadence.
+The alternative to a hand-chained dream job is the maintenance lane, which runs dream, reindex, bridges and clusters under one lease and only inside its window: `o2b brain maintenance run --vault /path/to/vault --cron-template` prints a script and the `hermes cron create` line that schedules it (hourly by default; `--interval`, `--window H-H --tz ZONE` narrow it). The script is silent when the lane succeeds or a gate skips, and prints the lane's JSON report when a task failed, timed out or was refused, so Hermes delivers only the runs that need attention. Every recipe this CLI prints - the maintenance lane, `o2b search reindex --cron-template` and `o2b partner codegraph resync --cron-template` - also prints a systemd user timer with `--format systemd`, for a host where Hermes does not own the schedule.
+
## Discipline report (daily logging-discipline sanity-check)
`o2b discipline report` renders a deterministic Telegram MarkdownV2 block comparing brain-event counts per agent (parsed from `Brain/log/<yesterday>.md`) against runtime-agnostic activity proxies (git on watched repos + mtime walk on watched non-repo paths + vault delta on `Brain/inbox|preferences|retired/`). Status is binary - `alert` if taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero, `info` for a quiet day, `ok` otherwise. No LLM in the report path.
-`o2b discipline install --vault <v> --telegram-target <target>` writes one cron entry into the Hermes scheduler (job id derived from `sha256(vault)` so multiple vaults on one host do not collide). The configuration block lives in `Brain/_brain.yaml`:
+`o2b discipline install --vault <v> --telegram-target <target>` writes one cron entry into the Hermes scheduler (job id derived from `sha256(vault)` so multiple vaults on one host do not collide). The entry goes into `~/.hermes/cron/jobs.json` of the user running the command; set `OSB_HERMES_JOBS` to write another jobs file. The configuration block lives in `Brain/_brain.yaml`:
```yaml
discipline_report:
diff --git a/docs/mcp.md b/docs/mcp.md
index 1db22a0e..86f9ed8d 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -154,7 +154,7 @@ release because nothing checked it; its replacement is checked.
| `brain_dream` (`step`) | one step (`scan` or `heal-enrich`), not a pass | `dream` — a step is part of a dream pass, so it draws on that budget. Checked per file and per directory in `scan`, and per page in each of `heal-enrich`'s two loops, plus around the two phases that cross no boundary of their own — the vault listing (checkpoint after it only) and the one-shot title/alias phrase build (before and after). So it stops within one page **plus** whichever of those two is running, not within one page flat | yes, under the step's own stage (`scan` / `heal-enrich`) |
| `brain_bridges` (`discover`) | `bridges` | `bridges` | yes |
| `brain_clusters` (`run`) | `clusters` | `clusters` | yes |
-| `brain_maintenance` (`run`) | all four, sequentially; since v1.64.0 the reindex task stays keyword-only unless config `maintenance_embeddings` is `true`; then it requests the embedding phase when the resolved semantic config can reach a provider, announcing the predicted spend and receipting the completed pass (additive `spend` block: `banner` estimate, `receipt` with model, tokens, `estimated_usd` and whether `force_cost` overrode a refusing gate) | one fresh guard per task; a tripped task is a `timed_out` row, not an aborted call | yes, in its tasks' voices |
+| `brain_maintenance` (`run`) | the four built-ins plus declared custom tasks (since v1.65.0), sequentially; since v1.64.0 the reindex task stays keyword-only unless config `maintenance_embeddings` is `true`; then it requests the embedding phase when the resolved semantic config can reach a provider, announcing the predicted spend and receipting the completed pass (additive `spend` block: `banner` estimate, `receipt` with model, tokens, `estimated_usd` and whether `force_cost` overrode a refusing gate) | one fresh guard per task; a tripped task is a `timed_out` row, not an aborted call | yes, in its tasks' voices |
| `brain_brief` (`view: "operator"`) | `dream`, dry run | `dream` | yes |
| `brain_review_candidates` | `dream`, dry run | `dream` | yes |
@@ -638,6 +638,70 @@ dispatched, and counting it would let a client retrying in a tight loop hold
the shutdown open for its whole deadline over work the server had already
declined.
+## Background faults (since v1.65.0)
+
+A promise rejection nobody awaited used to end the server: no process-level
+fault handler was registered, so the runtime default ended the process and one
+stray rejection anywhere in core took the whole tool surface down
+mid-session, with no line on stderr that named it.
+
+`o2b mcp` now installs a fault guard on both served transports (stdio and
+`--transport http`), before the background vault refresh and before the
+transport starts, and releases it when the server stops, so the CLI's own
+top-level error handling applies again once it has:
+
+- **An unhandled rejection is survived.** It is logged on stderr by name -
+ `[mcp] unhandled_rejection #N: <reason> (server keeps serving)` plus the
+ first stack frame, and a non-Error reason is named as
+ `non-error reason: <value>` - counted, and the server goes on answering.
+ Each line is redacted before it is written, so a credential in an error
+ message (a token, or a password in a URL) does not reach the host's log.
+- **The log is rate-limited, the count is not.** Five full lines per 60
+ seconds, then one summary line (`[mcp] unhandled_rejection: N more
+ suppressed in the last 60000ms`). The summary is printed when the window
+ ends, or when the server stops first, so a suppressed count is never
+ lost; past the window the next rejection is logged in full again. A loop
+ that rejects on every request therefore cannot fill the log, and the
+ count still says how often it happened.
+- **An uncaught exception exits 70.** It is logged by name -
+ `[mcp] uncaught_exception: <reason>; exiting 70 so the exit hooks
+ checkpoint the index and release locks` plus the first stack frame - and
+ the process exits through `process.exit(70)`. A second exception thrown
+ while the process is already exiting goes straight to the exit, without
+ another line. A thrown exception
+ leaves the process in a state nothing measured, so continuing to serve
+ from it would answer requests from unknown state. Exiting rather than
+ dying keeps the two `exit` hooks described under "Shutdown and draining":
+ the search store checkpoints its WAL and the sync lockfile releases every
+ held lock.
+- **No drain on an exception.** A drain keeps serving the requests already
+ begun, which is exactly the unknown state the exit is there to leave. The
+ drain stays the answer to a signal, where the process is healthy and was
+ asked to stop.
+- **A closed stderr does not turn the guard into the crash:** the write is
+ dropped and the fault is still counted.
+
+`GET /health` on the HTTP transport carries the counts beside the drain
+fields:
+
+```json
+{
+ "status": "ok",
+ "transport": "http",
+ "in_flight": 0,
+ "faults": { "unhandled_rejection": 3, "uncaught_exception": 0, "last_fault_at": "2026-10-01T03:12:40.000Z" }
+}
+```
+
+`last_fault_at` is `null` before any fault. A supervisor can see a server
+that is surviving rejections before an operator reads its log.
+
+What happens after an exit 70 depends on the client. The Hermes bridge
+restarts the server once; Claude Code and Codex do not restart it, and the
+tools stay unavailable until the session reconnects the server. The guard is
+installed only on the served transports: `o2b mcp --probe` and every other
+`o2b` verb keep the runtime's default behaviour.
+
## Runtime capability window
Runtime capability flags are evaluated after the static scope. They can narrow
@@ -1661,3 +1725,22 @@ log line is machine-composed rather than authored.
finding. `brain_doctor` reports `merge-chain-dangling` warnings for a
`merged_into:` pointer whose canonical resolves to no file - reporting
only, with the repair named as the content judgement it is.
+- Since v1.65.0 `brain_maintenance` (`run`) also runs the custom lane tasks
+ an install declares in its machine config (`maintenance_custom_<name>`,
+ behind the default-off `maintenance_custom_tasks` switch), after the four
+ built-ins and under the same gates; they appear as `custom:<name>` task
+ rows. `retry_tasks` accepts `custom:<name>` for a declared task, refuses
+ an undeclared one by name with the registered list, and refuses a list
+ longer than the tasks this install registered; the schema `maxItems` is
+ the built-ins plus the custom-task cap of 8. A refused declaration comes
+ back in `custom_task_errors` while the valid tasks still run. No argument
+ can add, edit or read a command: commands live only in the machine
+ config, never in the vault. Once the switch is on, a caller with
+ `force: true` and `retry_tasks` can run the declared commands whenever
+ it calls, past the window and busy gates; leave the switch off on a
+ server whose callers should not. A task runs from the home directory
+ unless it declares a `_cwd`, without the variables whose names declare
+ a credential, and its background processes are killed with its process
+ group at its timeout or when the server exits. A duplicated
+ `retry_tasks` entry counts once, and the `status` notice names the env
+ override when that turned the tasks off.
diff --git a/docs/updating.md b/docs/updating.md
index a551e59d..99f4f7ef 100644
--- a/docs/updating.md
+++ b/docs/updating.md
@@ -47,6 +47,42 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed
`.claude/skills/`) and warns with the exact replacement for any stale
reference it finds (`removed-tool-reference`).
+## Upgrading to 1.65.0
+
+No step below is required, and an existing install sees no change in what
+the maintenance lane runs.
+
+**Custom maintenance lane tasks are a new opt-in.** An install can declare
+its own upkeep commands in the machine config file
+(`maintenance_custom_<name>: <command>`, with optional `_cwd` and
+`_timeout_seconds` keys); they run only once `maintenance_custom_tasks: true`
+(env `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`) is set, after the four
+built-in tasks and under the same gates. Without the switch nothing runs,
+and `o2b brain maintenance status` says so when keys are declared. A task
+runs from the running user's home directory unless it declares `_cwd`
+(the vault only when named), its environment drops every variable whose
+name declares a credential (`*_API_KEY`, `*_TOKEN`, `*_SECRET` and the
+like) while keeping `PATH`, `HOME`, `LANG`, `LC_*`, `TZ`, `TMPDIR` and
+`O2B_VAULT`, and the declared timeouts (default 120 s each) together stay
+within 1200 s of the 30-minute lease. See the maintenance lane in
+[`cli-reference.md`](cli-reference.md).
+
+**The lane can print its own schedule.** `o2b brain maintenance run
+--cron-template` prints a cron recipe, or a systemd user timer with
+`--format systemd`; it installs nothing, so an existing hand-written cron
+line keeps working as it is.
+
+**`o2b discipline install` writes the Hermes jobs file of the running
+user.** The default moved from a fixed path under the root user's home to
+`~/.hermes/cron/jobs.json`. On a host where Hermes runs as root the path is
+the same; on any other host the install used to fail and now works.
+`OSB_HERMES_JOBS` still overrides it.
+
+**A served `o2b mcp` exits 70 on an uncaught exception** and survives an
+unhandled promise rejection, naming it on stderr. A supervisor that treated
+every exit of the server the same way can now tell a fault (70) from a
+signal (130 / 143). See "Background faults" in [`mcp.md`](mcp.md).
+
## Upgrading to 1.64.0
No step below is required. Two changes are visible to a nightly cron, and
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 8e7ead23..211dfcad 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.64.0",
+ "version": "1.65.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 91edbe16..b3079f76 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1913,7 +1913,9 @@ function vaultStoreReference(vaultPath, configPath) {
}
function resolveConfigFlag(envKey, configKey, configPath) {
const env = process.env[envKey]?.trim();
- const raw = env || discoverConfig(configPath).data[configKey]?.trim();
+ return isFlagOn(env || discoverConfig(configPath).data[configKey]?.trim());
+}
+function isFlagOn(raw) {
return raw === "true" || raw === "1";
}
var PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";
diff --git a/package.json b/package.json
index c9154e65..3dc8edac 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.64.0",
+ "version": "1.65.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 5043014f..874327ae 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.64.0"
+version: "1.65.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index c84ed205..4fd16b26 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.64.0",
+ "version": "1.65.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/codex/README.md b/plugins/codex/README.md
index f665d708..2ad22c0d 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.64.0 teaches search what the operator marked and when things happened (persisted per-document event-time windows, a bounded pinned boost, opt-in rerank and metadata-boost guards, one hybrid-path deadline), teaches diagnostics to prove function instead of only inspecting state (`o2b doctor selftest`, probes for the installer's registered commands and the workspace write-back contract, honest maintenance timeouts with announced and receipted embedding spend), and names residue where it lands (near-duplicate write advisories, slug-collision and inline-tag hygiene findings, hub candidates staged at inbox drain). Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.65.0 makes the maintenance lane something an unattended host can schedule and extend (a cron recipe of its own, a systemd user timer for every recipe, install-owned `custom:<name>` upkeep tasks under the lane's gates) and keeps a served `o2b mcp` alive through a stray promise rejection, naming and counting it on stderr and in `/health`, while an uncaught exception still exits through the hooks that checkpoint the index and release the locks. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 5043014f..874327ae 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.64.0"
+version: "1.65.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 5ff97912..7cfcd217 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.64.0"
+version = "1.65.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index ff4eed27..50ed5dab 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -29,6 +29,16 @@ const RECALL_MODE_CHOICES = RECALL_TELEMETRY_MODES.join("|");
const RECALL_STATUS_CHOICES = RECALL_TELEMETRY_STATUSES.join("|");
const RECALL_CHANNEL_CHOICES = RECALL_CHANNELS.join("|");
+/**
+ * `o2b brain maintenance` usage line, defined once: the verb prints it on
+ * a usage error and its `--help` text below opens with it.
+ */
+export const MAINTENANCE_USAGE =
+ "usage: o2b brain maintenance run [--force] [--retry <task|custom:name>] [--window H-H] [--tz ZONE] " +
+ "[--busy-minutes N] [--busy-threshold N] [--force-cost] [--progress] " +
+ "| run --cron-template [--interval N] [--format cron|systemd] [--window H-H --tz ZONE] " +
+ "| status [--limit N] [--vault <path>] [--json]";
+
export const BRAIN_HELP = `usage: o2b brain <verb> [args...]
Brain verbs (observing memory):
@@ -99,7 +109,7 @@ Brain verbs (observing memory):
attr Typed-page attribute fields: assign, remove, show (schema-pack declared)
tiers Frontmatter tier guard: check identity-field drift, restore or accept
secret Capability-gated secret custody: set, list, rm, run (use w/o exposure)
- maintenance Quiet-window, lease-guarded lane (dream, reindex, bridges, clusters)
+ maintenance Quiet-window, lease-guarded lane (dream, reindex, bridges, clusters, custom tasks)
audit Render a preference's full mutation audit trail
morning-brief Session-start summary: top prefs, open questions, recent notes
codec Compress/expand session prose with the deterministic codec (stdin/--in)
@@ -599,17 +609,24 @@ export const VERB_HELP: Record<string, string> = {
"no-values record in Brain/log/secret-custody/. Protects against\n" +
"context leakage and vault sync exposure - not against root.\n",
maintenance:
- "usage: o2b brain maintenance run [--force] [--retry <task>] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]\n" +
+ MAINTENANCE_USAGE +
+ "\n" +
"Quiet-window, lease-guarded lane for heavy passes. run gates on the\n" +
"local-time window (unset = always open), recent interactive query-rate\n" +
"from recall telemetry, and an expiring SQLite lease no second worker\n" +
- "can grab, then executes dream, reindex, bridges, and clusters\n" +
- "stale-first. A task that has failed maintenance.failure_streak_limit\n" +
- "times in a row is REFUSED by name (exit 7) while the others still run;\n" +
- "--retry <task> attempts that one task with every gate still in force,\n" +
- "and --force bypasses the soft gates and every refusal, never the\n" +
- "lease. Every attempt - including gate\n" +
- "refusals - lands in a bounded journal; status renders lease + journal.\n",
+ "can grab, then executes dream, reindex, bridges, clusters and the\n" +
+ "declared custom:<name> tasks stale-first. A task that has failed\n" +
+ "maintenance.failure_streak_limit times in a row is REFUSED by name\n" +
+ "(exit 7) while the others still run; --retry <task> attempts that one\n" +
+ "task with every gate still in force, and --force bypasses the soft\n" +
+ "gates and every refusal, never the lease. Every attempt - including\n" +
+ "gate refusals - lands in a bounded journal; status renders lease +\n" +
+ "journal. Custom tasks are shell commands declared in the machine\n" +
+ "config (maintenance_custom_<name>), run only with\n" +
+ "maintenance_custom_tasks: true, from the home directory unless a\n" +
+ "_cwd is declared, with credential-named variables dropped from their\n" +
+ "environment. --cron-template prints the cron or systemd recipe that\n" +
+ "schedules the lane (default interval 1h) and installs nothing.\n",
audit:
"usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +
"Render a preference's full mutation audit trail (create / promote /\n" +
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index cf35a7f5..f6f3d5b4 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -110,7 +110,7 @@ export function usageError(message: string): number {
export { ISO_8601_RE, parseOptionalIsoDate } from "../coerce.ts";
export { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
-export { BRAIN_HELP, VERB_HELP } from "./help-text.ts";
+export { BRAIN_HELP, MAINTENANCE_USAGE, VERB_HELP } from "./help-text.ts";
export {
renderUpgradePlanJson,
printUpgradePlanText,
diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.ts
index 0d880fe9..23fe83d4 100644
--- a/src/cli/brain/verbs/maintenance.ts
+++ b/src/cli/brain/verbs/maintenance.ts
@@ -15,32 +15,20 @@
* `status` renders the lease holder and recent journal. Designed as
* the cron entry point: a dead dashboard hour surfaces as
* skipped:window in the journal instead of a contended vault.
+ * `run --cron-template [--interval N] [--format cron|systemd]` prints
+ * the recipe that schedules this very verb and returns before the
+ * lease, the gates, the journal and the metrics: it installs nothing.
*
* Exit codes: see {@link MAINTENANCE_EXIT}.
*/
-import { dream } from "../../../core/brain/dream.ts";
-import {
- discoverBridges,
- readDismissedBridges,
- writeBridgeProposals,
-} from "../../../core/brain/link-graph/bridge-discovery.ts";
-import {
- detectCommunities,
- materializeClusterNotes,
-} from "../../../core/brain/link-graph/communities.ts";
-import { appendMetric } from "../../../core/brain/metrics.ts";
import {
createSafeguard,
OPERATION,
resolveSafeguardTimeoutMs,
} from "../../../core/brain/safeguard.ts";
-import { isoSecond } from "../../../core/brain/time.ts";
-import { Store } from "../../../core/search/store.ts";
import { currentLease, MAINTENANCE_LEASE_NAME } from "../../../core/brain/maintenance/lease.ts";
import {
- isLaneTask,
- LANE_TASK,
MAINTENANCE_BUSY_MINUTES,
MAINTENANCE_BUSY_MINUTES_MAX,
MAINTENANCE_BUSY_THRESHOLD,
@@ -48,22 +36,29 @@ import {
runMaintenance,
type DailyWindow,
type LaneTask,
- type MaintenanceTask,
+ type LaneTaskId,
type MaintenanceTaskResult,
} from "../../../core/brain/maintenance/lane.ts";
import { listJournal, MAINTENANCE_JOURNAL_CAP } from "../../../core/brain/maintenance/journal.ts";
-import { createLaneReindex } from "../../../core/brain/maintenance/reindex-task.ts";
+import {
+ customTasksOffNotice,
+ resolveCustomTasks,
+} from "../../../core/brain/maintenance/custom-tasks.ts";
+import { isCustomLaneTask } from "../../../core/brain/maintenance/custom-task-id.ts";
+import { buildLaneTasks } from "../../../core/brain/maintenance/lane-tasks.ts";
import { resolveAgentName } from "../../../core/config.ts";
+import { CronTemplateError, parseRecipeFormat } from "../../cron-recipe.ts";
+import {
+ DEFAULT_MAINTENANCE_INTERVAL,
+ MAX_WINDOW_HOUR,
+ parseWindowBounds,
+ renderMaintenanceCronTemplate,
+} from "../../maintenance-cron.ts";
import type { EmbeddingSpendPreview } from "../../../core/search/indexer.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { onInterrupt } from "../../interrupt.ts";
import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";
-import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
-
-const USAGE =
- "usage: o2b brain maintenance run [--force] [--retry <task>] [--window H-H] [--tz ZONE] " +
- "[--busy-minutes N] [--busy-threshold N] [--force-cost] [--progress] | status [--limit N] " +
- "[--vault <path>] [--json]";
+import { MAINTENANCE_USAGE, brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
/**
* What this verb's exit code says, and why a refusal has its own number.
@@ -93,6 +88,9 @@ const USAGE =
* spend 6 on. Collapsing it into 1 told a nightly cron that a pass is
* broken when the only proved fact is that the pass did not finish; the
* timeout already names itself (and its budget) in the row's error.
+ * A `custom:<name>` task is the exception: its timeout is the command
+ * hanging, which the failure streak already counts as a failure, so it
+ * exits 1 and the exit code reads the row the way the journal does.
*
* Precedence follows `exitCodeForCheck` and `doctorExitCode`: a proved
* failure keeps the generic code even when another task timed out or was
@@ -110,6 +108,23 @@ export const MAINTENANCE_EXIT = Object.freeze({
export type MaintenanceExit = (typeof MAINTENANCE_EXIT)[keyof typeof MAINTENANCE_EXIT];
+/** Flags that shape a lane run and have no place in the printed recipe. */
+const RUN_ONLY_FLAGS = [
+ "force",
+ "retry",
+ "force-cost",
+ "busy-minutes",
+ "busy-threshold",
+ "agent",
+ "progress",
+ "json",
+] as const;
+
+/** A built-in task's safeguard timeout: the one row whose outcome is unmeasured. */
+function builtInTimeout(t: MaintenanceTaskResult): boolean {
+ return t.timed_out === true && !isCustomLaneTask(t.name);
+}
+
/**
* The run's exit code from the lane's task rows, keyed ONLY on rows the
* lane itself distinguished: `timed_out` (safeguard deadline, outcome
@@ -119,10 +134,10 @@ export type MaintenanceExit = (typeof MAINTENANCE_EXIT)[keyof typeof MAINTENANCE
* would make the exit 6 impossible to reach.
*/
export function maintenanceExitCode(tasks: ReadonlyArray<MaintenanceTaskResult>): MaintenanceExit {
- if (tasks.some((t) => !t.ok && t.refused !== true && t.timed_out !== true)) {
+ if (tasks.some((t) => !t.ok && t.refused !== true && !builtInTimeout(t))) {
return MAINTENANCE_EXIT.failed;
}
- if (tasks.some((t) => t.timed_out === true)) return MAINTENANCE_EXIT.probeIncomplete;
+ if (tasks.some(builtInTimeout)) return MAINTENANCE_EXIT.probeIncomplete;
return tasks.some((t) => t.refused === true) ? MAINTENANCE_EXIT.refused : MAINTENANCE_EXIT.ok;
}
@@ -140,11 +155,53 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
progress: { type: "boolean" },
json: { type: "boolean" },
"force-cost": { type: "boolean" },
+ "cron-template": { type: "boolean" },
+ interval: { type: "string" },
+ format: { type: "string" },
});
const op = positional[0];
const asJson = flags["json"] === true;
if (op !== "run" && op !== "status") {
- process.stderr.write(`${USAGE}\n`);
+ process.stderr.write(`${MAINTENANCE_USAGE}\n`);
+ return MAINTENANCE_EXIT.usage;
+ }
+
+ const cronTemplate = flags["cron-template"] === true;
+ const intervalRaw = flags["interval"] as string | undefined;
+ const formatRaw = flags["format"] as string | undefined;
+ // Named, not ignored: a recipe flag on a verb that is not printing a
+ // recipe would otherwise be accepted and do nothing, and `status
+ // --cron-template` would render the journal to someone who asked for a
+ // schedule.
+ if (cronTemplate && op === "status") {
+ process.stderr.write(
+ "brain maintenance status: --cron-template applies to run only " +
+ "(o2b brain maintenance run --cron-template)\n",
+ );
+ return MAINTENANCE_EXIT.usage;
+ }
+ if (!cronTemplate && (intervalRaw !== undefined || formatRaw !== undefined)) {
+ process.stderr.write(
+ `brain maintenance ${op}: --interval and --format apply only with --cron-template\n`,
+ );
+ return MAINTENANCE_EXIT.usage;
+ }
+ // The reverse rule: the recipe has no place for a lane-run flag, so
+ // printing it with one would schedule something other than was asked.
+ const runOnly = cronTemplate
+ ? RUN_ONLY_FLAGS.filter((name) => {
+ const value = flags[name];
+ return (
+ value !== undefined && value !== false && !(Array.isArray(value) && value.length === 0)
+ );
+ })
+ : [];
+ if (runOnly.length > 0) {
+ process.stderr.write(
+ "brain maintenance run: --cron-template prints the recipe only and does not take " +
+ runOnly.map((name) => `--${name}`).join(", ") +
+ " (a lane-run flag)\n",
+ );
return MAINTENANCE_EXIT.usage;
}
@@ -168,8 +225,12 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
}
const lease = currentLease(vault, { name: MAINTENANCE_LEASE_NAME, now });
const journal = listJournal(vault, limit);
- if (asJson) okJson({ lease, journal });
+ // Declared and switched off is said once, here, rather than left to
+ // look like a lane that forgot the operator's tasks.
+ const customOff = customTasksOffNotice(resolveCustomTasks(config ?? undefined));
+ if (asJson) okJson({ lease, journal, ...(customOff !== null ? { notice: customOff } : {}) });
else {
+ if (customOff !== null) ok(customOff);
ok(lease === null ? "lease: free" : `lease: ${lease.holder} until ${lease.expiresAt}`);
ok(`journal (${journal.length} recent):`);
for (const e of journal) {
@@ -186,16 +247,23 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
let window: DailyWindow | undefined;
const windowRaw = flags["window"] as string | undefined;
if (windowRaw !== undefined) {
- const match = /^(\d{1,2})-(\d{1,2})$/.exec(windowRaw.trim());
- const startHour = match ? Number(match[1]) : Number.NaN;
- const endHour = match ? Number(match[2]) : Number.NaN;
- if (!match || startHour > 23 || endHour > 23) {
+ // The recipe renderer's own parser, so the lane and the recipe it
+ // prints cannot disagree on what a window is.
+ const bounds = parseWindowBounds(windowRaw.trim());
+ if (bounds === null) {
process.stderr.write(
- `brain maintenance run: --window must be H-H with hours 0..23, got: ${windowRaw}\n`,
+ `brain maintenance run: --window must be H-H with hours 0..${MAX_WINDOW_HOUR}, got: ${windowRaw}\n`,
);
return MAINTENANCE_EXIT.usage;
}
- window = { startHour, endHour, tz: (flags["tz"] as string | undefined) ?? "UTC" };
+ window = { ...bounds, tz: (flags["tz"] as string | undefined) ?? "UTC" };
+ }
+ if (cronTemplate) {
+ // Before the busy flags, the lease and every gate: printing the
+ // recipe is not a lane pass, so it must leave no lease, no journal
+ // row and no metric behind. The window was validated above so a
+ // recipe never embeds a window the lane would refuse at 3 a.m.
+ return printMaintenanceRecipe(vault, intervalRaw, formatRaw, windowRaw, flags["tz"]);
}
// Same ceilings the MCP tool's schema declares and its handler
// enforces, read from the same constants beside the defaults: one
@@ -232,12 +300,12 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
// and then say nothing for the length of a full reindex, which is
// the silence this release exists to remove - and it would ALSO
// double-count, because each of the four already reports its own
- // stages. Forwarding needs no change to `MaintenanceTask`: the tasks
- // are built here, so the sink reaches them by closure, and every
+ // stages. Forwarding needs no change to `MaintenanceTask`: the shared
+ // builder hands the sink to each built-in task by closure, and every
// record names the operation that emitted it, which is exactly what
// tells a reader which task the lane is currently inside. The MCP
- // lane took the same decision for the same reason; a second shape
- // here would make the two surfaces disagree about one mechanism.
+ // lane passes its sink to the same builder; a second shape would
+ // make the two surfaces disagree about one mechanism.
const observation =
flags["progress"] === true
? attachProgress({ command: "brain", argv: ["maintenance"], jsonRequested: asJson })
@@ -271,29 +339,28 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
let result: Awaited<ReturnType<typeof runMaintenance>>;
try {
// Built once and read twice - the lane runs these, and `--retry` is
- // checked against their names. That intent is unchanged; what
- // changed is where the names come from. They were four literals
- // here and four more in `admin-tools.ts`, and the two lists drifted
- // apart twice, so both are now built from `LANE_TASK` and `--retry`
- // validates against the vocabulary rather than against whichever
- // list happens to be nearest.
+ // checked against their names. The task bodies live in one shared
+ // builder that the MCP tool calls too: the two surfaces carried
+ // inline copies of the four built-ins and the copies drifted, so
+ // neither surface spells a task any more. `taskNames` is the
+ // vocabulary THIS install registered - the built-ins plus any
+ // declared custom tasks - which is what `--retry` validates against.
//
// Inside the `try`, because the check below can return: a return
// between `onInterrupt()` and the `try` would skip `release`.
//
- // Spend is opt-in (`maintenance_embeddings`): the shared builder
- // decides whether the pass may embed, announces the predicted spend
- // inside the task and receipts what the phase priced. An offline or
- // un-opted vault stays keyword-only and reaches no provider.
- // `--force-cost` bypasses a positive gate for this run and is
- // recorded on the receipt when it did override one.
- const reindexTask = createLaneReindex({
+ // Spend is opt-in (`maintenance_embeddings`): the builder decides
+ // whether the reindex pass may embed, announces the predicted spend
+ // inside the task and receipts what the phase priced. `--force-cost`
+ // bypasses a positive gate for this run and is recorded on the
+ // receipt when it did override one.
+ const lane = buildLaneTasks({
vault,
...(config ? { configPath: config } : {}),
searchConfig,
now,
forceCost: flags["force-cost"] === true,
- safeguard: () => laneSafeguard(OPERATION.reindex),
+ safeguardFor: laneSafeguard,
signal: interrupt.signal,
...laneProgress,
...(asJson
@@ -303,91 +370,26 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
ok(formatSpendBanner(preview, searchConfig.semantic.costGateUsd)),
}),
});
- const laneTasks: ReadonlyArray<MaintenanceTask> = [
- {
- name: LANE_TASK.dream,
- run: async () => {
- dream(vault, { now, safeguard: laneSafeguard(OPERATION.dream), ...laneProgress });
- },
- },
- reindexTask.task,
- // Link-recall-intelligence passes ride the same lease, after
- // reindex so they see fresh edges. Both are fail-soft inside:
- // a vault without embeddings simply proposes nothing.
- {
- name: LANE_TASK.bridges,
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const report = discoverBridges(store, {
- dismissed: readDismissedBridges(vault),
- safeguard: laneSafeguard(OPERATION.bridges),
- ...laneProgress,
- });
- writeBridgeProposals(vault, report, { now });
- try {
- appendMetric(vault, {
- surface: "bridge_discovery",
- runAt: isoSecond(now),
- payload: {
- proposals: report.proposals.length,
- scanned_candidates: report.scannedCandidates,
- vec_available: report.vecAvailable,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- {
- name: LANE_TASK.clusters,
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const communities = detectCommunities(store, {
- safeguard: laneSafeguard(OPERATION.clusters),
- ...laneProgress,
- });
- const materialized = materializeClusterNotes(vault, communities, { store, now });
- try {
- appendMetric(vault, {
- surface: "communities",
- runAt: isoSecond(now),
- payload: {
- communities: communities.length,
- sizes: communities.map((c) => c.size),
- written: materialized.written.length,
- removed: materialized.removed.length,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- ];
- const requested = stringArrayFlag(flags["retry"]);
- const unknownRetries = requested.filter((name) => !isLaneTask(name));
+ // Named, never dropped: a refused declaration journals nothing, and
+ // the valid tasks still run.
+ for (const reason of lane.custom.errors) {
+ process.stderr.write(`custom task refused: ${reason}\n`);
+ }
+ const registered = new Set<string>(lane.taskNames);
+ // Deduplicated, as the MCP tool does: naming a task twice retries it once.
+ const requested = [...new Set(stringArrayFlag(flags["retry"]))];
+ const unknownRetries = requested.filter((name) => !registered.has(name));
if (unknownRetries.length > 0) {
// Named, not ignored: a typo that silently retried nothing would
// leave the operator reading a refusal they thought they had just
// asked past.
process.stderr.write(
`brain maintenance run: --retry names no lane task: ${unknownRetries.join(", ")} ` +
- `(tasks: ${laneTasks.map((task) => task.name).join(", ")})\n`,
+ `(tasks: ${lane.taskNames.join(", ")})\n`,
);
return MAINTENANCE_EXIT.usage;
}
- const retryTasks = requested.filter(isLaneTask);
+ const retryTasks = requested as LaneTaskId[];
result = await runMaintenance(vault, {
now,
holder,
@@ -395,12 +397,12 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
...(window !== undefined ? { window } : {}),
busy: { minutes: busyMinutes, threshold: busyThreshold },
...(retryTasks.length > 0 ? { retryTasks } : {}),
- tasks: laneTasks,
+ tasks: lane.tasks,
});
// The run-level spend block: the banner this run announced and the
// receipt its reindex pass returned, both absent when nothing spent.
- const spend = reindexTask.spendBlock(result.tasks);
+ const spend = lane.reindex.spendBlock(result.tasks);
if (asJson) {
okJson({
verdict: result.verdict,
@@ -442,6 +444,37 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
}
}
+/**
+ * Print the lane's cron or systemd recipe for `vault`. A bad interval or
+ * format is the lane's usage code 2, not the 1 the two older recipe
+ * surfaces return: in this verb's vocabulary 1 means "attempted and
+ * failed" (see {@link MAINTENANCE_EXIT}).
+ */
+function printMaintenanceRecipe(
+ vault: string,
+ intervalRaw: string | undefined,
+ formatRaw: string | undefined,
+ windowRaw: string | undefined,
+ tzRaw: unknown,
+): MaintenanceExit {
+ try {
+ const body = renderMaintenanceCronTemplate(intervalRaw ?? DEFAULT_MAINTENANCE_INTERVAL, {
+ vault,
+ format: parseRecipeFormat(formatRaw),
+ ...(windowRaw !== undefined ? { window: windowRaw.trim() } : {}),
+ ...(typeof tzRaw === "string" ? { tz: tzRaw } : {}),
+ });
+ process.stdout.write(body.endsWith("\n") ? body : `${body}\n`);
+ return MAINTENANCE_EXIT.ok;
+ } catch (err) {
+ if (err instanceof CronTemplateError) {
+ process.stderr.write(`brain maintenance run: ${err.message}\n`);
+ return MAINTENANCE_EXIT.usage;
+ }
+ throw err;
+ }
+}
+
/**
* One task row of the human run report. A refusal is rendered as neither
* `ok` nor FAILED and carries no duration - the task never ran, and
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 5fb3403c..ef26e223 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -303,7 +303,41 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("attr", "Assign, remove, or show typed-page attribute fields"),
command("tiers", "Check, restore, or accept identity-field drift"),
command("secret", "Capability-gated secret custody: set, list, rm, run"),
- command("maintenance", "Quiet-window, lease-guarded heavy maintenance lane"),
+ command(
+ "maintenance",
+ "Quiet-window, lease-guarded heavy maintenance lane",
+ [],
+ [
+ // The whole `run` schema: the lane is the cron entry point, and
+ // `--cron-template` is the only way to reach its recipe, so a
+ // flag missing here would be missing from help and completions.
+ command(
+ "run",
+ "Run the lane tasks behind its gates, or print a cron or systemd recipe with --cron-template (writes nothing)",
+ [
+ flag("vault", "string"),
+ flag("force", "boolean"),
+ flag("retry", "string-array"),
+ flag("window", "string"),
+ flag("tz", "string"),
+ flag("busy-minutes", "string"),
+ flag("busy-threshold", "string"),
+ flag("agent", "string"),
+ flag("progress", "boolean"),
+ flag("json", "boolean"),
+ flag("force-cost", "boolean"),
+ flag("cron-template", "boolean"),
+ flag("interval", "string"),
+ flag("format", "string"),
+ ],
+ ),
+ command("status", "Render the lane lease holder and recent journal", [
+ flag("vault", "string"),
+ flag("limit", "string"),
+ flag("json", "boolean"),
+ ]),
+ ],
+ ),
command("audit", "Render mutation audit trail"),
command(
"generation-reports",
@@ -777,6 +811,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("progress", "boolean"),
flag("cron-template", "boolean"),
flag("interval", "string"),
+ flag("format", "string"),
flag("self-heal", "string"),
]),
command("watch", "Watch the vault and incrementally sync the index on .md edits"),
@@ -932,10 +967,11 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
]),
command(
"resync",
- "Print a cron recipe that re-indexes the code project when its commit moves (requires --cron-template; writes nothing)",
+ "Print a cron or systemd recipe that re-indexes the code project when its commit moves (requires --cron-template; writes nothing)",
[
flag("cron-template", "boolean"),
flag("interval", "string"),
+ flag("format", "string"),
flag("project", "string"),
flag("vault", "string"),
],
diff --git a/src/cli/cron-recipe.ts b/src/cli/cron-recipe.ts
index e9a8d89c..f03c5f13 100644
--- a/src/cli/cron-recipe.ts
+++ b/src/cli/cron-recipe.ts
@@ -37,6 +37,17 @@
* Inputs outside those bounds raise a CronTemplateError naming what the
* field can express, rather than a schedule that quietly means something
* else.
+ *
+ * A second renderer, {@link renderSystemdTimer}, reads the same spec and
+ * prints the same script section followed by a systemd user service and
+ * timer pair instead of the crontab and Hermes paths. It is print-only in
+ * exactly the same way: the unit files, `systemctl --user` and
+ * `loginctl enable-linger` are commands the operator runs, never this
+ * CLI. It validates the interval through the same {@link parseInterval},
+ * so a cadence cron cannot express is refused in both formats with the
+ * same message - a recipe cannot say one thing in cron and another in
+ * systemd. {@link parseRecipeFormat} maps a `--format` flag onto one of
+ * {@link RECIPE_FORMATS}.
*/
export class CronTemplateError extends Error {
@@ -46,6 +57,67 @@ export class CronTemplateError extends Error {
}
}
+/**
+ * Single-quote a value for bash, the way `discipline-install.ts` quotes
+ * the vault it bakes into its job: a quote inside the value closes the
+ * string, emits an escaped quote and reopens it. Inside single quotes a
+ * backslash, a `$` and a backtick are literal, so nothing else needs
+ * escaping. Every operator path a recipe bakes into its script goes
+ * through here.
+ */
+export function shellQuote(value: string): string {
+ return "'" + value.replace(/'/gu, "'\\''") + "'";
+}
+
+/** A line feed or a carriage return anywhere in a value. */
+const LINE_BREAK_PATTERN = /[\n\r]/u;
+
+/**
+ * Refuse a path that would not survive being baked into a recipe. The
+ * script travels inside a heredoc, so a line break in a baked value
+ * could end that heredoc early; no real vault or repository path needs
+ * one. Returns the value unchanged when it is a single line.
+ */
+export function singleLinePath(label: string, value: string): string {
+ if (LINE_BREAK_PATTERN.test(value)) {
+ throw new CronTemplateError(
+ label + " path must not contain a line break, got: " + JSON.stringify(value),
+ );
+ }
+ return value;
+}
+
+/** Every recipe format a `--format` flag can select; the first is the default. */
+export const RECIPE_FORMATS = Object.freeze(["cron", "systemd"] as const);
+
+export type RecipeFormat = (typeof RECIPE_FORMATS)[number];
+
+/** The format a recipe verb renders when no `--format` is given. */
+const DEFAULT_RECIPE_FORMAT: RecipeFormat = RECIPE_FORMATS[0];
+
+function isRecipeFormat(value: string): value is RecipeFormat {
+ return (RECIPE_FORMATS as ReadonlyArray<string>).includes(value);
+}
+
+/**
+ * Map a `--format` flag value onto a recipe format. No flag means cron, the
+ * format every recipe printed before systemd existed. Anything else that is
+ * not a known format is a {@link CronTemplateError}, which every recipe verb
+ * already reports through its own refusal exit.
+ */
+export function parseRecipeFormat(raw: string | undefined): RecipeFormat {
+ if (raw === undefined) return DEFAULT_RECIPE_FORMAT;
+ if (isRecipeFormat(raw)) return raw;
+ throw new CronTemplateError(
+ "unknown recipe format " +
+ JSON.stringify(raw) +
+ ": expected " +
+ RECIPE_FORMATS.slice(0, -1).join(", ") +
+ " or " +
+ RECIPE_FORMATS[RECIPE_FORMATS.length - 1],
+ );
+}
+
/** Cron's minute field restarts every hour, so a step must stay under it. */
const MINUTES_PER_HOUR = 60;
@@ -73,6 +145,11 @@ export interface ParsedInterval {
readonly human: string;
/** Schedule string for 'hermes cron create --schedule ...'. */
readonly hermesSchedule: string;
+ /**
+ * The same cadence as a systemd time span (`30m`, `6h`, `1d`): the
+ * normalised `<N><unit>`, which systemd reads natively for m, h and d.
+ */
+ readonly systemdSpan: string;
}
export function parseInterval(raw: string): ParsedInterval {
@@ -85,6 +162,7 @@ export function parseInterval(raw: string): ParsedInterval {
}
const n = parseInt(m[1]!, 10);
const unit = m[2]!;
+ const systemdSpan = n + unit;
if (n <= 0) {
throw new CronTemplateError("interval must be positive; got " + JSON.stringify(raw));
}
@@ -105,7 +183,7 @@ export function parseInterval(raw: string): ParsedInterval {
);
}
const cron = "*/" + n + " * * * *";
- return { cron, human: n + " minutes", hermesSchedule: cron };
+ return { cron, human: n + " minutes", hermesSchedule: cron, systemdSpan };
}
if (unit === "h") {
if (n >= HOURS_PER_DAY) {
@@ -115,7 +193,7 @@ export function parseInterval(raw: string): ParsedInterval {
);
}
const cron = "0 */" + n + " * * *";
- return { cron, human: n + " hours", hermesSchedule: cron };
+ return { cron, human: n + " hours", hermesSchedule: cron, systemdSpan };
}
// unit === "d". The day-of-month field is the one that cannot be widened
// by moving to a larger unit, because there is none - so the refusal
@@ -137,7 +215,7 @@ export function parseInterval(raw: string): ParsedInterval {
);
}
const cron = "0 0 */" + n + " * *";
- return { cron, human: n + " days", hermesSchedule: cron };
+ return { cron, human: n + " days", hermesSchedule: cron, systemdSpan };
}
/** Options every recipe accepts. Consumers widen this with their own inputs. */
@@ -199,6 +277,25 @@ const RULE = "# ----------------------------------------------------------------
/** Prefix of the commentary lines under the script section. */
const NOTE_PREFIX = "## ";
+/** Where a systemd user manager reads unit files from, in tilde form. */
+const SYSTEMD_USER_UNIT_DIR = "~/.config/systemd/user/";
+
+/**
+ * systemd's own home-directory specifier. `ExecStart=` expands no tilde
+ * and no shell variable, so a tilde-relative script path reaches the unit
+ * in this form.
+ */
+const SYSTEMD_HOME_PREFIX = "%h/";
+
+/**
+ * Delay after boot before the first run. The timer is monotonic
+ * (`OnBootSec=` plus `OnUnitActiveSec=`), not calendar based: without an
+ * `OnBootSec=` it has no first activation after a reboot and never fires
+ * again. `Persistent=` applies to `OnCalendar=` timers only, so the unit
+ * carries none; the boot delay is what catches up after downtime.
+ */
+const SYSTEMD_BOOT_DELAY = "5m";
+
/**
* Conventional install path for a recipe's script, derived from the cron
* job name so the two can never drift: `osb-reindex` becomes
@@ -220,35 +317,57 @@ function homeExpanded(path: string): string {
: path;
}
+/** The `%h` form of a tilde-relative path, for `ExecStart=`. */
+function systemdHomeExpanded(path: string): string {
+ return path.startsWith(TILDE_HOME_PREFIX)
+ ? SYSTEMD_HOME_PREFIX + path.slice(TILDE_HOME_PREFIX.length)
+ : path;
+}
+
+/** What both renderers derive from one call before printing anything. */
+interface RecipeInputs<TOptions extends CronRecipeOptions> {
+ readonly parsed: ParsedInterval;
+ readonly resolved: ResolvedCronRecipeOptions<TOptions>;
+}
+
/**
- * Render one recipe: header, script section, native crontab section,
- * scheduler section, footer. Throws {@link CronTemplateError} for an
- * interval cron cannot express - the caller reports it rather than
- * emitting a recipe on a cadence the scheduler would silently round.
+ * Validate the interval and fill the option defaults. Shared so the two
+ * renderers refuse the same intervals with the same message.
*/
-export function renderCronRecipe<TOptions extends CronRecipeOptions>(
- spec: CronRecipeSpec<TOptions>,
+function recipeInputs<TOptions extends CronRecipeOptions>(
interval: string,
opts: TOptions,
-): string {
+): RecipeInputs<TOptions> {
const parsed = parseInterval(interval);
const resolved: ResolvedCronRecipeOptions<TOptions> = {
...opts,
o2bBin: opts.o2bBin ?? DEFAULT_O2B_BIN,
};
- const header =
+ return { parsed, resolved };
+}
+
+/** The opening block: title, interval and the format's own lead lines. */
+function renderHeader(title: string, parsed: ParsedInterval, lead: ReadonlyArray<string>): string {
+ return (
RULE +
"# " +
- spec.title +
+ title +
"\n" +
"# interval: " +
parsed.human +
"\n" +
"#\n" +
- "# Pick ONE of the three paths below. The watchdog script is the\n" +
- "# common piece; both crontab and Hermes-cron rely on it.\n" +
- RULE;
- const watchdog =
+ lead.map((line) => "# " + line + "\n").join("") +
+ RULE
+ );
+}
+
+/** Section 1, identical in every format: save the script, make it executable. */
+function renderScriptSection<TOptions extends CronRecipeOptions>(
+ spec: CronRecipeSpec<TOptions>,
+ resolved: ResolvedCronRecipeOptions<TOptions>,
+): string {
+ return (
"## 1. Watchdog script - save to " +
spec.scriptPath +
"\n" +
@@ -264,7 +383,35 @@ export function renderCronRecipe<TOptions extends CronRecipeOptions>(
"\n" +
"chmod +x " +
spec.scriptPath +
- "\n";
+ "\n"
+ );
+}
+
+/** The closing block: how the operator checks the install worked. */
+function renderFooter<TOptions extends CronRecipeOptions>(
+ spec: CronRecipeSpec<TOptions>,
+ resolved: ResolvedCronRecipeOptions<TOptions>,
+): string {
+ return RULE + "# After install, verify with: " + spec.buildVerifyCommand(resolved) + "\n" + RULE;
+}
+
+/**
+ * Render one recipe: header, script section, native crontab section,
+ * scheduler section, footer. Throws {@link CronTemplateError} for an
+ * interval cron cannot express - the caller reports it rather than
+ * emitting a recipe on a cadence the scheduler would silently round.
+ */
+export function renderCronRecipe<TOptions extends CronRecipeOptions>(
+ spec: CronRecipeSpec<TOptions>,
+ interval: string,
+ opts: TOptions,
+): string {
+ const { parsed, resolved } = recipeInputs(interval, opts);
+ const header = renderHeader(spec.title, parsed, [
+ "Pick ONE of the three paths below. The watchdog script is the",
+ "common piece; both crontab and Hermes-cron rely on it.",
+ ]);
+ const watchdog = renderScriptSection(spec, resolved);
const nativeCron =
"## 2. Native crontab - open 'crontab -e' and append:\n" +
"\n" +
@@ -288,7 +435,101 @@ export function renderCronRecipe<TOptions extends CronRecipeOptions>(
homeExpanded(spec.scriptPath) +
'" \\\n' +
" --no-agent\n";
- const footer =
- RULE + "# After install, verify with: " + spec.buildVerifyCommand(resolved) + "\n" + RULE;
+ const footer = renderFooter(spec, resolved);
return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer].join("\n");
}
+
+/**
+ * Render one recipe as a systemd user timer: header, the same script
+ * section {@link renderCronRecipe} prints, a `.service`/`.timer` pair to
+ * save under `~/.config/systemd/user/`, the commands that load and enable
+ * the timer, the lingering note, and the same verify footer.
+ *
+ * Print-only, like the cron form: every file and every `systemctl` call
+ * in the output is the operator's to run. Throws
+ * {@link CronTemplateError} for exactly the intervals the cron form
+ * refuses, so switching `--format` never changes which cadences exist.
+ */
+export function renderSystemdTimer<TOptions extends CronRecipeOptions>(
+ spec: CronRecipeSpec<TOptions>,
+ interval: string,
+ opts: TOptions,
+): string {
+ const { parsed, resolved } = recipeInputs(interval, opts);
+ const servicePath = SYSTEMD_USER_UNIT_DIR + spec.cronName + ".service";
+ const timerPath = SYSTEMD_USER_UNIT_DIR + spec.cronName + ".timer";
+ const timerUnit = spec.cronName + ".timer";
+ const header = renderHeader(spec.title, parsed, [
+ "systemd user timer. Save the script and both units below, then",
+ "enable the timer. Nothing here is installed for you.",
+ ]);
+ const watchdog = renderScriptSection(spec, resolved);
+ const service =
+ "## 2. systemd service - save to " +
+ servicePath +
+ "\n" +
+ "\n" +
+ "mkdir -p " +
+ SYSTEMD_USER_UNIT_DIR +
+ "\n" +
+ "cat >" +
+ servicePath +
+ " <<'" +
+ HEREDOC_MARKER +
+ "'\n" +
+ "[Unit]\n" +
+ "Description=" +
+ spec.title +
+ "\n" +
+ "\n" +
+ "[Service]\n" +
+ "Type=oneshot\n" +
+ "ExecStart=" +
+ systemdHomeExpanded(spec.scriptPath) +
+ "\n" +
+ HEREDOC_MARKER +
+ "\n";
+ const timer =
+ "## 3. systemd timer - save to " +
+ timerPath +
+ "\n" +
+ "\n" +
+ "cat >" +
+ timerPath +
+ " <<'" +
+ HEREDOC_MARKER +
+ "'\n" +
+ "[Unit]\n" +
+ "Description=" +
+ spec.title +
+ " (every " +
+ parsed.human +
+ ")\n" +
+ "\n" +
+ "[Timer]\n" +
+ "OnBootSec=" +
+ SYSTEMD_BOOT_DELAY +
+ "\n" +
+ "OnUnitActiveSec=" +
+ parsed.systemdSpan +
+ "\n" +
+ "\n" +
+ "[Install]\n" +
+ "WantedBy=timers.target\n" +
+ HEREDOC_MARKER +
+ "\n";
+ const enable =
+ "## 4. Load and enable the timer:\n" +
+ "\n" +
+ "systemctl --user daemon-reload\n" +
+ "systemctl --user enable --now " +
+ timerUnit +
+ "\n" +
+ "\n" +
+ NOTE_PREFIX +
+ "A user timer stops with your last session unless lingering is on;\n" +
+ NOTE_PREFIX +
+ "run 'loginctl enable-linger \"$USER\"' once so it keeps firing.\n";
+ const footer = renderFooter(spec, resolved);
+ return [header, "", watchdog, "", service, "", timer, "", enable, "", footer].join("\n");
+}
diff --git a/src/cli/discipline-install.ts b/src/cli/discipline-install.ts
index e012aefe..35ffd578 100644
--- a/src/cli/discipline-install.ts
+++ b/src/cli/discipline-install.ts
@@ -1,25 +1,78 @@
/**
* `o2b discipline install` / `o2b discipline uninstall` verb handlers.
*
- * Manages the Hermes cron job that delivers the daily OSB discipline report
- * to a Telegram topic. The real cron config lives at DEFAULT_JOBS_FILE;
- * tests override via the OSB_HERMES_JOBS env var to avoid touching the
- * user's live config.
+ * Manages the Hermes cron job that delivers the daily Open Second Brain
+ * discipline report to a Telegram topic. The real cron config is the
+ * Hermes jobs file under the home directory of the user running the verb
+ * (see {@link resolveJobsFilePath}); OSB_HERMES_JOBS names another file,
+ * which is also how tests avoid touching the user's live config.
*/
import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import { homedir } from "node:os";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { atomicWriteFileSync } from "../core/fs-atomic.ts";
-const DEFAULT_JOBS_FILE = "/root/.hermes/cron/jobs.json";
+/** Env var that names the jobs file explicitly. */
+const JOBS_FILE_ENV = "OSB_HERMES_JOBS";
-function jobsFilePath(): string {
- return process.env.OSB_HERMES_JOBS ?? DEFAULT_JOBS_FILE;
+/** Where Hermes keeps its cron jobs, relative to the home directory. */
+const JOBS_FILE_SEGMENTS = Object.freeze([".hermes", "cron", "jobs.json"]);
+
+/** No home directory and no override: there is no jobs file to name. */
+export class HermesJobsPathError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "HermesJobsPathError";
+ }
+}
+
+/**
+ * The Hermes jobs file this verb reads and writes: `OSB_HERMES_JOBS` when
+ * set and non-empty, otherwise `~/.hermes/cron/jobs.json` of the running
+ * user. The default used to be the root user's file whatever the user,
+ * so on a non-root Hermes host install wrote where Hermes never reads (or
+ * failed on permissions). Root hosts resolve to the same path as before.
+ * An empty home with no override is a named error rather than a relative
+ * `.hermes/...` path written into whatever directory the verb ran in.
+ */
+export function resolveJobsFilePath(
+ env: Readonly<Record<string, string | undefined>>,
+ home: string,
+): string {
+ const override = env[JOBS_FILE_ENV];
+ if (override !== undefined && override !== "") return override;
+ if (home === "") {
+ throw new HermesJobsPathError(
+ "o2b discipline: cannot resolve the home directory to find the Hermes jobs file; " +
+ "set " +
+ JOBS_FILE_ENV +
+ " to its path",
+ );
+ }
+ return join(home, ...JOBS_FILE_SEGMENTS);
}
+/**
+ * The jobs file for this process, or `null` after naming on stderr why it
+ * cannot be resolved.
+ */
+function jobsFilePathOrReport(): string | null {
+ try {
+ return resolveJobsFilePath(process.env, homedir());
+ } catch (err) {
+ if (!(err instanceof HermesJobsPathError)) throw err;
+ process.stderr.write(err.message + "\n");
+ return null;
+ }
+}
+
+/** Exit when the jobs file cannot be located: an environment problem, not argv. */
+const EXIT_JOBS_PATH_UNRESOLVED = 1;
+
/**
* Resolve the absolute path to `bin/o2b-discipline-report` from this
* module's own location instead of hardcoding `/srv/projects/...`. The
@@ -138,7 +191,8 @@ export async function disciplineInstallVerb(args: string[], defaultVault: string
);
return 2;
}
- const file = jobsFilePath();
+ const file = jobsFilePathOrReport();
+ if (file === null) return EXIT_JOBS_PATH_UNRESOLVED;
const data = loadJobs(file);
const id = weekly ? weeklyJobId(vault) : jobId(vault);
const existing = data.jobs.find((j) => j.id === id);
@@ -185,7 +239,8 @@ export async function disciplineUninstallVerb(
process.stderr.write("o2b discipline uninstall: --vault is required\n");
return 2;
}
- const file = jobsFilePath();
+ const file = jobsFilePathOrReport();
+ if (file === null) return EXIT_JOBS_PATH_UNRESOLVED;
const data = loadJobs(file);
const ids = weekly ? [weeklyJobId(vault)] : [jobId(vault), weeklyJobId(vault)];
const before = data.jobs.length;
diff --git a/src/cli/main.ts b/src/cli/main.ts
index a50f99f3..a5750aee 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -48,6 +48,7 @@ import { handleSearchSubcommand } from "./search.ts";
import { handleDecisionModelSubcommand } from "./decision-model.ts";
import { handleStateSubcommand } from "./state.ts";
import { installMcpSignalDrain, type McpSignalDrainHandle } from "./mcp-drain.ts";
+import { installMcpFaultGuard } from "./mcp-fault-guard.ts";
import { handleVaultSubcommand } from "./vault.ts";
import {
NoVaultConfiguredError,
@@ -849,65 +850,78 @@ async function cmdMcp(argv: string[]): Promise<number> {
const vault = requireVault(flags["vault"] as string | undefined, config);
const repoRoot = (flags["repo"] as string | undefined) ?? null;
- // 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") {
- void ensureVaultCurrent(vault, { background: true, configPath: config }).catch(() => {
- // best-effort; the server must come up regardless
- });
- }
+ // 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") {
+ void ensureVaultCurrent(vault, { background: true, configPath: config }).catch(() => {
+ // best-effort; the server must come up regardless
+ });
+ }
+
+ if (transport === "http") {
+ const handle = await startHttp(
+ { vault, configPath: config, repoRoot },
+ { host, port, apiKey, faultCounts: () => faults.counts() },
+ { scope, serverName, capabilityWindow, hostTarget },
+ );
+ // 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=${vault})\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;
+ }
- if (transport === "http") {
- const handle = await startHttp(
- { vault, configPath: config, repoRoot },
- { host, port, apiKey },
- { scope, serverName, capabilityWindow, hostTarget },
- );
- // 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=${vault})\n`,
+ `[mcp] ${serverName} ${SERVER_VERSION} listening on stdio (vault=${vault})\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() });
+ // 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 {
- // `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));
+ const code = await serveStdio(
+ { vault, configPath: config, repoRoot },
+ {
+ onStart: (live) => {
+ stdio.signals = installMcpSignalDrain({ close: () => live.close() });
+ },
+ },
+ { scope, serverName, capabilityWindow, hostTarget },
+ );
+ return stdio.signals?.exitCode() ?? code;
} finally {
- signals.release();
+ stdio.signals?.release();
}
- return signals.exitCode() ?? 0;
- }
-
- process.stderr.write(
- `[mcp] ${serverName} ${SERVER_VERSION} listening on stdio (vault=${vault})\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: (transport) => {
- stdio.signals = installMcpSignalDrain({ close: () => transport.close() });
- },
- },
- { scope, serverName, capabilityWindow, hostTarget },
- );
- return stdio.signals?.exitCode() ?? code;
} finally {
- stdio.signals?.release();
+ faults.release();
}
}
diff --git a/src/cli/maintenance-cron.ts b/src/cli/maintenance-cron.ts
new file mode 100644
index 00000000..6c3d8615
--- /dev/null
+++ b/src/cli/maintenance-cron.ts
@@ -0,0 +1,242 @@
+/**
+ * `o2b brain maintenance run --cron-template` renderer.
+ *
+ * The maintenance lane is the cron entry point for the heavy passes: it
+ * gates itself on the quiet window, recent interactive load, memory
+ * pressure, its lease and each task's failure streak, and a gate skip
+ * exits 0. So the intended schedule is a frequent, dumb trigger - hourly
+ * by default - and the lane decides whether any work happens. This module
+ * is that trigger's recipe, a third consumer of the shared kernel in
+ * `cron-recipe.ts`: text on stdout in either the cron or the systemd
+ * format, never a file, a unit or a scheduler entry written by this CLI.
+ *
+ * A scheduler runs the script without the operator's shell environment,
+ * so the recipe bakes in what the lane cannot discover on its own: the
+ * vault, and the window and zone when the operator gave them. The vault
+ * is single-quoted; the window and the zone must be plain tokens, because
+ * they are pasted into a shell line and a value that needs quoting is
+ * almost certainly not a window or a zone.
+ *
+ * The script keeps the lane's exit code. Exit 0 (ran, or skipped by a
+ * gate) prints nothing, so cron mails nothing; any other exit prints the
+ * lane's JSON verdict and exits with the same code, so cron mail or a
+ * Hermes job surfaces it.
+ */
+
+import { createHash } from "node:crypto";
+import { resolve } from "node:path";
+
+import {
+ CronTemplateError,
+ operatorScriptPath,
+ parseRecipeFormat,
+ renderCronRecipe,
+ renderSystemdTimer,
+ shellQuote,
+ singleLinePath,
+ type CronRecipeOptions,
+ type CronRecipeSpec,
+ type RecipeFormat,
+} from "./cron-recipe.ts";
+
+/**
+ * Stem of the per-vault job name. The full name appends a vault suffix
+ * ({@link maintenanceCronName}), because the script bakes in its vault.
+ */
+export const MAINTENANCE_CRON_NAME = "osb-maintenance";
+
+/** Hex characters of the vault hash the job name carries. */
+const VAULT_SUFFIX_LENGTH = 8;
+
+/**
+ * The job name for one vault: the stem plus the first hex characters of
+ * `sha256(resolve(vault))`, the same scheme `discipline install` uses for
+ * its job id. The script, the Hermes job and the systemd units all take
+ * this name, so a second vault's recipe never overwrites the first's, and
+ * re-rendering for the same vault yields the same name.
+ */
+export function maintenanceCronName(vault: string): string {
+ const suffix = createHash("sha256")
+ .update(resolve(vault))
+ .digest("hex")
+ .slice(0, VAULT_SUFFIX_LENGTH);
+ return MAINTENANCE_CRON_NAME + "-" + suffix;
+}
+
+/**
+ * Cadence when the caller names none. Hourly is cheap because the lane's
+ * own gates make most firings a quiet exit 0; `--window` narrows when the
+ * work actually happens.
+ */
+export const DEFAULT_MAINTENANCE_INTERVAL = "1h";
+
+/** Inputs the maintenance recipe needs on top of the shared ones. */
+export interface MaintenanceCronOptions extends CronRecipeOptions {
+ /** Absolute vault path the scheduled run targets. */
+ readonly vault: string;
+ /** Quiet window as `H-H`, forwarded to `--window`. */
+ readonly window?: string;
+ /** Time zone of the window, forwarded to `--tz`. */
+ readonly tz?: string;
+}
+
+/** The lane verb the emitted script runs, and the one the footer checks. */
+const RUN_COMMAND = "brain maintenance run";
+const STATUS_COMMAND = "brain maintenance status";
+
+/**
+ * `H-H` with hours 0..23: the one shape of a quiet window, shared by the
+ * lane's own `--window` parser and this recipe so the two cannot drift.
+ */
+export const MAINTENANCE_WINDOW_PATTERN = /^(\d{1,2})-(\d{1,2})$/u;
+
+/** Highest hour a window bound may name. */
+export const MAX_WINDOW_HOUR = 23;
+
+/** The two bounds of a quiet window, in hours. */
+export interface WindowBounds {
+ readonly startHour: number;
+ readonly endHour: number;
+}
+
+/**
+ * Parse an `H-H` window into its bounds, or null when the value is not
+ * that shape or names an hour above {@link MAX_WINDOW_HOUR}. Callers
+ * word their own refusal.
+ */
+export function parseWindowBounds(raw: string): WindowBounds | null {
+ const match = MAINTENANCE_WINDOW_PATTERN.exec(raw);
+ if (!match) return null;
+ const startHour = Number(match[1]);
+ const endHour = Number(match[2]);
+ if (startHour > MAX_WINDOW_HOUR || endHour > MAX_WINDOW_HOUR) return null;
+ return { startHour, endHour };
+}
+
+/**
+ * Characters an IANA zone name (`Europe/Berlin`, `Etc/GMT+3`, `UTC`) is
+ * made of, none of which a shell treats specially. The first character
+ * is a letter, so a zone can never look like a flag (`--force`).
+ */
+const TZ_PATTERN = /^[A-Za-z][A-Za-z0-9_+\-/]*$/u;
+
+/** The window as given, after proving it is a plain `H-H` token. */
+function checkedWindow(raw: string): string {
+ if (parseWindowBounds(raw) === null) {
+ throw new CronTemplateError(
+ "--window must be H-H with hours 0.." + MAX_WINDOW_HOUR + ", got: " + JSON.stringify(raw),
+ );
+ }
+ return raw;
+}
+
+/** Whether the runtime knows the zone, the same check the lane makes. */
+function isKnownTimeZone(zone: string): boolean {
+ try {
+ new Intl.DateTimeFormat(undefined, { timeZone: zone }).resolvedOptions();
+ return true;
+ } catch (err) {
+ if (err instanceof RangeError) return false;
+ throw err;
+ }
+}
+
+/**
+ * The zone as given, after proving it is a plain zone-name token AND a
+ * zone the runtime resolves: the lane formats the window through `Intl`
+ * on every firing, so a recipe must not bake in a zone it would refuse.
+ */
+function checkedTz(raw: string): string {
+ if (!TZ_PATTERN.test(raw)) {
+ throw new CronTemplateError(
+ "--tz must be a time zone name such as Europe/Berlin or UTC, got: " + JSON.stringify(raw),
+ );
+ }
+ if (!isKnownTimeZone(raw)) {
+ throw new CronTemplateError("--tz names an unknown time zone: " + JSON.stringify(raw));
+ }
+ return raw;
+}
+
+/** Label the line-break refusal names the vault with. */
+const VAULT_LABEL = "vault";
+
+/** The lane invocation the script runs, every input already checked. */
+function laneCommand(o2bBin: string, opts: MaintenanceCronOptions): string {
+ const parts = [
+ o2bBin,
+ RUN_COMMAND,
+ "--vault",
+ shellQuote(singleLinePath(VAULT_LABEL, opts.vault)),
+ ];
+ if (opts.window !== undefined) parts.push("--window", checkedWindow(opts.window));
+ if (opts.tz !== undefined) parts.push("--tz", checkedTz(opts.tz));
+ parts.push("--json");
+ return parts.join(" ");
+}
+
+/**
+ * The bash body of the trigger script. JS-side strings are plain text:
+ * the heredoc that carries them is quoted, so every `$name` is expanded
+ * later, when the scheduler runs the script.
+ */
+function renderMaintenanceBody(o2bBin: string, opts: MaintenanceCronOptions): string {
+ const lines = [
+ "#!/usr/bin/env bash",
+ "set -euo pipefail",
+ "",
+ "# Pick up OPEN_SECOND_BRAIN_EMBEDDING_* from the Hermes env file if it",
+ "# exists: the lane's reindex task embeds when maintenance_embeddings is on.",
+ 'if [[ -f "$HOME/.hermes/.env" ]]; then',
+ ' set -a; . "$HOME/.hermes/.env"; set +a',
+ "fi",
+ "",
+ "# The lane decides whether work happens; a gate skip exits 0. Keep its",
+ "# exit code: `|| status=$?` stops set -e from ending the script before",
+ "# a failure can be reported.",
+ "status=0",
+ "out=$(" + laneCommand(o2bBin, opts) + ") || status=$?",
+ 'if [ "$status" -ne 0 ]; then',
+ ' printf "%s\\n" "$out"',
+ ' exit "$status"',
+ "fi",
+ ];
+ return lines.join("\n") + "\n";
+}
+
+/** The maintenance recipe for one vault: the lane-specific half of the shared layout. */
+export function maintenanceRecipe(vault: string): CronRecipeSpec<MaintenanceCronOptions> {
+ const cronName = maintenanceCronName(vault);
+ return Object.freeze<CronRecipeSpec<MaintenanceCronOptions>>({
+ title: "Open Second Brain - maintenance lane template",
+ cronName,
+ scriptPath: operatorScriptPath(cronName),
+ scriptNotes: Object.freeze([
+ "(then chmod +x). Silent when the lane exits 0, including a gate",
+ "skip; any other exit prints the lane's JSON and keeps its code.",
+ ]),
+ schedulerNote: "(when Hermes owns the schedule)",
+ buildScriptBody: (opts) => renderMaintenanceBody(opts.o2bBin, opts),
+ buildVerifyCommand: ({ o2bBin, vault: target }) =>
+ o2bBin + " " + STATUS_COMMAND + " --vault " + shellQuote(singleLinePath(VAULT_LABEL, target)),
+ });
+}
+
+/**
+ * Render the maintenance lane recipe in the requested format (cron when
+ * omitted). Pure text: nothing is created, spawned or scheduled. Throws
+ * {@link CronTemplateError} for an interval the scheduler cannot express,
+ * a window that is not `H-H` with hours 0..23, a zone that is not a
+ * plain zone name the runtime knows, or a vault path with a line break.
+ */
+export function renderMaintenanceCronTemplate(
+ interval: string,
+ opts: MaintenanceCronOptions & { readonly format?: RecipeFormat },
+): string {
+ const { format, ...recipeOpts } = opts;
+ const render: RecipeFormat = parseRecipeFormat(format);
+ const spec = maintenanceRecipe(recipeOpts.vault);
+ return render === "systemd"
+ ? renderSystemdTimer(spec, interval, recipeOpts)
+ : renderCronRecipe(spec, interval, recipeOpts);
+}
diff --git a/src/cli/mcp-fault-guard.ts b/src/cli/mcp-fault-guard.ts
new file mode 100644
index 00000000..5344a474
--- /dev/null
+++ b/src/cli/mcp-fault-guard.ts
@@ -0,0 +1,248 @@
+/**
+ * A served MCP transport survives a stray promise rejection.
+ *
+ * Before this module `o2b mcp` registered no process-level fault handler,
+ * so one promise rejected anywhere in core with nobody awaiting it ended
+ * the server with the runtime default: no named line, no count, and a
+ * dead server. Claude Code and Codex never restart a dead MCP server
+ * mid-session (the Hermes bridge restarts it once), so the operator's
+ * agent lost the whole Brain surface over a fault that broke no request.
+ *
+ * ## Two faults, two answers
+ *
+ * - An unhandled REJECTION is a promise nobody awaited. The request that
+ * created it has already been answered (or was never a request at all),
+ * and the process state is intact, so the guard names it on stderr with
+ * its first stack frame, counts it, and the server keeps serving.
+ * Logging is rate-limited - {@link REJECTION_LOG_BURST} full lines per
+ * {@link REJECTION_LOG_WINDOW_MS}, then one summary line for the rest of
+ * that window - so a loop that rejects on every tick cannot fill a log
+ * disk; the count is never limited.
+ * - An uncaught EXCEPTION unwound a synchronous stack to the top. Nothing
+ * says the state it left behind is consistent, so continuing would
+ * serve answers from a process that is already wrong. The guard names
+ * it and calls `process.exit(EXIT_INTERNAL_FAULT)`. `process.exit`,
+ * unlike the runtime default for an uncaught exception, emits `exit`,
+ * so the two hooks registered there still run: the search store
+ * checkpoints its WAL and the sync lockfile module unlinks every held
+ * lock. No drain is attempted: a drain waits for in-flight work, and
+ * the work in flight is the work that just proved the process is wrong.
+ *
+ * ## Why it lives on the CLI side
+ *
+ * The same reason as `mcp-drain.ts`: the process belongs to the CLI. A
+ * transport module reaching for `process.on("uncaughtException")` would
+ * install it for every host that embeds the transport, including tests
+ * and the probe, where a crash SHOULD be loud. Only the two served
+ * transports of `o2b mcp` install it, and they release it before the verb
+ * returns, so the top-level `main().catch` still fails loudly once the
+ * server has stopped. `src/mcp/http.ts` reads the counts through a getter
+ * the CLI injects, so `src/mcp` imports nothing from here.
+ *
+ * `process.on` rather than `once`: with `once`, a second rejection would
+ * fall through to the default handler and kill the process - the exact
+ * outcome the guard exists to prevent. Every stderr write is wrapped,
+ * because a closed stderr must not turn the guard into the crash.
+ */
+
+import type { McpFaultCounts } from "../mcp/http.ts";
+import { redactRawOutput } from "../core/redactor.ts";
+import type { DrainReportStream } from "./mcp-drain.ts";
+
+/** sysexits `EX_SOFTWARE`: distinct from 1 (CLI error) and 130/143 (signals). */
+export const EXIT_INTERNAL_FAULT = 70;
+
+/** The two faults the guard handles, as they appear on stderr and `/health`. */
+export const FAULT_KIND = Object.freeze({
+ unhandledRejection: "unhandled_rejection",
+ uncaughtException: "uncaught_exception",
+} as const);
+
+export type FaultKind = (typeof FAULT_KIND)[keyof typeof FAULT_KIND];
+
+/** Full rejection lines per window before the rest are summarised. */
+export const REJECTION_LOG_BURST = 5;
+
+/** The rate-limit window for rejection lines. */
+export const REJECTION_LOG_WINDOW_MS = 60_000;
+
+export interface McpFaultGuardOptions {
+ readonly stderr?: DrainReportStream;
+ /**
+ * How the process ends after an uncaught exception. Injected only by
+ * tests; the product uses the real `process.exit`, which is the call
+ * that lets the registered `exit` hooks run.
+ */
+ readonly exit?: (code: number) => void;
+ /** The clock for the rate limit and `last_fault_at`. */
+ readonly now?: () => Date;
+ /**
+ * Arms the one-shot timer that flushes the summary of a window once it
+ * ends. Injected only by tests; the product uses an unref'd
+ * `setTimeout`.
+ */
+ readonly schedule?: FaultGuardScheduler;
+}
+
+/** Run `fire` once after `delayMs`; the returned function cancels it. */
+export type FaultGuardScheduler = (fire: () => void, delayMs: number) => () => void;
+
+/**
+ * The product scheduler: unref'd, so the timer never holds a stopping
+ * process open.
+ */
+const unrefTimeout: FaultGuardScheduler = (fire, delayMs) => {
+ const timer = setTimeout(fire, delayMs);
+ timer.unref?.();
+ return () => clearTimeout(timer);
+};
+
+/**
+ * Redaction applied to every line the guard writes: an error message can
+ * carry a credential-bearing URL or a token echoed by a provider, and a
+ * stdio host captures this stderr into its own log files.
+ */
+const FAULT_LINE_REDACTION = Object.freeze({ redactTokens: true, redactUrlCredentials: true });
+
+export interface McpFaultGuardHandle {
+ /** A snapshot of the counts, the shape `/health` reports. */
+ counts(): McpFaultCounts;
+ /**
+ * Stop listening and flush a pending summary line. MUST be called when
+ * the server stops: the listeners are process-global. Idempotent.
+ */
+ release(): void;
+}
+
+/** Install the process-level fault handlers for a served MCP transport. */
+export function installMcpFaultGuard(opts: McpFaultGuardOptions = {}): McpFaultGuardHandle {
+ const stderr = opts.stderr ?? process.stderr;
+ const exit = opts.exit ?? ((code: number) => process.exit(code));
+ const now = opts.now ?? (() => new Date());
+ const schedule = opts.schedule ?? unrefTimeout;
+
+ let rejections = 0;
+ let exceptions = 0;
+ let lastFaultAt: string | null = null;
+ let windowStartMs = Number.NEGATIVE_INFINITY;
+ let loggedInWindow = 0;
+ let suppressedInWindow = 0;
+ let cancelSummary: (() => void) | null = null;
+ let exiting = false;
+ let released = false;
+
+ const write = (chunk: string): void => {
+ try {
+ stderr.write(redactRawOutput(chunk, FAULT_LINE_REDACTION));
+ } catch {
+ // A closed stderr has nowhere to report to; the count still records it.
+ }
+ };
+
+ const flushSummary = (): void => {
+ if (cancelSummary !== null) {
+ cancelSummary();
+ cancelSummary = null;
+ }
+ if (suppressedInWindow === 0) return;
+ write(
+ `[mcp] ${FAULT_KIND.unhandledRejection}: ${suppressedInWindow} more suppressed ` +
+ `in the last ${REJECTION_LOG_WINDOW_MS}ms\n`,
+ );
+ suppressedInWindow = 0;
+ };
+
+ const onRejection = (reason: unknown): void => {
+ try {
+ rejections += 1;
+ const at = now();
+ lastFaultAt = at.toISOString();
+ const atMs = at.getTime();
+ if (atMs - windowStartMs >= REJECTION_LOG_WINDOW_MS) {
+ flushSummary();
+ windowStartMs = atMs;
+ loggedInWindow = 0;
+ }
+ if (loggedInWindow < REJECTION_LOG_BURST) {
+ loggedInWindow += 1;
+ write(
+ `[mcp] ${FAULT_KIND.unhandledRejection} #${rejections}: ${describeReason(reason)} ` +
+ `(server keeps serving)\n${firstFrameLine(reason)}`,
+ );
+ return;
+ }
+ suppressedInWindow += 1;
+ // A quiet server still reports what it suppressed once the window
+ // ends.
+ if (cancelSummary === null) {
+ cancelSummary = schedule(flushSummary, windowStartMs + REJECTION_LOG_WINDOW_MS - atMs);
+ }
+ } catch {
+ // The guard must never become the fault it is guarding against.
+ }
+ };
+
+ const onException = (error: unknown): void => {
+ if (exiting) {
+ exit(EXIT_INTERNAL_FAULT);
+ return;
+ }
+ exiting = true;
+ try {
+ exceptions += 1;
+ lastFaultAt = now().toISOString();
+ flushSummary();
+ write(
+ `[mcp] ${FAULT_KIND.uncaughtException}: ${describeReason(error)}; ` +
+ `exiting ${EXIT_INTERNAL_FAULT} so the exit hooks checkpoint the index and release locks\n` +
+ firstFrameLine(error),
+ );
+ } catch {
+ // Fall through to the exit: a half-written report beats a hung process.
+ }
+ exit(EXIT_INTERNAL_FAULT);
+ };
+
+ process.on("unhandledRejection", onRejection);
+ process.on("uncaughtException", onException);
+
+ return Object.freeze({
+ counts: (): McpFaultCounts =>
+ Object.freeze({
+ unhandled_rejection: rejections,
+ uncaught_exception: exceptions,
+ last_fault_at: lastFaultAt,
+ }),
+ release: (): void => {
+ if (released) return;
+ released = true;
+ process.removeListener("unhandledRejection", onRejection);
+ process.removeListener("uncaughtException", onException);
+ flushSummary();
+ },
+ });
+}
+
+/** `Error: message` for an Error, a quoted value for anything else. */
+function describeReason(reason: unknown): string {
+ if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
+ let shown: string;
+ try {
+ shown = JSON.stringify(reason) ?? String(reason);
+ } catch {
+ // BigInt, a cycle, a throwing toJSON: fall back to the coercion.
+ try {
+ shown = String(reason);
+ } catch {
+ shown = Object.prototype.toString.call(reason);
+ }
+ }
+ return `non-error reason: ${shown}`;
+}
+
+/** The first `at ...` frame of an Error's stack, as its own line, or nothing. */
+function firstFrameLine(reason: unknown): string {
+ if (!(reason instanceof Error) || typeof reason.stack !== "string") return "";
+ const frame = reason.stack.split("\n").find((line) => line.trimStart().startsWith("at "));
+ return frame === undefined ? "" : `[mcp] ${frame.trim()}\n`;
+}
diff --git a/src/cli/partner-codegraph-cron.ts b/src/cli/partner-codegraph-cron.ts
index a6eb6df0..4ce96a42 100644
--- a/src/cli/partner-codegraph-cron.ts
+++ b/src/cli/partner-codegraph-cron.ts
@@ -32,9 +32,14 @@
import {
operatorScriptPath,
+ parseRecipeFormat,
renderCronRecipe,
+ renderSystemdTimer,
+ shellQuote,
+ singleLinePath,
type CronRecipeOptions,
type CronRecipeSpec,
+ type RecipeFormat,
} from "./cron-recipe.ts";
import { CODEGRAPH_CLI } from "../core/partner/codegraph.ts";
import { GRAPH_HEALTH_CODES } from "../core/partner/codegraph-health.ts";
@@ -71,6 +76,9 @@ const FAIL_ON_HEALTH_FLAG = "--fail-on-health";
/** Flag that makes the report machine-readable. */
const JSON_FLAG = "--json";
+/** Label the line-break refusal names the repository path with. */
+const PROJECT_LABEL = "project";
+
/** The JSON parser the health gate requires. */
const JSON_PARSER = "jq";
@@ -98,7 +106,7 @@ function renderResyncBody(o2bBin: string, projectPath: string): string {
"",
"# The repository this recipe keeps indexed, baked in when the recipe",
"# was rendered. Re-render for a different repository.",
- 'project="' + projectPath + '"',
+ "project=" + shellQuote(singleLinePath(PROJECT_LABEL, projectPath)),
'stamp_dir="' + STAMP_DIR_EXPRESSION + '"',
'stamp_file="$stamp_dir/' + stampFileName(projectPath) + '"',
"",
@@ -202,14 +210,25 @@ export const CODEGRAPH_RESYNC_RECIPE: CronRecipeSpec<CodegraphResyncOptions> = O
buildVerifyCommand: ({ o2bBin }) => `${o2bBin} ${REPORT_COMMAND} ${FAIL_ON_HEALTH_FLAG}`,
});
+/** Options for {@link renderCodegraphResyncTemplate}. */
+export interface RenderCodegraphResyncOptions extends CronRecipeOptions {
+ /** Recipe format; cron when omitted. */
+ readonly format?: RecipeFormat;
+}
+
/**
- * Render the resync recipe for one repository. Pure text: nothing is
+ * Render the resync recipe for one repository, as a crontab and Hermes
+ * recipe (the default) or as a systemd user timer. Pure text: nothing is
* created, spawned or scheduled here.
*/
export function renderCodegraphResyncTemplate(
projectPath: string,
interval: string,
- opts: CronRecipeOptions = {},
+ opts: RenderCodegraphResyncOptions = {},
): string {
- return renderCronRecipe(CODEGRAPH_RESYNC_RECIPE, interval, { ...opts, projectPath });
+ const { format, ...rest } = opts;
+ const recipeOpts: CodegraphResyncOptions = { ...rest, projectPath };
+ return parseRecipeFormat(format) === "systemd"
+ ? renderSystemdTimer(CODEGRAPH_RESYNC_RECIPE, interval, recipeOpts)
+ : renderCronRecipe(CODEGRAPH_RESYNC_RECIPE, interval, recipeOpts);
}
diff --git a/src/cli/partner.ts b/src/cli/partner.ts
index 826a2735..44d52558 100644
--- a/src/cli/partner.ts
+++ b/src/cli/partner.ts
@@ -13,7 +13,7 @@
import { resolve } from "node:path";
import { CliError, parseFlags } from "./argparse.ts";
-import { CronTemplateError } from "./cron-recipe.ts";
+import { CronTemplateError, parseRecipeFormat } from "./cron-recipe.ts";
import { renderCodegraphResyncTemplate } from "./partner-codegraph-cron.ts";
import { defaultConfigPath, resolveVault } from "../core/config.ts";
import { isDir } from "../core/fs-utils.ts";
@@ -25,7 +25,7 @@ import { buildCodegraphReport, type CodegraphReport } from "../core/partner/code
const PARTNER_USAGE =
"usage: o2b partner codegraph report [--vault <path>] [--fail-on-health] [--json]\n" +
" o2b partner codegraph resync --cron-template [--interval <N>] " +
- "[--project <path>] [--vault <path>]\n";
+ "[--format cron|systemd] [--project <path>] [--vault <path>]\n";
/** Cadence the resync recipe uses when the caller names none. */
const DEFAULT_RESYNC_INTERVAL = "6h";
@@ -38,7 +38,10 @@ const DEFAULT_RESYNC_INTERVAL = "6h";
*/
const EXIT_HEALTH_REFUSED = 1;
-/** Exit for an interval cron cannot express - the input is a value, not a flag error. */
+/**
+ * Exit for an interval cron cannot express, or a recipe format this CLI
+ * does not render - the input is a value, not a flag error.
+ */
const EXIT_INTERVAL_REFUSED = 1;
function resolveScopeVault(flagVal: string | undefined): string {
@@ -168,6 +171,7 @@ function codegraphResyncVerb(argv: ReadonlyArray<string>): number {
vault: { type: "string" },
project: { type: "string" },
interval: { type: "string" },
+ format: { type: "string" },
"cron-template": { type: "boolean" },
});
if (positional.length > 0) {
@@ -187,7 +191,8 @@ function codegraphResyncVerb(argv: ReadonlyArray<string>): number {
);
const interval = (flags["interval"] as string | undefined) ?? DEFAULT_RESYNC_INTERVAL;
try {
- process.stdout.write(renderCodegraphResyncTemplate(projectPath, interval));
+ const format = parseRecipeFormat(flags["format"] as string | undefined);
+ process.stdout.write(renderCodegraphResyncTemplate(projectPath, interval, { format }));
} catch (err) {
if (err instanceof CronTemplateError) {
process.stderr.write(`error: ${err.message}\n`);
diff --git a/src/cli/search-cron-template.ts b/src/cli/search-cron-template.ts
index dee70297..8be97750 100644
--- a/src/cli/search-cron-template.ts
+++ b/src/cli/search-cron-template.ts
@@ -2,8 +2,9 @@
* §E.3 -- 'o2b search reindex --cron-template' renderer.
*
* Prints a watchdog script body, a native crontab line, and an
- * optional 'hermes cron create' invocation. Pure stdout, writes
- * nothing. The operator (or agent in the user's name) copies what
+ * optional 'hermes cron create' invocation - or, with
+ * `--format systemd`, the same script as a systemd user timer. Pure
+ * stdout, writes nothing. The operator (or agent in the user's name) copies what
* fits their host into the cron infrastructure of choice.
*
* The layout, the interval parser and the heredoc mechanics live in
@@ -22,17 +23,23 @@
import {
CronTemplateError,
operatorScriptPath,
- renderCronRecipe,
parseInterval,
+ parseRecipeFormat,
+ renderCronRecipe,
+ renderSystemdTimer,
type CronRecipeOptions,
type CronRecipeSpec,
type ParsedInterval,
+ type RecipeFormat,
} from "./cron-recipe.ts";
export { CronTemplateError, parseInterval };
export type { ParsedInterval };
-export type RenderCronTemplateOptions = CronRecipeOptions;
+export interface RenderCronTemplateOptions extends CronRecipeOptions {
+ /** Recipe format; cron (the byte-pinned output) when omitted. */
+ readonly format?: RecipeFormat;
+}
/** Cron job name, and the stem of the script path derived from it. */
const SEARCH_REINDEX_CRON_NAME = "osb-reindex";
@@ -51,8 +58,15 @@ export const SEARCH_REINDEX_RECIPE: CronRecipeSpec = Object.freeze<CronRecipeSpe
buildVerifyCommand: ({ o2bBin }) => o2bBin + " search status",
});
+/**
+ * Render the reindex recipe. The cron format is the byte-pinned output;
+ * `format: "systemd"` prints the same script as a systemd user timer.
+ */
export function renderCronTemplate(interval: string, opts: RenderCronTemplateOptions = {}): string {
- return renderCronRecipe(SEARCH_REINDEX_RECIPE, interval, opts);
+ const { format, ...recipeOpts } = opts;
+ return parseRecipeFormat(format) === "systemd"
+ ? renderSystemdTimer(SEARCH_REINDEX_RECIPE, interval, recipeOpts)
+ : renderCronRecipe(SEARCH_REINDEX_RECIPE, interval, recipeOpts);
}
function renderWatchdogBody(o2bBin: string): string {
diff --git a/src/cli/search/verbs/indexing.ts b/src/cli/search/verbs/indexing.ts
index 0238b380..61eacc54 100644
--- a/src/cli/search/verbs/indexing.ts
+++ b/src/cli/search/verbs/indexing.ts
@@ -33,6 +33,7 @@ import {
reportProgressRefusal,
type ProgressAttachment,
} from "../../progress-rail.ts";
+import { parseRecipeFormat } from "../../cron-recipe.ts";
import { CronTemplateError, renderCronTemplate } from "../../search-cron-template.ts";
import {
flagBoolean,
@@ -235,12 +236,26 @@ export async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<num
progress: { type: "boolean" },
"cron-template": { type: "boolean" },
interval: { type: "string" },
+ format: { type: "string" },
"self-heal": { type: "string" },
});
- if (flagBoolean(flags, "cron-template")) {
+ const cronTemplate = flagBoolean(flags, "cron-template");
+ if (
+ !cronTemplate &&
+ (flagString(flags, "interval") !== undefined || flagString(flags, "format") !== undefined)
+ ) {
+ // Named, not ignored: without the template these flags would fall
+ // through to a full reindex the caller never asked for.
+ process.stderr.write(
+ "search reindex: --interval and --format apply only with --cron-template\n",
+ );
+ return 2;
+ }
+ if (cronTemplate) {
const intervalRaw = flagString(flags, "interval") ?? DEFAULT_CRON_INTERVAL;
try {
- const body = renderCronTemplate(intervalRaw);
+ const format = parseRecipeFormat(flagString(flags, "format"));
+ const body = renderCronTemplate(intervalRaw, { format });
process.stdout.write(body);
return 0;
} catch (err) {
diff --git a/src/core/brain/maintenance/custom-task-id.ts b/src/core/brain/maintenance/custom-task-id.ts
new file mode 100644
index 00000000..d9d0c9e1
--- /dev/null
+++ b/src/core/brain/maintenance/custom-task-id.ts
@@ -0,0 +1,25 @@
+/**
+ * The identity of an install-owned custom maintenance lane task: the
+ * `custom:<name>` form and its well-formedness check, with no imports.
+ *
+ * The lane kernel and the journal need only this to widen their task
+ * identities and to count a custom task's timeouts toward its streak.
+ * Keeping it in a leaf module lets them do that without importing the
+ * runner in `custom-tasks.ts`, which itself reads the machine config and
+ * the lane's lease length, and would otherwise close an import cycle
+ * through the lane kernel.
+ */
+
+export const CUSTOM_TASK_PREFIX = "custom:";
+export const CUSTOM_TASK_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
+
+export type CustomLaneTask = `custom:${string}`;
+
+/** Whether `value` is a well-formed custom identity (not whether it is declared). */
+export function isCustomLaneTask(value: unknown): value is CustomLaneTask {
+ return (
+ typeof value === "string" &&
+ value.startsWith(CUSTOM_TASK_PREFIX) &&
+ CUSTOM_TASK_NAME_PATTERN.test(value.slice(CUSTOM_TASK_PREFIX.length))
+ );
+}
diff --git a/src/core/brain/maintenance/custom-tasks.ts b/src/core/brain/maintenance/custom-tasks.ts
new file mode 100644
index 00000000..e6ac5764
--- /dev/null
+++ b/src/core/brain/maintenance/custom-tasks.ts
@@ -0,0 +1,551 @@
+/**
+ * Install-owned custom maintenance lane tasks.
+ *
+ * An install can put its own upkeep under the lane's window, busy,
+ * pressure, lease and streak gates by declaring a shell command in the
+ * MACHINE config file, as flat keys:
+ *
+ * maintenance_custom_tasks: true # master switch, default off
+ * maintenance_custom_<name>: <command>
+ * maintenance_custom_<name>_cwd: /absolute/dir # optional, default the home directory
+ * maintenance_custom_<name>_timeout_seconds: 300 # optional, default 120
+ *
+ * Never the vault: the vault syncs between devices and is writable through
+ * the MCP write tools, so a command stored there would let a synced edit or
+ * an agent plant code the lane then runs. No MCP parameter can add, edit or
+ * read a command either; a caller can only name `custom:<name>` to retry.
+ *
+ * The identity is `custom:<name>` with `<name>` matching
+ * {@link CUSTOM_TASK_NAME_PATTERN}. A colon never occurs in an `OPERATION`
+ * value, so a custom identity cannot collide with a built-in task, and the
+ * name bans underscores so the `_cwd` and `_timeout_seconds` suffixes are
+ * unambiguous.
+ *
+ * Every bad declaration is an error string naming its key, never a silent
+ * skip; the valid declarations still resolve. A custom task never calls a
+ * model and records no spend receipt: the lane cannot police spend or side
+ * effects inside an operator's own command, and it does not pretend to.
+ */
+
+import { spawn, spawnSync, type ChildProcess } from "node:child_process";
+import { statSync } from "node:fs";
+import { homedir } from "node:os";
+import { isAbsolute } from "node:path";
+
+import {
+ discoverConfig,
+ MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY,
+ MAINTENANCE_CUSTOM_TASKS_ENV,
+ resolveMaintenanceCustomTasksSwitch,
+ type MaintenanceSwitchSource,
+} from "../../config.ts";
+import { isSecretKeyName, redactRawOutput } from "../../redactor.ts";
+import { shellArgv } from "../../reliability/command-bridge.ts";
+import { SafeguardAbortError, SafeguardTimeoutError } from "../safeguard.ts";
+import { LANE_ERROR_MAX_BYTES, MAINTENANCE_LEASE_TTL_MS, type MaintenanceTask } from "./lane.ts";
+import {
+ CUSTOM_TASK_NAME_PATTERN,
+ CUSTOM_TASK_PREFIX,
+ type CustomLaneTask,
+} from "./custom-task-id.ts";
+
+export {
+ CUSTOM_TASK_NAME_PATTERN,
+ CUSTOM_TASK_PREFIX,
+ type CustomLaneTask,
+ isCustomLaneTask,
+} from "./custom-task-id.ts";
+
+/** Each declared task adds a journal row per pass against the 500-row cap. */
+export const CUSTOM_TASK_MAX = 8;
+
+/**
+ * Time the maintenance lease keeps for the four built-in tasks. The lease
+ * is acquired once per pass and not renewed, so whatever the custom tasks
+ * may spend comes out of the same 1800 s.
+ */
+export const BUILT_IN_TASKS_LEASE_MARGIN_SECONDS = 600;
+
+/**
+ * The most the declared custom timeouts may add up to: the lease length
+ * minus {@link BUILT_IN_TASKS_LEASE_MARGIN_SECONDS}, 1200 s. A per-task
+ * bound alone does not keep the lease: eight tasks just under it would
+ * hold the lane for hours after the lease expired, and a second pass
+ * would start beside the first.
+ */
+export const CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS =
+ MAINTENANCE_LEASE_TTL_MS / 1000 - BUILT_IN_TASKS_LEASE_MARGIN_SECONDS;
+
+/** Sized so the full {@link CUSTOM_TASK_MAX} tasks fit the budget at their default. */
+export const CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS = 120;
+
+/** What `status` says when custom tasks are declared but the config switch is off. */
+export const CUSTOM_TASKS_OFF_NOTICE = `custom tasks declared but ${MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY} is off`;
+
+/** What `status` says when the env override turned declared custom tasks off. */
+export const CUSTOM_TASKS_ENV_OFF_NOTICE = `custom tasks declared but ${MAINTENANCE_CUSTOM_TASKS_ENV} turns them off`;
+
+export interface CustomTaskSpec {
+ readonly name: string;
+ readonly id: CustomLaneTask;
+ readonly command: string;
+ /** Absent = the running user's home directory. */
+ readonly cwd?: string;
+ readonly timeoutSeconds: number;
+}
+
+export interface CustomTaskResolution {
+ /** The master switch, as resolved (env over config). */
+ readonly enabled: boolean;
+ /** Which source decided {@link enabled}: the env override, the config key, or neither. */
+ readonly switchSource: MaintenanceSwitchSource;
+ /** Valid declarations, sorted by name; empty while the switch is off. */
+ readonly specs: ReadonlyArray<CustomTaskSpec>;
+ /** One named reason per refused declaration; empty while the switch is off. */
+ readonly errors: ReadonlyArray<string>;
+ /** Distinct task names declared in the config, valid or not, switch on or off. */
+ readonly declared: number;
+}
+
+const KEY_PREFIX = "maintenance_custom_";
+const CWD_SUFFIX = "_cwd";
+const TIMEOUT_SUFFIX = "_timeout_seconds";
+
+interface Declaration {
+ command?: string;
+ cwd?: string;
+ timeout?: string;
+}
+
+/**
+ * The custom tasks the config at `configPath` declares, with every refused
+ * declaration named. Reads the flat config through the shared loader, so an
+ * unreadable config file raises its named `ConfigReadError` here rather
+ * than resolving to "nothing declared".
+ */
+export function resolveCustomTasks(configPath?: string): CustomTaskResolution {
+ const data = discoverConfig(configPath).data;
+ const declarations = new Map<string, Declaration>();
+ for (const [key, value] of Object.entries(data)) {
+ if (!key.startsWith(KEY_PREFIX)) continue;
+ // The master switch shares the prefix; it is not a task named "tasks".
+ if (key === MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY) continue;
+ const rest = key.slice(KEY_PREFIX.length);
+ let name = rest;
+ let field: keyof Declaration = "command";
+ if (rest.endsWith(TIMEOUT_SUFFIX)) {
+ name = rest.slice(0, -TIMEOUT_SUFFIX.length);
+ field = "timeout";
+ } else if (rest.endsWith(CWD_SUFFIX)) {
+ name = rest.slice(0, -CWD_SUFFIX.length);
+ field = "cwd";
+ }
+ const entry = declarations.get(name) ?? {};
+ entry[field] = value.trim();
+ declarations.set(name, entry);
+ }
+ const declared = declarations.size;
+ const { enabled, source: switchSource } = resolveMaintenanceCustomTasksSwitch(configPath, data);
+ if (!enabled) return { enabled, switchSource, specs: [], errors: [], declared };
+
+ const budget = CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS;
+ let committed = 0;
+ const specs: CustomTaskSpec[] = [];
+ const errors: string[] = [];
+ for (const name of [...declarations.keys()].toSorted()) {
+ const decl = declarations.get(name)!;
+ const key = `${KEY_PREFIX}${name}`;
+ if (decl.command === undefined) {
+ // A `_cwd`/`_timeout_seconds` key whose command is missing: either a
+ // typo in the command key or a leftover after removing it. Each
+ // dangling key is named, not only the first.
+ if (decl.cwd !== undefined)
+ errors.push(`${key}${CWD_SUFFIX}: no ${key} command is declared for it`);
+ if (decl.timeout !== undefined) {
+ errors.push(`${key}${TIMEOUT_SUFFIX}: no ${key} command is declared for it`);
+ }
+ continue;
+ }
+ if (!CUSTOM_TASK_NAME_PATTERN.test(name)) {
+ errors.push(
+ `${key}: task name "${name}" does not match ${CUSTOM_TASK_NAME_PATTERN.source} ` +
+ `(lowercase letters, digits and hyphens, starting with a letter, at most 32)`,
+ );
+ continue;
+ }
+ if (decl.command === "") {
+ errors.push(`${key}: the command is empty`);
+ continue;
+ }
+ let timeoutSeconds = CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS;
+ if (decl.timeout !== undefined) {
+ const parsed = /^\d+$/.test(decl.timeout) ? Number(decl.timeout) : Number.NaN;
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > budget) {
+ errors.push(
+ `${key}${TIMEOUT_SUFFIX}: "${decl.timeout}" is not a whole number of seconds ` +
+ `from 1 to ${budget} (the custom timeouts together stay within ${budget} s ` +
+ `of the ${MAINTENANCE_LEASE_TTL_MS / 1000} s maintenance lease)`,
+ );
+ continue;
+ }
+ timeoutSeconds = parsed;
+ }
+ if (decl.cwd !== undefined && (decl.cwd === "" || !isAbsolute(decl.cwd))) {
+ errors.push(`${key}${CWD_SUFFIX}: "${decl.cwd}" is not an absolute path`);
+ continue;
+ }
+ if (specs.length >= CUSTOM_TASK_MAX) {
+ errors.push(
+ `${key}: more than ${CUSTOM_TASK_MAX} custom tasks are declared; this one is not run`,
+ );
+ continue;
+ }
+ if (committed + timeoutSeconds > budget) {
+ errors.push(
+ `${key}: its ${timeoutSeconds} s timeout takes the custom timeouts to ` +
+ `${committed + timeoutSeconds} s, over the ${budget} s budget of the ` +
+ `${MAINTENANCE_LEASE_TTL_MS / 1000} s maintenance lease; this one is not run`,
+ );
+ continue;
+ }
+ committed += timeoutSeconds;
+ specs.push({
+ name,
+ id: `${CUSTOM_TASK_PREFIX}${name}`,
+ command: decl.command,
+ ...(decl.cwd !== undefined ? { cwd: decl.cwd } : {}),
+ timeoutSeconds,
+ });
+ }
+ return { enabled, switchSource, specs, errors, declared };
+}
+
+/**
+ * The notice `status` gives when custom tasks are declared but not run,
+ * naming the switch that turned them off; `null` when there is nothing to
+ * say. One definition for the CLI verb and the MCP tool.
+ */
+export function customTasksOffNotice(resolution: CustomTaskResolution): string | null {
+ if (resolution.enabled || resolution.declared === 0) return null;
+ return resolution.switchSource === "env" ? CUSTOM_TASKS_ENV_OFF_NOTICE : CUSTOM_TASKS_OFF_NOTICE;
+}
+
+/** How much stderr is held in memory; only the tail is ever reported. */
+const STDERR_HOLD_BYTES = 64 * 1024;
+/**
+ * How long the stderr pipe may stay open after the shell exited. A process
+ * the command left in the background can hold the pipe for as long as it
+ * lives; the task's outcome is the shell's exit status, so the runner
+ * reads what arrived in this window and stops waiting.
+ */
+const STDERR_DRAIN_MS = 200;
+/** Between SIGTERM and SIGKILL to a timed-out or aborted process group. */
+const KILL_GRACE_MS = 1000;
+
+/**
+ * Variables the child always keeps, even if a secret-name check matched
+ * them. Compared upper-cased, because Windows env names are
+ * case-insensitive (`Path`).
+ */
+const CHILD_ENV_KEEP: ReadonlySet<string> = new Set([
+ "PATH",
+ "HOME",
+ "LANG",
+ "TZ",
+ "TMPDIR",
+ "O2B_VAULT",
+]);
+const CHILD_ENV_KEEP_PREFIX = "LC_";
+
+/**
+ * The child's environment: this process's variables minus every one whose
+ * NAME declares a credential ({@link isSecretKeyName}: `*_API_KEY`,
+ * `*_TOKEN`, `*_SECRET`, `*PASSWORD*`, ...), plus `O2B_VAULT`. The
+ * provider keys the lane itself holds are not the operator command's to
+ * read; a command that needs one reads it from its own configuration.
+ */
+export function customTaskEnv(
+ vault: string,
+ source: NodeJS.ProcessEnv = process.env,
+): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [name, value] of Object.entries(source)) {
+ if (value === undefined) continue;
+ const upper = name.toUpperCase();
+ const kept = CHILD_ENV_KEEP.has(upper) || upper.startsWith(CHILD_ENV_KEEP_PREFIX);
+ if (!kept && isSecretKeyName(name)) continue;
+ env[name] = value;
+ }
+ env["O2B_VAULT"] = vault;
+ return env;
+}
+
+/**
+ * POSIX process groups of custom children that may still have members.
+ * The lane does not wait for what a command left in the background, but
+ * it does not leave it behind either: every group still listed when this
+ * process exits is killed then.
+ */
+const liveGroups = new Set<number>();
+let exitHookInstalled = false;
+
+function trackGroup(pgid: number): void {
+ liveGroups.add(pgid);
+ if (exitHookInstalled) return;
+ exitHookInstalled = true;
+ process.on("exit", () => {
+ for (const group of liveGroups) signalGroup(group, "SIGKILL");
+ liveGroups.clear();
+ });
+}
+
+/** Signal a whole POSIX process group. ESRCH (the group is gone) is not an error. */
+function signalGroup(pgid: number, signal: NodeJS.Signals): void {
+ try {
+ process.kill(-pgid, signal);
+ } catch {
+ // ESRCH: no member of the group is left.
+ }
+}
+
+/** Whether any member of a POSIX process group is still running. */
+function groupAlive(pgid: number): boolean {
+ try {
+ process.kill(-pgid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The lane task that runs one declared command.
+ *
+ * The command runs through the shared platform shell form
+ * ({@link shellArgv}) with stdin closed, stdout discarded (the lane's own
+ * stdout may be the JSON a caller parses), the environment of
+ * {@link customTaskEnv}, and the running user's home directory as the
+ * working directory unless the declaration names one. Never the vault by
+ * default: it syncs and is writable through the MCP write tools, and a
+ * shell resolves a bare command name in the working directory first on
+ * Windows. Exit 0 resolves with no receipt: a custom task never calls a
+ * model on the lane's behalf and has no spend to account for. A non-zero
+ * exit throws `exit <N>: <stderr tail>`, the tail redacted BEFORE it is
+ * capped so a secret cannot straddle the cut, at most
+ * {@link LANE_ERROR_MAX_BYTES} in all.
+ *
+ * The outcome is the shell's exit status: the task does not wait for
+ * processes the command left in the background. Those still belong to the
+ * task. On POSIX the command runs in its own process group, and that group
+ * is killed when the task's timeout elapses or when this process exits,
+ * whichever comes first, also after the shell itself has exited.
+ *
+ * The timeout is enforced here, not by the `OPERATION`-keyed safeguard (a
+ * custom identity is not an operation): past `timeoutSeconds` the process
+ * group gets SIGTERM, then SIGKILL after a short grace (`taskkill /T /F`
+ * on Windows), and the task throws {@link SafeguardTimeoutError}, so the
+ * journal row carries `timed_out: true` exactly as a built-in's does -
+ * and, for a custom identity, that row counts toward the failure streak.
+ * An aborted `signal` kills the group the same way and throws
+ * {@link SafeguardAbortError}.
+ */
+export function createCustomLaneTask(
+ spec: CustomTaskSpec,
+ ctx: { readonly vault: string; readonly signal?: AbortSignal },
+): MaintenanceTask {
+ return {
+ name: spec.id,
+ run: () => runCustomCommand(spec, ctx),
+ };
+}
+
+/** The directory a task runs in: its declared `_cwd`, else the running user's home. */
+function customTaskCwd(spec: CustomTaskSpec): string {
+ if (spec.cwd !== undefined) return spec.cwd;
+ const home = homedir();
+ if (home === "") {
+ throw new Error(
+ `custom task ${spec.name}: the home directory, its default working directory, ` +
+ `cannot be resolved; set ${KEY_PREFIX}${spec.name}${CWD_SUFFIX}`,
+ );
+ }
+ return home;
+}
+
+function runCustomCommand(
+ spec: CustomTaskSpec,
+ ctx: { readonly vault: string; readonly signal?: AbortSignal },
+): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ if (ctx.signal?.aborted === true) {
+ reject(new SafeguardAbortError(spec.id));
+ return;
+ }
+ let cwd: string;
+ try {
+ cwd = customTaskCwd(spec);
+ } catch (err) {
+ reject(err as Error);
+ return;
+ }
+ // Named before the spawn: a missing directory otherwise surfaces as
+ // `ENOENT ... posix_spawn 'sh'`, which names the shell, not the path.
+ const stat = statSync(cwd, { throwIfNoEntry: false });
+ if (stat === undefined || !stat.isDirectory()) {
+ reject(
+ new Error(
+ `custom task ${spec.name}: cwd ${stat === undefined ? "does not exist" : "is not a directory"}: ${cwd}`,
+ ),
+ );
+ return;
+ }
+ const [shell, argv] = shellArgv(spec.command);
+ const posix = process.platform !== "win32";
+ let child: ChildProcess;
+ try {
+ child = spawn(shell, argv, {
+ cwd,
+ env: customTaskEnv(ctx.vault),
+ stdio: ["ignore", "ignore", "pipe"],
+ windowsVerbatimArguments: !posix,
+ // Its own process group on POSIX, so a kill reaches whatever the
+ // shell started, not only the shell.
+ detached: posix,
+ windowsHide: true,
+ });
+ } catch (err) {
+ reject(new Error(`${spec.id}: could not start: ${(err as Error).message ?? String(err)}`));
+ return;
+ }
+ const pgid = posix ? child.pid : undefined;
+ if (pgid !== undefined) trackGroup(pgid);
+
+ let stderr = Buffer.alloc(0);
+ child.stderr?.on("data", (chunk: Buffer) => {
+ stderr = Buffer.concat([stderr, chunk]);
+ if (stderr.length > STDERR_HOLD_BYTES) stderr = stderr.subarray(-STDERR_HOLD_BYTES);
+ });
+
+ let settled = false;
+ let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined;
+ let drainTimer: ReturnType<typeof setTimeout> | undefined;
+ const timeoutMs = spec.timeoutSeconds * 1000;
+ const finish = (error?: Error): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(drainTimer);
+ ctx.signal?.removeEventListener("abort", onAbort);
+ // A background holder of the pipe must not keep this process alive.
+ child.stderr?.destroy();
+ if (pgid !== undefined && groupAlive(pgid)) {
+ // The deadline outlives the outcome while the group still has
+ // members: it then only kills what the command left behind.
+ deadline.unref();
+ } else {
+ clearTimeout(deadline);
+ if (pgid !== undefined) liveGroups.delete(pgid);
+ }
+ if (error === undefined) resolve();
+ else reject(error);
+ };
+ const killGroup = (): void => {
+ if (pgid === undefined) {
+ killWindowsTree(child);
+ return;
+ }
+ signalGroup(pgid, "SIGTERM");
+ const hard = setTimeout(() => {
+ signalGroup(pgid, "SIGKILL");
+ liveGroups.delete(pgid);
+ }, KILL_GRACE_MS);
+ hard.unref();
+ };
+ const deadline = setTimeout(() => {
+ killGroup();
+ // The shell already exited and only the stderr drain is pending: its
+ // status is the outcome, and the deadline only kills the leftovers.
+ if (exit !== undefined) {
+ settleExit();
+ return;
+ }
+ finish(new SafeguardTimeoutError(spec.id, timeoutMs));
+ }, timeoutMs);
+ const onAbort = (): void => {
+ clearTimeout(deadline);
+ killGroup();
+ finish(new SafeguardAbortError(spec.id));
+ };
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
+
+ const settleExit = (): void => {
+ if (exit === undefined) return;
+ if (exit.code === 0) {
+ finish();
+ return;
+ }
+ const head =
+ exit.code !== null
+ ? `exit ${exit.code}`
+ : `killed by ${exit.signal ?? "an unknown signal"}`;
+ finish(new Error(failureMessage(head, stderr.toString("utf8"))));
+ };
+ child.on("error", (err) => {
+ killGroup();
+ finish(new Error(`${spec.id}: could not run: ${err.message}`));
+ });
+ child.on("exit", (code, signal) => {
+ exit = { code, signal };
+ drainTimer = setTimeout(settleExit, STDERR_DRAIN_MS);
+ });
+ child.on("close", (code, signal) => {
+ exit ??= { code, signal };
+ settleExit();
+ });
+ });
+}
+
+/** `<head>: <redacted stderr tail>`, at most {@link LANE_ERROR_MAX_BYTES}. */
+function failureMessage(head: string, stderr: string): string {
+ const redacted = redactRawOutput(stderr, {
+ redactTokens: true,
+ redactUrlCredentials: true,
+ }).trim();
+ if (redacted === "") return `${head}: (no stderr)`;
+ const prefix = `${head}: `;
+ const budget = LANE_ERROR_MAX_BYTES - Buffer.byteLength(prefix, "utf8");
+ if (Buffer.byteLength(redacted, "utf8") <= budget) return `${prefix}${redacted}`;
+ const marker = "[stderr truncated, tail follows]\n";
+ return `${prefix}${marker}${utf8Tail(redacted, budget - Buffer.byteLength(marker, "utf8"))}`;
+}
+
+/** The last `maxBytes` of `text`, cut on a character boundary. */
+function utf8Tail(text: string, maxBytes: number): string {
+ const chars = [...text];
+ let bytes = 0;
+ let start = chars.length;
+ while (start > 0) {
+ const size = Buffer.byteLength(chars[start - 1]!, "utf8");
+ if (bytes + size > maxBytes) break;
+ bytes += size;
+ start -= 1;
+ }
+ return chars.slice(start).join("");
+}
+
+/**
+ * Windows: kill the shell and the tree it started. `taskkill /T` walks the
+ * tree from a live parent, so once the shell has exited there is no tree
+ * left to walk. Never throws.
+ */
+function killWindowsTree(child: ChildProcess): void {
+ if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;
+ try {
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true });
+ } catch {
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ // Already gone.
+ }
+ }
+}
diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.ts
index 1a0da513..734f3bb1 100644
--- a/src/core/brain/maintenance/journal.ts
+++ b/src/core/brain/maintenance/journal.ts
@@ -21,6 +21,7 @@ import {
import { DERIVED_STORE_DIR } from "../path-constants.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import type { HostPressureUnmeasurableReason } from "./host-pressure.ts";
+import { isCustomLaneTask } from "./custom-task-id.ts";
import { renameWithRetry } from "../../fs-atomic.ts";
export const MAINTENANCE_JOURNAL_CAP = 500;
@@ -75,9 +76,11 @@ export interface MaintenanceJournalEntry {
readonly error?: string;
/**
* True on a failed row whose task hit its safeguard deadline. Journaled
- * and reported like any failure, but not counted toward the streak that
- * refuses the task: a pass that ran out of time is not a broken pass,
- * and refusing it would stop the keyword index from refreshing at all.
+ * and reported like any failure. For a built-in task it is not counted
+ * toward the streak that refuses the task: a pass that ran out of time
+ * is not a broken pass, and refusing it would stop the keyword index
+ * from refreshing at all. For a `custom:<name>` task it IS counted: see
+ * {@link consecutiveTaskFailures}.
*/
readonly timed_out?: boolean;
/** Host pressure the gate read, on a `skipped:pressure` row. */
@@ -225,9 +228,13 @@ export function listJournal(vault: string, limit?: number): MaintenanceJournalEn
* - only rows that record a completed ATTEMPT are counted. A gate
* refusal and a lease skip are not attempts, so they cannot deepen a
* streak.
- * - a failure that is a safeguard TIMEOUT (`timed_out`) is skipped: it
- * neither deepens the streak nor ends it, so a long pass that keeps
- * running out of budget is reported every night but never refused.
+ * - a failure of a BUILT-IN task that is a safeguard TIMEOUT
+ * (`timed_out`) is skipped: it neither deepens the streak nor ends it,
+ * so a long pass that keeps running out of budget is reported every
+ * night but never refused. A custom (`custom:<name>`) task's timeout
+ * COUNTS: its budget is the operator's own `_timeout_seconds`, so a
+ * timeout there is the command hanging, not a slow vault, and a
+ * command that always hangs must reach the refusal like any failure.
*
* A row that ran but recorded no outcome stops the walk as well: refusing
* work on evidence this build cannot read is the wrong direction to err.
@@ -268,8 +275,12 @@ export function consecutiveTaskFailures(vault: string, task: string): number {
}
if (entry.verdict !== MAINTENANCE_VERDICT.run) continue;
if (entry.ok !== false) break;
- // A timeout neither counts nor ends the streak: see `timed_out`.
- if (entry.timed_out === true) continue;
+ // A built-in timeout neither counts nor ends the streak: see
+ // `timed_out`. A custom task's timeout counts like any failure: the
+ // operator chose its budget, so running out of it is the command
+ // hanging, and a command that always hangs would otherwise never be
+ // refused while costing its full timeout of lease time every pass.
+ if (entry.timed_out === true && !isCustomLaneTask(entry.task)) continue;
streak += 1;
}
return streak;
diff --git a/src/core/brain/maintenance/lane-tasks.ts b/src/core/brain/maintenance/lane-tasks.ts
new file mode 100644
index 00000000..fe17362f
--- /dev/null
+++ b/src/core/brain/maintenance/lane-tasks.ts
@@ -0,0 +1,162 @@
+/**
+ * The maintenance lane's task list, built once for both front doors
+ * (`o2b brain maintenance run` and the `brain_maintenance` MCP tool).
+ *
+ * The two surfaces carried the same four task bodies inline, and the
+ * copies drifted. This builder owns them now: the four built-ins in their
+ * registration order ({@link LANE_TASKS}), then the install-owned custom
+ * tasks the machine config declares, when the master switch is on. What
+ * differs per surface arrives by injection: the per-task safeguard (built
+ * lazily, so each deadline starts when its task starts), the abort
+ * signal, the progress sink and the spend banner.
+ *
+ * `taskNames` is the registered vocabulary both surfaces validate
+ * `--retry`/`retry_tasks` against, and `custom.errors` carries every
+ * refused declaration by name for the surface to report.
+ */
+
+import { dream } from "../dream.ts";
+import {
+ discoverBridges,
+ readDismissedBridges,
+ writeBridgeProposals,
+} from "../link-graph/bridge-discovery.ts";
+import { detectCommunities, materializeClusterNotes } from "../link-graph/communities.ts";
+import { appendMetric } from "../metrics.ts";
+import type { ProgressSink } from "../progress.ts";
+import type { Safeguard } from "../safeguard.ts";
+import { isoSecond } from "../time.ts";
+import type { EmbeddingSpendPreview } from "../../search/indexer.ts";
+import { Store } from "../../search/store.ts";
+import type { ResolvedSearchConfig } from "../../search/types.ts";
+import {
+ createCustomLaneTask,
+ resolveCustomTasks,
+ type CustomTaskResolution,
+} from "./custom-tasks.ts";
+import { LANE_TASK, type LaneTask, type LaneTaskId, type MaintenanceTask } from "./lane.ts";
+import { createLaneReindex, type LaneReindex } from "./reindex-task.ts";
+
+export interface LaneTaskBuildOptions {
+ readonly vault: string;
+ readonly configPath?: string;
+ readonly searchConfig: ResolvedSearchConfig;
+ readonly now: Date;
+ /** Bypass a positive embedding cost gate for this run (`--force-cost`). */
+ readonly forceCost: boolean;
+ /** One fresh deadline per built-in task, called when that task starts. */
+ readonly safeguardFor: (operation: LaneTask) => Safeguard;
+ readonly signal?: AbortSignal;
+ readonly onProgress?: ProgressSink;
+ /** Called once with the reindex spend preview, before the pass, when there is one. */
+ readonly onBanner?: (preview: EmbeddingSpendPreview) => void;
+}
+
+export interface LaneTaskSet {
+ readonly tasks: ReadonlyArray<MaintenanceTask>;
+ readonly reindex: LaneReindex;
+ /** Every registered identity, in registration order. */
+ readonly taskNames: ReadonlyArray<LaneTaskId>;
+ readonly custom: CustomTaskResolution;
+}
+
+export function buildLaneTasks(opts: LaneTaskBuildOptions): LaneTaskSet {
+ const { vault, now, searchConfig, safeguardFor } = opts;
+ const laneProgress = opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {};
+ // Spend is opt-in (`maintenance_embeddings`): the reindex builder decides
+ // whether the pass may embed, announces the predicted spend inside the
+ // task and receipts what the phase priced.
+ const reindex = createLaneReindex({
+ vault,
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ searchConfig,
+ now,
+ forceCost: opts.forceCost,
+ safeguard: () => safeguardFor(LANE_TASK.reindex),
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
+ ...laneProgress,
+ ...(opts.onBanner !== undefined ? { onBanner: opts.onBanner } : {}),
+ });
+ const builtIns: MaintenanceTask[] = [
+ {
+ name: LANE_TASK.dream,
+ run: async () => {
+ dream(vault, { now, safeguard: safeguardFor(LANE_TASK.dream), ...laneProgress });
+ },
+ },
+ reindex.task,
+ // Link-recall-intelligence passes ride the same lease, after reindex
+ // so they see fresh edges. Both are fail-soft inside: a vault without
+ // embeddings simply proposes nothing, and a metrics write failure
+ // never fails the task.
+ {
+ name: LANE_TASK.bridges,
+ run: async () => {
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ const report = discoverBridges(store, {
+ dismissed: readDismissedBridges(vault),
+ safeguard: safeguardFor(LANE_TASK.bridges),
+ ...laneProgress,
+ });
+ writeBridgeProposals(vault, report, { now });
+ try {
+ appendMetric(vault, {
+ surface: "bridge_discovery",
+ runAt: isoSecond(now),
+ payload: {
+ proposals: report.proposals.length,
+ scanned_candidates: report.scannedCandidates,
+ vec_available: report.vecAvailable,
+ lane: true,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ } finally {
+ await store.close();
+ }
+ },
+ },
+ {
+ name: LANE_TASK.clusters,
+ run: async () => {
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ const communities = detectCommunities(store, {
+ safeguard: safeguardFor(LANE_TASK.clusters),
+ ...laneProgress,
+ });
+ const materialized = materializeClusterNotes(vault, communities, { store, now });
+ try {
+ appendMetric(vault, {
+ surface: "communities",
+ runAt: isoSecond(now),
+ payload: {
+ communities: communities.length,
+ sizes: communities.map((c) => c.size),
+ written: materialized.written.length,
+ removed: materialized.removed.length,
+ lane: true,
+ },
+ });
+ } catch {
+ // Metrics are observability, not correctness.
+ }
+ } finally {
+ await store.close();
+ }
+ },
+ },
+ ];
+ const custom = resolveCustomTasks(opts.configPath);
+ const customTasks = custom.specs.map((spec) =>
+ createCustomLaneTask(spec, {
+ vault,
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
+ }),
+ );
+ const tasks = [...builtIns, ...customTasks];
+ return { tasks, reindex, taskNames: tasks.map((task) => task.name), custom };
+}
diff --git a/src/core/brain/maintenance/lane.ts b/src/core/brain/maintenance/lane.ts
index 4fdd85ec..b9ad4f10 100644
--- a/src/core/brain/maintenance/lane.ts
+++ b/src/core/brain/maintenance/lane.ts
@@ -67,6 +67,7 @@ import {
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";
@@ -144,7 +145,7 @@ export interface MaintenanceGateDecision {
}
/** Cap for persisted per-task error strings (journal + results). */
-const LANE_ERROR_MAX_BYTES = 4096;
+export const LANE_ERROR_MAX_BYTES = 4096;
/**
* The heavy passes this lane dispatches.
@@ -199,8 +200,17 @@ 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: LaneTask;
+ readonly name: LaneTaskId;
/**
* Run the pass. A pass that spent model budget returns the
* {@link MaintenanceSpendReceipt} the cost kernel priced for it, and
@@ -229,12 +239,12 @@ export interface RunMaintenanceOptions extends EvaluateGatesOptions {
* 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<LaneTask>;
+ readonly retryTasks?: ReadonlyArray<LaneTaskId>;
readonly leaseTtlMs?: number;
}
export interface MaintenanceTaskResult {
- readonly name: LaneTask;
+ readonly name: LaneTaskId;
readonly ok: boolean;
readonly duration_ms: number;
readonly error?: string;
@@ -447,7 +457,7 @@ function resolvePressureGate(
/** The task-result and journal rows of a streak refusal, or `undefined` to run. */
function refuseOnStreak(
vault: string,
- task: LaneTask,
+ task: LaneTaskId,
limit: number,
):
| { result: MaintenanceTaskResult; entry: Omit<MaintenanceJournalEntry, "ts" | "holder"> }
diff --git a/src/core/config.ts b/src/core/config.ts
index d2c1de57..8f5de1cd 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -668,7 +668,11 @@ export function resolveSkillsDir(configPath?: string): string | null {
*/
function resolveConfigFlag(envKey: string, configKey: string, configPath?: string): boolean {
const env = process.env[envKey]?.trim();
- const raw = env || discoverConfig(configPath).data[configKey]?.trim();
+ return isFlagOn(env || discoverConfig(configPath).data[configKey]?.trim());
+}
+
+/** The one parse every boolean switch in this file shares. */
+function isFlagOn(raw: string | undefined): boolean {
return raw === "true" || raw === "1";
}
@@ -1118,6 +1122,44 @@ export function resolveMaintenanceEmbeddings(configPath?: string): boolean {
);
}
+/**
+ * Env var and config key of the maintenance lane's custom-task master
+ * switch. Named because the lane quotes them back: `status` says which
+ * of the two turned declared custom tasks off.
+ */
+export const MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS";
+export const MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks";
+
+/** Which source decided a boolean switch: the env override, the config key, or neither. */
+export type MaintenanceSwitchSource = "env" | "config" | "unset";
+
+/**
+ * Whether the maintenance lane may run the install-owned custom tasks
+ * declared as `maintenance_custom_<name>` keys in this config file, and
+ * the source that decided it, so `status` can name the env override when
+ * that is what turned the declared tasks off. Default OFF: a declared
+ * command is operator-authored shell, so it runs only behind an explicit
+ * opt-in, and `..._CUSTOM_TASKS=0` in the env turns it off on one host
+ * without editing the shared file. The commands themselves are read from
+ * this machine config only, never from the vault. Same parse as every
+ * other flag in this file. A caller that already parsed the config passes
+ * its `data`, so the switch and the declarations come from one snapshot.
+ */
+export function resolveMaintenanceCustomTasksSwitch(
+ configPath?: string,
+ data: Readonly<Record<string, string>> = discoverConfig(configPath).data,
+): {
+ readonly enabled: boolean;
+ readonly source: MaintenanceSwitchSource;
+} {
+ const env = process.env[MAINTENANCE_CUSTOM_TASKS_ENV]?.trim();
+ const fromConfig = data[MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY]?.trim();
+ return {
+ enabled: isFlagOn(env || fromConfig),
+ source: env ? "env" : fromConfig ? "config" : "unset",
+ };
+}
+
/**
* Env var and config key of the codegraph partner-check switch. Named
* rather than inlined because the doctor QUOTES them: the line it prints
diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.ts
index 14fc7bd0..d33a7b31 100644
--- a/src/core/install/ownership.ts
+++ b/src/core/install/ownership.ts
@@ -275,11 +275,14 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
label: "cron recipe scripts and their stamps",
location:
"~/.local/bin/<job>.sh, plus ${XDG_STATE_HOME:-~/.local/state}/open-second-brain/ for the " +
- "codegraph resync stamp",
+ "codegraph resync stamp, and ~/.config/systemd/user/<job>.service and <job>.timer when the " +
+ "recipe was printed with `--format systemd`",
carries_memory: false,
created_by:
"you, following a recipe printed by a `--cron-template` verb - this tool installs none of it",
- removed_by: "deleting the script and the stamp, and removing the crontab line yourself",
+ removed_by:
+ "deleting the script and the stamp, and removing the crontab line yourself, or for a " +
+ "systemd recipe `systemctl --user disable --now <job>.timer` and deleting both unit files",
note:
"The recipes are text on stdout: every write in them is a shell command your own crontab " +
"runs on your own host. Nothing in this tool creates, updates or removes them.",
@@ -287,8 +290,24 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
"src/cli/cron-recipe.ts",
"src/cli/partner-codegraph-cron.ts",
"src/cli/search-cron-template.ts",
+ "src/cli/maintenance-cron.ts",
],
},
+ {
+ id: "hermes_discipline_jobs",
+ label: "Hermes cron jobs for the discipline report",
+ location:
+ "~/.hermes/cron/jobs.json of the user running the verb, or the file OSB_HERMES_JOBS names",
+ carries_memory: false,
+ created_by:
+ "`o2b discipline install`, which adds or updates the daily or the weekly job of each vault in that file, so a vault can own two entries",
+ removed_by:
+ "`o2b discipline uninstall`, which removes this tool's jobs and leaves every other job in the file alone",
+ note:
+ "The jobs file belongs to Hermes; this tool edits only the entries whose ids it derives from the " +
+ "vault path. Each job names the vault, the report script and the delivery target, not memory content.",
+ sources: ["src/cli/discipline-install.ts"],
+ },
{
id: "bench_run_artifacts",
label: "benchmark run artifacts",
@@ -346,6 +365,12 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma
"The ratchet state it actually persists lives inside the vault, so this module leaves " +
"nothing behind on the machine",
],
+ [
+ "src/core/brain/maintenance/custom-tasks.ts",
+ "it reads the home directory only to hand it to a declared custom task as its default " +
+ "working directory; it builds no path to write, and whatever the operator's own command " +
+ "does there is that command's state, not this program's",
+ ],
[
"src/core/install/ownership.ts",
"this module IS the enumeration: the home- and XDG-rooted strings in it are the `location` " +
@@ -492,6 +517,12 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma
* claim about a census.
*/
export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new Map([
+ [
+ "src/cli/maintenance-cron.ts",
+ "the maintenance lane recipe takes its script path from `operatorScriptPath()` in " +
+ "`cli/cron-recipe.ts` and its systemd unit paths from the shared renderer there, so there " +
+ "is no home or XDG token in this file for the sweep to match on",
+ ],
[
"src/core/brain/dedup-index-cache.ts",
"the cache root comes from `cacheBaseDir()` in `core/platform-dirs.ts`, or from " +
diff --git a/src/core/reliability/command-bridge.ts b/src/core/reliability/command-bridge.ts
index 277622ab..33935b24 100644
--- a/src/core/reliability/command-bridge.ts
+++ b/src/core/reliability/command-bridge.ts
@@ -33,9 +33,11 @@ const DEFAULT_TIMEOUT_MS = 60_000;
* The shell an operator-configured command line runs under: `sh -c` on
* POSIX, `cmd.exe /d /s /c` on native Windows (the same invocation Node
* uses for `shell: true`; `/d` skips AutoRun, whose output would corrupt
- * the JSON on stdout).
+ * the JSON on stdout). Exported because the maintenance lane's custom
+ * tasks run an operator-configured command line too, and one invocation
+ * form for both keeps the Windows quoting in one place.
*/
-function shellArgv(cmd: string): [string, string[]] {
+export function shellArgv(cmd: string): [string, string[]] {
if (process.platform === "win32") {
return [process.env["ComSpec"] || "cmd.exe", ["/d", "/s", "/c", `"${cmd}"`]];
}
diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.ts
index ab4b87f0..407d0117 100644
--- a/src/mcp/brain/admin-tools.ts
+++ b/src/mcp/brain/admin-tools.ts
@@ -27,24 +27,17 @@ import { assertVaultIdentityForWrite } from "../../core/brain/vault-identity.ts"
import { loadSchemaPack } from "../../core/brain/schema-pack.ts";
import { listSecrets } from "../../core/brain/secrets/store.ts";
import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";
-import {
- discoverBridges,
- readDismissedBridges,
- writeBridgeProposals,
-} from "../../core/brain/link-graph/bridge-discovery.ts";
-import {
- detectCommunities,
- materializeClusterNotes,
-} from "../../core/brain/link-graph/communities.ts";
-import { appendMetric } from "../../core/brain/metrics.ts";
import type { ProgressSink } from "../../core/brain/progress.ts";
import { requiredStringArg, toolSafeguard } from "./shared.ts";
import { currentLease } from "../../core/brain/maintenance/lease.ts";
import { listJournal, MAINTENANCE_JOURNAL_CAP } from "../../core/brain/maintenance/journal.ts";
-import { createLaneReindex } from "../../core/brain/maintenance/reindex-task.ts";
import {
- isLaneTask,
- LANE_TASK,
+ CUSTOM_TASK_MAX,
+ customTasksOffNotice,
+ resolveCustomTasks,
+} from "../../core/brain/maintenance/custom-tasks.ts";
+import { buildLaneTasks } from "../../core/brain/maintenance/lane-tasks.ts";
+import {
LANE_TASKS,
MAINTENANCE_BUSY_MINUTES,
MAINTENANCE_BUSY_MINUTES_MAX,
@@ -53,13 +46,12 @@ import {
runMaintenance,
type DailyWindow,
type LaneTask,
+ type LaneTaskId,
} from "../../core/brain/maintenance/lane.ts";
import { writeFrontmatterAtomic } from "../../core/vault.ts";
import { resolveNotePath } from "../../core/brain/note-path.ts";
import type { FrontmatterMap } from "../../core/types.ts";
import { parseFrontmatter } from "../../core/vault.ts";
-import { dream } from "../../core/brain/dream.ts";
-import { isoSecond } from "../../core/brain/time.ts";
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
import { coerceInt, coerceStrList } from "../coerce.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
@@ -333,8 +325,10 @@ async function toolBrainSecrets(
// ----- brain_maintenance (t_166d1226) ------------------------------------------
/**
- * Bound for `retry_tasks`: naming more tasks than the lane dispatches is
- * a mistake, not a request.
+ * Advertised bound for `retry_tasks`: the widest list any install can
+ * need, the built-ins plus the custom-task cap. The handler refuses
+ * against the tasks THIS install registered, which can be fewer; naming
+ * more tasks than the lane dispatches is a mistake, not a request.
*
* The `maxItems` this feeds into the schema is ADVERTISEMENT, not
* enforcement - nothing in the request path validates a JSON Schema.
@@ -344,7 +338,7 @@ async function toolBrainSecrets(
* itself for that reason; the schema keeps the number so a client that
* does validate refuses before spending a round trip.
*/
-const MAX_RETRY_TASKS = LANE_TASKS.length;
+const MAX_RETRY_TASKS = LANE_TASKS.length + CUSTOM_TASK_MAX;
/** Quiet-window, lease-guarded heavy maintenance lane. */
async function toolBrainMaintenance(
@@ -362,9 +356,11 @@ async function toolBrainMaintenance(
// hardcoded at ten here, so an agent reading a lane that had refused
// a task days ago could not see far enough back to find the failures
// behind the streak - the one thing the journal is kept for.
+ const notice = customTasksOffNotice(resolveCustomTasks(ctx.configPath ?? undefined));
return {
lease: currentLease(ctx.vault, { now }),
journal: listJournal(ctx.vault, coerceInt(args, "limit", 10, 1, MAINTENANCE_JOURNAL_CAP)),
+ ...(notice !== null ? { notice } : {}),
};
}
let window: DailyWindow | undefined;
@@ -408,27 +404,6 @@ async function toolBrainMaintenance(
MAINTENANCE_BUSY_THRESHOLD_MAX,
),
};
- // Refused BY NAME, exactly as the CLI refuses a `--retry` typo: a name
- // this lane does not dispatch retries nothing, and silently accepting
- // it would leave the caller reading a refusal it believed it had just
- // asked past.
- const requestedRetries = coerceStrList(args, "retry_tasks");
- if (requestedRetries.length > MAX_RETRY_TASKS) {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_maintenance run: retry_tasks accepts at most ${MAX_RETRY_TASKS} entries ` +
- `(one per lane task: ${LANE_TASKS.join(", ")}), got ${requestedRetries.length}`,
- );
- }
- const unknownRetries = requestedRetries.filter((name) => !isLaneTask(name));
- if (unknownRetries.length > 0) {
- throw new MCPError(
- INVALID_PARAMS,
- `brain_maintenance run: retry_tasks names no lane task: ${unknownRetries.join(", ")} ` +
- `(tasks: ${LANE_TASKS.join(", ")})`,
- );
- }
- const retryTasks: ReadonlyArray<LaneTask> = requestedRetries.filter(isLaneTask);
const agentArg = args["agent"];
const agent =
normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
@@ -439,33 +414,44 @@ async function toolBrainMaintenance(
});
// Same per-task deadlines as the CLI lane (t_06784b8d): one fresh
// cooperative safeguard per task, budget resolved per-op -> global
- // -> default. The lane is the only surface that wants a guard PER
- // TASK rather than per call, so it names the shared factory four
- // times instead of holding one guard.
- // A lane task IS one of the guarded operations, so the task name is the
- // budget key. The union that used to be retyped here is gone: both
- // surfaces read `LANE_TASK`, whose values come from `OPERATION`.
+ // -> default. A lane task IS one of the guarded operations, so the task
+ // name is the budget key.
const laneSafeguard = (operation: LaneTask) => toolSafeguard(ctx, operation);
- // The lane is a dispatcher over four long operations, not a fifth one,
- // so it forwards the caller's sink to each task rather than counting
- // tasks itself: every event names the operation that emitted it, which
- // is what tells a reader which of the four the lane is currently in.
- const laneProgress = onProgress ? { onProgress } : {};
- // Spend parity with the CLI lane: the same builder decides whether the
- // pass may embed (`maintenance_embeddings` opt-in plus a reachable
- // provider), computes the preview inside the task - so a run a gate
- // skips reads nothing and reports no banner - and receipts what the
- // phase priced. `force_cost` bypasses a positive gate for this run and
- // is recorded on the receipt when it did.
- const reindexTask = createLaneReindex({
+ // The lane is a dispatcher over its tasks, not one more operation, so
+ // it forwards the caller's sink to each task rather than counting tasks
+ // itself: every event names the operation that emitted it.
+ //
+ // One shared builder serves this tool and the CLI verb, so the task
+ // bodies - and the spend rules of the reindex task: `maintenance_embeddings`
+ // opt-in, the preview computed inside the task so a gated-out run reports
+ // no banner, `force_cost` recorded on the receipt - cannot drift between
+ // the two surfaces. Declared custom tasks ride after the built-ins.
+ const lane = buildLaneTasks({
vault: ctx.vault,
...(ctx.configPath ? { configPath: ctx.configPath } : {}),
searchConfig,
now,
forceCost: args["force_cost"] === true,
- safeguard: () => laneSafeguard(LANE_TASK.reindex),
- ...laneProgress,
+ safeguardFor: laneSafeguard,
+ ...(onProgress ? { onProgress } : {}),
});
+ // Refused BY NAME, exactly as the CLI refuses a `--retry` typo: a name
+ // this lane does not dispatch retries nothing, and silently accepting
+ // it would leave the caller reading a refusal it believed it had just
+ // asked past. The bound is the tasks this install registered: once the
+ // names are deduplicated, a list longer than that always names an
+ // unknown task, so the one refusal below covers it with the CLI's words.
+ const requestedRetries = [...new Set(coerceStrList(args, "retry_tasks"))];
+ const registered = new Set<string>(lane.taskNames);
+ const unknownRetries = requestedRetries.filter((name) => !registered.has(name));
+ if (unknownRetries.length > 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_maintenance run: retry_tasks names no lane task: ${unknownRetries.join(", ")} ` +
+ `(tasks: ${lane.taskNames.join(", ")})`,
+ );
+ }
+ const retryTasks = requestedRetries as LaneTaskId[];
const result = await runMaintenance(ctx.vault, {
now,
holder: `${agent}@${process.pid}`,
@@ -473,86 +459,17 @@ async function toolBrainMaintenance(
busy,
...(retryTasks.length > 0 ? { retryTasks } : {}),
...(window !== undefined ? { window } : {}),
- tasks: [
- {
- name: LANE_TASK.dream,
- run: async () => {
- dream(ctx.vault, { now, safeguard: laneSafeguard(LANE_TASK.dream), ...laneProgress });
- },
- },
- reindexTask.task,
- // Same lane contract as the CLI verb (link-recall-intelligence):
- // bridges and clusters run after reindex so they see fresh
- // edges; both are fail-soft without embeddings, and a metrics
- // write failure never fails the task.
- {
- name: LANE_TASK.bridges,
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const report = discoverBridges(store, {
- dismissed: readDismissedBridges(ctx.vault),
- safeguard: laneSafeguard(LANE_TASK.bridges),
- ...laneProgress,
- });
- writeBridgeProposals(ctx.vault, report, { now });
- try {
- appendMetric(ctx.vault, {
- surface: "bridge_discovery",
- runAt: isoSecond(now),
- payload: {
- proposals: report.proposals.length,
- scanned_candidates: report.scannedCandidates,
- vec_available: report.vecAvailable,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- {
- name: LANE_TASK.clusters,
- run: async () => {
- const store = await Store.open(searchConfig, { mode: "read" });
- try {
- const communities = detectCommunities(store, {
- safeguard: laneSafeguard(LANE_TASK.clusters),
- ...laneProgress,
- });
- const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });
- try {
- appendMetric(ctx.vault, {
- surface: "communities",
- runAt: isoSecond(now),
- payload: {
- communities: communities.length,
- sizes: communities.map((c) => c.size),
- written: materialized.written.length,
- removed: materialized.removed.length,
- lane: true,
- },
- });
- } catch {
- // Metrics are observability, not correctness.
- }
- } finally {
- await store.close();
- }
- },
- },
- ],
+ tasks: lane.tasks,
});
// The run-level spend block, the CLI JSON payload's shape.
- const spend = reindexTask.spendBlock(result.tasks);
+ const spend = lane.reindex.spendBlock(result.tasks);
return {
verdict: result.verdict,
tasks: result.tasks,
...(spend !== undefined ? { spend } : {}),
+ // Named, never dropped: a refused declaration journals nothing, and
+ // the valid tasks still ran.
+ ...(lane.custom.errors.length > 0 ? { custom_task_errors: lane.custom.errors } : {}),
};
}
@@ -634,7 +551,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_maintenance",
description:
- "Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters behind window, busy, pressure and streak gates; status renders lease and journal. Reindex is keyword-only unless config maintenance_embeddings is true; then spend is announced, receipted and cost-gated.",
+ "Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters and declared custom:<name> tasks behind window, busy, pressure and streak gates; status renders lease and journal. Reindex embeds only with config maintenance_embeddings.",
inputSchema: {
type: "object",
properties: {
@@ -652,7 +569,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "array",
items: { type: "string" },
maxItems: MAX_RETRY_TASKS,
- description: `Tasks to retry past their streak refusal, this run only; gates still apply. Known: ${LANE_TASKS.join(", ")}. An unknown name is refused.`,
+ description: `Tasks to retry past their streak refusal, this run only; gates still apply. Known: ${LANE_TASKS.join(", ")}, custom:<name>. Unknown names are refused.`,
},
force_cost: {
type: "boolean",
diff --git a/src/mcp/http.ts b/src/mcp/http.ts
index 3c24ed4d..13b70a32 100644
--- a/src/mcp/http.ts
+++ b/src/mcp/http.ts
@@ -31,6 +31,21 @@ import { DRAIN_STATE, RequestDrain, resolveDrainDeadlineMs, type DrainOutcome }
import { ORIGIN_CHANNEL, setOriginChannel } from "../core/origin-channel.ts";
import { TRANSPORT_REACH, type TransportReach } from "../core/graph/transport-reach.ts";
+/**
+ * The process-level fault counts a served transport reports on `/health`.
+ *
+ * Typed here and filled by a getter the CLI injects
+ * ({@link ServeHttpOptions.faultCounts}): the guard that counts them is
+ * process-global and lives in `src/cli/mcp-fault-guard.ts`, and this
+ * module imports nothing from the CLI.
+ */
+export interface McpFaultCounts {
+ readonly unhandled_rejection: number;
+ readonly uncaught_exception: number;
+ /** ISO time of the latest fault of either kind, `null` before any. */
+ readonly last_fault_at: string | null;
+}
+
export interface ServeHttpOptions {
readonly host?: string;
readonly port?: number;
@@ -41,6 +56,12 @@ export interface ServeHttpOptions {
* Defaults to `O2B_MCP_DRAIN_MS`, and to ten seconds without it.
*/
readonly drainDeadlineMs?: number;
+ /**
+ * The process-level fault counts, read on every `/health` request.
+ * Injected by `o2b mcp` from its fault guard; without it `/health`
+ * carries no `faults` field, exactly as before.
+ */
+ readonly faultCounts?: () => McpFaultCounts;
}
export interface HttpServerHandle {
@@ -114,7 +135,7 @@ export async function startHttp(
// shutdown then waits for a client that is waiting for it.
res.on("close", finish);
try {
- await handleHttpRequest(mcp, apiKey, host, drain, req, res);
+ await handleHttpRequest(mcp, apiKey, host, drain, opts.faultCounts, req, res);
} catch (exc) {
// This promise used to be floated. A throw from the dispatch left
// the socket open with no response on it and no record anywhere;
@@ -218,6 +239,7 @@ async function handleHttpRequest(
apiKey: string | null,
boundHost: string,
drain: RequestDrain,
+ faultCounts: (() => McpFaultCounts) | undefined,
req: IncomingMessage,
res: ServerResponse,
): Promise<void> {
@@ -244,14 +266,18 @@ async function handleHttpRequest(
// and wait, and the count says how long that wait has left in it.
// The health probe itself is never refused during a drain - a
// shutdown a supervisor cannot observe is a shutdown it will report
- // as a crash. The drain counts this request like any other; it
- // answers within the same tick, so it never holds one open.
+ // as a crash. The drain does not count this request (see the
+ // `untracked` note in `startHttp`), so `in_flight` never includes
+ // the act of reading it.
+ // `faults` only when the CLI injected a getter: a supervisor that
+ // parses this body today sees exactly the three fields it knows.
res.writeHead(200, { "content-type": "application/json" });
res.end(
JSON.stringify({
status: drain.draining ? DRAIN_STATE.draining : "ok",
transport: "http",
in_flight: drain.inFlight,
+ ...(faultCounts !== undefined ? { faults: faultCounts() } : {}),
}) + "\n",
);
return;
diff --git a/tests/cli/brain-maintenance.test.ts b/tests/cli/brain-maintenance.test.ts
index 6f70d924..19046379 100644
--- a/tests/cli/brain-maintenance.test.ts
+++ b/tests/cli/brain-maintenance.test.ts
@@ -9,6 +9,7 @@ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSy
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
+import { MAINTENANCE_USAGE, VERB_HELP } from "../../src/cli/brain/help-text.ts";
import {
MAINTENANCE_EXIT,
formatSpendBanner,
@@ -21,11 +22,14 @@ import {
type MaintenanceSpendReceipt,
type MaintenanceTaskResult,
} from "../../src/core/brain/maintenance/lane.ts";
+import { listJournal, MAINTENANCE_JOURNAL_CAP } from "../../src/core/brain/maintenance/journal.ts";
+import { currentLease, MAINTENANCE_LEASE_NAME } from "../../src/core/brain/maintenance/lease.ts";
import { MAINTENANCE_EMBEDDINGS_ENV } from "../../src/core/config.ts";
import { MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT } from "../../src/core/brain/policy/blocks/maintenance.ts";
import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";
import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";
import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
+import { homeEnv } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
/**
@@ -111,9 +115,15 @@ test("a malformed window is a usage error", async () => {
expect(result.returncode).toBe(2);
});
-/** The per-test config, which alone names the test vault. */
+/**
+ * The per-test config, which alone names the test vault. The lane mints per-device state and runs custom tasks from the home
+ * directory, so every lane-running child gets a home of its own under
+ * the test's temp dir rather than the runner's.
+ */
function baseEnv(): Record<string, string> {
- return { OPEN_SECOND_BRAIN_CONFIG: configPath };
+ const home = join(tmp, "home");
+ mkdirSync(home, { recursive: true });
+ return { OPEN_SECOND_BRAIN_CONFIG: configPath, ...homeEnv(home) };
}
/** The local provider is configured, model-free and price-free, and the lane is opted in. */
@@ -192,6 +202,183 @@ test("--retry runs the refused task and names an unknown task as a usage error",
expect(dream?.ok).toBe(true);
});
+/** `run --cron-template` with `extra` flags against the test vault. */
+function recipe(extra: ReadonlyArray<string>) {
+ return runCli(["brain", "maintenance", "run", "--cron-template", "--vault", vault, ...extra], {
+ env: baseEnv(),
+ });
+}
+
+describe("run --cron-template prints the lane recipe and writes nothing", () => {
+ test("prints a recipe naming the job and the vault; no lease, no journal", async () => {
+ const printed = await recipe([]);
+ expect(printed.returncode).toBe(MAINTENANCE_EXIT.ok);
+ expect(printed.stdout).toContain("osb-maintenance");
+ expect(printed.stdout).toContain(`o2b brain maintenance run --vault '${vault}' --json`);
+ expect(printed.stdout).toContain("0 */1 * * *");
+ // Returned before the lease and the journal: printing a recipe is not
+ // a lane pass, so it must leave no trace a later status would read.
+ expect(currentLease(vault, { name: MAINTENANCE_LEASE_NAME, now: new Date() })).toBeNull();
+ expect(listJournal(vault, MAINTENANCE_JOURNAL_CAP)).toEqual([]);
+ expect(existsSync(join(vault, ".open-second-brain", "maintenance-runs.jsonl"))).toBe(false);
+ });
+
+ test("a bad interval or format is the lane's usage code, with the kernel's message", async () => {
+ const seconds = await recipe(["--interval", "30s"]);
+ expect(seconds.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(seconds.stderr).toContain("second-level intervals are not supported");
+ const months = await recipe(["--interval", "90d"]);
+ expect(months.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(months.stderr).toContain("an interval of 90 days cannot be expressed");
+ const launchd = await recipe(["--format", "launchd"]);
+ expect(launchd.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(launchd.stderr).toContain("systemd");
+ });
+
+ test("a lane-run flag beside --cron-template is the usage code, named, and writes nothing", async () => {
+ const forced = await recipe(["--force"]);
+ expect(forced.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(forced.stderr).toContain(
+ "--cron-template prints the recipe only and does not take --force (a lane-run flag)",
+ );
+ expect(forced.stdout).toBe("");
+ const several = await recipe(["--json", "--retry", "dream"]);
+ expect(several.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(several.stderr).toContain("--retry, --json");
+ expect(currentLease(vault, { name: MAINTENANCE_LEASE_NAME, now: new Date() })).toBeNull();
+ expect(listJournal(vault, MAINTENANCE_JOURNAL_CAP)).toEqual([]);
+ });
+
+ test("the window is validated and carried into the printed body", async () => {
+ const bad = await recipe(["--window", "25-3"]);
+ expect(bad.returncode).toBe(MAINTENANCE_EXIT.usage);
+ const windowed = await recipe(["--window", "3-5", "--tz", "Europe/Berlin"]);
+ expect(windowed.returncode).toBe(MAINTENANCE_EXIT.ok);
+ expect(windowed.stdout).toContain("--window 3-5");
+ expect(windowed.stdout).toContain("--tz Europe/Berlin");
+ const unwindowed = await recipe([]);
+ expect(unwindowed.stdout).not.toContain("--window");
+ });
+
+ test("status refuses --cron-template", async () => {
+ const status = await runCli(
+ ["brain", "maintenance", "status", "--cron-template", "--vault", vault],
+ { env: baseEnv() },
+ );
+ expect(status.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(status.stderr).toContain("--cron-template");
+ });
+
+ test("--format systemd prints a user timer at the default interval", async () => {
+ const timer = await recipe(["--format", "systemd"]);
+ expect(timer.returncode).toBe(MAINTENANCE_EXIT.ok);
+ expect(timer.stdout).toContain("OnUnitActiveSec=1h");
+ expect(timer.stdout).toContain(`o2b brain maintenance run --vault '${vault}' --json`);
+ });
+});
+
+/** Rewrite the per-test config with `lines` after the vault key. */
+function writeConfig(lines: ReadonlyArray<string>): void {
+ writeFileSync(configPath, [`vault: ${vault}`, ...lines].join("\n") + "\n");
+}
+
+async function initVault(): Promise<void> {
+ const init = await runCli(["brain", "init", "--vault", vault], { env: baseEnv() });
+ expect(init.returncode).toBe(0);
+}
+
+describe("declared custom tasks ride the lane", () => {
+ test("with the switch on, run reports the custom row after the built-ins", async () => {
+ writeConfig(["maintenance_custom_tasks: true", "maintenance_custom_tidy: exit 0"]);
+ await initVault();
+ const run = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"], {
+ env: baseEnv(),
+ });
+ expect(run.returncode).toBe(MAINTENANCE_EXIT.ok);
+ const payload = JSON.parse(run.stdout) as { tasks: Array<{ name: string; ok: boolean }> };
+ const tidy = payload.tasks.find((t) => t.name === "custom:tidy");
+ expect(tidy?.ok).toBe(true);
+ expect(payload.tasks.map((t) => t.name).toSorted()).toEqual(
+ [...LANE_TASKS, "custom:tidy"].toSorted(),
+ );
+ });
+
+ test("--retry accepts a declared custom task and names an undeclared one", async () => {
+ writeConfig(["maintenance_custom_tasks: true", "maintenance_custom_tidy: exit 0"]);
+ await initVault();
+ seedFailureStreak("custom:tidy", MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);
+
+ const refused = await runCli(["brain", "maintenance", "run", "--vault", vault], {
+ env: baseEnv(),
+ });
+ expect(refused.returncode).toBe(MAINTENANCE_EXIT.refused);
+ expect(refused.stdout).toContain("custom:tidy: REFUSED");
+
+ const unknown = await runCli(
+ ["brain", "maintenance", "run", "--retry", "custom:nope", "--vault", vault],
+ { env: baseEnv() },
+ );
+ expect(unknown.returncode).toBe(MAINTENANCE_EXIT.usage);
+ expect(unknown.stderr).toContain("custom:nope");
+ expect(unknown.stderr).toContain("custom:tidy");
+
+ const retried = await runCli(
+ ["brain", "maintenance", "run", "--retry", "custom:tidy", "--vault", vault, "--json"],
+ { env: baseEnv() },
+ );
+ expect(retried.returncode).toBe(MAINTENANCE_EXIT.ok);
+ const payload = JSON.parse(retried.stdout) as {
+ tasks: Array<{ name: string; ok: boolean; refused?: boolean }>;
+ };
+ const tidy = payload.tasks.find((t) => t.name === "custom:tidy");
+ expect(tidy?.refused).toBeUndefined();
+ expect(tidy?.ok).toBe(true);
+ });
+
+ test("a bad declaration is named on stderr and the valid tasks still run", async () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_tidy: exit 0",
+ "maintenance_custom_Bad: exit 0",
+ ]);
+ await initVault();
+ const run = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"], {
+ env: baseEnv(),
+ });
+ expect(run.stderr).toContain("custom task refused:");
+ expect(run.stderr).toContain("Bad");
+ const payload = JSON.parse(run.stdout) as {
+ tasks: MaintenanceTaskResult[];
+ };
+ // A refused declaration journals nothing and is not a failed attempt:
+ // the run that only refused it exits 0.
+ expect(run.returncode).toBe(0);
+ expect(payload.tasks.find((t) => t.name === "custom:Bad")).toBeUndefined();
+ expect(payload.tasks.find((t) => t.name === "custom:tidy")?.ok).toBe(true);
+ });
+
+ test("status shows custom rows, and says when declared tasks are switched off", async () => {
+ writeConfig(["maintenance_custom_tasks: true", "maintenance_custom_tidy: exit 0"]);
+ await initVault();
+ const run = await runCli(["brain", "maintenance", "run", "--vault", vault], {
+ env: baseEnv(),
+ });
+ expect(run.returncode).toBe(MAINTENANCE_EXIT.ok);
+ const on = await runCli(["brain", "maintenance", "status", "--vault", vault], {
+ env: baseEnv(),
+ });
+ expect(on.stdout).toContain("custom:tidy ok");
+ expect(on.stdout).not.toContain("custom tasks declared but maintenance_custom_tasks is off");
+
+ writeConfig(["maintenance_custom_tidy: exit 0"]);
+ const off = await runCli(["brain", "maintenance", "status", "--vault", vault], {
+ env: baseEnv(),
+ });
+ expect(off.returncode).toBe(MAINTENANCE_EXIT.ok);
+ expect(off.stdout).toContain("custom tasks declared but maintenance_custom_tasks is off");
+ });
+});
+
/** A clean task row, as the lane produces it. */
function okRow(name: MaintenanceTaskResult["name"]): MaintenanceTaskResult {
return { name, ok: true, duration_ms: 1 };
@@ -225,6 +412,24 @@ function refusedRow(name: MaintenanceTaskResult["name"]): MaintenanceTaskResult
};
}
+describe("brain maintenance --help", () => {
+ test("opens with the verb's own usage line and names custom tasks and the recipe", () => {
+ const help = VERB_HELP["maintenance"]!;
+ expect(help.startsWith(`${MAINTENANCE_USAGE}\n`)).toBe(true);
+ for (const flag of [
+ "--cron-template",
+ "--interval",
+ "--format",
+ "--force-cost",
+ "--progress",
+ ]) {
+ expect(MAINTENANCE_USAGE).toContain(flag);
+ }
+ expect(help).toContain("custom:<name>");
+ expect(help).toContain("maintenance_custom_tasks: true");
+ });
+});
+
describe("maintenanceExitCode", () => {
test("a clean run exits 0 and a deterministic task fault exits 1", () => {
expect(maintenanceExitCode([okRow(LANE_TASK.dream), okRow(LANE_TASK.reindex)])).toBe(
@@ -246,6 +451,13 @@ describe("maintenanceExitCode", () => {
);
});
+ test("a timed-out custom task exits 1: the streak counts its hang as a failure", () => {
+ expect(maintenanceExitCode([timedOutRow("custom:tidy")])).toBe(MAINTENANCE_EXIT.failed);
+ expect(maintenanceExitCode([timedOutRow("custom:tidy"), timedOutRow(LANE_TASK.bridges)])).toBe(
+ MAINTENANCE_EXIT.failed,
+ );
+ });
+
test("a refusal-only run still exits 7", () => {
expect(maintenanceExitCode([refusedRow(LANE_TASK.dream), okRow(LANE_TASK.reindex)])).toBe(
MAINTENANCE_EXIT.refused,
diff --git a/tests/cli/cron-recipe.test.ts b/tests/cli/cron-recipe.test.ts
index 221b2796..ed04acfb 100644
--- a/tests/cli/cron-recipe.test.ts
+++ b/tests/cli/cron-recipe.test.ts
@@ -19,7 +19,10 @@ import { describe, expect, test } from "bun:test";
import {
CronTemplateError,
operatorScriptPath,
+ parseRecipeFormat,
+ RECIPE_FORMATS,
renderCronRecipe,
+ renderSystemdTimer,
type CronRecipeSpec,
} from "../../src/cli/cron-recipe.ts";
@@ -118,3 +121,123 @@ describe("renderCronRecipe", () => {
expect(() => renderCronRecipe(SPEC, "nonsense", {})).toThrow(CronTemplateError);
});
});
+
+/**
+ * The synthetic spec rendered at 30m, captured BEFORE the header and the
+ * script section were extracted into a helper shared with the systemd
+ * renderer. The extraction is only correct if the cron path changed by
+ * zero bytes, and only a pinned string can say so.
+ */
+const PINNED_CRON_30M =
+ "# ----------------------------------------------------------------------\n# Synthetic Suite - probe recipe\n# interval: 30 minutes\n#\n# Pick ONE of the three paths below. The watchdog script is the\n# common piece; both crontab and Hermes-cron rely on it.\n# ----------------------------------------------------------------------\n\n\n## 1. Watchdog script - save to ~/.local/bin/probe-runner.sh\n## probe note line\n\ncat >~/.local/bin/probe-runner.sh <<'OSBEOF'\n#!/usr/bin/env bash\nprobe_body_marker o2b\nOSBEOF\nchmod +x ~/.local/bin/probe-runner.sh\n\n\n## 2. Native crontab - open 'crontab -e' and append:\n\n*/30 * * * * ~/.local/bin/probe-runner.sh\n\n\n## 3. Hermes cron (probe scheduler note):\n\nhermes cron create \\\n --name probe-job \\\n --schedule '*/30 * * * *' \\\n --command \"$HOME/.local/bin/probe-runner.sh\" \\\n --no-agent\n\n\n# ----------------------------------------------------------------------\n# After install, verify with: o2b probe-verify --now\n# ----------------------------------------------------------------------\n";
+
+/** The watchdog section: from its heading through the chmod that closes it. */
+function scriptSection(out: string): string {
+ const start = out.indexOf("## 1. Watchdog script - save to ");
+ const chmod = out.indexOf("chmod +x ", start);
+ const end = out.indexOf("\n", chmod) + 1;
+ expect(start).toBeGreaterThan(-1);
+ expect(chmod).toBeGreaterThan(start);
+ return out.slice(start, end);
+}
+
+/** The message a throwing render produced, so two renderers can be compared. */
+function refusal(render: () => string): string {
+ try {
+ render();
+ } catch (err) {
+ expect(err).toBeInstanceOf(CronTemplateError);
+ return (err as Error).message;
+ }
+ throw new Error("expected a CronTemplateError, got a rendered recipe");
+}
+
+describe("renderCronRecipe is unchanged by the systemd sibling", () => {
+ test("the synthetic spec renders byte for byte as before the extraction", () => {
+ expect(renderCronRecipe(SPEC, "30m", {})).toBe(PINNED_CRON_30M);
+ });
+});
+
+describe("renderSystemdTimer", () => {
+ const UNIT_DIR = "~/.config/systemd/user/";
+
+ test("carries the same script section as the cron recipe", () => {
+ const systemd = renderSystemdTimer(SPEC, "30m", {});
+ expect(scriptSection(systemd)).toBe(scriptSection(renderCronRecipe(SPEC, "30m", {})));
+ });
+
+ test("names the service and timer pair and the commands that enable it", () => {
+ const out = renderSystemdTimer(SPEC, "30m", {});
+ for (const needle of [
+ `${UNIT_DIR}${SENTINEL.cronName}.service`,
+ `${UNIT_DIR}${SENTINEL.cronName}.timer`,
+ "OnUnitActiveSec=30m",
+ "OnBootSec=",
+ "systemctl --user daemon-reload",
+ `systemctl --user enable --now ${SENTINEL.cronName}.timer`,
+ "loginctl enable-linger",
+ `# After install, verify with: o2b ${SENTINEL.verify}`,
+ ]) {
+ expect(`${needle} present: ${out.includes(needle)}`).toBe(`${needle} present: true`);
+ }
+ });
+
+ test("the monotonic timer carries no Persistent= line", () => {
+ // systemd honours Persistent= on OnCalendar= timers only; on this
+ // OnBootSec=/OnUnitActiveSec= timer it would claim a catch-up that
+ // never happens.
+ expect(renderSystemdTimer(SPEC, "30m", {})).not.toContain("Persistent=");
+ });
+
+ test("the service runs the script through the systemd home specifier", () => {
+ // ExecStart= does not expand a tilde, so the path must reach systemd in
+ // the %h form it resolves itself.
+ const out = renderSystemdTimer(SPEC, "30m", {});
+ expect(out).toContain(`ExecStart=%h/.local/bin/${SENTINEL.scriptStem}.sh`);
+ expect(out).not.toContain("ExecStart=~/");
+ });
+
+ test("prints no crontab line and no Hermes scheduler", () => {
+ const out = renderSystemdTimer(SPEC, "30m", {});
+ expect(out).not.toContain("*/30 * * * *");
+ expect(out).not.toContain("crontab -e");
+ expect(out).not.toContain("hermes cron create");
+ });
+
+ test("the interval reaches the timer in the unit systemd reads natively", () => {
+ expect(renderSystemdTimer(SPEC, "6h", {})).toContain("OnUnitActiveSec=6h\n");
+ expect(renderSystemdTimer(SPEC, "1d", {})).toContain("OnUnitActiveSec=1d\n");
+ expect(renderSystemdTimer(SPEC, " 15 m ", {})).toContain("OnUnitActiveSec=15m\n");
+ });
+
+ test("refuses every interval the cron renderer refuses, with the same message", () => {
+ for (const interval of ["90m", "30s", "24h", "28d", "nonsense"]) {
+ expect(refusal(() => renderSystemdTimer(SPEC, interval, {}))).toBe(
+ refusal(() => renderCronRecipe(SPEC, interval, {})),
+ );
+ }
+ });
+
+ test("the binary override reaches both builders", () => {
+ const out = renderSystemdTimer(SPEC, "30m", { o2bBin: "/opt/probe/o2b" });
+ expect(out).toContain(`${SENTINEL.bodyMarker} /opt/probe/o2b`);
+ expect(out).toContain(`# After install, verify with: /opt/probe/o2b ${SENTINEL.verify}`);
+ });
+});
+
+describe("parseRecipeFormat", () => {
+ test("the formats are cron and systemd, cron first", () => {
+ expect([...RECIPE_FORMATS]).toEqual(["cron", "systemd"]);
+ });
+
+ test("no flag means cron; systemd passes through", () => {
+ expect(parseRecipeFormat(undefined)).toBe("cron");
+ expect(parseRecipeFormat("cron")).toBe("cron");
+ expect(parseRecipeFormat("systemd")).toBe("systemd");
+ });
+
+ test("an unknown format is refused by name, naming both formats", () => {
+ const message = refusal(() => parseRecipeFormat("launchd"));
+ expect(message).toBe('unknown recipe format "launchd": expected cron or systemd');
+ });
+});
diff --git a/tests/cli/discipline-install.test.ts b/tests/cli/discipline-install.test.ts
index 603d8bf2..dd32a27c 100644
--- a/tests/cli/discipline-install.test.ts
+++ b/tests/cli/discipline-install.test.ts
@@ -5,16 +5,22 @@
* jobs.length transitions: 0 → 1 → 1 → 0 → 0
*
* OSB_HERMES_JOBS points at a tmp file so the user's real cron config
- * (/root/.hermes/cron/jobs.json) is never touched.
+ * (~/.hermes/cron/jobs.json of whoever runs the suite) is never touched.
+ * The default path itself is asserted through the pure resolver, which
+ * takes the environment and the home directory as arguments.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { HermesJobsPathError, resolveJobsFilePath } from "../../src/cli/discipline-install.ts";
import { runCli } from "../helpers/run-cli.ts";
+const CLI_ENTRY = join(import.meta.dir, "..", "..", "src", "cli", "main.ts");
+const NO_HOME_PRELOAD = join(import.meta.dir, "..", "fixtures", "discipline-install", "no-home.ts");
+
let tmp: string;
let vault: string;
let jobsFile: string;
@@ -206,3 +212,58 @@ describe("o2b discipline install / uninstall", () => {
expect(readJobs().jobs.length).toBe(0);
});
});
+
+describe("resolveJobsFilePath", () => {
+ const JOBS_TAIL = [".hermes", "cron", "jobs.json"] as const;
+
+ test("defaults to the Hermes jobs file under the given home", () => {
+ expect(resolveJobsFilePath({}, "/home/op")).toBe(join("/home/op", ...JOBS_TAIL));
+ // Root hosts keep the path they always had.
+ expect(resolveJobsFilePath({}, "/root")).toBe(join("/root", ...JOBS_TAIL));
+ });
+
+ test("OSB_HERMES_JOBS overrides the default, even without a home", () => {
+ expect(resolveJobsFilePath({ OSB_HERMES_JOBS: "/srv/jobs.json" }, "/home/op")).toBe(
+ "/srv/jobs.json",
+ );
+ expect(resolveJobsFilePath({ OSB_HERMES_JOBS: "/srv/jobs.json" }, "")).toBe("/srv/jobs.json");
+ });
+
+ test("an empty OSB_HERMES_JOBS is unset, not a path", () => {
+ expect(resolveJobsFilePath({ OSB_HERMES_JOBS: "" }, "/home/op")).toBe(
+ join("/home/op", ...JOBS_TAIL),
+ );
+ });
+
+ test("no home and no override is a named error that names the way out", () => {
+ let caught: unknown;
+ try {
+ resolveJobsFilePath({}, "");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(HermesJobsPathError);
+ expect((caught as Error).name).toBe("HermesJobsPathError");
+ expect((caught as Error).message).toContain("OSB_HERMES_JOBS");
+ });
+});
+
+describe("o2b discipline on a host without a home directory", () => {
+ test("install and uninstall exit 1 naming OSB_HERMES_JOBS and write nothing", () => {
+ for (const verb of [
+ ["install", "--vault", vault, "--telegram-target", "telegram:-100123:42"],
+ ["uninstall", "--vault", vault],
+ ]) {
+ const env: Record<string, string> = { PATH: process.env["PATH"] ?? "", HOME: tmp };
+ if (process.env["SYSTEMROOT"]) env["SYSTEMROOT"] = process.env["SYSTEMROOT"];
+ const run = Bun.spawnSync(
+ [process.execPath, "--preload", NO_HOME_PRELOAD, CLI_ENTRY, "discipline", ...verb],
+ { cwd: tmp, env, stdout: "pipe", stderr: "pipe" },
+ );
+ expect(run.stderr.toString()).toContain("cannot resolve the home directory");
+ expect(run.stderr.toString()).toContain("OSB_HERMES_JOBS");
+ expect(run.exitCode).toBe(1);
+ expect(existsSync(join(tmp, ".hermes"))).toBe(false);
+ }
+ });
+});
diff --git a/tests/cli/maintenance-cron.test.ts b/tests/cli/maintenance-cron.test.ts
new file mode 100644
index 00000000..7899bfb0
--- /dev/null
+++ b/tests/cli/maintenance-cron.test.ts
@@ -0,0 +1,246 @@
+/**
+ * The maintenance lane recipe printed by
+ * `o2b brain maintenance run --cron-template`.
+ *
+ * The lane is the cron entry point for the heavy passes, and a scheduler
+ * runs it without the operator's shell environment, so the recipe has to
+ * carry everything the lane needs on the command line: the vault, and the
+ * window and zone when the operator gave them. It also has to keep the
+ * lane's exit code - a gate skip exits 0 and should cost a cron mail
+ * nothing, while any other exit is a verdict someone must read.
+ *
+ * Rendering is pure text: the last case lists a vault tree before and
+ * after and requires them to be the same.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { CronTemplateError } from "../../src/cli/cron-recipe.ts";
+import {
+ DEFAULT_MAINTENANCE_INTERVAL,
+ MAINTENANCE_CRON_NAME,
+ maintenanceCronName,
+ parseWindowBounds,
+ renderMaintenanceCronTemplate,
+} from "../../src/cli/maintenance-cron.ts";
+import { IS_WINDOWS } from "../helpers/platform.ts";
+
+/** The heredoc body: the script exactly as the operator's host will run it. */
+function scriptBody(out: string): string {
+ const open = out.indexOf("<<'OSBEOF'\n");
+ const close = out.indexOf("\nOSBEOF\n", open);
+ expect(open).toBeGreaterThan(-1);
+ expect(close).toBeGreaterThan(open);
+ return out.slice(open + "<<'OSBEOF'\n".length, close + 1);
+}
+
+/** The job name for `vault`, after proving every recipe section carries it. */
+function namesIn(vault: string): string {
+ const name = maintenanceCronName(vault);
+ const cron = renderMaintenanceCronTemplate("1h", { vault });
+ const systemd = renderMaintenanceCronTemplate("1h", { vault, format: "systemd" });
+ expect(cron).toContain(`cat >~/.local/bin/${name}.sh <<'OSBEOF'`);
+ expect(cron).toContain(` --name ${name} \\`);
+ expect(systemd).toContain(`${name}.service`);
+ expect(systemd).toContain(`${name}.timer`);
+ return name;
+}
+
+describe("renderMaintenanceCronTemplate", () => {
+ test("names the lane job and renders the hourly default", () => {
+ expect(MAINTENANCE_CRON_NAME).toBe("osb-maintenance");
+ expect(DEFAULT_MAINTENANCE_INTERVAL).toBe("1h");
+ const name = maintenanceCronName("/v");
+ expect(name).toMatch(/^osb-maintenance-[0-9a-f]{8}$/u);
+ const out = renderMaintenanceCronTemplate("1h", { vault: "/v" });
+ expect(out).toContain("# interval: 1 hours");
+ expect(out).toContain(`0 */1 * * * ~/.local/bin/${name}.sh`);
+ expect(out).toContain(`cat >~/.local/bin/${name}.sh <<'OSBEOF'`);
+ expect(out).toContain(` --name ${name} \\`);
+ expect(out).toContain("(when Hermes owns the schedule)");
+ });
+
+ test("the script runs the lane against the baked-in vault as JSON", () => {
+ const body = scriptBody(renderMaintenanceCronTemplate("1h", { vault: "/v" }));
+ expect(body).toContain("o2b brain maintenance run --vault '/v' --json");
+ expect(body).not.toContain("--window");
+ expect(body).not.toContain("--tz");
+ });
+
+ test("the window and the zone reach the command only when given", () => {
+ const both = scriptBody(
+ renderMaintenanceCronTemplate("1h", { vault: "/v", window: "3-5", tz: "Europe/Berlin" }),
+ );
+ expect(both).toContain(
+ "o2b brain maintenance run --vault '/v' --window 3-5 --tz Europe/Berlin --json",
+ );
+ const windowOnly = scriptBody(
+ renderMaintenanceCronTemplate("1h", { vault: "/v", window: "22-6" }),
+ );
+ expect(windowOnly).toContain("o2b brain maintenance run --vault '/v' --window 22-6 --json");
+ });
+
+ test("a vault with a single quote stays one shell word", () => {
+ const body = scriptBody(renderMaintenanceCronTemplate("1h", { vault: "/srv/it's vault" }));
+ expect(body).toContain("--vault '/srv/it'\\''s vault' --json");
+ });
+
+ test("a window or zone that is not a plain token is refused, not pasted into shell", () => {
+ for (const window of ["25-3", "3-5; rm -rf ~", "3"]) {
+ expect(() => renderMaintenanceCronTemplate("1h", { vault: "/v", window })).toThrow(
+ CronTemplateError,
+ );
+ }
+ for (const tz of ["$(id)", "--force"]) {
+ expect(() => renderMaintenanceCronTemplate("1h", { vault: "/v", window: "3-5", tz })).toThrow(
+ CronTemplateError,
+ );
+ }
+ });
+
+ test("a zone the runtime does not know is refused by name", () => {
+ expect(() =>
+ renderMaintenanceCronTemplate("1h", { vault: "/v", window: "3-5", tz: "Mars/Base" }),
+ ).toThrow(/unknown time zone: "Mars\/Base"/u);
+ for (const tz of ["Europe/Berlin", "Etc/GMT+3", "UTC"]) {
+ expect(renderMaintenanceCronTemplate("1h", { vault: "/v", window: "3-5", tz })).toContain(
+ `--tz ${tz} --json`,
+ );
+ }
+ });
+
+ test("a vault path with a line break is refused by name in both formats", () => {
+ for (const vault of ["/v\nOSBEOF", "/v\rx"]) {
+ for (const format of ["cron", "systemd"] as const) {
+ expect(() => renderMaintenanceCronTemplate("1h", { vault, format })).toThrow(
+ /vault path must not contain a line break/u,
+ );
+ }
+ }
+ });
+
+ test.skipIf(IS_WINDOWS)(
+ "the script is silent on exit 0 and passes any other exit through with its JSON",
+ () => {
+ // Run the rendered script for real against a stub o2b that prints a
+ // verdict and exits with the code the case asks for.
+ const dir = mkdtempSync(join(tmpdir(), "o2b-maint-cron-run-"));
+ try {
+ const stub = join(dir, "o2b-stub");
+ writeFileSync(stub, '#!/bin/sh\nprintf \'{"x":1}\\n\'\nexit "$STUB_EXIT"\n');
+ chmodSync(stub, 0o755);
+ const script = join(dir, "run.sh");
+ writeFileSync(
+ script,
+ scriptBody(renderMaintenanceCronTemplate("1h", { vault: "/v", o2bBin: stub })),
+ );
+ const run = (code: string) =>
+ Bun.spawnSync(["bash", script], {
+ env: { PATH: process.env["PATH"] ?? "", HOME: dir, STUB_EXIT: code },
+ });
+ const quiet = run("0");
+ expect(quiet.exitCode).toBe(0);
+ expect(quiet.stdout.toString()).toBe("");
+ const failed = run("3");
+ expect(failed.exitCode).toBe(3);
+ expect(failed.stdout.toString()).toBe('{"x":1}\n');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test("the verify footer points at the lane status of the baked-in vault", () => {
+ const out = renderMaintenanceCronTemplate("1h", { vault: "/srv/it's vault" });
+ expect(out).toContain(
+ "# After install, verify with: o2b brain maintenance status --vault '/srv/it'\\''s vault'",
+ );
+ });
+
+ test("the binary override reaches the script and the footer", () => {
+ const out = renderMaintenanceCronTemplate("1h", { vault: "/v", o2bBin: "/opt/o2b" });
+ expect(out).toContain("/opt/o2b brain maintenance run --vault '/v' --json");
+ expect(out).toContain(
+ "# After install, verify with: /opt/o2b brain maintenance status --vault '/v'",
+ );
+ });
+
+ test("two vaults get different job names; the same vault always gets the same one", () => {
+ expect(namesIn("/a")).not.toBe(namesIn("/b"));
+ expect(namesIn("/a")).toBe(namesIn("/a"));
+ expect(renderMaintenanceCronTemplate("1h", { vault: "/a" })).toBe(
+ renderMaintenanceCronTemplate("1h", { vault: "/a" }),
+ );
+ });
+
+ test("an explicit cron format renders the default recipe", () => {
+ expect(renderMaintenanceCronTemplate("1h", { vault: "/v", format: "cron" })).toBe(
+ renderMaintenanceCronTemplate("1h", { vault: "/v" }),
+ );
+ });
+
+ test("the systemd format prints a timer on the same cadence with the same script", () => {
+ const cron = renderMaintenanceCronTemplate("1h", { vault: "/v" });
+ const systemd = renderMaintenanceCronTemplate("1h", { vault: "/v", format: "systemd" });
+ expect(systemd).toContain("OnUnitActiveSec=1h");
+ expect(systemd).toContain(`systemctl --user enable --now ${maintenanceCronName("/v")}.timer`);
+ expect(systemd).not.toContain("hermes cron create");
+ expect(scriptBody(systemd)).toBe(scriptBody(cron));
+ });
+
+ test("an interval cron cannot express is refused", () => {
+ expect(() => renderMaintenanceCronTemplate("30s", { vault: "/v" })).toThrow(CronTemplateError);
+ expect(() => renderMaintenanceCronTemplate("90d", { vault: "/v", format: "systemd" })).toThrow(
+ CronTemplateError,
+ );
+ });
+});
+
+/** Every path under `root`, recursively, as a sorted list. */
+function listTree(root: string): string[] {
+ const out: string[] = [];
+ const walk = (dir: string, prefix: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
+ out.push(rel);
+ if (entry.isDirectory()) walk(join(dir, entry.name), rel);
+ }
+ };
+ walk(root, "");
+ return out.toSorted();
+}
+
+describe("parseWindowBounds", () => {
+ test("reads H-H bounds and refuses any other shape or an hour above 23", () => {
+ expect(parseWindowBounds("22-6")).toEqual({ startHour: 22, endHour: 6 });
+ expect(parseWindowBounds("0-23")).toEqual({ startHour: 0, endHour: 23 });
+ for (const raw of ["24-3", "3-24", "3", "3-5x", " 3-5", "a-b"]) {
+ expect(parseWindowBounds(raw)).toBeNull();
+ }
+ });
+});
+
+describe("rendering writes nothing", () => {
+ let tmp: string;
+
+ beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-maintenance-cron-"));
+ });
+
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ });
+
+ test("a vault tree is unchanged by both formats", () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "note.md"), "# note\n");
+ const before = listTree(tmp);
+ renderMaintenanceCronTemplate("1h", { vault });
+ renderMaintenanceCronTemplate("6h", { vault, format: "systemd" });
+ expect(listTree(tmp)).toEqual(before);
+ });
+});
diff --git a/tests/cli/manifest-completeness.test.ts b/tests/cli/manifest-completeness.test.ts
index f4e97f0a..dc1ce3f6 100644
--- a/tests/cli/manifest-completeness.test.ts
+++ b/tests/cli/manifest-completeness.test.ts
@@ -34,6 +34,7 @@ import { join } from "node:path";
import {
CLI_COMMAND_MANIFEST,
+ nestedCommand,
nestedCommandNames,
type CliCommandManifest,
} from "../../src/cli/command-manifest.ts";
@@ -273,11 +274,44 @@ describe("the repaired manifest reaches its two consumers", () => {
// Completion flag lists are built by walking the whole manifest, so a
// declared flag at any depth reaches every shell.
const zsh = renderCompletions("zsh", CLI_COMMAND_MANIFEST);
- for (const token of ["--cron-template", "--interval", "--fail-on-health", "--project"]) {
+ for (const token of [
+ "--cron-template",
+ "--interval",
+ "--format",
+ "--fail-on-health",
+ "--project",
+ ]) {
expect(`${token}: ${zsh.includes(token)}`).toBe(`${token}: true`);
}
});
+ test("brain maintenance models run and status, with the recipe flags on run", () => {
+ // The lane is the cron entry point, and `run --cron-template` is the
+ // only way to reach its recipe; a flag the manifest does not declare
+ // completes nowhere and is invisible to `o2b help --json`.
+ const maintenance = nestedCommand("brain", "maintenance");
+ expect((maintenance?.commands ?? []).map((c) => c.name).toSorted()).toEqual(["run", "status"]);
+ const run = maintenance?.commands?.find((c) => c.name === "run");
+ const runFlags = new Set((run?.flags ?? []).map((f) => f.name));
+ for (const name of [
+ "cron-template",
+ "interval",
+ "format",
+ "window",
+ "tz",
+ "retry",
+ "force",
+ "force-cost",
+ ]) {
+ expect(`run --${name}: ${runFlags.has(name)}`).toBe(`run --${name}: true`);
+ }
+ const status = maintenance?.commands?.find((c) => c.name === "status");
+ const statusFlags = new Set((status?.flags ?? []).map((f) => f.name));
+ expect(`status --cron-template: ${statusFlags.has("cron-template")}`).toBe(
+ "status --cron-template: false",
+ );
+ });
+
test("help --json carries the partner codegraph verbs", async () => {
// `partner` is the one modelled parent whose verbs live two levels
// down, so the top-level census above cannot see them.
diff --git a/tests/cli/mcp-fault-guard-spawn.test.ts b/tests/cli/mcp-fault-guard-spawn.test.ts
new file mode 100644
index 00000000..82c45baf
--- /dev/null
+++ b/tests/cli/mcp-fault-guard-spawn.test.ts
@@ -0,0 +1,240 @@
+/**
+ * The fault guard in a real process.
+ *
+ * The in-process suite (`mcp-fault-guard.test.ts`) dispatches faults with
+ * `process.emit`, because the test runner fails a test on any genuine
+ * unhandled rejection. Only a spawned process proves the two claims the
+ * guard makes about the runtime: a detached rejection does NOT end the
+ * server, and an uncaught exception ends it with 70 THROUGH the exit
+ * hooks (the lock file the hook unlinks is gone afterwards).
+ *
+ * Children get a throwaway HOME and TMPDIR under this run's own temp
+ * directory, so no product code they run reaches the operator's config.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { EXIT_INTERNAL_FAULT, FAULT_KIND } from "../../src/cli/mcp-fault-guard.ts";
+import { IS_WINDOWS, homeEnv } from "../helpers/platform.ts";
+
+const REPO_ROOT = join(import.meta.dir, "../..");
+const FIXTURES = join(import.meta.dir, "../fixtures/mcp-fault-guard");
+const CLI = join(REPO_ROOT, "src/cli/main.ts");
+/** The runtime running this suite, so children never pick another Bun from PATH. */
+const BUN = process.execPath;
+/** A generous ceiling: each child starts and finishes in well under a second. */
+const SPAWN_TIMEOUT_MS = 30_000;
+
+const temps: string[] = [];
+
+afterEach(() => {
+ while (temps.length > 0) rmSync(temps.pop()!, { recursive: true, force: true });
+});
+
+function sandbox(): { vault: string; env: Record<string, string> } {
+ const root = mkdtempSync(join(tmpdir(), "osb-mcp-fault-guard-"));
+ temps.push(root);
+ const vault = join(root, "vault");
+ const home = join(root, "home");
+ const tmp = join(root, "tmp");
+ for (const dir of [vault, home, tmp]) mkdirSync(dir, { recursive: true });
+ return {
+ vault,
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ // Without it a Windows child cannot initialise Winsock.
+ ...(process.env["SYSTEMROOT"] ? { SYSTEMROOT: process.env["SYSTEMROOT"] } : {}),
+ ...homeEnv(home),
+ TMPDIR: tmp,
+ TMP: tmp,
+ TEMP: tmp,
+ },
+ };
+}
+
+function frame(id: number, method: string, params: Record<string, unknown> = {}): string {
+ return `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`;
+}
+
+/**
+ * Collect stdout lines as they arrive, so a test can wait for one by id.
+ * A wait still pending when stdout ends is rejected by name: a child that
+ * died fails the test at once instead of at the timeout.
+ */
+function lineReader(stream: ReadableStream<Uint8Array>): {
+ waitFor: (pred: (line: string) => boolean) => Promise<string>;
+} {
+ interface Waiter {
+ readonly pred: (line: string) => boolean;
+ readonly done: (line: string) => void;
+ readonly fail: (error: Error) => void;
+ }
+ const lines: string[] = [];
+ let waiters: Waiter[] = [];
+ let ended = false;
+ const settle = (line: string): void => {
+ lines.push(line);
+ waiters = waiters.filter((w) => {
+ if (!w.pred(line)) return true;
+ w.done(line);
+ return false;
+ });
+ };
+ void (async () => {
+ const decoder = new TextDecoder();
+ let buffer = "";
+ for await (const chunk of stream) {
+ buffer += decoder.decode(chunk, { stream: true });
+ const parts = buffer.split("\n");
+ buffer = parts.pop() ?? "";
+ for (const line of parts) settle(line);
+ }
+ ended = true;
+ for (const w of waiters) w.fail(new Error("child stdout ended before the awaited response"));
+ waiters = [];
+ })();
+ return {
+ waitFor: (pred) =>
+ new Promise((done, fail) => {
+ const hit = lines.find(pred);
+ if (hit !== undefined) done(hit);
+ else if (ended) fail(new Error("child stdout ended before the awaited response"));
+ else waiters.push({ pred, done, fail });
+ }),
+ };
+}
+
+const responseTo =
+ (id: number) =>
+ (line: string): boolean => {
+ try {
+ return (JSON.parse(line) as { id?: unknown }).id === id;
+ } catch {
+ return false;
+ }
+ };
+
+describe("mcp fault guard in a spawned process", () => {
+ test(
+ "a detached rejection is named and the server keeps answering",
+ async () => {
+ const { vault, env } = sandbox();
+ const proc = Bun.spawn([BUN, join(FIXTURES, "serve-with-rejection.ts"), vault], {
+ cwd: REPO_ROOT,
+ env,
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const stderrText = new Response(proc.stderr).text();
+ const out = lineReader(proc.stdout);
+
+ proc.stdin.write(
+ frame(1, "initialize", {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "fault-guard-spawn", version: "0" },
+ }),
+ );
+ await out.waitFor(responseTo(1));
+ proc.stdin.write(frame(2, "tools/call", { name: "brain_context", arguments: {} }));
+ proc.stdin.write(frame(3, "tools/list"));
+ const [called, listed] = await Promise.all([
+ out.waitFor(responseTo(2)),
+ out.waitFor(responseTo(3)),
+ ]);
+ expect(JSON.parse(called)).toHaveProperty("result");
+ expect(JSON.parse(listed).result.tools.length).toBeGreaterThan(0);
+ expect(proc.exitCode).toBeNull();
+
+ proc.stdin.end();
+ const code = await proc.exited;
+ const stderr = await stderrText;
+ expect(stderr).toContain(
+ `[mcp] ${FAULT_KIND.unhandledRejection} #1: Error: fixture rejection nobody awaits (server keeps serving)`,
+ );
+ expect(code).toBe(0);
+ },
+ SPAWN_TIMEOUT_MS,
+ );
+
+ test(
+ "an uncaught exception exits 70 through the exit hooks",
+ async () => {
+ const { vault, env } = sandbox();
+ const proc = Bun.spawn([BUN, join(FIXTURES, "serve-with-throw.ts"), vault], {
+ cwd: REPO_ROOT,
+ env,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, code] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ const lockPath = stdout.trim();
+ expect(lockPath).toEndWith(".lock");
+ expect(stderr).toContain(
+ `[mcp] ${FAULT_KIND.uncaughtException}: Error: fixture exception from a timer`,
+ );
+ expect(code).toBe(EXIT_INTERNAL_FAULT);
+ // The sync lockfile module's `exit` hook ran: the lock is gone.
+ expect(existsSync(lockPath)).toBe(false);
+ },
+ SPAWN_TIMEOUT_MS,
+ );
+
+ test(
+ "a rejection inside o2b mcp over HTTP raises the /health count, and the guard is released",
+ async () => {
+ const { vault, env } = sandbox();
+ const proc = Bun.spawn(
+ [
+ BUN,
+ "--preload",
+ join(FIXTURES, "reject-once-guarded.ts"),
+ CLI,
+ "mcp",
+ "--transport",
+ "http",
+ "--port",
+ "0",
+ "--vault",
+ vault,
+ ],
+ { cwd: REPO_ROOT, env, stdin: "ignore", stdout: "ignore", stderr: "pipe" },
+ );
+ const err = lineReader(proc.stderr);
+ try {
+ const named = err.waitFor((line) =>
+ line.includes(`[mcp] ${FAULT_KIND.unhandledRejection} #1: Error: fixture rejection`),
+ );
+ const listening = await err.waitFor((line) => line.includes(" listening on http://"));
+ const url = /listening on (http:\/\/\S+)/.exec(listening)?.[1];
+ expect(url).toBeDefined();
+ await named;
+ const body = (await (await fetch(`${url}/health`)).json()) as {
+ faults?: { unhandled_rejection: number; last_fault_at: string | null };
+ };
+ expect(body.faults?.unhandled_rejection).toBe(1);
+ expect(Number.isNaN(Date.parse(body.faults?.last_fault_at ?? ""))).toBe(false);
+ expect(proc.exitCode).toBeNull();
+ } finally {
+ proc.kill("SIGTERM");
+ }
+ await proc.exited;
+ // A Windows kill ends the child without running its exit hooks, so
+ // only POSIX can watch the verb release the guard on the way out.
+ if (!IS_WINDOWS) {
+ const exitLine = await err.waitFor((line) => line.includes("listeners at exit: "));
+ expect(exitLine).toEndWith("listeners at exit: 0");
+ }
+ },
+ SPAWN_TIMEOUT_MS,
+ );
+});
diff --git a/tests/cli/mcp-fault-guard.test.ts b/tests/cli/mcp-fault-guard.test.ts
new file mode 100644
index 00000000..be98dce5
--- /dev/null
+++ b/tests/cli/mcp-fault-guard.test.ts
@@ -0,0 +1,257 @@
+/**
+ * The MCP fault guard, in process.
+ *
+ * Every case installs the guard with an injected `stderr`, `exit` and
+ * `now`, and releases it in `finally`: the listeners are process-global
+ * and one left behind would swallow a rejection from the next suite. The
+ * real behaviour of the process (it keeps serving after a rejection, it
+ * exits 70 through the exit hooks after an exception) is proved by
+ * `mcp-fault-guard-spawn.test.ts`; this file pins the wording, the rate
+ * limit and the bookkeeping.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ EXIT_INTERNAL_FAULT,
+ FAULT_KIND,
+ installMcpFaultGuard,
+ REJECTION_LOG_BURST,
+ REJECTION_LOG_WINDOW_MS,
+} from "../../src/cli/mcp-fault-guard.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+interface Harness {
+ readonly lines: string[];
+ readonly exits: number[];
+ readonly clock: { ms: number };
+ readonly guard: ReturnType<typeof installMcpFaultGuard>;
+ /** Timers the guard armed, in order; `fire()` runs one as if it elapsed. */
+ readonly timers: { delayMs: number; fire: () => void; cancelled: boolean }[];
+}
+
+const START_MS = Date.parse("2026-10-01T03:00:00.000Z");
+
+function harness(opts: { throwingStderr?: boolean } = {}): Harness {
+ const lines: string[] = [];
+ const exits: number[] = [];
+ const clock = { ms: START_MS };
+ const timers: Harness["timers"] = [];
+ const guard = installMcpFaultGuard({
+ stderr: {
+ write(chunk: string): void {
+ if (opts.throwingStderr) throw new Error("EPIPE: stderr closed");
+ lines.push(chunk);
+ },
+ },
+ exit: (code) => exits.push(code),
+ now: () => new Date(clock.ms),
+ schedule: (fire, delayMs) => {
+ const timer = { delayMs, fire, cancelled: false };
+ timers.push(timer);
+ return () => {
+ timer.cancelled = true;
+ };
+ },
+ });
+ return { lines, exits, clock, guard, timers };
+}
+
+/** The rejection count, checked after each synchronous dispatch. */
+function expectRejections(h: Harness, expected: number): void {
+ expect(h.guard.counts().unhandled_rejection).toBe(expected);
+}
+
+/**
+ * Dispatch an unhandled rejection the way the runtime does.
+ *
+ * Not a bare `Promise.reject`: the Bun test runner fails the running test
+ * on any real unhandled rejection, whatever listeners the process has, so
+ * in process the event is emitted directly. The spawned-process suite
+ * proves the runtime path with a genuinely detached promise.
+ */
+function emitRejection(reason: unknown): void {
+ const promise = Promise.resolve();
+ process.emit("unhandledRejection", reason, promise);
+}
+
+describe("installMcpFaultGuard: unhandled rejections", () => {
+ test("names the rejection with its first stack frame and keeps serving", () => {
+ const h = harness();
+ try {
+ emitRejection(new Error("probe"));
+ expectRejections(h, 1);
+ const out = h.lines.join("");
+ expect(out).toContain("[mcp] unhandled_rejection #1: Error: probe (server keeps serving)\n");
+ expect(out).toMatch(/\[mcp\] {3}at .*mcp-fault-guard\.test\.ts/);
+ expect(h.exits).toEqual([]);
+ } finally {
+ h.guard.release();
+ }
+ });
+
+ test("a non-Error reason is still named", () => {
+ const h = harness();
+ try {
+ emitRejection("x");
+ emitRejection(undefined);
+ expectRejections(h, 2);
+ const out = h.lines.join("");
+ expect(out).toContain(
+ '[mcp] unhandled_rejection #1: non-error reason: "x" (server keeps serving)',
+ );
+ expect(out).toContain(
+ "[mcp] unhandled_rejection #2: non-error reason: undefined (server keeps serving)",
+ );
+ } finally {
+ h.guard.release();
+ }
+ });
+
+ test("logs a burst in full, then one summary line per window", () => {
+ const h = harness();
+ try {
+ for (let i = 0; i < 8; i += 1) emitRejection(new Error(`flood ${i}`));
+ expectRejections(h, 8);
+ const full = () => h.lines.filter((l) => l.startsWith("[mcp] unhandled_rejection #"));
+ expect(full()).toHaveLength(REJECTION_LOG_BURST);
+
+ // The window rolls over on the next fault: the summary for the old
+ // window comes first, then the new fault is logged in full again.
+ h.clock.ms += REJECTION_LOG_WINDOW_MS + 1;
+ emitRejection(new Error("after the window"));
+ expectRejections(h, 9);
+ const summaries = h.lines.filter((l) => l.includes("suppressed"));
+ expect(summaries).toEqual([
+ `[mcp] unhandled_rejection: 3 more suppressed in the last ${REJECTION_LOG_WINDOW_MS}ms\n`,
+ ]);
+ expect(full()).toHaveLength(REJECTION_LOG_BURST + 1);
+ expect(full().at(-1)).toContain("#9: Error: after the window");
+ } finally {
+ h.guard.release();
+ }
+ });
+
+ test("a quiet server reports what it suppressed once the window ends", () => {
+ const h = harness();
+ try {
+ emitRejection(new Error("first"));
+ h.clock.ms += 10_000;
+ for (let i = 0; i < REJECTION_LOG_BURST + 1; i += 1) emitRejection(new Error("x"));
+ // One timer, armed for the rest of the window the first fault opened.
+ expect(h.timers.map((t) => t.delayMs)).toEqual([REJECTION_LOG_WINDOW_MS - 10_000]);
+ expect(h.lines.filter((l) => l.includes("suppressed"))).toEqual([]);
+ h.clock.ms += REJECTION_LOG_WINDOW_MS;
+ h.timers[0]!.fire();
+ expect(h.lines.filter((l) => l.includes("suppressed"))).toEqual([
+ `[mcp] unhandled_rejection: 2 more suppressed in the last ${REJECTION_LOG_WINDOW_MS}ms\n`,
+ ]);
+ } finally {
+ h.guard.release();
+ }
+ // Nothing left to flush: release adds no second summary.
+ expect(h.lines.filter((l) => l.includes("suppressed"))).toHaveLength(1);
+ });
+
+ test("a credential in a fault message is redacted before it reaches stderr", () => {
+ const h = harness();
+ const secret = fakeCredential("s3cr3t", "-pass-value");
+ try {
+ emitRejection(new Error(`fetch failed for https://op:${secret}@example.invalid/v1`));
+ process.emit("uncaughtException", new Error(`provider said token=${secret}`));
+ } finally {
+ h.guard.release();
+ }
+ const out = h.lines.join("");
+ expect(out).toContain("[mcp] unhandled_rejection #1: Error: fetch failed for https://");
+ expect(out).toContain("[mcp] uncaught_exception: Error: provider said");
+ expect(out).not.toContain(secret);
+ });
+
+ test("release flushes a pending summary so a suppressed count is never lost", () => {
+ const h = harness();
+ try {
+ for (let i = 0; i < REJECTION_LOG_BURST + 2; i += 1) emitRejection(new Error("x"));
+ expectRejections(h, REJECTION_LOG_BURST + 2);
+ } finally {
+ h.guard.release();
+ }
+ expect(h.lines.filter((l) => l.includes("2 more suppressed"))).toHaveLength(1);
+ });
+});
+
+describe("installMcpFaultGuard: uncaught exceptions", () => {
+ test("logs by name and exits 70, without draining", () => {
+ const h = harness();
+ try {
+ process.emit("uncaughtException", new Error("boom"));
+ expect(h.exits).toEqual([EXIT_INTERNAL_FAULT]);
+ expect(EXIT_INTERNAL_FAULT).toBe(70);
+ const out = h.lines.join("");
+ expect(out).toContain(`[mcp] ${FAULT_KIND.uncaughtException}: Error: boom`);
+ expect(out).toContain(`exiting ${EXIT_INTERNAL_FAULT}`);
+ expect(h.guard.counts().uncaught_exception).toBe(1);
+ } finally {
+ h.guard.release();
+ }
+ });
+
+ test("a second exception while exiting goes straight to exit", () => {
+ const h = harness();
+ try {
+ process.emit("uncaughtException", new Error("first"));
+ const linesAfterFirst = h.lines.length;
+ process.emit("uncaughtException", new Error("second"));
+ expect(h.exits).toEqual([EXIT_INTERNAL_FAULT, EXIT_INTERNAL_FAULT]);
+ expect(h.lines.length).toBe(linesAfterFirst);
+ } finally {
+ h.guard.release();
+ }
+ });
+});
+
+describe("installMcpFaultGuard: robustness and bookkeeping", () => {
+ test("a throwing stderr does not escape either handler", () => {
+ const h = harness({ throwingStderr: true });
+ try {
+ emitRejection(new Error("quiet"));
+ expectRejections(h, 1);
+ expect(() => process.emit("uncaughtException", new Error("loud"))).not.toThrow();
+ expect(h.exits).toEqual([EXIT_INTERNAL_FAULT]);
+ expect(h.guard.counts().uncaught_exception).toBe(1);
+ } finally {
+ h.guard.release();
+ }
+ });
+
+ test("release restores the listener counts and is idempotent", () => {
+ const rejectionsBefore = process.listenerCount("unhandledRejection");
+ const exceptionsBefore = process.listenerCount("uncaughtException");
+ const h = harness();
+ expect(process.listenerCount("unhandledRejection")).toBe(rejectionsBefore + 1);
+ expect(process.listenerCount("uncaughtException")).toBe(exceptionsBefore + 1);
+ h.guard.release();
+ h.guard.release();
+ expect(process.listenerCount("unhandledRejection")).toBe(rejectionsBefore);
+ expect(process.listenerCount("uncaughtException")).toBe(exceptionsBefore);
+ });
+
+ test("last_fault_at is null before any fault and the time of the latest after", () => {
+ const h = harness();
+ try {
+ expect(h.guard.counts()).toEqual({
+ unhandled_rejection: 0,
+ uncaught_exception: 0,
+ last_fault_at: null,
+ });
+ emitRejection(new Error("one"));
+ expectRejections(h, 1);
+ expect(h.guard.counts().last_fault_at).toBe(new Date(START_MS).toISOString());
+ h.clock.ms += 1234;
+ process.emit("uncaughtException", new Error("two"));
+ expect(h.guard.counts().last_fault_at).toBe(new Date(START_MS + 1234).toISOString());
+ } finally {
+ h.guard.release();
+ }
+ });
+});
diff --git a/tests/cli/partner-codegraph-resync.test.ts b/tests/cli/partner-codegraph-resync.test.ts
index 7ff11eab..d87e3c58 100644
--- a/tests/cli/partner-codegraph-resync.test.ts
+++ b/tests/cli/partner-codegraph-resync.test.ts
@@ -19,7 +19,9 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { CronTemplateError } from "../../src/cli/cron-recipe.ts";
import { renderCodegraphResyncTemplate } from "../../src/cli/partner-codegraph-cron.ts";
+import { IS_WINDOWS } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -62,7 +64,7 @@ describe("the resync recipe renders", () => {
expect(body).toContain("--name osb-codegraph-resync");
expect(body).toContain("hermes cron create");
expect(body).toContain('codegraph init "$project"');
- expect(body).toContain('project="/srv/projects/demo"');
+ expect(body).toContain("project='/srv/projects/demo'");
});
test("the wrong-root guard precedes the indexer invocation", () => {
@@ -113,6 +115,42 @@ describe("the resync recipe renders", () => {
expect(body).toContain("${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain");
});
+ test("the systemd format carries the same script on the same cadence", () => {
+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h", { format: "systemd" });
+ expect(body).toContain("OnUnitActiveSec=6h");
+ expect(body).toContain('codegraph init "$project"');
+ expect(body).not.toContain("0 */6 * * *");
+ });
+
+ test.skipIf(IS_WINDOWS)(
+ "a project path with shell syntax reaches the script as a literal value",
+ () => {
+ // The first path is valid inside double quotes too, so only quoting
+ // that disables substitution keeps the marker from being created;
+ // the second adds the quote characters themselves.
+ for (const path of ["/srv/x$(touch marker)", "/srv/x$(touch marker)`id`\"q'y"]) {
+ const body = renderCodegraphResyncTemplate(path, "6h");
+ const line = body.split("\n").find((l) => l.startsWith("project="));
+ expect(line).toBeDefined();
+ // Evaluate exactly the line the script carries: nothing inside the
+ // value may run, and it must come back byte for byte.
+ const run = Bun.spawnSync(["bash", "-c", `${line}\nprintf %s "$project"`], { cwd: tmp });
+ expect(`marker created: ${existsSync(join(tmp, "marker"))}`).toBe("marker created: false");
+ expect(run.exitCode).toBe(0);
+ expect(run.stdout.toString()).toBe(path);
+ }
+ },
+ );
+
+ test("a project path with a line break is refused by name", () => {
+ for (const path of ["/srv/a\nOSBEOF", "/srv/a\rb"]) {
+ expect(() => renderCodegraphResyncTemplate(path, "6h")).toThrow(CronTemplateError);
+ expect(() => renderCodegraphResyncTemplate(path, "6h", { format: "systemd" })).toThrow(
+ /project path must not contain a line break/,
+ );
+ }
+ });
+
test("two repositories get two stamp files", () => {
const a = renderCodegraphResyncTemplate("/srv/projects/alpha", "6h");
const b = renderCodegraphResyncTemplate("/srv/projects/beta", "6h");
@@ -128,7 +166,7 @@ describe("o2b partner codegraph resync (CLI)", () => {
const res = await runCli(["partner", "codegraph", "resync", "--cron-template"], { cwd: repo });
expect(res.returncode).toBe(0);
expect(res.stdout).toContain("cat >~/.local/bin/osb-codegraph-resync.sh");
- expect(res.stdout).toContain(`project="${repo}"`);
+ expect(res.stdout).toContain(`project='${repo}'`);
expect(listTree(tmp)).toEqual(before);
});
@@ -140,7 +178,7 @@ describe("o2b partner codegraph resync (CLI)", () => {
{ cwd: tmp },
);
expect(res.returncode).toBe(0);
- expect(res.stdout).toContain(`project="${repo}"`);
+ expect(res.stdout).toContain(`project='${repo}'`);
expect(listTree(tmp)).toEqual(before);
});
@@ -165,6 +203,44 @@ describe("o2b partner codegraph resync (CLI)", () => {
expect(listTree(tmp)).toEqual(before);
});
+ test("without --format the CLI prints the cron recipe, not the systemd pair", async () => {
+ const repo = makeRepo("repo");
+ const res = await runCli(["partner", "codegraph", "resync", "--cron-template"], {
+ cwd: repo,
+ });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("0 */6 * * * ~/.local/bin/osb-codegraph-resync.sh");
+ expect(res.stdout).toContain("hermes cron create");
+ expect(res.stdout).not.toContain("OnUnitActiveSec=");
+ });
+
+ test("--format systemd prints a service and timer pair and writes nothing", async () => {
+ const repo = makeRepo("repo");
+ const before = listTree(tmp);
+ const res = await runCli(
+ ["partner", "codegraph", "resync", "--cron-template", "--format", "systemd"],
+ { cwd: repo },
+ );
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("~/.config/systemd/user/osb-codegraph-resync.service");
+ expect(res.stdout).toContain("~/.config/systemd/user/osb-codegraph-resync.timer");
+ expect(res.stdout).toContain("OnUnitActiveSec=6h");
+ expect(res.stdout).toContain(`project='${repo}'`);
+ expect(res.stdout).not.toContain("hermes cron create");
+ expect(listTree(tmp)).toEqual(before);
+ });
+
+ test("--format launchd exits 1 naming the formats it knows", async () => {
+ const repo = makeRepo("repo");
+ const res = await runCli(
+ ["partner", "codegraph", "resync", "--cron-template", "--format", "launchd"],
+ { cwd: repo },
+ );
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain('unknown recipe format "launchd": expected cron or systemd');
+ expect(res.stdout).toBe("");
+ });
+
test("an interval cron cannot express exits 1 with the inherited parser error", async () => {
const repo = makeRepo("repo");
const res = await runCli(
diff --git a/tests/cli/search-cron-template.test.ts b/tests/cli/search-cron-template.test.ts
index 5b4abc96..76e7d85a 100644
--- a/tests/cli/search-cron-template.test.ts
+++ b/tests/cli/search-cron-template.test.ts
@@ -151,6 +151,20 @@ describe("renderCronTemplate", () => {
const body = renderCronTemplate("6h");
expect(body).toContain("0 */6 * * *");
});
+
+ test("the cron format is the default and renders the pinned fixture", () => {
+ expect(renderCronTemplate("30m", { format: "cron" })).toBe(
+ readFileSync(PINNED_FIXTURE, "utf8"),
+ );
+ });
+
+ test("the systemd format renders a timer on the same cadence", () => {
+ const body = renderCronTemplate("30m", { format: "systemd" });
+ expect(body).toContain("OnUnitActiveSec=30m");
+ expect(body).toContain("~/.config/systemd/user/osb-reindex.timer");
+ expect(body).toContain("search reindex --embeddings");
+ expect(body).not.toContain("hermes cron create");
+ });
});
let tmp: string;
@@ -166,14 +180,14 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
-describe("o2b search reindex --cron-template (CLI)", () => {
- async function bootstrap(): Promise<void> {
- const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
- env: { OPEN_SECOND_BRAIN_CONFIG: config },
- });
- expect(init.returncode).toBe(0);
- }
+async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+}
+describe("o2b search reindex --cron-template (CLI)", () => {
test("default 30m prints the template and writes nothing under tmp", async () => {
await bootstrap();
const before = readdirSync(tmp);
@@ -197,6 +211,49 @@ describe("o2b search reindex --cron-template (CLI)", () => {
expect(r.stdout).toContain("0 */6 * * *");
});
+ test("--format systemd prints a systemd user timer", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["search", "reindex", "--cron-template", "--format", "systemd", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("OnUnitActiveSec=30m");
+ expect(r.stdout).toContain("systemctl --user enable --now osb-reindex.timer");
+ expect(r.stdout).not.toContain("*/30 * * * *");
+ });
+
+ test("--format launchd exits 1 naming the formats it knows", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["search", "reindex", "--cron-template", "--format", "launchd", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain('unknown recipe format "launchd": expected cron or systemd');
+ expect(r.stdout).toBe("");
+ });
+
+ test("--format or --interval without --cron-template exits 2 and runs no reindex", async () => {
+ await bootstrap();
+ const before = readdirSync(tmp, { recursive: true }).toSorted();
+ for (const extra of [
+ ["--format", "systemd"],
+ ["--interval", "6h"],
+ ]) {
+ // oxlint-disable-next-line no-await-in-loop -- each spawn must finish before the tree is compared.
+ const r = await runCli(["search", "reindex", ...extra, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain(
+ "search reindex: --interval and --format apply only with --cron-template",
+ );
+ expect(r.stdout).toBe("");
+ }
+ expect(readdirSync(tmp, { recursive: true }).toSorted()).toEqual(before);
+ });
+
test("--interval garbage exits 1 with the parser error", async () => {
await bootstrap();
const r = await runCli(
diff --git a/tests/core/brain/maintenance/custom-tasks.test.ts b/tests/core/brain/maintenance/custom-tasks.test.ts
new file mode 100644
index 00000000..1f1945d2
--- /dev/null
+++ b/tests/core/brain/maintenance/custom-tasks.test.ts
@@ -0,0 +1,540 @@
+/**
+ * Install-owned custom lane tasks: declared as flat keys in the machine
+ * config file (never the vault), gated by a default-off master switch,
+ * resolved into `custom:<name>` identities with every bad declaration
+ * named rather than dropped, and run through the platform shell with the
+ * home directory as the default cwd, credential-named variables dropped
+ * from the env, a closed stdin, a redacted and capped stderr tail on
+ * failure, and the whole process group killed on timeout or abort.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ createCustomLaneTask,
+ CUSTOM_TASK_MAX,
+ CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS,
+ CUSTOM_TASKS_ENV_OFF_NOTICE,
+ CUSTOM_TASKS_OFF_NOTICE,
+ customTaskEnv,
+ customTasksOffNotice,
+ CUSTOM_TASK_NAME_PATTERN,
+ CUSTOM_TASK_PREFIX,
+ CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS,
+ isCustomLaneTask,
+ resolveCustomTasks,
+ type CustomTaskSpec,
+} from "../../../../src/core/brain/maintenance/custom-tasks.ts";
+import {
+ MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY,
+ MAINTENANCE_CUSTOM_TASKS_ENV,
+ resolveMaintenanceCustomTasksSwitch,
+} from "../../../../src/core/config.ts";
+import {
+ SafeguardAbortError,
+ SafeguardTimeoutError,
+} from "../../../../src/core/brain/safeguard.ts";
+import { MAINTENANCE_LEASE_TTL_MS } from "../../../../src/core/brain/maintenance/lane.ts";
+import { IS_WINDOWS } from "../../../helpers/platform.ts";
+
+let dir: string;
+let configPath: string;
+let savedEnv: string | undefined;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "o2b-custom-tasks-"));
+ configPath = join(dir, "config.yaml");
+ savedEnv = process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+ delete process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+});
+
+afterEach(() => {
+ if (savedEnv === undefined) delete process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+ else process.env[MAINTENANCE_CUSTOM_TASKS_ENV] = savedEnv;
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeConfig(lines: ReadonlyArray<string>): void {
+ writeFileSync(configPath, `${lines.join("\n")}\n`);
+}
+
+describe("the custom task vocabulary", () => {
+ test("identities carry the custom: prefix and a pattern-checked name", () => {
+ expect(CUSTOM_TASK_PREFIX).toBe("custom:");
+ expect(CUSTOM_TASK_MAX).toBe(8);
+ expect(CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS).toBe(120);
+ // The full cap fits the budget at the default timeout.
+ expect(CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS * CUSTOM_TASK_MAX).toBeLessThanOrEqual(
+ CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS,
+ );
+ expect(CUSTOM_TASK_NAME_PATTERN.test("tidy")).toBe(true);
+ expect(CUSTOM_TASK_NAME_PATTERN.test("a-b9")).toBe(true);
+ expect(CUSTOM_TASK_NAME_PATTERN.test("Bad")).toBe(false);
+ expect(CUSTOM_TASK_NAME_PATTERN.test("a_b")).toBe(false);
+ expect(CUSTOM_TASK_NAME_PATTERN.test(`a${"b".repeat(32)}`)).toBe(false);
+ expect(isCustomLaneTask("custom:tidy")).toBe(true);
+ expect(isCustomLaneTask("custom:Bad")).toBe(false);
+ expect(isCustomLaneTask("custom:")).toBe(false);
+ expect(isCustomLaneTask("reindex")).toBe(false);
+ expect(isCustomLaneTask(42)).toBe(false);
+ });
+});
+
+describe("the master switch", () => {
+ test("is off by default, on with the config key, and the env 0 overrides config true", () => {
+ expect(MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY).toBe("maintenance_custom_tasks");
+ expect(MAINTENANCE_CUSTOM_TASKS_ENV).toBe("OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS");
+ writeConfig(["vault: /nowhere"]);
+ expect(resolveMaintenanceCustomTasksSwitch(configPath).enabled).toBe(false);
+ writeConfig(["maintenance_custom_tasks: true"]);
+ expect(resolveMaintenanceCustomTasksSwitch(configPath).enabled).toBe(true);
+ process.env[MAINTENANCE_CUSTOM_TASKS_ENV] = "0";
+ expect(resolveMaintenanceCustomTasksSwitch(configPath).enabled).toBe(false);
+ });
+});
+
+describe("resolveCustomTasks", () => {
+ test("reads a command with its cwd and timeout into one custom:<name> spec, sorted by name", () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_tidy: ./tidy.sh",
+ "maintenance_custom_tidy_cwd: /srv/x",
+ "maintenance_custom_tidy_timeout_seconds: 120",
+ "maintenance_custom_archive: archive --all",
+ ]);
+ const resolved = resolveCustomTasks(configPath);
+ expect(resolved.enabled).toBe(true);
+ expect(resolved.errors).toEqual([]);
+ expect(resolved.declared).toBe(2);
+ expect(resolved.specs).toEqual([
+ {
+ name: "archive",
+ id: "custom:archive",
+ command: "archive --all",
+ timeoutSeconds: CUSTOM_TASK_TIMEOUT_DEFAULT_SECONDS,
+ },
+ {
+ name: "tidy",
+ id: "custom:tidy",
+ command: "./tidy.sh",
+ cwd: "/srv/x",
+ timeoutSeconds: 120,
+ },
+ ]);
+ });
+
+ test("names every bad declaration while the good ones still resolve", () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_good: true-command",
+ "maintenance_custom_Bad: echo bad",
+ "maintenance_custom_a_b: echo ab",
+ "maintenance_custom_empty:",
+ "maintenance_custom_zero: echo z",
+ "maintenance_custom_zero_timeout_seconds: 0",
+ "maintenance_custom_word: echo w",
+ "maintenance_custom_word_timeout_seconds: abc",
+ "maintenance_custom_long: echo l",
+ "maintenance_custom_long_timeout_seconds: 1201",
+ "maintenance_custom_orphan_cwd: /srv/orphan",
+ "maintenance_custom_rel: echo r",
+ "maintenance_custom_rel_cwd: relative/dir",
+ ]);
+ const resolved = resolveCustomTasks(configPath);
+ expect(resolved.specs.map((s) => s.id)).toEqual(["custom:good"]);
+ const errors = resolved.errors.join("\n");
+ expect(errors).toContain("maintenance_custom_Bad");
+ expect(errors).toContain("maintenance_custom_a_b");
+ expect(errors).toContain("maintenance_custom_empty");
+ expect(errors).toContain("maintenance_custom_zero_timeout_seconds");
+ expect(errors).toContain("maintenance_custom_word_timeout_seconds");
+ expect(errors).toContain("maintenance_custom_long_timeout_seconds");
+ expect(errors).toContain("maintenance_custom_orphan_cwd");
+ expect(errors).toContain("maintenance_custom_rel_cwd");
+ // One named error per bad declaration, never a silent skip.
+ expect(resolved.errors.length).toBe(8);
+ });
+
+ test("a command-less name with both suffix keys names each key", () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_ghost_cwd: /srv/ghost",
+ "maintenance_custom_ghost_timeout_seconds: 30",
+ ]);
+ const resolved = resolveCustomTasks(configPath);
+ expect(resolved.specs).toEqual([]);
+ expect(resolved.errors).toEqual([
+ "maintenance_custom_ghost_cwd: no maintenance_custom_ghost command is declared for it",
+ "maintenance_custom_ghost_timeout_seconds: no maintenance_custom_ghost command is declared for it",
+ ]);
+ });
+
+ test("the custom timeouts together stay within a budget below the lease", () => {
+ expect(CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS).toBe(1200);
+ expect(CUSTOM_TASK_TOTAL_TIMEOUT_BUDGET_SECONDS).toBeLessThan(MAINTENANCE_LEASE_TTL_MS / 1000);
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_a: echo a",
+ "maintenance_custom_a_timeout_seconds: 700",
+ "maintenance_custom_b: echo b",
+ "maintenance_custom_b_timeout_seconds: 600",
+ "maintenance_custom_c: echo c",
+ "maintenance_custom_c_timeout_seconds: 500",
+ ]);
+ const resolved = resolveCustomTasks(configPath);
+ // In name order: a (700) fits, b would make 1300, c makes 1200 exactly.
+ expect(resolved.specs.map((s) => s.id)).toEqual(["custom:a", "custom:c"]);
+ expect(resolved.errors).toEqual([
+ "maintenance_custom_b: its 600 s timeout takes the custom timeouts to 1300 s, " +
+ "over the 1200 s budget of the 1800 s maintenance lease; this one is not run",
+ ]);
+ });
+
+ test("more than the cap names the ninth declaration onward", () => {
+ const names = Array.from({ length: CUSTOM_TASK_MAX + 2 }, (_, i) => `t${i}`);
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ ...names.map((n) => `maintenance_custom_${n}: echo ${n}`),
+ ]);
+ const resolved = resolveCustomTasks(configPath);
+ const sorted = names.toSorted();
+ expect(resolved.specs.map((s) => s.name)).toEqual(sorted.slice(0, CUSTOM_TASK_MAX));
+ expect(resolved.errors.length).toBe(2);
+ expect(resolved.errors[0]).toContain(sorted[CUSTOM_TASK_MAX]!);
+ expect(resolved.errors[1]).toContain(sorted[CUSTOM_TASK_MAX + 1]!);
+ expect(resolved.declared).toBe(CUSTOM_TASK_MAX + 2);
+ });
+
+ test("with the switch off, declared keys are counted and nothing resolves to run", () => {
+ writeConfig(["maintenance_custom_tidy: ./tidy.sh", "maintenance_custom_sweep: ./sweep.sh"]);
+ const resolved = resolveCustomTasks(configPath);
+ expect(resolved).toEqual({
+ enabled: false,
+ switchSource: "unset",
+ specs: [],
+ errors: [],
+ declared: 2,
+ });
+ expect(customTasksOffNotice(resolved)).toBe(CUSTOM_TASKS_OFF_NOTICE);
+ });
+
+ test("the off notice names the env variable when the env override decided", () => {
+ writeConfig(["maintenance_custom_tasks: true", "maintenance_custom_tidy: ./tidy.sh"]);
+ expect(customTasksOffNotice(resolveCustomTasks(configPath))).toBeNull();
+ process.env[MAINTENANCE_CUSTOM_TASKS_ENV] = "0";
+ const resolved = resolveCustomTasks(configPath);
+ expect(resolved.switchSource).toBe("env");
+ expect(customTasksOffNotice(resolved)).toBe(CUSTOM_TASKS_ENV_OFF_NOTICE);
+ expect(CUSTOM_TASKS_ENV_OFF_NOTICE).toContain(MAINTENANCE_CUSTOM_TASKS_ENV);
+ writeConfig(["maintenance_custom_tasks: false", "maintenance_custom_tidy: ./tidy.sh"]);
+ delete process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+ expect(customTasksOffNotice(resolveCustomTasks(configPath))).toBe(CUSTOM_TASKS_OFF_NOTICE);
+ });
+
+ test("an absent config file declares nothing", () => {
+ expect(resolveCustomTasks(join(dir, "missing.yaml"))).toEqual({
+ enabled: false,
+ switchSource: "unset",
+ specs: [],
+ errors: [],
+ declared: 0,
+ });
+ });
+});
+
+describe("customTaskEnv", () => {
+ test("drops credential-named variables and keeps the rest, with O2B_VAULT set", () => {
+ const env = customTaskEnv("/v", {
+ PATH: "/bin",
+ HOME: "/home/op",
+ LANG: "C.UTF-8",
+ LC_ALL: "C",
+ TZ: "UTC",
+ TMPDIR: "/t",
+ EDITOR: "vi",
+ OPENAI_API_KEY: "k",
+ GITHUB_TOKEN: "t",
+ DB_PASSWORD: "p",
+ AWS_SECRET_ACCESS_KEY: "s",
+ O2B_VAULT: "/elsewhere",
+ });
+ expect(env).toEqual({
+ PATH: "/bin",
+ HOME: "/home/op",
+ LANG: "C.UTF-8",
+ LC_ALL: "C",
+ TZ: "UTC",
+ TMPDIR: "/t",
+ EDITOR: "vi",
+ O2B_VAULT: "/v",
+ });
+ });
+});
+
+/**
+ * A portable fixture: the command runs the current Bun binary on a small
+ * script, so the same declaration works under `sh -c` and `cmd.exe /c`.
+ * Every mode that reports writes to an absolute path given as its second
+ * argument, never to its working directory.
+ */
+const FIXTURE = String.raw`
+const fs = require("node:fs");
+const { spawn } = require("node:child_process");
+const mode = process.argv[2];
+const out = process.argv[3];
+if (mode === "ok") {
+ fs.writeFileSync(out, JSON.stringify({
+ vault: process.env.O2B_VAULT ?? null,
+ cwd: process.cwd(),
+ stdin: fs.readFileSync(0, "utf8"),
+ secret: process.env.O2B_FIXTURE_API_KEY ?? null,
+ plain: process.env.O2B_FIXTURE_PLAIN ?? null,
+ }));
+} else if (mode === "fail") {
+ process.stderr.write("x".repeat(10000) + "\n");
+ process.stderr.write("api_key=abcd1234secretvalue\n");
+ process.exit(3);
+} else if (mode === "tree") {
+ // A child that starts a grandchild, both recording their pids.
+ const grandchild = spawn(process.execPath, ["-e", "setTimeout(() => {}, 30000)"], {
+ stdio: "ignore",
+ });
+ fs.writeFileSync(out, JSON.stringify({ child: process.pid, grandchild: grandchild.pid }));
+ setTimeout(() => {}, 30000);
+} else if (mode === "linger") {
+ // Left in the background by its shell, holding the inherited stderr.
+ fs.writeFileSync(out, String(process.pid));
+ setTimeout(() => {}, 30000);
+}
+`;
+
+/** What `run` rejected with; `undefined` when it resolved. */
+function rejection(run: Promise<unknown>): Promise<unknown> {
+ return run.then(
+ () => undefined,
+ (e: unknown) => e,
+ );
+}
+
+function alive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Resolve once every pid is gone; fail after `boundMs`. */
+async function expectGone(pids: ReadonlyArray<number>, boundMs = 4000): Promise<void> {
+ const until = Date.now() + boundMs;
+ while (pids.some(alive)) {
+ if (Date.now() > until) {
+ throw new Error(`still running after ${boundMs} ms: ${pids.filter(alive).join(", ")}`);
+ }
+ await Bun.sleep(50);
+ }
+}
+
+/**
+ * Per-test budget for the process-tree cases: above the task timeout plus
+ * the {@link expectGone} bound, so a surviving child fails on the
+ * "still running" assertion rather than on the runner's 5 s default.
+ */
+const PROCESS_TREE_TEST_TIMEOUT_MS = 15_000;
+
+async function waitForFile(path: string, boundMs = 4000): Promise<string> {
+ const until = Date.now() + boundMs;
+ while (!existsSync(path) || readFileSync(path, "utf8") === "") {
+ if (Date.now() > until) throw new Error(`${path} was not written within ${boundMs} ms`);
+ await Bun.sleep(20);
+ }
+ return readFileSync(path, "utf8");
+}
+
+describe("createCustomLaneTask", () => {
+ let vault: string;
+ let script: string;
+ let seenPath: string;
+
+ beforeEach(() => {
+ vault = join(dir, "vault");
+ mkdirSync(vault);
+ script = join(dir, "fixture.cjs");
+ writeFileSync(script, FIXTURE);
+ seenPath = join(dir, "seen.json");
+ });
+
+ function command(mode: string, out: string = seenPath): string {
+ return `"${process.execPath}" "${script}" ${mode} "${out}"`;
+ }
+
+ function spec(mode: string, extra: Partial<CustomTaskSpec> = {}): CustomTaskSpec {
+ return {
+ name: "fx",
+ id: "custom:fx",
+ command: command(mode),
+ timeoutSeconds: 30,
+ ...extra,
+ };
+ }
+
+ test("the task carries its identity", () => {
+ expect(createCustomLaneTask(spec("ok"), { vault }).name).toBe("custom:fx");
+ });
+
+ test("exit 0 resolves with no receipt; cwd is the home directory, O2B_VAULT is set, stdin is closed", async () => {
+ const receipt = await createCustomLaneTask(spec("ok"), { vault }).run();
+ expect(receipt).toBeUndefined();
+ const seen = JSON.parse(readFileSync(seenPath, "utf8")) as {
+ vault: string;
+ cwd: string;
+ stdin: string;
+ };
+ expect(seen.vault).toBe(vault);
+ expect(realpathSync(seen.cwd)).toBe(realpathSync(homedir()));
+ expect(seen.stdin).toBe("");
+ });
+
+ test("a credential-named variable of this process does not reach the command", async () => {
+ process.env["O2B_FIXTURE_API_KEY"] = "do-not-pass";
+ process.env["O2B_FIXTURE_PLAIN"] = "pass";
+ try {
+ await createCustomLaneTask(spec("ok"), { vault }).run();
+ } finally {
+ delete process.env["O2B_FIXTURE_API_KEY"];
+ delete process.env["O2B_FIXTURE_PLAIN"];
+ }
+ const seen = JSON.parse(readFileSync(seenPath, "utf8")) as {
+ secret: string | null;
+ plain: string | null;
+ };
+ expect(seen.secret).toBeNull();
+ expect(seen.plain).toBe("pass");
+ });
+
+ test("a declared cwd, the vault included, replaces the home directory", async () => {
+ const elsewhere = join(dir, "elsewhere");
+ mkdirSync(elsewhere);
+ await createCustomLaneTask(spec("ok", { cwd: elsewhere }), { vault }).run();
+ let seen = JSON.parse(readFileSync(seenPath, "utf8")) as { cwd: string };
+ expect(realpathSync(seen.cwd)).toBe(realpathSync(elsewhere));
+ await createCustomLaneTask(spec("ok", { cwd: vault }), { vault }).run();
+ seen = JSON.parse(readFileSync(seenPath, "utf8")) as { cwd: string };
+ expect(realpathSync(seen.cwd)).toBe(realpathSync(vault));
+ });
+
+ test("a non-zero exit throws exit <N> with the stderr tail, redacted and capped", async () => {
+ const err = (await rejection(createCustomLaneTask(spec("fail"), { vault }).run())) as Error;
+ expect(err).toBeInstanceOf(Error);
+ expect(err.message.startsWith("exit 3:")).toBe(true);
+ expect(err.message).toContain("api_key=");
+ expect(err.message).not.toContain("abcd1234secretvalue");
+ expect(Buffer.byteLength(err.message, "utf8")).toBeLessThanOrEqual(4096);
+ });
+
+ test(
+ "past its timeout the child and its grandchild are killed and it throws SafeguardTimeoutError",
+ async () => {
+ const pidsPath = join(dir, "tree.json");
+ const started = Date.now();
+ const pending = createCustomLaneTask(
+ spec("tree", { command: command("tree", pidsPath), timeoutSeconds: 1 }),
+ { vault },
+ ).run();
+ const err = await rejection(pending);
+ expect(err).toBeInstanceOf(SafeguardTimeoutError);
+ expect((err as SafeguardTimeoutError).operation).toBe("custom:fx");
+ expect(Date.now() - started).toBeLessThan(4000);
+ const pids = JSON.parse(await waitForFile(pidsPath)) as { child: number; grandchild: number };
+ await expectGone([pids.child, pids.grandchild]);
+ },
+ PROCESS_TREE_TEST_TIMEOUT_MS,
+ );
+
+ test(
+ "an aborted signal kills the child and its grandchild and rejects",
+ async () => {
+ const pidsPath = join(dir, "tree.json");
+ const controller = new AbortController();
+ const started = Date.now();
+ const pending = createCustomLaneTask(spec("tree", { command: command("tree", pidsPath) }), {
+ vault,
+ signal: controller.signal,
+ }).run();
+ const pids = JSON.parse(await waitForFile(pidsPath)) as { child: number; grandchild: number };
+ controller.abort();
+ const err = await rejection(pending);
+ expect(err).toBeInstanceOf(SafeguardAbortError);
+ expect(Date.now() - started).toBeLessThan(6000);
+ await expectGone([pids.child, pids.grandchild]);
+
+ const already = new AbortController();
+ already.abort();
+ const early = await rejection(
+ createCustomLaneTask(spec("ok"), { vault, signal: already.signal }).run(),
+ );
+ expect(early).toBeInstanceOf(SafeguardAbortError);
+ },
+ PROCESS_TREE_TEST_TIMEOUT_MS,
+ );
+
+ test.skipIf(IS_WINDOWS)(
+ "a shell that exits 0 succeeds at once; what it left in the background dies at the timeout",
+ async () => {
+ const pidPath = join(dir, "linger.pid");
+ const started = Date.now();
+ await createCustomLaneTask(
+ spec("linger", { command: `${command("linger", pidPath)} & exit 0`, timeoutSeconds: 2 }),
+ { vault },
+ ).run();
+ expect(Date.now() - started).toBeLessThan(1500);
+ const pid = Number(await waitForFile(pidPath));
+ expect(alive(pid)).toBe(true);
+ await expectGone([pid], 5000);
+ },
+ PROCESS_TREE_TEST_TIMEOUT_MS,
+ );
+
+ test.skipIf(IS_WINDOWS)(
+ "a shell that exits 0 just before its deadline, a stderr holder left behind, succeeds",
+ async () => {
+ const pidPath = join(dir, "linger.pid");
+ // The shell exits about 150 ms before the 1 s deadline, inside the
+ // stderr drain window the background holder keeps open.
+ const err = await rejection(
+ createCustomLaneTask(
+ spec("linger", {
+ command: `${command("linger", pidPath)} & sleep 0.85; exit 0`,
+ timeoutSeconds: 1,
+ }),
+ { vault },
+ ).run(),
+ );
+ expect(err).toBeUndefined();
+ const pid = Number(await waitForFile(pidPath));
+ await expectGone([pid], 5000);
+ },
+ PROCESS_TREE_TEST_TIMEOUT_MS,
+ );
+
+ test("a working directory that does not exist fails by name before the spawn", async () => {
+ const missing = join(dir, "missing");
+ const err = (await rejection(
+ createCustomLaneTask(spec("ok", { cwd: missing }), { vault }).run(),
+ )) as Error;
+ expect(err).toBeInstanceOf(Error);
+ expect(err.message).toBe(`custom task fx: cwd does not exist: ${missing}`);
+ });
+});
diff --git a/tests/core/brain/maintenance/lane-tasks.test.ts b/tests/core/brain/maintenance/lane-tasks.test.ts
new file mode 100644
index 00000000..a57bf78c
--- /dev/null
+++ b/tests/core/brain/maintenance/lane-tasks.test.ts
@@ -0,0 +1,144 @@
+/**
+ * The one lane task builder both front doors (the CLI verb and the MCP
+ * tool) call: the four built-ins in their registration order, then the
+ * declared custom tasks when the master switch is on, with the config
+ * errors passed through and every per-task safeguard built lazily.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildLaneTasks } from "../../../../src/core/brain/maintenance/lane-tasks.ts";
+import {
+ LANE_TASK,
+ LANE_TASKS,
+ type LaneTask,
+} from "../../../../src/core/brain/maintenance/lane.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { createSafeguard, SafeguardAbortError } from "../../../../src/core/brain/safeguard.ts";
+import { MAINTENANCE_CUSTOM_TASKS_ENV } from "../../../../src/core/config.ts";
+import { resolveSearchConfig } from "../../../../src/core/search/index.ts";
+
+const NOW = new Date("2026-06-05T03:30:00Z");
+
+let dir: string;
+let vault: string;
+let configPath: string;
+let savedEnv: string | undefined;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "o2b-lane-tasks-"));
+ vault = join(dir, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(dir, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+ savedEnv = process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+ delete process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+});
+
+afterEach(() => {
+ if (savedEnv === undefined) delete process.env[MAINTENANCE_CUSTOM_TASKS_ENV];
+ else process.env[MAINTENANCE_CUSTOM_TASKS_ENV] = savedEnv;
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeConfig(lines: ReadonlyArray<string>): void {
+ writeFileSync(configPath, `${[`vault: ${vault}`, ...lines].join("\n")}\n`);
+}
+
+function build(calls: LaneTask[] = [], signal?: AbortSignal) {
+ return buildLaneTasks({
+ vault,
+ configPath,
+ searchConfig: resolveSearchConfig({ vault, configPath }),
+ now: NOW,
+ forceCost: false,
+ ...(signal !== undefined ? { signal } : {}),
+ safeguardFor: (operation) => {
+ calls.push(operation);
+ return createSafeguard({ operation, timeoutMs: null });
+ },
+ });
+}
+
+/**
+ * A config value for a command that writes the marker file at the absolute
+ * path `marker`, portably: the Bun path quoted (it may hold a space), the
+ * whole value wrapped in single quotes so the config reader does not strip
+ * the double quotes the command starts and ends with.
+ */
+function touchCommand(marker: string): string {
+ const target = marker.replaceAll("\\", "/");
+ return `'"${process.execPath}" -e "require('node:fs').writeFileSync('${target}', 'ran')"'`;
+}
+
+describe("buildLaneTasks", () => {
+ test("with the switch off the task names are exactly the built-ins, in order", () => {
+ writeConfig(["maintenance_custom_a: echo a"]);
+ const set = build();
+ expect(set.taskNames).toEqual(LANE_TASKS);
+ expect(set.tasks.map((t) => t.name)).toEqual([...LANE_TASKS]);
+ expect(set.custom.enabled).toBe(false);
+ expect(set.custom.declared).toBe(1);
+ expect(set.reindex.task.name).toBe(LANE_TASK.reindex);
+ });
+
+ test("with the switch on, declared custom tasks follow the built-ins and errors pass through", () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_b: echo b",
+ "maintenance_custom_a: echo a",
+ "maintenance_custom_Bad: echo bad",
+ ]);
+ const set = build();
+ expect(set.taskNames).toEqual([...LANE_TASKS, "custom:a", "custom:b"]);
+ expect(set.tasks.map((t) => t.name)).toEqual([...set.taskNames]);
+ expect(set.custom.errors.length).toBe(1);
+ expect(set.custom.errors[0]).toContain("maintenance_custom_Bad");
+ });
+
+ test("safeguardFor is called lazily, with the running task's operation, once per run", async () => {
+ const calls: LaneTask[] = [];
+ const set = build(calls);
+ expect(calls).toEqual([]);
+ const dream = set.tasks.find((t) => t.name === LANE_TASK.dream)!;
+ await dream.run();
+ expect(calls).toEqual([LANE_TASK.dream]);
+ await dream.run();
+ expect(calls).toEqual([LANE_TASK.dream, LANE_TASK.dream]);
+ });
+
+ test("a built custom task runs its command and returns no spend receipt", async () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ `maintenance_custom_a: ${touchCommand(join(dir, "a.txt"))}`,
+ ]);
+ const set = build();
+ const custom = set.tasks.find((t) => t.name === "custom:a")!;
+ const receipt = await custom.run();
+ expect(receipt).toBeUndefined();
+ expect(existsSync(join(dir, "a.txt"))).toBe(true);
+ expect(
+ set.reindex.spendBlock([{ name: "custom:a", ok: true, duration_ms: 1 }]),
+ ).toBeUndefined();
+ });
+
+ test("the lane's abort signal reaches the custom tasks it builds", async () => {
+ writeConfig([
+ "maintenance_custom_tasks: true",
+ `maintenance_custom_a: ${touchCommand(join(dir, "aborted.txt"))}`,
+ ]);
+ const controller = new AbortController();
+ controller.abort();
+ const custom = build([], controller.signal).tasks.find((t) => t.name === "custom:a")!;
+ const err = await custom.run().then(
+ () => undefined,
+ (e: unknown) => e,
+ );
+ expect(err).toBeInstanceOf(SafeguardAbortError);
+ expect(existsSync(join(dir, "aborted.txt"))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/maintenance/maintenance.test.ts b/tests/core/brain/maintenance/maintenance.test.ts
index 22baf29b..3f38bbf3 100644
--- a/tests/core/brain/maintenance/maintenance.test.ts
+++ b/tests/core/brain/maintenance/maintenance.test.ts
@@ -605,6 +605,90 @@ describe("the consecutive-failure streak", () => {
});
});
+async function failingCustom(): Promise<void> {
+ throw new Error("exit 3: broken");
+}
+
+describe("custom task identities and the custom timeout streak rule", () => {
+ const CUSTOM = "custom:x" as const;
+
+ function customRun(
+ run: () => Promise<void>,
+ extra: { retryTasks?: ReadonlyArray<typeof CUSTOM>; dreamFirst?: boolean } = {},
+ ) {
+ const custom = { name: CUSTOM, run };
+ const dreamTask = { name: LANE_TASK.dream, run: async () => void 0 };
+ return runMaintenance(vault, {
+ now: NOW,
+ holder: "worker-a",
+ ...(extra.retryTasks !== undefined ? { retryTasks: extra.retryTasks } : {}),
+ tasks: extra.dreamFirst === true ? [dreamTask, custom] : [custom, dreamTask],
+ });
+ }
+
+ test("a failing custom task is refused by name at the limit while the built-ins still run", async () => {
+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ await customRun(failingCustom);
+ }
+ const refused = await customRun(failingCustom);
+ const custom = refused.tasks.find((t) => t.name === CUSTOM)!;
+ expect(custom.refused).toBe(true);
+ expect(custom.error).toContain(`--retry ${CUSTOM}`);
+ expect(refused.tasks.find((t) => t.name === LANE_TASK.dream)?.ok).toBe(true);
+ });
+
+ test("a custom task that keeps timing out is refused: its timeouts count", async () => {
+ const timingOut = async () => {
+ throw new SafeguardTimeoutError(CUSTOM, 1000);
+ };
+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ const run = await customRun(timingOut);
+ expect(run.tasks.find((t) => t.name === CUSTOM)?.timed_out).toBe(true);
+ }
+ expect(consecutiveTaskFailures(vault, CUSTOM)).toBe(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);
+ const refused = await customRun(timingOut);
+ expect(refused.tasks.find((t) => t.name === CUSTOM)?.refused).toBe(true);
+ });
+
+ test("a built-in task timing out as often is still not refused", async () => {
+ for (let i = 0; i <= MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ const run = await runMaintenance(vault, {
+ now: NOW,
+ holder: "worker-a",
+ tasks: [
+ {
+ name: LANE_TASK.reindex,
+ run: async () => {
+ throw new SafeguardTimeoutError(LANE_TASK.reindex, 1000);
+ },
+ },
+ ],
+ });
+ expect(run.tasks[0]!.refused).toBeUndefined();
+ }
+ expect(consecutiveTaskFailures(vault, LANE_TASK.reindex)).toBe(0);
+ });
+
+ test("retryTasks names a custom identity past its refusal, and stale-first orders it", async () => {
+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ await customRun(failingCustom);
+ }
+ // dream has succeeded on every pass, the custom task never: it runs
+ // first, although it is registered after dream.
+ const retried = await customRun(async () => void 0, {
+ retryTasks: [CUSTOM],
+ dreamFirst: true,
+ });
+ expect(retried.tasks.map((t) => t.name)).toEqual([CUSTOM, LANE_TASK.dream]);
+ expect(retried.tasks[0]!.ok).toBe(true);
+ expect(consecutiveTaskFailures(vault, CUSTOM)).toBe(0);
+ });
+});
+
describe("maintenance journal per-device shards (t_774dea61)", () => {
test("two devices write their own shards; lists merge and the sweep trims only the local shard", () => {
appendAs("a", "2026-06-01T10:00:00Z", false);
diff --git a/tests/fixtures/discipline-install/no-home.ts b/tests/fixtures/discipline-install/no-home.ts
new file mode 100644
index 00000000..56ba5aae
--- /dev/null
+++ b/tests/fixtures/discipline-install/no-home.ts
@@ -0,0 +1,14 @@
+/**
+ * Preload for a spawned `o2b discipline ...`: a host whose home directory
+ * cannot be resolved.
+ *
+ * Spawned by `tests/cli/discipline-install.test.ts` as
+ * `bun --preload <this> src/cli/main.ts discipline ...`. An empty HOME is
+ * not enough on POSIX, because the runtime falls back to the password
+ * database, so `homedir()` itself is replaced before the CLI loads.
+ */
+
+import { mock } from "bun:test";
+import * as os from "node:os";
+
+mock.module("node:os", () => ({ ...os, default: { ...os, homedir: () => "" }, homedir: () => "" }));
diff --git a/tests/fixtures/mcp-fault-guard/reject-once-guarded.ts b/tests/fixtures/mcp-fault-guard/reject-once-guarded.ts
new file mode 100644
index 00000000..e61a2a40
--- /dev/null
+++ b/tests/fixtures/mcp-fault-guard/reject-once-guarded.ts
@@ -0,0 +1,33 @@
+/**
+ * Preload for a real `o2b mcp` process: one detached rejection, raised
+ * only once the fault guard is listening.
+ *
+ * Spawned by `tests/cli/mcp-fault-guard-spawn.test.ts` as
+ * `bun --preload <this> src/cli/main.ts mcp ...`. Product code has no
+ * hook to inject a fault, so this file watches the process-global
+ * `unhandledRejection` listener count from outside: when the guard that
+ * `o2b mcp` installs raises it above the count seen at preload, a promise
+ * is rejected with nothing awaiting it. At exit the file prints the
+ * listener count again, so the test can see that the verb released the
+ * guard before the process ended.
+ */
+
+/** How often the listener count is checked while waiting for the guard. */
+const POLL_MS = 10;
+
+/** Prefix of the exit line the spawned test parses. */
+const EXIT_LINE_PREFIX = "fixture: unhandledRejection listeners at exit: ";
+
+const EVENT = "unhandledRejection";
+const baseline = process.listenerCount(EVENT);
+
+const poll = setInterval(() => {
+ if (process.listenerCount(EVENT) <= baseline) return;
+ clearInterval(poll);
+ void Promise.reject(new Error("fixture rejection inside o2b mcp"));
+}, POLL_MS);
+poll.unref();
+
+process.on("exit", () => {
+ process.stderr.write(EXIT_LINE_PREFIX + (process.listenerCount(EVENT) - baseline) + "\n");
+});
diff --git a/tests/fixtures/mcp-fault-guard/serve-with-rejection.ts b/tests/fixtures/mcp-fault-guard/serve-with-rejection.ts
new file mode 100644
index 00000000..eb4dc1fd
--- /dev/null
+++ b/tests/fixtures/mcp-fault-guard/serve-with-rejection.ts
@@ -0,0 +1,31 @@
+/**
+ * A served stdio transport that suffers one detached promise rejection.
+ *
+ * Spawned by `tests/cli/mcp-fault-guard-spawn.test.ts`. The guard is
+ * installed exactly as `o2b mcp` installs it; once the loop is live a
+ * promise is rejected with nothing awaiting it. Without the guard the
+ * runtime default ends the process there; with it, the server must go on
+ * answering and exit 0 on EOF.
+ *
+ * argv: <vault>
+ */
+
+import { installMcpFaultGuard } from "../../../src/cli/mcp-fault-guard.ts";
+import { serveStdio } from "../../../src/mcp/stdio.ts";
+
+const vault = process.argv[2];
+if (vault === undefined) throw new Error("usage: serve-with-rejection.ts <vault>");
+
+const guard = installMcpFaultGuard();
+try {
+ process.exitCode = await serveStdio(
+ { vault },
+ {
+ onStart: () => {
+ void Promise.reject(new Error("fixture rejection nobody awaits"));
+ },
+ },
+ );
+} finally {
+ guard.release();
+}
diff --git a/tests/fixtures/mcp-fault-guard/serve-with-throw.ts b/tests/fixtures/mcp-fault-guard/serve-with-throw.ts
new file mode 100644
index 00000000..7d1f3396
--- /dev/null
+++ b/tests/fixtures/mcp-fault-guard/serve-with-throw.ts
@@ -0,0 +1,28 @@
+/**
+ * A process holding a real sync lock that then throws from a timer.
+ *
+ * Spawned by `tests/cli/mcp-fault-guard-spawn.test.ts`. The lock is taken
+ * through the product's own lock module, whose `exit` hook unlinks every
+ * held lock. The guard turns the uncaught exception into
+ * `process.exit(70)`, which emits `exit`; the runtime default would not,
+ * and the lock file would outlive the process.
+ *
+ * argv: <vault>; prints the lock path on stdout before throwing.
+ */
+
+import { join } from "node:path";
+
+import { installMcpFaultGuard } from "../../../src/cli/mcp-fault-guard.ts";
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+
+const vault = process.argv[2];
+if (vault === undefined) throw new Error("usage: serve-with-throw.ts <vault>");
+
+installMcpFaultGuard();
+const lock = acquireLockSync(join(vault, "fault-guard-probe"));
+process.stdout.write(`${lock.path}\n`);
+setTimeout(() => {
+ throw new Error("fixture exception from a timer");
+}, 10);
+// Keep the event loop alive the way a served transport would.
+setInterval(() => {}, 1_000);
diff --git a/tests/mcp/http-health-faults.test.ts b/tests/mcp/http-health-faults.test.ts
new file mode 100644
index 00000000..90c658da
--- /dev/null
+++ b/tests/mcp/http-health-faults.test.ts
@@ -0,0 +1,67 @@
+/**
+ * `/health` reports the process-level fault counts when the CLI hands
+ * the transport a getter for them, and stays exactly as it was without
+ * one, so a supervisor already parsing the body sees no change.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { startHttp, type HttpServerHandle, type McpFaultCounts } from "../../src/mcp/http.ts";
+
+const temps: string[] = [];
+const handles: HttpServerHandle[] = [];
+
+afterEach(async () => {
+ await Promise.all(handles.splice(0).map((handle) => handle.close()));
+ while (temps.length > 0) rmSync(temps.pop()!, { recursive: true, force: true });
+});
+
+async function serve(faultCounts?: () => McpFaultCounts): Promise<HttpServerHandle> {
+ const vault = mkdtempSync(join(tmpdir(), "osb-mcp-health-faults-"));
+ temps.push(vault);
+ const handle = await startHttp(
+ { vault },
+ { port: 0, ...(faultCounts !== undefined ? { faultCounts } : {}) },
+ );
+ handles.push(handle);
+ return handle;
+}
+
+async function health(handle: HttpServerHandle): Promise<Record<string, unknown>> {
+ const res = await fetch(`${handle.url}/health`);
+ expect(res.status).toBe(200);
+ return (await res.json()) as Record<string, unknown>;
+}
+
+describe("/health fault counts", () => {
+ test("carries the counts the injected getter returns, read per request", async () => {
+ let counts: McpFaultCounts = {
+ unhandled_rejection: 0,
+ uncaught_exception: 0,
+ last_fault_at: null,
+ };
+ const handle = await serve(() => counts);
+ expect((await health(handle))["faults"]).toEqual(counts);
+
+ counts = {
+ unhandled_rejection: 3,
+ uncaught_exception: 0,
+ last_fault_at: "2026-10-01T03:00:00.000Z",
+ };
+ const body = await health(handle);
+ expect(body["faults"]).toEqual(counts);
+ // The drain fields are unchanged beside it.
+ expect(body["status"]).toBe("ok");
+ expect(body["transport"]).toBe("http");
+ expect(body["in_flight"]).toBe(0);
+ });
+
+ test("without a getter the body has no faults field", async () => {
+ const handle = await serve();
+ const body = await health(handle);
+ expect(Object.keys(body).toSorted()).toEqual(["in_flight", "status", "transport"]);
+ });
+});
diff --git a/tests/mcp/maintenance-parity-census.test.ts b/tests/mcp/maintenance-parity-census.test.ts
index 3b2cac9c..a06d76b9 100644
--- a/tests/mcp/maintenance-parity-census.test.ts
+++ b/tests/mcp/maintenance-parity-census.test.ts
@@ -59,10 +59,15 @@ import {
MAINTENANCE_BUSY_THRESHOLD_MAX,
} from "../../src/core/brain/maintenance/lane.ts";
import { MAINTENANCE_JOURNAL_CAP } from "../../src/core/brain/maintenance/journal.ts";
+import {
+ CUSTOM_TASK_MAX,
+ CUSTOM_TASKS_OFF_NOTICE,
+} from "../../src/core/brain/maintenance/custom-tasks.ts";
import { isOperation } from "../../src/core/brain/safeguard.ts";
import { ADMIN_TOOLS } from "../../src/mcp/brain/admin-tools.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";
+import { homeEnv } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
import { lexSource } from "../helpers/source-lexer.ts";
@@ -99,6 +104,15 @@ const CLI_ONLY: Readonly<Record<string, string>> = Object.freeze({
progress:
"a client asks for progress with a _meta progressToken on the request, which the transport " +
"turns into the handler's onProgress sink; a boolean argument would be a second way to ask.",
+ "cron-template":
+ "a recipe is shell an operator pastes into the scheduler of the machine they are on; an MCP " +
+ "caller has no crontab or systemd user session to paste it into, and the tool runs the lane.",
+ interval:
+ "the schedule interval exists only for the printed recipe (--cron-template), which has no " +
+ "MCP counterpart; the lane itself has no interval, its gates decide when work happens.",
+ format:
+ "cron or systemd selects the renderer of the printed recipe (--cron-template), which has no " +
+ "MCP counterpart; a format argument on the tool would select nothing.",
});
/**
@@ -429,11 +443,15 @@ describe("the two surfaces refuse the same values, not only the same names", ()
}
test("retry_tasks longer than the lane has tasks is refused, not merely advertised", async () => {
- // `maxItems` on the schema is advertisement: no JSON-Schema validator
- // runs on the request path, and the unknown-argument guard checks
- // names rather than shapes. So the handler owes the check itself -
- // without it a thousand-entry array was accepted while the schema
- // said it could not be.
+ // The schema advertises the widest list any install can need (the
+ // built-ins plus the custom-task cap); the handler refuses against
+ // the tasks THIS install declared. `maxItems` on the schema is
+ // advertisement: no JSON-Schema validator runs on the request path,
+ // and the unknown-argument guard checks names rather than shapes. So
+ // the handler owes the check itself - without it a thousand-entry
+ // array was accepted while the schema said it could not be. After
+ // deduplication a longer list always names an unknown task, so it is
+ // refused by name, in the same words the CLI uses.
const server = new MCPServer({ vault, configPath });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
@@ -446,7 +464,8 @@ describe("the two surfaces refuse the same values, not only the same names", ()
properties: { retry_tasks: { maxItems?: number } };
};
const advertised = schema.properties.retry_tasks.maxItems;
- expect(advertised).toBe(LANE_TASKS.length);
+ expect(advertised).toBe(LANE_TASKS.length + CUSTOM_TASK_MAX);
+ const declared = LANE_TASKS.length;
const res = (await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 2,
@@ -455,14 +474,14 @@ describe("the two surfaces refuse the same values, not only the same names", ()
name: TOOL_NAME,
arguments: {
operation: "run",
- // Every entry a REAL lane task, so the only thing wrong with
- // the request is its length.
- retry_tasks: Array.from({ length: advertised! + 1 }, () => LANE_TASK.dream),
+ // Distinct entries: duplicates collapse before the bound, so
+ // only more distinct names than the lane has can exceed it.
+ retry_tasks: Array.from({ length: declared + 1 }, (_, i) => `task-${i}`),
},
},
})) as { error?: { code: number; message: string } };
expect(res.error?.code).toBe(INVALID_PARAMS);
- expect(res.error?.message).toContain(String(advertised));
+ expect(res.error?.message).toContain("retry_tasks names no lane task: task-0");
});
});
@@ -523,3 +542,150 @@ describe("an unknown retry name is refused by name on both surfaces", () => {
for (const task of LANE_TASKS) expect(message).toContain(task);
});
});
+
+/** Measured caps on the tool's text: the registry keeps every description short. */
+const TOOL_DESCRIPTION_MAX = 300;
+const RETRY_PROPERTY_DESCRIPTION_MAX = 160;
+
+describe("the tool's text stays inside its budget", () => {
+ test("description and retry_tasks property are measured, and name no configured task", () => {
+ const tool = ADMIN_TOOLS.find((t) => t.name === TOOL_NAME)!;
+ const schema = tool.inputSchema as {
+ properties: { retry_tasks: { description: string } };
+ };
+ const retry = schema.properties.retry_tasks.description;
+ expect(tool.description.length).toBeLessThan(TOOL_DESCRIPTION_MAX);
+ expect(retry.length).toBeLessThan(RETRY_PROPERTY_DESCRIPTION_MAX);
+ expect(tool.description).toContain("custom:<name>");
+ expect(retry).toContain("custom:<name>");
+ // Configured names vary per install; the schema is the same for all.
+ expect(/custom:(?!<name>)/.test(`${tool.description} ${retry}`)).toBe(false);
+ });
+});
+
+describe("declared custom tasks are retried and refused the same way on both surfaces", () => {
+ let tmp: string;
+ let vault: string;
+ let configPath: string;
+
+ beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-maint-custom-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(
+ configPath,
+ [
+ `vault: ${vault}`,
+ "agent_name: claude",
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_tidy: exit 0",
+ "maintenance_custom_Bad: exit 0",
+ ].join("\n") + "\n",
+ );
+ const init = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(init.returncode).toBe(0);
+ });
+
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ });
+
+ async function callTool(args: Record<string, unknown>) {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: PROTOCOL_VERSION },
+ });
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: TOOL_NAME, arguments: args },
+ })) as {
+ error?: { code: number; message: string };
+ result?: { structuredContent?: Record<string, unknown>; content?: Array<{ text: string }> };
+ };
+ }
+
+ /** The tool's result object, from structured content or the text block. */
+ function toolPayload(res: Awaited<ReturnType<typeof callTool>>): Record<string, unknown> {
+ if (res.result?.structuredContent) return res.result.structuredContent;
+ return JSON.parse(res.result?.content?.[0]?.text ?? "{}") as Record<string, unknown>;
+ }
+
+ test("an undeclared custom name is refused by name on both surfaces", async () => {
+ const cli = await runCli(
+ ["brain", "maintenance", "run", "--retry", "custom:nope", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(cli.returncode).toBe(2);
+ expect(cli.stderr).toContain("custom:nope");
+ expect(cli.stderr).toContain("custom:tidy");
+
+ const res = await callTool({ operation: "run", retry_tasks: ["custom:nope"] });
+ expect(res.error?.code).toBe(INVALID_PARAMS);
+ expect(res.error?.message ?? "").toContain("custom:nope");
+ expect(res.error?.message ?? "").toContain("custom:tidy");
+ });
+
+ test("a declared custom name, even named twice, runs on both surfaces, and config errors come back by name", async () => {
+ const home = join(tmp, "home");
+ mkdirSync(home);
+ const cli = await runCli(
+ [
+ "brain",
+ "maintenance",
+ "run",
+ "--force",
+ "--retry",
+ "custom:tidy",
+ "--retry",
+ "custom:tidy",
+ "--vault",
+ vault,
+ "--json",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath, ...homeEnv(home) } },
+ );
+ expect(cli.returncode).toBe(0);
+ expect(cli.stderr).toContain("custom task refused:");
+ const cliTasks = (JSON.parse(cli.stdout) as { tasks: Array<{ name: string; ok?: boolean }> })
+ .tasks;
+ expect(cliTasks.find((t) => t.name === "custom:tidy")?.ok).toBe(true);
+
+ const res = await callTool({
+ operation: "run",
+ retry_tasks: ["custom:tidy", "custom:tidy"],
+ force: true,
+ });
+ expect(res.error).toBeUndefined();
+ const payload = toolPayload(res);
+ const tasks = payload["tasks"] as Array<{ name: string; ok?: boolean }>;
+ expect(tasks.find((t) => t.name === "custom:tidy")?.ok).toBe(true);
+ const errors = payload["custom_task_errors"] as ReadonlyArray<string>;
+ expect(errors.some((e) => e.includes("Bad"))).toBe(true);
+ });
+
+ test("status gives the shared off notice while the switch is off, and none while it is on", async () => {
+ const on = toolPayload(await callTool({ operation: "status" }));
+ expect(on["notice"]).toBeUndefined();
+ writeFileSync(
+ configPath,
+ readFileSync(configPath, "utf8").replace(
+ "maintenance_custom_tasks: true",
+ "maintenance_custom_tasks: false",
+ ),
+ );
+ const off = toolPayload(await callTool({ operation: "status" }));
+ expect(off["notice"]).toBe(CUSTOM_TASKS_OFF_NOTICE);
+ const cli = await runCli(["brain", "maintenance", "status", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect((JSON.parse(cli.stdout) as { notice?: string }).notice).toBe(CUSTOM_TASKS_OFF_NOTICE);
+ });
+});
diff --git a/uv.lock b/uv.lock
index 1bbda022..6ae1db7a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.64.0"
+version = "1.65.0"
source = { editable = "." }