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: no dead ends - every diagnosis names its exit (v1.40.0) (#151)

Sol Aitken0963ef0a9c15
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 061afbb0..d5308b78 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.39.0",
+ "version": "1.40.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 1e8986b1..99488f6a 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.39.0",
+ "version": "1.40.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1dd60b7f..181de64c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,46 @@ 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.40.0] - 2026-07-27
+
+A no-dead-ends wave: eleven units that make the system say what to do next, do it where the fix is provably mechanical, and refuse by name where it is not. Reconnaissance against the code invalidated at least one premise in eight of the ten scoped sources before a line was written, so most of this release is not new machinery but delivery of machinery that already existed and did not reach the caller. A registry of structural next commands had twenty entries and two consumers; the notice channel carried its command inside an English sentence; three repair pipelines each decided privately what they could fix; a repair planner shared a vocabulary with the detector while re-scanning the vault independently; the dream journal marked phases complete before their work began; the command manifest omitted a third of the real verb surface that shell completions are generated from; and two advisories stated things that were not true, one of them contradicting the same screen it printed on. The kernel still calls no LLM, and every new flag, argument, and configuration key is byte-identical when absent.
+
+### Added
+
+- One advisory rail for every forward pointer the command-line interface prints. It takes a diagnostic code, never a sentence, so prose cannot enter the surface, and it owns the question of whether advisory output is legal on the current stream - the twelve commands that render their own JSON receive nothing on stdout, while the envelope-wrapped family is safe because the envelope buffers. A suppressed emission still resolves, so a machine caller carries the command as a field instead of losing it. A ratchet fails the build when a forward pointer is hand-written outside the rail; four sites remain sanctioned, each with a written reason and a pinned count so a new pointer cannot hide behind a neighbour's justification.
+- `o2b brain dream run --step <scan|heal-enrich>` and a repeatable `--gate <name>=<true|false>`, with `step` and `gates` on the `brain_dream` tool. The override applies to one run and never touches `_brain.yaml`. Any other step, including all five phase labels, is refused with an error that names the coupling literally: two planning steps mutate each other's accumulators specifically so a preference is never both refreshed and retired, and running the refresh half alone with writes enabled would write a preference the same pass had decided to retire.
+- `o2b brain skill-proposals recover [--discard-unreadable]` and a `recover` operation on `brain_skill_proposals`. The accept transaction added in this release could strand a vault two ways, and both now name their exit: an unparseable journal marker blocked every future accept with no operator-facing recovery path, and a crash left an accept lock that no command mentioned. The lock is not broken automatically - a live writer cannot be told from a dead one - so the refusal names the exact file and the command that inspects it.
+- A skill contract on acceptance: prerequisites, rollback, side effects, and verification are written and read back by the procedural-memory reader, so they are a contract rather than decoration. A proposal's self-reported evidence is now resolved against the independently recorded procedural outcome ledger, joined by a key derived from the proposal's own slug that the accept path already causes to exist. Three states stay distinguishable and are never conflated: recorded successes, recorded failures, and no recorded outcome at all.
+- `--dry-run` on `o2b brain pending apply` - the one repair path that had no preview. It runs every check the apply runs and stops before the two disk calls, and a conflict an apply would reject is now reported by the preview rather than surfacing only at write time.
+- Ingest dedup counts as a queryable signal: a new `ingest_dedup` continuity record with a `brain_analytics` view over it. The counters existed and were reported one call deep, then discarded, so a re-ingest spike could not be seen over time. The record is dimensioned by surface and source, and a run that deduped nothing writes nothing rather than a zero row that would make a real zero indistinguishable from an absent measurement. The semantic layers are reported as what they are - nominations, never drops.
+- A `project` scope on session digests, reusing the existing scope axis, its slug rule, and the `project_scope` argument spelling already carried by search rather than introducing a parallel dimension.
+- An applier capability table: per finding code, whether repair is mechanical - naming the fixer - or refused, naming the reason. The three repair pipelines consume it instead of each deciding privately, and a test re-derives the population from the fixer registry and the three planners so the table and the code cannot disagree in either direction.
+- Machine-readable broken-link findings: the field name, the target, and the source list are carried as fields, where a consumer previously had to match the message text.
+- Expected-output blocks in every per-runtime install document, bound to the adapters by a conformance test that installs each target into an injected environment, calls its verify, renders through the command-line interface's own renderer, and names the document in the failure.
+- Ratchets that keep the release honest after it ships: a terminal-state census enumerated from the dispatchers, a manifest-completeness ratchet, a configuration-key ratchet over the generated template, a doctor-exit census, and the forward-pointer ratchet above. Each fails until a new surface is classified, and none can be satisfied by an empty reason.
+
+### Changed
+
+- Every issue `o2b brain doctor` reports now carries its structural next command on the human surface and as a field under `--json` and on `brain_doctor`. Where no single command resolves a class, the doctor says so instead of falling silent: an additive `no_exit` object gives the reason once per code, so an operator can tell "there is no command for this" from "the system forgot". All forty-one doctor codes are classified - three gained a genuine exit, twenty-four are excluded with written reasons - and four of them were assembled by string concatenation and existed nowhere in the source as readable literals.
+- The command manifest gained sixty-four entries the dispatchers already handled - two top-level commands, seven search subcommands, and fifty-five brain subcommands - and `o2b help` is now rendered from that manifest instead of a parallel hand-written constant. Shell completions and `o2b help --json` widen accordingly. The two help surfaces previously described materially different command sets.
+- The dream workrun journal now marks a phase complete where its durable writes actually land. Three markers were previously appended before a single preference was written and four after every mutation had finished, so a crash mid-write left a journal claiming work that had not started. Emission order is now execution order rather than the reporting order, which moves one marker to the end; any consumer outside this repository treating marker position as monotonic progress should re-read it. A fifth safeguard checkpoint was added before finalize, covering the log writes, the ledger write, snapshot pruning, and digest regeneration that ran unguarded.
+- The repair planner derives its plan from the findings the doctor already produced, instead of re-scanning the vault independently and sharing only a vocabulary of codes with it. No hidden re-scan was kept: one finding population turned out to be a strict superset of the other, and that is recorded rather than papered over.
+- `_brain.yaml` is generated from the resolver's own default tables. Sixteen of twenty-three top-level keys resolved silently from defaults because a hand-maintained template and a set of resolver tables had drifted apart with nothing keeping them in sync. Newly surfaced keys are emitted commented, so the resolver stays authoritative and a later default change is not silently frozen into every vault created today.
+- Repair-path guards were unified: assert at the applier's entry point, before any other work, and only when the call will write. One of the three pipelines refused dry runs and no longer does.
+- `o2b brain init` creates the two directories it declared but never made, and the runtime notice channel carries its command as a field rather than inside a sentence a consumer had to match.
+- The stale search-index notice was corrected. It claimed recall returns nothing without an index; the read path builds the index and retries, so recall returns late rather than empty.
+- `--` is honoured when detecting a JSON request, so a value after the terminator is a positional rather than a flag.
+
+### Fixed
+
+- A read-only verb could fail with a write-path error: the consolidation lint asserted vault identity before its apply branch, so `o2b brain actions` could refuse a pure read on a vault root whose marker differed from the pinned one.
+- Two advisories stated things that were not true. The empty-Brain pointer fired after every initialization, including re-runs where nothing was created, and `o2b init` contradicted itself two lines apart on one screen by naming a command its own checklist then asked for again. Each now fires only where its claim holds, and a table-driven test asserts that for every occurrence of every registered terminal state.
+- A repair item with no fixer was silently skipped and reported as success; it now raises a named error.
+- The profile registry silently overwrote an existing entry, performed no directory check at create time although switching did, and did a lock-free read-modify-write so two concurrent creates lost an update. All three are closed, and both concurrent creates now land.
+- A configuration key that gates a destructive path reached block merging but was dropped when the typed configuration was assembled, so it could not be switched on from `_brain.yaml` at all, and no warning said so.
+- Preferences created with forced confirmation wrote an absent confidence value that read back as null, which ranks below zero on the two surfaces that rank on the number. They now write an explicit zero, matching what the dream pass already does for new preferences, and the doctor check that detects this population names recording real evidence as the exit. Reported as [#149](https://github.com/itechmeat/open-second-brain/issues/149). Both fixes proposed in that report were declined with measured reasons: one writes an apply-evidence row asserting a rule was applied to an artifact when it was not, which is defined in this codebase as the canonical durable signal that a preference was exercised against real work; the other cannot see the timestamp it needs, breaks two assertions, and drifts about one ten-thousandth per hour against a one-millionth no-op threshold, so every dream pass would rewrite every zero-evidence preference forever. Measured: the reported feedback loop has no code path, because the injected context applies no confidence cutoff and orders by band rather than by value, so both proposed values would have left the preference in the same position.
+- An emission record did not carry the code it was made for, while the batch form's own documentation promised unregistered codes come back "by name". The test covering it asserted only the outcome, so the gap was invisible from both sides.
+
## [1.39.0] - 2026-07-26
A context-integrity wave: ten units that convert a silent failure in the read and delivery path into an explicit, named one. Owner-scoped isolation was enforced on one surface out of thirteen; a context pack carried no record of the vault state it was built from; session continuation resolved ambiguity by picking the most recent candidate; the lineage ledger lost history on compaction and had no writer lock; an embedding store written against a different model, dimension, or sqlite-vec ABI returned zero or garbage neighbours with no check on the read path; a frontmatter line the parser did not understand was dropped without a trace; nothing counted broken links vault-wide, nothing measured the SessionStart injection, nothing joined retrieval receipts across a session, and a mis-resolved vault root was materialized by the first write while the doctor reported it clean. Two shared seams carry the wave: a closed-vocabulary degradation channel and a stamp-and-compare module with three-mode gates. The kernel still calls no LLM, and every new surface is byte-identical when its flag, argument, or config key is absent.
@@ -6675,6 +6715,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.40.0]: https://github.com/itechmeat/open-second-brain/compare/v1.39.0...v1.40.0
[1.39.0]: https://github.com/itechmeat/open-second-brain/compare/v1.38.0...v1.39.0
[1.38.0]: https://github.com/itechmeat/open-second-brain/compare/v1.37.0...v1.38.0
[1.37.0]: https://github.com/itechmeat/open-second-brain/compare/v1.36.0...v1.37.0
diff --git a/README.md b/README.md
index 61667fd8..c60b9a9f 100644
--- a/README.md
+++ b/README.md
@@ -8,9 +8,9 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.39.0 is a context-integrity wave: ten units that turn a silent failure in the read and delivery path into an explicit, named one. Owner scoping now reaches every content-returning surface rather than search alone, and fails closed when a page's ownership cannot be read. Context packs carry a stamp of the vault state they were built from and an expiry, so a stale pack is refused instead of served. Session continuation abstains with a named reason when it cannot tell one candidate from another, and the lineage ledger is hash-chained, locked, and compacted without losing history. A frontmatter line the parser does not understand, an embedding store written against a different model or sqlite-vec ABI, a vault root that is not the one you meant, and a broken-link count that only ever rises are each reported now instead of passing quietly. Two shared seams carry the wave - a closed-vocabulary degradation channel and a stamp-and-compare module whose gates the operator sets to `off`, `warn`, or `fail`. Every new surface is byte-identical when its flag, argument, or config key is absent.
+Open Second Brain 1.40.0 is a no-dead-ends wave: eleven units that make the system say what to do next, do it where the fix is provably mechanical, and refuse by name where it is not. Every issue `o2b brain doctor` reports now carries the exact command that acts on it, on the human surface and as a field over MCP - and where no single command resolves a class, the doctor gives the reason rather than falling silent, so an operator can tell "there is no command for this" from "the system forgot". Terminal states that used to exit zero without a word now name their next move through one rail that a ratchet keeps singular. `o2b brain dream` gained a single-step run and a one-run gate override, so a targeted pass no longer means editing `_brain.yaml` and remembering to revert it; a step that cannot run alone is refused with the coupling named. The dream journal marks a phase complete where its writes actually land instead of before they begin, `_brain.yaml` is generated from the resolver's own defaults so sixteen silently-defaulted keys are visible, and the repair planner consumes the doctor's findings instead of re-scanning behind it. Most of this release is not new machinery: reconnaissance invalidated at least one premise in eight of the ten scoped sources, and what shipped is the delivery of mechanisms that already existed and did not reach the caller.
-Previous release, 1.38.0, added baselining for semantic-health advisories: an optional `health.silence_before` watermark in `_brain.yaml`, managed by `o2b brain health-baseline set <date>|now`, `get`, and `clear`, filters findings whose underlying entries are entirely older than the watermark and always reports how many it hid. Details live in the [CHANGELOG](CHANGELOG.md).
+Previous release, 1.39.0, was a context-integrity wave: owner scoping reached every content-returning surface, context packs gained a provenance stamp and an expiry, session continuation learned to abstain by name, and a frontmatter line the parser cannot read is reported instead of dropped. Details live in the [CHANGELOG](CHANGELOG.md).
## Why
diff --git a/docs/brainstorm/no-dead-ends/cli-output/claude.md b/docs/brainstorm/no-dead-ends/cli-output/claude.md
new file mode 100644
index 00000000..08308393
--- /dev/null
+++ b/docs/brainstorm/no-dead-ends/cli-output/claude.md
@@ -0,0 +1,46 @@
+### Variant 1: Registry as the spine
+
+- **Approach**: Promote `DiagnosticSignal`/`DIAGNOSTIC_SIGNALS` to the single next-step source of truth and demote the other three shapes to projections of it — `RuntimeNotice` drops its prose command and resolves by code, `OnboardingStep.command` and `CheckResult.fix` render from the registry, and `o2b brain doctor` (text and `--json`) emits `nextCommand` for every code it raises. The registry entry additionally names its fixer (replacing `coversDoctorCode`) so `Fixer.plan` consumes detector findings instead of re-scanning, and a shared base is extracted across the 15 finding record types to carry `{code, identity, severity, path, line}`. Units C/D/E/F/H/I/J then each register their exits as registry codes rather than inventing local hints.
+- **Trade-offs**:
+ - Pro: one vocabulary, one place to add a code, and the diagnosis→exit contract is structurally impossible to skip once the registry is the only carrier.
+ - Pro: kills the `Fixer.plan` double-scan outright, which is the one undisputed defect in Unit B, and makes blast-radius guards (`assertExpectedCount`) uniform across all three appliers.
+ - Pro: the "refuse by name" half becomes a registry field, so frontmatter drops, semantic-health `needs-review`, and the coupled dream phases all refuse from the same table as the ones that fix.
+ - Con: a shared finding base collides head-on with `DegradationCode`'s deliberate closure and with three incompatible severity unions; widening them is exactly the reversal the brief forbids without explicit justification.
+ - Con: `DoctorIssue.code` is an unenumerated `string` with ~35 literals inline across 1754 lines — enumerating it is a large mechanical refactor with real risk to the byte-identical constraint on `--json` consumers.
+ - Con: consumes most of the release on Units A and B, leaving C/D/G/H/I/J as thin follow-ons or deferred; the stale command manifest must also be repaired first or terminal-state enumeration silently misses a third of the surface.
+ - Con: three `RuntimeNotice` surfaces (onboarding, SessionStart hook, `vault_health`) change shape at once, so a regression lands in agent context injection rather than in a CLI nobody scripts.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: One advisory rail, four shapes preserved
+
+- **Approach**: Leave all four record types and all 15 finding types alone; unify the *emission point* instead. Add a single advisory-output seam that every next-step line must pass through — it resolves payloads by code from the existing `DIAGNOSTIC_SIGNALS` registry, and it is the one place that knows whether advisory chrome is legal on the current stdout (fixing `wantsJsonFlag`'s raw-argv scan and honouring the `COMMANDS_WITH_INTERNAL_JSON` split). Each existing shape gets a thin adapter into that rail, each of the three appliers publishes a capability descriptor (`mechanical` with a fixer id, or a named refusal), and a census test enumerated from the dispatchers — not the stale manifest — fails until every terminal state is classified as *has exit*, *has named refusal*, or *deliberately silent*.
+- **Trade-offs**:
+ - Pro: gets the whole thesis (machine-readable exit, mechanical fix, named refusal) without touching a single closed vocabulary; `DegradationCode` stays closed and the three severity unions stay separate.
+ - Pro: byte-identical-when-absent is cheap to guarantee, because the rail is additive and the existing prose messages remain the fallback until each code is migrated.
+ - Pro: leaves budget for the smaller units, which are where most of the verified defects actually live — the `lint-consolidate` guard misplacement on a read path, `createProfile`'s silent overwrite and lock-free write, `pending apply`'s missing dry-run, the `null`-ranks-below-`0` defect on the two topK surfaces, dedup counters persisted as a `ContinuityRecord` kind, `project` on the session summary, skill-acceptance frontmatter joined to `recordProceduralOutcome`, `install --check` expected-output blocks with Windows/WSL2 named as an unsupported-path error rather than an unconditional POSIX assumption.
+ - Pro: the census test is the enforcement artifact and matches established precedent, so next release's new verbs cannot silently reintroduce dead ends.
+ - Con: four shapes remain four shapes; the registry becomes the source of truth for *content* but not for *structure*, so a fifth shape is still possible.
+ - Con: `Fixer.plan`'s independent re-scan is corrected only by making the detector's findings the input to the capability lookup, not by a full findings-contract merge — the double-scan shrinks rather than disappears.
+ - Con: the manifest repair is a prerequisite with its own surface (7 missing `search` subverbs, 55 missing `brain` labels, absent `secrets`/`partner`), and it changes shell completions and `o2b help --json` output for real users.
+ - Con: adapters are a per-shape cost, so the cheapest-looking unification is not free.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Conformance obligation only — correct each mechanism in place
+
+- **Approach**: Introduce no shared type and no shared emitter; the only new artifact is a conformance census asserting that every diagnosis-emitting site either names a structural exit, names a refusal, or is listed as deliberately silent with written justification. Each unit is then repaired at its own site under that obligation — `doctor` prints the registry's `nextCommand` for codes it already shares, `RuntimeNotice` gains an optional `command?` field and its stale self-heal text is corrected, `DEFAULT_BRAIN_CONFIG_YAML` is generated from the resolver default tables so the 16-key gap cannot recur, `dream --only` accepts the two provably self-contained steps and refuses the mutually-coupled ones by name, and Unit J refuses both proposed fixes by name while fixing the ranking defect and pointing at the existing `low-evidence-confirmed` signpost.
+- **Trade-offs**:
+ - Pro: lowest risk against the byte-identical and no-silent-fallback constraints; almost every change is additive at one call site with a local test.
+ - Pro: the honest answer to the units where the ticket premise collapsed (D's non-existent phase functions, E's non-existent semantic drop, I's non-existent profile artifact, J's non-existent de-prioritization) is a named refusal, and this variant makes refusal the default posture rather than an exception.
+ - Pro: fits comfortably in one release with room for the two missing CLI-level tests (`brain lint`, `brain hygiene`) and the dream checkpoint honesty fix.
+ - Con: the four incompatible next-step shapes survive intact, so the drift that produced them continues; the next wave inherits the identical Unit A.
+ - Con: a census that permits "named refusal" can be satisfied by writing refusals everywhere, which technically passes the thesis while delivering little forward motion.
+ - Con: `Fixer.plan`'s re-scan and the three divergent write-guard placements go unaddressed, leaving Unit B's genuine architectural defect for later.
+ - Con: without a shared emitter, the JSON-discipline hazard remains per-verb, so a future advisory line on an internal-`--json` verb still breaks `JSON.parse`.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 2
+
+**Rationale**: The verified state says the well-shaped mechanism already exists — `DiagnosticSignal.nextCommand` with a ~20-code registry — and the defect is delivery, not modelling, so unifying the emission point buys the entire thesis while Variant 1 pays for a 15-type findings merge that collides with `DegradationCode`'s deliberate closure and with the byte-identical constraint on three context-injection surfaces. Variant 2 also keeps enough budget for the units where the real, verified bugs are small and local (the read-path vault-identity throw, the silent profile overwrite, the `null`-below-`0` ranking defect, the missing `pending apply` dry-run), which Variant 1 would starve. Variant 3 is safest but leaves Unit A structurally unchanged and lets a census of refusals stand in for the wiring the release is actually about.
diff --git a/docs/brainstorm/no-dead-ends/cli-output/prompt.md b/docs/brainstorm/no-dead-ends/cli-output/prompt.md
new file mode 100644
index 00000000..4af49b41
--- /dev/null
+++ b/docs/brainstorm/no-dead-ends/cli-output/prompt.md
@@ -0,0 +1,223 @@
+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
+
+Ship one release for Open Second Brain under a single thesis: **nothing stops at a diagnosis.** The system must tell the caller what to do next in a machine-readable form, and where a fix is provably mechanical, be able to perform it — and where it is not, refuse by name rather than pretend.
+
+Ten units were selected: nine kanban tasks plus one external GitHub bug report. Reconnaissance against the real code invalidated at least one premise in eight of the ten. What follows is the CORRECTED problem statement, with `path:line` evidence. Treat the corrections as ground truth; the original ticket text is given only where it explains intent.
+
+A note on what makes this brief unusual, and what the variants must therefore reckon with: in almost every unit the mechanism the ticket asks for already exists, and the defect is that it is unwired, prose-only, duplicated three ways, or actively lying. Variants that propose building new subsystems will be wrong. The design space is about which existing seam becomes the single source of truth, and how much unification is worth paying for in one release.
+
+## Unit A — The next-step channel is four incompatible shapes, and the best one is unwired
+
+Verified state:
+
+- `RuntimeNotice` (`src/core/brain/runtime-notices.ts:32-36`) has exactly `{code, severity, message}`. The next command is embedded in English prose inside `message` — e.g. `"Search index is not built yet, so recall returns nothing. Run: o2b search index"` (`runtime-notices.ts:122`). A consumer must regex `/Run: (.+)$/`. Three of its five codes carry no command at all.
+- `DiagnosticSignal` (`src/core/brain/diagnostics.ts:66-76`) HAS a structured `nextCommand: string`, documented "Exact next command to run (a structural CLI string, never prose)". Its registry `DIAGNOSTIC_SIGNALS` (`diagnostics.ts:88-231`) holds ~20 codes. It has exactly two consumers (`operator-snapshot.ts:88`, `diagnostics.ts:514`).
+- `OnboardingStep.command: string | null` (`src/cli/onboarding.ts:33`) is a third shape.
+- `CheckResult.fix?: string` (`src/core/types.ts:27`) is a fourth.
+- `o2b brain doctor` — the verb the ticket names — prints `[ERROR] <code>: <message> (<path>)` and never touches the registry (`src/cli/brain/verbs/doctor.ts:100-110`). Under `--json` it emits `{warnings, errors, uncertain?}` with no command field.
+- Terminal states that print nothing forward: `o2b brain init` (`src/cli/brain/verbs/init.ts:59-63`) — the command that creates the empty `Brain/`; `o2b search index` on success (`src/cli/search.ts:1057`); `o2b search query` with zero hits on an existing index (`src/cli/search.ts:892`); and a family of `brain` empty-state verbs (`pending.ts:64`, `intent-review.ts:31`, `intention.ts:51`).
+- Counter-examples proving the pattern is achievable but hand-written per verb: `o2b brain git status` (`src/cli/brain/verbs/git.ts:60`) and `o2b brain bridges` (`src/cli/brain/verbs/bridges.ts:88,123`).
+- Premise CORRECTED: the ticket claims `o2b search` with no index is a dead end. It is not — `openReadOrSelfHeal` (`src/core/search/search.ts:166-184`) silently builds the index and retries, pinned by `tests/cli/search.test.ts:170-178`. Designing a "run `o2b search index`" hint there would regress a deliberate feature. Relatedly, the `search_index_missing` notice text is now stale — it describes a world self-heal removed.
+- Premise CORRECTED: "OSB has no interactive/TTY mode" is false. `o2b init --interactive` is a stdin wizard (`src/cli/install/init-interactive.ts`) and six brain verbs gate destructive applies on `process.stdin.isTTY`.
+- Premise CORRECTED: notices are not init-only. They reach three surfaces: the onboarding checklist, the SessionStart hook (`hooks/active-inject.ts:292`), and the `vault_health` MCP tool (`src/mcp/tools.ts:224`). What is init-only is `writeSearchInitBlock`, whose own docblock says so (`src/cli/main.ts:202-203`).
+- Discovered, not in any ticket: the CLI command manifest is materially stale, and it is the source of shell completions and `o2b help --json` (`src/cli/completions.ts:24-27`). It models 130 entries. The dispatchers handle more: `secrets` and `partner` are absent at top level; 7 of 14 `search` subverbs are missing; 55 of the `brain` dispatcher's 139 case labels have no entry. Any plan that iterates the manifest to enumerate terminal states silently skips a third of the real surface.
+- Discovered: `wantsJsonFlag` (`src/cli/json-helpers.ts:5-7`) scans raw argv, so `o2b brain note "see --json for details"` is misread as a JSON request.
+- JSON discipline: 12 verbs own an internal `--json` branch (`COMMANDS_WITH_INTERNAL_JSON`, `src/cli/main.ts:891-904`); everything else goes through `withJsonFallback`, which buffers stdout into an envelope. A stray advisory line breaks `JSON.parse` only on the first path. There is no shared "should I print advisory chrome?" helper today.
+
+## Unit B — The fix applier is not keyed off the findings contract
+
+Verified state:
+
+- Premise CORRECTED: `brain lint` is NOT read-only. Its docblock reads "read-only structural drift scan **with optional `--apply` mode that rewrites the smallest possible fix per finding**" (`src/cli/brain/verbs/lint.ts:2-4`); `--apply` writes via `atomicWriteFileSync` (`src/core/brain/lint-consolidate.ts:216,227`).
+- Premise CORRECTED: the two cited "findings with no fix consumer" lines are string literals in MCP schemas — `src/mcp/brain/review-tools.ts:198` is a tool `description`, `src/mcp/brain/health-tools.ts:207` is `enum: ["markdown","json"]`. The `brain_doctor` `repair`/`apply` arguments sit eight lines above at `health-tools.ts:194-203` and dispatch to `applyRepair`.
+- Three Finding→apply pipelines already ship, each with dry-run, audit and the write guard: `applyHygienePlan` (`src/core/brain/hygiene/apply.ts:137`), `applyRepair` (`src/core/brain/diagnostics.ts:564`), `applyRemediation` (`src/core/brain/health/remediation.ts:336`). A blast-radius primitive `assertExpectedCount` (`src/core/brain/count-guard.ts:48`) is wired into the hygiene CLI and MCP paths.
+- The one true statement in the ticket: `Fixer.plan(vault)` (`diagnostics.ts:504`) **re-scans the vault independently**; `runDoctor` supplies only counts of classes no fixer covers (`diagnostics.ts:506-511`). The applier shares codes with the detector via `coversDoctorCode` but does not consume its findings.
+- There are 15 independent finding record types with no shared base. They disagree on the identity field (content hash vs `::`-joined tuple vs none), on severity vocabulary (three different unions), and on whether a code exists at all. `DoctorIssue.code` (`src/core/brain/types.ts:1743-1750`) is an unenumerated `string` with ~35 literals inline across 1754 lines of `doctor.ts`. `DegradationCode` (`src/core/integrity/degradation.ts:105`) is deliberately closed so that adding a member breaks every exhaustive consumer — folding it into a wider union reverses a stated policy.
+- Nothing vault-side carries a structured line number. The frontmatter-drop notice interpolates its line into prose (`src/core/vault.ts:268`), and that number is **1-based within the frontmatter block, not the file**; the offending text is **truncated at 120 chars** (`vault.ts:139-140,311-315`). `DegradationNotice` has four fields: `code, site, path?, detail`.
+- `broken-wikilink` puts the field name and target in prose only (`doctor.ts:1174-1179`); `broken-backlinks` is pushed with no `path` at all (`doctor.ts:1209-1216`). Neither is machine-actionable.
+- Discovered bug: `lintConsolidate` calls `assertVaultIdentityForWrite` unconditionally at `lint-consolidate.ts:172`, before the `apply` branch. `o2b brain actions`, a read-only ranking verb, calls `lintConsolidate(vault, {apply:false})` (`src/cli/brain/verbs/actions.ts:32`) and can therefore throw `VaultIdentityMismatchError` on a pure read.
+- Discovered inconsistency: three appliers place the write guard three different ways — after the dry-run return (hygiene, with a stated rationale at `apply.ts:152-155`), before it (repair), unconditionally including dry-run (remediation).
+- Discovered gap: `brain pending apply` (`src/core/brain/pending.ts:126-135`) has no dry-run — the one approval-queue path lacking the preview every other applier has.
+- Which findings are provably mechanical is already answered by the code: six classes have fixers (merged-link rewrite, stale-stable demotion, wal-gap, orphaned `_evidenced_by` reference, content-hash restamp, wide permissions). Frontmatter drops are NOT mechanically fixable — the parser is line-based, so a dropped line is by definition grammar it has no branch for, and repair requires choosing a target grammar per shape. Semantic-health findings are hard-coded `needs-review` with a stated rationale (`health/remediation.ts:15-18,228-254`). "Stale scope keys" (from the ticket) does not exist as a finding kind anywhere.
+- Hard constraint: `tests/core/brain/vault-guard-census.test.ts` walks `src/core/brain/`, and fails naming any module that calls a write primitive without `assertVaultIdentityForWrite` or `brainDirsForWrite`, unless listed in `UNGUARDED_WITH_REASON` with a written justification.
+- Coverage gap: neither `o2b brain lint` nor `o2b brain hygiene` has a CLI-level test today.
+
+## Unit C — `brain init` writes a template that hides 16 of 23 config keys
+
+Verified state:
+
+- `DEFAULT_BRAIN_CONFIG_YAML` (`src/core/brain/policy.ts:596-640`) emits 7 top-level keys. The resolver understands 23. Sixteen resolve silently from defaults: `active, lessons, discipline_report, guardrails, rollup, link_graph, temporal, health, integrity, notes, sessions, schema, hygiene, anticipatory, recall, feedback`. Two sub-keys inside templated blocks are likewise invisible (`dream.heal_enrich_enabled`, `retire.confirmed_evidence_min_threshold`). The `integrity:` block from the previous release is not the exception the ticket frames it as — it is the newest member of a 16-key set, so the ticket understates the surface roughly eightfold.
+- The template is a hand-maintained string constant; the defaults live in separate resolver tables (`BRAIN_GUARDRAIL_DEFAULTS` `policy.ts:143`, `BRAIN_INTEGRITY_DEFAULTS` `policy.ts:346`, and peers). Nothing keeps the two in sync — the 16-key gap is the accumulated drift.
+- Premise CORRECTED: the two link-style settings the ticket wants to autodetect are NOT in `_brain.yaml`. `wiki_link_format` (`src/core/config.ts:580-590`) and `link_output_format` (`src/core/config.ts:370-375`) live in the machine-level plugin config. A per-vault autofit needs either a move or a vault-side override — an architectural decision the ticket does not acknowledge.
+- No `_brain.yaml` key exists for date format, frontmatter key naming, or path/case convention. Date format is hard-coded (`src/core/brain/time.ts:18,25`).
+- Detectors the ticket assumes: setext headers — does not exist anywhere in `src/`. Filename-case collisions — does not exist. CRLF — only ever tolerated, never reported. Unresolved links — `normalizeWikilinks` reports `ambiguous[]` only; a target resolving to nothing is silently left alone (`src/core/brain/link-graph/format-wikilink.ts:155`).
+- Chicken-and-egg: `resolveVaultScope` reads `<vault>/Brain/_brain.yaml` (`src/core/vault-scope/index.ts:107`) — the file init is about to create. Detection at init time runs under `DEFAULT_SCOPE`, i.e. against the wrong exclusions on the very run meant to learn the vault's conventions.
+- Precedent for surgically writing one key into an existing `_brain.yaml` without disturbing the rest: `applyHealthSilenceBeforeToYaml` (`src/core/brain/health-baseline.ts:81`) — a pure string transform preserving CRLF, indent width and unrelated blocks byte-for-byte, committed under `withFileLock` + `atomicWriteText`.
+- Preview precedent: `o2b brain links normalize` is already dry-run-by-default over the whole vault with per-file change counts, applying only on `--write` (`src/cli/brain/verbs/links.ts:83-85,102-111`). Note its write is `writeFileSync`, not atomic — an existing bug not to replicate.
+- Discovered: `o2b brain init` does not create `Brain/pending/` or `Brain/entities/` although both are declared in `BrainDirs` (`src/core/brain/paths.ts:168,172`); the mkdir loop covers 8 of 10 (`init.ts:232-241`). Downstream writers create them lazily.
+
+## Unit D — Dream's five "phases" are a reporting label, not an execution architecture
+
+Verified state:
+
+- The ticket asks to run one dream phase ad-hoc. There are no phase functions. `DREAM_PHASE` (`src/core/brain/dream-phases.ts:19-26`) names five labels (`close, reconcile, synthesize, heal, log`) whose metrics are assembled at `dream.ts:896-919` **after** all work is done, by reading counters out of objects computed by entirely different functions. The module's own comment says it "only names the existing seams".
+- `planRefresh` and `planAutoRetires` are two-way mutably coupled: `planRefresh` pushes into `plan.retires` (`dream-refresh.ts:225-231`), and `planAutoRetires` deletes entries from `refresh.updated` (`dream.ts:1486,1535,1557`) so a preference is never both refreshed and retired. Running `planRefresh` alone with writes enabled is a data-correctness bug, not a missing feature.
+- Only two steps are genuinely self-contained: `scanBrain` (a pure read) and the opt-in `runHealEnrichment`.
+- The ticket's stated motivation is precise and achievable: "without the stateful, error-prone dance of toggling phase gates and remembering to revert them." The gates are real config booleans (`dream.heal_enrich_enabled` and peers) that an operator edits in `_brain.yaml` and must remember to revert.
+- Discovered: the workrun checkpoints lie. Three (`cluster_complete, close_complete, reconcile_complete`) are appended in one burst at `dream.ts:465-471` **before any preference is written**; four more (`promote_complete, synthesize_complete, retire_complete, heal_complete`) in another burst at `dream.ts:681-690` **after every mutation completed**. A crash during the actual writes leaves a journal claiming "reconcile complete" while promote/retire/heal were mid-flight. `scanDanglingWorkruns` reports it as forensic evidence and nothing resumes or rolls back.
+- Discovered: the `DreamOptions` docstring (`dream.ts:273-278`) claims safeguard checkpoints at "pre-mutation, post-promote, pre-finalize". The code has one call at `dream.ts:680` doing double duty; nothing checkpoints before `workrun?.finalize()` at `dream.ts:889`, leaving log writes, rollup ledger persistence, snapshot pruning and active/lessons regeneration unguarded.
+- `dryRun` is honoured completely: every planning step runs unconditionally, every filesystem mutation is inside `if (!dryRun)`. No exceptions found.
+- 12 call sites pass either nothing, `{dryRun:true}`, or a safeguard. A new optional field is additive for all of them, but there is no existing precedent for a partial-pipeline call to model a contract on.
+
+## Unit E — Dedup counts exist, die one call later, and the semantic half of the ticket describes nothing
+
+Verified state:
+
+- Premise CORRECTED: semantic dedup never drops anything, anywhere. Two embedding-cosine layers exist — `detectSemanticDedup` (threshold 0.97, `src/core/brain/hygiene/detectors/dedup.ts:119,32`) and `detectEntityAliasCandidates` (threshold 0.92, `src/core/brain/entities/semantic-dedup.ts:298,37`) — and both are explicitly opt-in, proposal-only nomination systems by design comment. The ticket's rationale ("a spike in semantic dedup means knowledge is being silently discarded") describes a mechanism this codebase does not have.
+- Every path that actually drops an item during ingest uses only an exact sha256: `emitSignal` (`src/core/brain/session-lifecycle.ts:597-603`), `scanInline` (`src/core/brain/inline-scan.ts:152-165`), `routeFacts` (`src/core/brain/fact-extract.ts:180-184`).
+- Those counters already exist (`signals_deduped`, `facts_deduped`, `deduped`) and already reach CLI text, `--json` and MCP responses — but they are **ephemeral**: threaded exactly one call deep and then gone. Nothing is persisted, so a spike over time cannot be observed. That is the real gap.
+- Premise CORRECTED: the ticket's hint file (`DedupReport` at `src/core/brain/page-dedup.ts:51-55`) is the wrong target — it belongs to the unrelated page-merge nomination flow.
+- The native persistence pattern for a queryable counter is an append-only `ContinuityRecord` of a fixed `kind` (`src/core/brain/continuity/types.ts:59-74`), emitted through `emitGatedTelemetry` (`continuity/emit.ts:27-37`), read back through a `summarize*` aggregator and exposed via `brain_analytics`. `generation_report` (`src/core/brain/generation-reports.ts:82-113,165-181`) is the closest working model.
+
+## Unit F — Project scope on session summary already has a home
+
+Verified state:
+
+- Premise CORRECTED: the project dimension is already fully built. `SCOPE_AXES = ["owner", "session", "project"]` and `CompositeScope` (`src/core/scope-key.ts:26-34`); read from the literal frontmatter key `project` (`scope-key.ts:59`); normalized by the same slug rule as `session` (`session-scope.ts:26-41`); already folded into the page-dedup key; already an MCP filter `project_scope` on `brain_search` (`src/mcp/search-tools.ts:183-186,549-556`); already in the activation half-life table (`src/core/search/activation/decay.ts:35`).
+- Premise CORRECTED: `buildSessionSummaryDigest` does not exist. The real write path is `appendSessionSummary` (`src/core/brain/session-summary.ts:64-112`), which validates, refuses an all-empty digest, computes a dedupe key and appends a `session_summary_digest` continuity record.
+- `SessionSummaryInput` (`session-summary.ts:32-44`) and `SessionSummaryDigest` (`:46-55`) indeed have no project field.
+- A distinct, unrelated concept shares the word: `o2b brain project link|list|remove|status` links a code-project directory to its owning vault at the config level. Do not conflate.
+- The `brain_session_summary` MCP tool (`src/mcp/brain/synthesis-tools.ts:307-353`) validates optional args ad hoc rather than through the shared `coerceStringOptional` helper that `search-tools.ts` uses for `project_scope`.
+
+## Unit G — The install runbook and its verification already exist; the gap is different
+
+Verified state:
+
+- Premise CORRECTED: verification is the best-developed part of the system, not the missing one. All 9 registered adapters implement `verify(env): VerifyResult` (interface-mandated, `src/core/install/types.ts:139-148`), wired to `o2b install --check` with documented exit codes (0 clean, 3 drift, 4 user-modified-block) at `src/cli/install/install.ts:238-270`, JSON output, drift detection against the canonical payload, and an optional live MCP handshake probe for the four JSON-MCP adapters.
+- Premise CORRECTED: an agent-followable runbook already exists — `install.md` (router, with a readiness checklist at `:88-113` explicitly telling an agent what "not done" means) plus `install/prerequisites.md` plus one `install/<runtime>.md` for each of 9 adapters and 4 pipeline-hosted runtimes. Building a new runbook would ship a second competing document.
+- The genuine gaps, narrowly: (a) no doc shows a literal expected-output block for `o2b install --check`, so the agent has nothing to pattern-match against — the docs say "run this" but never "and this is what success looks like"; (b) Windows/WSL2 is absent from both code and docs. `defaultConfigPath()` (`src/core/config.ts:45`) is unconditionally POSIX `~/.config/open-second-brain/config.yaml` with no `%APPDATA%` branch, and no code translates between a WSL2 `/mnt/c/...` mount and a native `C:\...` path. A repo-wide grep for windows/wsl across the docs returns zero matches.
+- Adapters are constructor-injected with `home`, `vault`, `env`, `cwd`, `now` (`types.ts:56-62`) rather than reading the real environment, so tests never touch host config — that same injection makes a documented-output assertion testable.
+
+## Unit H — Skill acceptance writes a contract with no prerequisites, no rollback, no verification
+
+Verified state:
+
+- `acceptSkillProposal` (`src/core/brain/skill-proposals.ts:272-351`) writes two files: an accepted-proposal archive and a materialized procedure at `Brain/procedures/proc-<slug>.md`. Neither frontmatter object contains `prerequisites`, `rollback`, `side_effects` or `verification` — verified by full read and grep. The procedure body is templated boilerplate (`renderProposalBody`, `:724-746`).
+- Evidence provenance: the accept path copies `evidence_count`/`confidence` straight from the candidate's own pattern-match support. Nothing resolves that against an independently recorded outcome.
+- Decisive finding — a real, joinable outcome source EXISTS, so no stub is needed. `recordProceduralOutcome` (`src/core/brain/procedural-memory.ts:176-209`) records host-supplied `success`/`failure` (never inferred), persisted as `successCount`/`failureCount` on a `ProceduralMemoryEntry` plus a `usage.jsonl` sidecar, written through the `brain_procedural_memory` `mark_outcome` MCP operation. The join key is derived from the slug with no lookup: `pmem-<sha256("Brain/procedures/proc-<slug>.md").slice(0,12)>` (`procedural-memory.ts:296-298`). `acceptSkillProposal` itself already causes that entry to exist, by calling `reconcileProceduralMemory` immediately after writing the procedure (`skill-proposals.ts:339-341`).
+- Ruled out as evidence sources with evidence: the lineage ledger from the previous release (session identity, not outcome — its own docblock says it exists for one consumer); `context_pack_outcome` (no skill/procedure reference); `brain_eval` (aggregate benchmark); `brain_recall_feedback` (search relevance). `recall_observed_use` and `brain_apply_evidence` join only incidentally through a free-text path nobody is required to populate.
+- Note the trap: `skill-usage.ts:10` says the dream pass ranks skills "on real evidence", but that evidence is invocation frequency and recency from `skill_invoked` records — not success or failure. Citing it as outcome evidence would be citing the wrong source.
+- Would new fields be write-only decoration? `collectEntries` (`procedural-memory.ts:223-240`) reads `triggers`, `tags`, `permissions`, `source`, `version` from procedure frontmatter and nothing else. New fields are inert until it is extended — a one-line-per-field additive change matching the existing pattern.
+- Atomicity: each file write is exclusive-atomic, and there is a compensating rollback if the procedure write throws. Three gaps remain: a crash (not an exception) between the two writes; an uncaught `unlinkSync(pendingPath)` at `:338` leaving both pending and accepted copies; and uncaught projection rebuilds at `:339-343` leaving stale indexes. The risk class is duplicate/orphaned state and stale projections, not torn files.
+
+## Unit I — The profile scaffolder ticket points at an artifact that does not exist
+
+Verified state:
+
+- Premise CORRECTED, twice over. The repository has **five** unrelated concepts named "profile", and the ticket's two hints point at different ones. `ProfileDoc` (`src/core/brain/profile-doc.ts:26-29`) is `{text, generatedAt}` — a rendered-document envelope for a machine-generated digest whose own body says "Auto-generated digest. Do not edit" (`:62`). There is no entity, no id, no schema. `profile init <id> --entity <type>` has no target, and the ticket's motivation ("profiles are authored in-vault by hand") is false.
+- The real bug of exactly the shape the ticket asks for lives in the file it did not name. `createProfile` (`src/core/brain/portability/profiles.ts:99-106`) **silently overwrites** an existing registry entry (`data.profiles[trimmed] = {vault}`), performs no directory check at create time (only `switchProfile` does, `:126-128`), and does a lock-free read-modify-write of `profiles.json` — so two concurrent creates lose an update. That is "refuses to overwrite" plus "serializes concurrent mutations", verbatim.
+- Every primitive the ticket asks for already exists and is conventional: `atomicCreateFileSyncExclusive` (`src/core/fs-atomic.ts:127`) is race-free refuse-to-overwrite via `link(2)`; `writeFrontmatterAtomic(..., {overwrite:false, existsErrorKind})` (`src/core/vault.ts:388`) is its ergonomic wrapper; `withTempFile` already unlinks partial output on failure; `withFileLock` (`src/core/reliability/lock.ts:22`) and `acquireLockSync` (`src/core/brain/sync-lockfile.ts:65`) cover async and sync serialization. `src/core/brain/entities/registry.ts:170-173` is a working end-to-end example of validate → refuse-overwrite → atomic-create.
+
+## Unit J — GitHub issue #149: a reported cold-start deadlock whose load-bearing half does not exist
+
+External bug report (issue #149, `Confirmed preferences with 0 evidence get stuck at 0.00 confidence`). The reporter claims: `brain_feedback(force_confirmed=true)` creates a confirmed preference with `_applied_count: 0` and `_last_evidence_at: null`; the Wilson lower bound divides by zero; freshness is zero; the result is 0.00; a 0.00-confidence preference is de-prioritized in context, so it is rarely applied, so it never accumulates evidence — a deadlock. Two fixes are proposed: (A) write one implicit apply-evidence event at force-confirm time, giving n=1 and ~0.21; (B) return `BASELINE_CONFIDENCE * freshness` when n=0, with freshness decaying from confirmation time.
+
+Verified state:
+
+- CONFIRMED: a `force_confirmed` preference does settle at `value = 0`, `band = low`, and nothing but an apply-evidence event can move it. `computeConfidence` (`src/core/brain/confidence.ts:38-78`) has exactly one production caller, `planRefresh` (`src/core/brain/dream-refresh.ts:279`), driven entirely by the log.
+- Premise CORRECTED: there is no division by zero. `confidence.ts:47` guards `if (n > 0)`; `wilsonLow` keeps its initializer. The zero is the product of two independent zeros — `wilsonLow = 0` AND `freshness = 0` — either sufficient on its own. A fix that only handles `n = 0` still yields `x * 0 = 0`.
+- Premise CORRECTED, and this is the load-bearing one: the de-prioritization does not exist on the primary surface. `Brain/active.md` filters only on `status === confirmed` with no confidence cutoff and no top-N (`src/core/brain/active.ts:148-157`), renders every confirmed preference (`:324,329`), and sorts by **band, not value** (`:446-452`). Both proposed values (0.2065 and 0.25) sit below `medium_min = 0.40`, so **neither fix would move the preference one position in the injected context.** Budget truncation drops whole lower-priority sections before touching Confirmed (`src/core/brain/active-budget.ts:33-40`, `src/core/brain/text/text-budget.ts:119-138`). The feedback loop the reporter describes has no code path. It is real only for `brain_pre_compress_pack` and `brain_brief`, two topK-limited secondary surfaces.
+- Premise CORRECTED: the initial on-disk value is `null`, not `0`. `preferenceFrontmatter` emits the literal `"null"` when the field is absent (`src/core/brain/preference.ts:494-498,525`), and neither force-confirmed writer passes it (`src/mcp/brain/feedback-tools.ts:202-212`, `src/cli/brain/verbs/feedback.ts:124-138`). `0` appears only after the first dream pass rewrites the file.
+- Discovered defect, not in the report: `null` ranks WORSE than `0`. Two surfaces map it to negative infinity — `pref.confidence_value ?? Number.NEGATIVE_INFINITY` at `src/core/brain/pre-compress-pack.ts:104` and `src/core/brain/morning-brief.ts:87` — then sort descending and slice to `topK` (`pre-compress-pack.ts:146-153`, `morning-brief.ts:161,165`). `src/core/brain/dream.ts:498-502` already pre-seeds new unconfirmed preferences with an explicit `0` for precisely this reason, with a comment saying `null` reads as "needs update".
+- Discovered defect, not in the report: the `force-confirmed` log event (`feedback-tools.ts:217-224`) carries `preference` and `agent` but no `result` field, and `scanApplyEvidence` requires a `result` in `{applied, violated, outdated}` (`dream-refresh.ts:129-138`). There is already an audit record of the force-confirm that the confidence pipeline is structurally unable to see.
+- The normal promotion path is gated on at least one `applied` event (`dream-refresh.ts:236-240`, `firstApplied` at `:213`), so n >= 1 there — the reporter is right about that. But its own first pass computes `computeConfidence(1, 0, fresh) = 0.2065`, also `low`. A young preference sitting at a tiny value in the low band is the normal, intended state; `force_confirmed` differs only in that its number is 0 rather than 0.21, in the same band.
+- Retirement does not read confidence at all. `dream.ts:1511-1519` retires a confirmed preference with no evidence at `stale_evidence_days` (default 90) measured from `confirmed_at`, with a comment reading "Confirmed with no evidence at all? Shouldn't happen". Force-confirmed preferences have been hitting that branch all along. `pinned: true` is the existing opt-out. So Option B's claimed safety net already exists and neither option changes retirement.
+- A cold-start visibility mechanism already exists and is not a number: `doctor.ts:1323-1345` reports `low-evidence-confirmed` for exactly this population — confirmed, `applied_count <= confidence.low_max_applied` (default 2), older than `dream.unconfirmed_window_days` — with the message "The rule hasn't seen real use — review or retire."
+- No cold-start provision exists in the formula: no additive smoothing, no prior, no floor, no `n === 0` special case. `confidence.ts:18-19` documents the hard zero deliberately.
+- Option A's cost, verified: `applied_count` stops meaning "times this rule was applied to real work". It would corrupt the most-applied ranking (`src/core/brain/most-applied.ts`), the "Recent applications" body section, the outcome-regression success/failure ratio (`dream-refresh.ts:287-294`), and would consume one of the two-event budget the `low-evidence-confirmed` doctor warning relies on. It also violates the contract stated in `src/core/brain/apply-evidence.ts:3-8`, which defines an apply-evidence row as the canonical durable signal that a preference was exercised against real work.
+- Option B's cost, verified: `computeConfidence` cannot see `confirmed_at`, so the proposal's freshness anchor is out of scope and would need a sixth parameter plus an undefined answer for unconfirmed preferences. It breaks two assertions outright (`tests/core/brain.confidence-value.test.ts:25-28`, `tests/core/brain/dream-modules.test.ts:29-33`) and introduces permanent churn: a decaying baseline drifts about 1e-4 per hour against a 1e-6 no-op threshold (`dream-refresh.ts:322-323`), so every dream pass would rewrite every zero-evidence preference, bumping `_revision` and emitting log and edit-history rows forever.
+- Test blast radius: only two hard-coded numeric confidence assertions exist repo-wide, and 27 files assert bands rather than values.
+
+The design question for this unit is therefore not "which of A or B", but: what is the honest fix when a reported deadlock turns out to be a real but cosmetic zero plus a genuine ranking defect plus a missing signpost — given that this release's whole thesis is that a diagnosis must name its exit rather than fabricate its way out of one.
+
+# Project context
+
+Open Second Brain — TypeScript on Bun, a CLI plus an MCP server (108 tools) over an Obsidian-compatible Markdown vault. The kernel is deterministic and makes no LLM calls. The vault is plain Markdown replicated peer-to-peer via Syncthing; there is no git transport for the vault.
+
+Recent commits:
+
+```
+f91a698b feat: context integrity gates (v1.39.0) (#150)
+c31a2574 feat: semantic-health baseline watermark (v1.38.0) (#148)
+b0c37977 feat: retrieval quality and context delivery (v1.37.0) (#146)
+842d690f feat: knowledge intake and consolidation (v1.36.0) (#145)
+95dc8577 feat: trusted recall and memory write surface (v1.35.0) (#144)
+426d06f8 fix(vault): parse block-style YAML lists in frontmatter (#142)
+4b8100ca feat: source pipeline integrity and operator tooling (v1.34.0) (#143)
+77513f2b feat: belief lifecycle and decision memory (v1.33.0) (#141)
+61e93d24 fix(config): derive vault store reference from a keyed installation secret (#140)
+9a649dd6 feat: memory write-path integrity and store safety wave (v1.32.0) (#139)
+f2a037eb feat: today operator surface - dashboard, open loops, marker write-back (v1.31.0) (#138)
+13bde6c3 refactor: remove all import cycles, decompose search.ts (v1.30.1) (#137)
+fd5661f9 feat: governance visibility - vitals scorecard + batch-inflation lint (v1.30.0) (#136)
+70fb36e1 feat: operability, safety & first-run experience (v1.29.0) (#134)
+ac26a675 feat: retrieval & ranking quality (v1.28.0) (#133)
+99adb65f feat: ingestion & import robustness (v1.27.0) (#132)
+```
+
+The immediately preceding release (v1.39.0) established two shared seams this wave will sit next to:
+
+- a closed-vocabulary degradation channel (`DegradationCode`, `src/core/integrity/degradation.ts`) whose closure is enforced by design so that adding a member breaks exhaustive consumers;
+- a stamp-and-compare module with `off | warn | fail` gate modes, and an `integrity:` config block resolving from defaults.
+
+Related files, by unit:
+
+- A: `src/core/brain/runtime-notices.ts`, `src/core/brain/diagnostics.ts`, `src/cli/onboarding.ts`, `src/cli/brain/verbs/doctor.ts`, `src/cli/command-manifest.ts`, `src/cli/json-helpers.ts`, `src/cli/main.ts`, `src/mcp/brain/health-tools.ts`
+- B: `src/core/brain/diagnostics.ts`, `src/core/brain/hygiene/{types,scan,plan,apply}.ts`, `src/core/brain/health/remediation.ts`, `src/core/brain/lint-consolidate.ts`, `src/core/brain/doctor.ts`, `src/core/brain/types.ts`, `src/core/integrity/degradation.ts`, `src/core/vault.ts`, `src/core/brain/pending.ts`, `src/core/brain/count-guard.ts`
+- C: `src/core/brain/init.ts`, `src/core/brain/policy.ts`, `src/core/brain/health-baseline.ts`, `src/core/vault-scope/index.ts`, `src/core/config.ts`
+- D: `src/core/brain/dream.ts`, `src/core/brain/dream-refresh.ts`, `src/core/brain/dream-phases.ts`, `src/core/brain/dream-workrun.ts`, `src/core/brain/safeguard.ts`
+- E: `src/core/brain/session-lifecycle.ts`, `src/core/brain/inline-scan.ts`, `src/core/brain/fact-extract.ts`, `src/core/brain/continuity/{types,emit,store}.ts`, `src/core/brain/generation-reports.ts`
+- F: `src/core/brain/session-summary.ts`, `src/core/scope-key.ts`, `src/core/brain/session-scope.ts`, `src/mcp/brain/synthesis-tools.ts`, `src/mcp/coerce.ts`
+- G: `src/core/install/{types,registry,identity}.ts`, `src/core/install/adapters/*.ts`, `src/cli/install/install.ts`, `src/core/config.ts`, `install.md`, `install/*.md`
+- H: `src/core/brain/skill-proposals.ts`, `src/core/brain/procedural-memory.ts`, `src/mcp/brain/procedure-tools.ts`
+- I: `src/core/brain/portability/profiles.ts`, `src/core/fs-atomic.ts`, `src/core/reliability/lock.ts`, `src/core/brain/entities/registry.ts`
+- J: `src/core/brain/confidence.ts`, `src/core/brain/dream-refresh.ts`, `src/core/brain/preference.ts`, `src/mcp/brain/feedback-tools.ts`, `src/cli/brain/verbs/feedback.ts`, `src/core/brain/pre-compress-pack.ts`, `src/core/brain/morning-brief.ts`, `src/core/brain/doctor.ts`, `src/core/brain/apply-evidence.ts`
+
+Conventions:
+
+- `package.json` `version` is the single source of truth, mirrored into seven manifests by `scripts/sync-version.ts`; CI gates on `--check`. The bump rides inside the feature pull request.
+- One pull request equals one CHANGELOG version, which may bundle many atomic units.
+- Every commit must pass, in the foreground: format, lint (an exact baseline of 134 warnings and 0 errors), typecheck, the full test suite (7260 passing today), the version-sync check, and a link-rot ratchet.
+- Tests use `bun:test`, build throwaway vaults with `mkdtempSync`, inject a config path so the real environment is never touched, and inject clocks rather than mocking time.
+- Writes under `src/core/brain/` must carry the vault-identity guard or be listed with a written justification; a census test enforces this.
+- A census/matrix test that fails until a new surface is classified is an established pattern in this codebase (the previous release added one partitioning all 108 MCP tools).
+
+Constraints:
+
+- Every new surface must be byte-identical when its flag, argument or config key is absent. Existing callers must not change behaviour.
+- No stubs. No fallback that silently does nothing — if something cannot be done, it must fail with a named, specific error rather than degrade quietly.
+- No hardcoded natural-language word or phrase lists in any language. Detection and classification must use structural signals, explicit fields, or corpus statistics — never a list of English (or any other) words.
+- The kernel makes no LLM calls; everything here must be deterministic and model-free.
+- Do not introduce a new external dependency.
+- Do not reverse the deliberate closure of `DegradationCode` without saying so explicitly and justifying it.
+- Do not build a second install document, a second fix applier, or a second next-step registry alongside an existing one. Where a mechanism already exists, the work is to wire, unify or correct it.
+- The vault has no git transport; do not propose vault-side git.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### 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 three variants, add exactly one recommendation:
+
+### 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/no-dead-ends/design.md b/docs/brainstorm/no-dead-ends/design.md
new file mode 100644
index 00000000..f5b6f485
--- /dev/null
+++ b/docs/brainstorm/no-dead-ends/design.md
@@ -0,0 +1,249 @@
+# No dead ends - every diagnosis names its exit, and performs it where the fix is mechanical
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain is driven by agents that know only what the last command printed.
+A verb that exits zero without saying what to run next is a dead end for such a
+caller, and a diagnosis that names a defect without naming its repair costs a
+round-trip in which the agent re-derives the fix non-deterministically.
+
+The system already knows the answer in several places. `DiagnosticSignal.nextCommand`
+is a populated registry of structural CLI strings, documented as "never prose", with
+two consumers. Three Finding-to-apply pipelines already ship, each with a dry run, an
+audit trail and the vault-identity write guard. What is missing is not machinery. It
+is that the answer does not reach the caller: it is embedded in English prose, or
+modelled four incompatible ways, or computed and discarded one call later, or - in two
+places found during reconnaissance - reported as complete when it is not.
+
+Reconnaissance against the real code invalidated at least one premise in eight of the
+ten selected units. This design is written against the corrected picture. Where a
+ticket asked for a subsystem that already exists, the unit is re-scoped to the defect
+that actually exists; where it asked for behaviour the codebase deliberately does not
+have, the unit refuses by name and says so in the release notes.
+
+## Scope
+
+Ten sources - nine kanban tasks and one external GitHub issue - decompose into eleven
+scope items, sharing two seams. The count differs because reconnaissance split the
+no-dead-end audit in two: the delivery of next steps, and the repair of the command
+manifest those steps would otherwise be enumerated from. The manifest defect was found
+during that audit and is not in any ticket.
+
+**Seam 1 - the advisory rail.** A single emission point through which every
+forward-pointer line passes. It resolves a payload by code from the existing
+`DIAGNOSTIC_SIGNALS` registry rather than carrying prose, and it is the one place that
+knows whether advisory chrome is legal on the current output stream. The four existing
+next-step shapes keep their types and gain thin adapters into the rail.
+
+**Seam 2 - the applier capability table.** One table stating, per finding code,
+whether repair is mechanical (naming the fixer) or refused (naming the reason). The
+three existing appliers publish into it rather than each deciding privately.
+
+Units:
+
+- **A. Next-step delivery.** Route `o2b brain doctor` (human and JSON) and MCP
+ `brain_doctor` through the rail so every issue carries its structural next command.
+ Give `RuntimeNotice` an optional structured command and stop embedding "Run: X" in
+ prose. Correct the `search_index_missing` notice, whose text describes a world that
+ self-heal removed. Cover the terminal states that print nothing forward, beginning
+ with `o2b brain init` - the command that creates the empty Brain.
+- **B. Manifest completeness.** Repair the command manifest, which is the source of
+ shell completions and `o2b help --json` and is missing two top-level verbs, seven
+ search subverbs and fifty-five brain cases. Add a ratchet test enumerated from the
+ dispatchers, not from the manifest, so a new verb cannot be added without an entry.
+- **C. Applier correctness.** Publish the capability table. Make `planRepair` consume
+ the doctor's findings instead of re-scanning the vault independently. Unify the three
+ divergent write-guard placements behind one documented rule. Fix the read-path throw:
+ `lintConsolidate` asserts vault identity before its apply branch, so the read-only
+ `o2b brain actions` verb can fail with a write-path error. Give `brain pending apply`
+ the dry run every other applier has. Make `broken-wikilink` and `broken-backlinks`
+ machine-actionable, since today the field name and target exist only in prose and the
+ backlink issue carries no path at all.
+- **D. Config template drift.** Generate `DEFAULT_BRAIN_CONFIG_YAML` from the resolver
+ default tables, so the sixteen keys that resolve silently from defaults become
+ visible, and add a ratchet test so the drift cannot recur. Create the two Brain
+ directories `init` declares but does not make.
+- **E. Dream honesty.** Add a per-run gate override so an operator can run a targeted
+ pass without editing the vault config and remembering to revert it. Make the workrun
+ checkpoints truthful: today three are appended before any preference is written and
+ four after every mutation completes, so a crash mid-write leaves a journal claiming
+ work that had not started. Add the safeguard checkpoint the docstring already
+ promises before finalize. Refuse a request for a phase that is not independently
+ runnable, by name, rather than silently running more than was asked.
+- **F. Dedup observability.** Persist the exact-hash ingest dedup counts as a
+ continuity record so a trend is observable, instead of threading them one call deep
+ and discarding them. Report the semantic layers as what they are - nominations, never
+ drops - rather than inventing the drop counter the ticket assumed.
+- **G. Project scope on session summaries.** Thread the existing `project` scope axis
+ through `SessionSummaryInput`, the digest and the MCP tool, reusing the established
+ normalization rather than introducing a parallel dimension.
+- **H. Install verification you can assert against.** Add expected-output blocks to the
+ Verify section of every per-runtime install document, and a test that fails when a
+ documented block stops matching what the adapter's `verify()` actually returns. Make
+ the POSIX-only configuration path an explicit, named refusal on platforms it does not
+ serve, instead of an unconditional assumption.
+- **I. Skill contract completeness.** Write prerequisites, rollback, side effects and
+ verification on acceptance, and read them back, so they are a contract rather than
+ decoration. Resolve a proposal's claimed evidence against the independently recorded
+ procedural outcome ledger, joined by a key the accept path already causes to exist.
+ Close the three atomicity gaps in the accept sequence.
+- **J. Profile registry safety.** Make `createProfile` refuse to overwrite an existing
+ entry, validate the target directory at create time rather than only at switch time,
+ and serialize concurrent mutations. Every primitive required already exists.
+- **K. Issue #149, the cold-start report.** Fix the real defect the report missed - the
+ confidence value is written as null, and null ranks below zero on the two surfaces
+ that rank on it. Name the exit rather than fabricating evidence: the doctor already
+ detects this exact population and needs only its next command. Refuse both proposed
+ fixes, by name, with the measured reason.
+
+## Out of scope
+
+- **A shared base type across the fifteen finding record types.** A real debt. It
+ collides with the deliberate closure of `DegradationCode`, whose closure is the point,
+ and it would change the shape of three context-injection surfaces at once. Not
+ required by this release's thesis.
+- **Enumerating `DoctorIssue.code`.** Approximately thirty-five string literals inline
+ across one large module. A prerequisite for any future applier keyed on doctor codes,
+ and worth its own change.
+- **Auto-repair of dropped frontmatter lines.** The parser is line based, so a dropped
+ line is by definition grammar it has no branch for, and repair requires choosing a
+ target grammar per shape. This is a policy choice, not a mechanical fix, and the
+ release refuses it by name rather than guessing.
+- **Wiring a semantic dedup layer into an ingest path as an auto-drop.** That is the
+ only way to make the ticket's exact-versus-semantic drop split real, and it is a
+ behaviour change far larger than adding a counter.
+- **Per-vault link-format settings.** The two link-style settings live in the machine
+ level plugin configuration, not the vault configuration. Moving them is an
+ architectural decision that deserves its own change.
+- **Convention autofit at init.** Setext-header and filename-case detectors do not
+ exist, the two settings a detector would target are not vault-side, and the walker's
+ exclusion policy is read from the very file `init` is about to create. The unit is
+ re-scoped to the drift that is real and measurable.
+- **A dream phase selector for coupled phases.** `planRefresh` and `planAutoRetires`
+ mutate each other's accumulators specifically so a preference is never both refreshed
+ and retired. Running one alone with writes enabled is a data-correctness bug.
+- **Changing the confidence formula.** Measured cost exceeds the benefit; see the
+ design decision below.
+- **A second install document.** One already exists and is agent-directed.
+
+## Chosen approach
+
+Variant 2 from the consultant, with two grafts. See
+[`variants.md`](variants.md) for the full audit trail and the reasoning for each graft.
+
+Unify the emission point rather than the record types. Every next-step line resolves
+its payload by code from the registry that already models a structural command, and
+passes through one seam that owns output discipline. The four shapes keep their types
+and gain adapters, so no closed vocabulary is reopened and no context-injection surface
+changes shape. The appliers publish capability rather than each deciding privately, and
+the repair planner consumes the findings the detector already produced.
+
+The enforcement artifact is a census test enumerated from the dispatchers: every
+terminal state is classified as having an exit, having a named refusal, or being
+deliberately silent with a written reason, and the test fails until a new one is
+classified. This is the established pattern in this codebase.
+
+## Design decisions
+
+- **The registry is the source of truth for content, not for structure.** Adapters
+ cost a little duplication and buy the ability to ship without reopening
+ `DegradationCode` or the three severity vocabularies. Structural unification remains
+ available later and is cheaper once every consumer already resolves by code.
+
+- **Advisory chrome is decided in one place, not per verb.** Twelve verbs own an
+ internal JSON branch; everything else is wrapped in an envelope where a stray line is
+ harmless. Only the first family can be broken by an advisory line, and today nothing
+ centrally knows which family a call is in. The rail owns that question. This also
+ fixes the raw-argv scan that misreads a note whose text happens to contain the JSON
+ flag.
+
+- **A refusal is a deliverable.** Four units turned out to rest on behaviour this
+ codebase does not have. The honest response is a named, specific error or a stated
+ limitation, never a silent no-op and never a fabricated success. This is not a
+ reduction in scope; naming the boundary is the feature, given a release whose thesis
+ is that degradation must not be concealed.
+
+- **Issue #149 is fixed by naming the exit, not by manufacturing evidence.** Option A
+ in the report writes an apply-evidence row asserting the rule was applied to an
+ artifact when it was not. That row is defined in the codebase as the canonical durable
+ signal that a preference was exercised against real work; forging it would corrupt the
+ most-applied ranking, the recent-applications section, the outcome-regression ratio,
+ and would consume one of the two events the low-evidence doctor warning depends on.
+ Option B cannot see the confirmation timestamp it needs, breaks two assertions, and
+ introduces permanent churn - a decaying baseline drifts about one ten-thousandth per
+ hour against a one-millionth no-op threshold, so every dream pass would rewrite every
+ zero-evidence preference forever. Neither is adopted. What is adopted: write the value
+ as zero rather than null, because null ranks below zero on the two surfaces that rank
+ on the number at all; and give the existing detector its next command, so the operator
+ is told that recording real evidence is the exit. Measured: both proposed values sit
+ below the medium band threshold, so neither would have moved the preference one
+ position in the injected context.
+
+- **Truthful checkpoints beat more checkpoints.** The dream workrun journal currently
+ batches its phase markers, claiming reconcile complete before promote has begun. A
+ journal that lies is worse than one that is coarse, and this is precisely the failure
+ class the release is about.
+
+- **Generate the template, do not re-sync it.** Hand-repairing sixteen keys leaves the
+ drift mechanism in place. Generating from the resolver default tables makes the gap
+ structurally impossible and the ratchet test makes it visible if the generation is
+ bypassed.
+
+- **Byte-identical when absent.** Every new field, flag and config key is additive.
+ With it absent, output is byte-for-byte what it is today. This is asserted per unit,
+ not assumed.
+
+- **No natural-language word lists.** Detection and classification use structural
+ signals, explicit fields and corpus statistics. No unit here requires matching words
+ in any human language, and none may introduce it.
+
+## File changes
+
+New modules, expected:
+
+- a next-step resolution surface over the existing registry
+- an advisory emission rail owning output discipline
+- an applier capability table
+- a continuity record kind and aggregator for dedup counters
+- a generator for the Brain configuration template
+
+Modified, expected: the doctor CLI verb and its MCP tool; runtime notices; the command
+manifest and its dispatchers; the repair planner and the three appliers; the pending
+queue; the lint consolidation pass; the Brain bootstrap; the dream pass, its refresh
+module and its workrun journal; the ingest counters; the session summary core and tool;
+the install documents and the configuration path resolver; the skill proposal accept
+path and the procedural memory reader; the vault profile registry; the two
+force-confirmed writers and the two ranking surfaces.
+
+Tests: a dispatcher-enumerated terminal-state census; a manifest completeness ratchet; a
+configuration-key ratchet; a documented-install-output conformance test; the first CLI
+level tests for the lint and hygiene verbs; per-unit regression tests including
+byte-identical-when-absent assertions.
+
+Documentation: CHANGELOG, README, the CLI reference, the MCP reference, the
+architecture note, and the per-runtime install documents.
+
+## Risks and open questions
+
+- **The manifest repair changes real output.** Shell completions and `o2b help --json`
+ gain the verbs they were missing. This is a correction, but it is visible, and the
+ release notes must say so.
+- **Routing the doctor through the rail touches a surface agents parse.** The addition
+ must be additive in JSON and byte-identical when the caller does not ask for it.
+- **`RuntimeNotice` reaches the SessionStart injection.** A regression here lands in
+ agent context rather than in a script. The structured command is additive and the
+ prose remains until each code is migrated.
+- **The install conformance test binds documentation to code.** That is the point, but
+ it means an adapter change can fail a test in a document. The failure message must say
+ which document and which line.
+- **Open question, to settle during implementation:** whether the per-run dream gate
+ override is expressed as an explicit set of named gates or as a general configuration
+ overlay. The narrow form is safer and is the default assumption; the general form is
+ only justified if the narrow one turns out to need more than a handful of entries.
+- **Open question:** whether the capability table lives beside the fixer registry or in
+ its own module. Decide by which produces the smaller import surface, and record the
+ reason in the module docblock.
diff --git a/docs/brainstorm/no-dead-ends/plan.md b/docs/brainstorm/no-dead-ends/plan.md
new file mode 100644
index 00000000..1e8e00dd
--- /dev/null
+++ b/docs/brainstorm/no-dead-ends/plan.md
@@ -0,0 +1,352 @@
+# No dead ends - implementation plan
+
+Twenty-four atomic tasks. Tasks 1 and 2 are the shared seams and gate the units that
+deliver a next step; tasks 8 and 9 are the applier seam. The remaining tasks are
+independent of each other and may be implemented in any order, one commit each.
+Each task is one conventional commit, and each must pass the full gate set in the
+foreground before the commit: format, lint at the exact baseline of 134 warnings and 0
+errors, typecheck, the whole test suite, the version-sync check, and the link ratchet.
+
+Every task carries the same two implicit acceptance criteria, not repeated below:
+
+- **Byte-identical when absent.** With the new field, flag or config key omitted, the
+ surface produces byte-for-byte the output it produces on `main`. Asserted by a test,
+ not assumed.
+- **No stub, no silent fallback.** Anything that cannot be done raises a named,
+ specific error. A code path that does nothing and reports success is a defect.
+
+## Tasks
+
+### Task 1: Next-step resolution over the existing registry
+
+- **Files**: `src/core/brain/diagnostics.ts`, a new resolution surface beside it,
+ `tests/core/brain/next-step.test.ts`
+- **What**: One function that turns a diagnostic code into a structured next step, and
+ one record type carrying the code and the structural command. Built over
+ `DIAGNOSTIC_SIGNALS`, which already models exactly this. No second registry. A code
+ with no registered signal resolves to an explicit absent result, never to a guessed
+ or empty command.
+- **Acceptance**: Every code in the registry resolves. An unregistered code returns the
+ absent result and never throws. A test asserts the returned command is a structural
+ CLI string and contains no sentence punctuation, so prose cannot re-enter through
+ this door.
+- **Depends on**: none
+
+### Task 2: The advisory emission rail
+
+- **Files**: a new rail module under `src/cli/`, `src/cli/json-helpers.ts`,
+ `tests/cli/advisory-rail.test.ts`
+- **What**: The single point through which every forward-pointer line is emitted. It
+ owns the question of whether advisory chrome is legal on the current output stream,
+ distinguishing the twelve verbs that own an internal JSON branch from everything else,
+ which is wrapped in an envelope. Fix `wantsJsonFlag`, which scans raw argv and so
+ misreads a note whose own text contains the JSON flag.
+- **Acceptance**: A verb with an internal JSON branch emits nothing advisory to stdout
+ under that flag, and its output still parses. A note whose text contains the flag as
+ literal content is no longer treated as a JSON request; a regression test pins that
+ exact string. Advisory output on the human path is unchanged where it already existed.
+- **Depends on**: Task 1
+
+### Task 3: Runtime notices carry a structured command
+
+- **Files**: `src/core/brain/runtime-notices.ts`, `hooks/active-inject.ts`,
+ `src/mcp/tools.ts`, `tests/core/brain/runtime-notices.test.ts`
+- **What**: Add an optional structured command to the notice record, resolved through
+ Task 1 rather than embedded in prose. Correct the search-index notice, whose text
+ claims recall returns nothing when the read path self-heals and builds the index. The
+ prose field stays for the human surfaces.
+- **Acceptance**: A notice with a registered code exposes its command as a field. The
+ corrected notice text no longer contradicts the self-heal behaviour that a test
+ already pins. The SessionStart injection and the vault-health tool output are
+ byte-identical for callers that do not read the new field.
+- **Depends on**: Task 1
+
+### Task 4: The Brain doctor names its exits
+
+- **Files**: `src/cli/brain/verbs/doctor.ts`, `src/mcp/brain/health-tools.ts`,
+ `tests/cli/brain-doctor-next-step.test.ts`, `tests/mcp/doctor-next-step.test.ts`
+- **What**: Route every issue the Brain doctor reports through the rail, so the human
+ surface prints the structural next command and the JSON surface carries it as a field.
+ The same for the MCP tool. The registry that already maps these codes has two
+ consumers today and the doctor is not one of them.
+- **Acceptance**: For an issue whose code is registered, the human output names the
+ command and the JSON output carries it. For an unregistered code, neither invents one.
+ A vault with no issues produces the output it produces today, byte for byte.
+- **Depends on**: Tasks 1, 2
+
+### Task 5: Terminal states that print nothing forward
+
+- **Files**: `src/cli/brain/verbs/init.ts`, `src/cli/search.ts`, the empty-state brain
+ verbs, `tests/cli/terminal-states.test.ts`
+- **What**: Emit a next step from the terminal states that currently exit zero in
+ silence, beginning with Brain initialization - the command that creates the empty
+ Brain and says nothing about what fills it. Reuse the rail; do not hand-write per-verb
+ copy. Leave the search read path alone: it self-heals by design and a hint there would
+ regress a pinned behaviour.
+- **Acceptance**: Each covered terminal state names a command on the human surface and
+ stays clean under the JSON flag. The self-healing search path is untouched, asserted
+ by the existing test still passing unmodified.
+- **Depends on**: Tasks 1, 2
+
+### Task 6: Command manifest completeness and its ratchet
+
+- **Files**: `src/cli/command-manifest.ts`, `tests/cli/manifest-completeness.test.ts`
+- **What**: The manifest is the source of shell completions and the JSON help output,
+ and it is missing two top-level verbs, seven search subverbs and fifty-five brain
+ cases. Repair it, and add a ratchet test that enumerates from the dispatchers, not from
+ the manifest, so a verb cannot be added without an entry.
+- **Acceptance**: The ratchet lists every dispatcher case with no manifest entry and
+ fails while any remains unclassified. Completions and JSON help include the repaired
+ set. A deliberately hidden verb, if any exists, is listed with a written reason rather
+ than silently skipped.
+- **Depends on**: none
+
+### Task 7: Terminal-state census
+
+- **Files**: `tests/cli/terminal-state-census.test.ts`
+- **What**: The enforcement artifact for the release. Enumerated from the dispatchers,
+ it partitions every terminal state into one of three classes: names an exit, names a
+ refusal, or is deliberately silent with a written reason. It fails until a new state
+ is classified.
+- **Acceptance**: The census names any unclassified state and fails. Every reason string
+ is non-empty. The census cannot be satisfied by an empty reason or a placeholder.
+- **Depends on**: Tasks 5, 6
+
+### Task 8: The applier capability table
+
+- **Files**: `src/core/brain/diagnostics.ts`, `src/core/brain/hygiene/apply.ts`,
+ `src/core/brain/health/remediation.ts`, a new table module,
+ `tests/core/brain/applier-capability.test.ts`
+- **What**: One table stating, per finding code, whether repair is mechanical - naming
+ the fixer - or refused, naming the reason. The three appliers publish into it instead
+ of each deciding privately. Unify their three divergent write-guard placements behind
+ one documented rule, preserving the stated rationale of whichever placement is chosen.
+- **Acceptance**: Every code with a fixer appears as mechanical; every code the code base
+ routes to review appears as refused with its reason. A test asserts the table and the
+ fixer registry cannot disagree. Guard placement is identical across the three appliers
+ and the choice is justified in a docblock.
+- **Depends on**: none
+
+### Task 9: The repair planner consumes the doctor's findings
+
+- **Files**: `src/core/brain/diagnostics.ts`, `tests/core/brain/repair-plan-source.test.ts`
+- **What**: The one verified true statement in the whole of the fix-applier ticket:
+ the planner re-scans the vault independently while the doctor's findings sit unused
+ beside it, consulted only for counts. Pass the findings in. This is what makes the
+ applier a consumer of the finding contract rather than a parallel detector sharing
+ vocabulary.
+- **Acceptance**: A test proves the plan is derived from the supplied findings - seed a
+ defect, capture the doctor's findings, and assert the plan matches them rather than a
+ fresh scan. Plans for existing fixable classes are unchanged. If a fixer covers a
+ class the doctor does not report, that is named explicitly, not silently re-scanned.
+- **Depends on**: Task 8
+
+### Task 10: A read-only verb must not fail with a write-path error
+
+- **Files**: `src/core/brain/lint-consolidate.ts`, `tests/core/brain/lint-read-path.test.ts`
+- **What**: The consolidation pass asserts vault identity unconditionally, before its
+ apply branch. The read-only actions verb calls it in report mode and can therefore
+ fail with a vault-identity mismatch on a pure read. Move the assertion to the write
+ branch, where the guard's own documented contract puts it.
+- **Acceptance**: A report-mode call against a vault whose marker would trip the guard
+ returns its report. An apply-mode call against the same vault still refuses. The
+ vault-guard census test still passes.
+- **Depends on**: none
+
+### Task 11: The approval queue gets its preview
+
+- **Files**: `src/core/brain/pending.ts`, `src/cli/brain/verbs/pending.ts`,
+ `tests/core/brain/pending-dry-run.test.ts`
+- **What**: The pending apply path is the only applier with no dry run. Add one, with
+ the same shape as the others: identical report, zero writes.
+- **Acceptance**: A dry run reports exactly what an apply would move and leaves the vault
+ byte-identical, asserted by digesting the tree before and after. Apply behaviour is
+ unchanged.
+- **Depends on**: none
+
+### Task 12: Broken-link findings become machine-actionable
+
+- **Files**: `src/core/brain/doctor.ts`, `src/core/brain/types.ts`,
+ `tests/core/brain/broken-link-findings.test.ts`
+- **What**: The broken-wikilink issue carries its field name and target only inside
+ prose, and the broken-backlinks issue carries no path at all. A consumer must regex
+ the message. Carry them as fields.
+- **Acceptance**: Both issues expose the data as structured fields; the message text is
+ unchanged for human readers. A test asserts a consumer can act without parsing prose.
+- **Depends on**: none
+
+### Task 13: Generate the Brain configuration template
+
+- **Files**: `src/core/brain/policy.ts`, a generator module,
+ `tests/core/brain/config-template-ratchet.test.ts`
+- **What**: The template is a hand-written constant emitting seven top-level keys; the
+ resolver understands twenty-three. Sixteen resolve silently from defaults because
+ nothing keeps the constant and the resolver default tables in sync. Generate the
+ template from the tables and add a ratchet asserting every key the resolver understands
+ is represented, or is listed as deliberately omitted with a written reason.
+- **Acceptance**: The generated template contains every resolver key. The ratchet fails
+ when a new key is added to the resolver without appearing. An existing vault whose
+ configuration omits keys still resolves exactly as before; adding the keys explicitly
+ at their default values produces identical behaviour, asserted by comparing resolved
+ configurations.
+- **Depends on**: none
+
+### Task 14: Initialization creates what it declares
+
+- **Files**: `src/core/brain/init.ts`, `tests/core/brain.init.test.ts`
+- **What**: The bootstrap declares ten Brain directories and creates eight; the missing
+ two are created lazily by downstream writers. Create them. The created-file count is
+ pinned by a test and must be updated deliberately, not incidentally.
+- **Acceptance**: All declared directories exist after initialization. The pinned count
+ test is updated with the new expected value and a comment saying why it changed.
+ Initialization remains idempotent.
+- **Depends on**: none
+
+### Task 15: Dream tells the truth about its own progress
+
+- **Files**: `src/core/brain/dream.ts`, `src/core/brain/dream-workrun.ts`,
+ `src/core/brain/safeguard.ts` consumers, `tests/core/brain/dream-checkpoints.test.ts`
+- **What**: Three things. Move the workrun phase markers to where the work actually
+ completes, instead of two batches that claim reconcile finished before promote began.
+ Add the safeguard checkpoint the options docstring already promises before finalize,
+ covering the log writes, the ledger write, snapshot pruning and digest regeneration
+ that currently run unguarded. Add a per-run override for the dream gates so a targeted
+ pass needs no vault-config edit and no remembering to revert.
+- **Acceptance**: A run interrupted mid-write leaves a journal whose last marker names
+ work that genuinely completed, asserted by injecting a failure between two phases. The
+ new checkpoint fires, asserted with an already-tripped guard. An override applies for
+ one run and leaves the stored configuration untouched, asserted by re-reading it. With
+ no override supplied, behaviour is byte-identical.
+- **Depends on**: none
+
+### Task 16: A phase request that cannot be honoured is refused by name
+
+- **Files**: `src/core/brain/dream.ts`, `tests/core/brain/dream-phase-refusal.test.ts`
+- **What**: The five phase labels are a reporting layer, not callable units, and two
+ planning steps mutate each other's accumulators specifically so a preference is never
+ both refreshed and retired. A request to run such a phase alone must raise a named
+ error stating which phases are independently runnable and why the requested one is not.
+ Silently running more than was asked is the failure mode this release exists to remove.
+- **Acceptance**: A request for a coupled phase raises the named error and writes
+ nothing. A request for an independently runnable step performs exactly that step. The
+ error names the coupling, not a generic message.
+- **Depends on**: Task 15
+
+### Task 17: Dedup counts become observable
+
+- **Files**: `src/core/brain/continuity/types.ts`, the ingest counter call sites, an
+ aggregator, `src/mcp/brain/analytics-tools.ts`,
+ `tests/core/brain/dedup-telemetry.test.ts`
+- **What**: The exact-hash counters exist and reach a response, then die one call deep,
+ so a spike cannot be observed. Persist them as a continuity record of a new kind and
+ read them back through an aggregator on the existing analytics surface, following the
+ generation-report model. Report the semantic layers as nominations, which is what they
+ are; do not invent a drop counter for a mechanism that never drops.
+- **Acceptance**: An ingest that dedupes writes a record; the aggregator returns a
+ trend over records. An ingest that dedupes nothing writes no record rather than a zero
+ row. The semantic figure is labelled a nomination count in every surface that shows it.
+- **Depends on**: none
+
+### Task 18: Project scope on session summaries
+
+- **Files**: `src/core/brain/session-summary.ts`, `src/mcp/brain/synthesis-tools.ts`,
+ `tests/core/brain.session-summary.test.ts`, `tests/mcp/session-summary-tool.test.ts`
+- **What**: Thread the existing project scope axis through the summary input, the digest
+ and the tool schema, reusing the established normalization and the shared optional-string
+ coercion. Do not introduce a parallel dimension; one already exists and is wired into
+ search, dedup keys and activation decay.
+- **Acceptance**: A digest written with a project carries it, normalized by the shared
+ rule; listing filters by it. A digest written without one is byte-identical to today,
+ including its dedupe key. The tool rejects a malformed value by name rather than
+ silently ignoring it.
+- **Depends on**: none
+
+### Task 19: Install verification you can assert against, and a named platform boundary
+
+- **Files**: `install/*.md`, `src/core/config.ts`,
+ `tests/docs/install-verify-conformance.test.ts`, `tests/core/config-path.test.ts`
+- **What**: Every per-runtime install document tells the agent to run the check and
+ never shows what success looks like. Add an expected-output block to each Verify
+ section, and a test that fails when a block stops matching what the adapter's verify
+ actually returns - binding the documentation to the code. Separately, the
+ configuration path is unconditionally POSIX with no branch for platforms that do not
+ use it; make that an explicit named refusal rather than a silent wrong answer.
+- **Acceptance**: Each document's expected block matches real output, asserted by
+ constructing the adapter with an injected environment. The failure message names the
+ document. On an unsupported platform the resolver raises a named error naming the
+ platform, instead of returning a path that cannot exist.
+- **Depends on**: none
+
+### Task 20: The skill contract is written and read
+
+- **Files**: `src/core/brain/skill-proposals.ts`, `src/core/brain/procedural-memory.ts`,
+ `src/mcp/brain/procedure-tools.ts`, `tests/core/brain/skill-contract.test.ts`
+- **What**: Acceptance writes prerequisites, rollback, side effects and verification, and
+ the procedural memory reader reads them back so they are a contract rather than
+ decoration. Resolve a proposal's claimed evidence against the independently recorded
+ outcome ledger, joined by a key derived from the slug that the accept path already
+ causes to exist. Close the three atomicity gaps: the window between the two writes, the
+ unguarded removal of the pending copy, and the unguarded projection rebuilds.
+- **Acceptance**: An accepted proposal carries the contract fields and a reader returns
+ them. A proposal whose recorded outcomes are failures is distinguishable from one whose
+ outcomes are successes, and from one with no recorded outcome at all - three distinct
+ states, none conflated. A failure injected at each of the three gaps leaves no
+ duplicate and no orphan. Accepting a proposal with no contract data supplied produces
+ today's output.
+- **Depends on**: none
+
+### Task 21: The profile registry refuses to lose data
+
+- **Files**: `src/core/brain/portability/profiles.ts`,
+ `tests/core/brain/portability/profiles.test.ts`
+- **What**: Creating a profile silently overwrites an existing entry, performs no
+ directory check at create time although switching does, and does a lock-free
+ read-modify-write so two concurrent creates lose an update. Refuse the overwrite,
+ validate at create, serialize the mutation. Every primitive needed already exists and is
+ conventional in this codebase.
+- **Acceptance**: Creating over an existing name raises a named error and leaves the
+ registry byte-identical. Creating against a path that is not a directory is refused at
+ create time with the same error shape switching already uses. Two concurrent creates
+ both land, asserted without sleeping.
+- **Depends on**: none
+
+### Task 22: Issue #149 - fix the real defect, name the exit, refuse the rest
+
+- **Files**: `src/mcp/brain/feedback-tools.ts`, `src/cli/brain/verbs/feedback.ts`,
+ `src/core/brain/doctor.ts`, `tests/core/brain/force-confirmed-cold-start.test.ts`
+- **What**: Write the confidence value as zero at force-confirm time in both writers,
+ matching what the dream pass already does for new unconfirmed preferences, because the
+ absent value is read back as null and null ranks below zero on the two surfaces that
+ rank on the number. Give the existing low-evidence detector its next command through
+ the rail, so the operator is told that recording real evidence is the exit. Do not
+ fabricate an evidence row and do not change the confidence formula; record both
+ refusals and their measured reasons in the release notes.
+- **Acceptance**: A force-confirmed preference carries an explicit zero, and the two
+ ranking surfaces order it above an entry with no value rather than below. The detector's
+ output names the command. No new evidence row is written anywhere. The two existing
+ confidence assertions are untouched, proving the formula did not move.
+- **Depends on**: Tasks 1, 2
+
+### Task 23: The first CLI-level tests for lint and hygiene
+
+- **Files**: `tests/cli/brain-lint.test.ts`, `tests/cli/brain-hygiene.test.ts`
+- **What**: Neither verb has a CLI-level test today; both are write-capable and both are
+ touched by this release. Establish the tier: dry run reports and writes nothing, apply
+ writes exactly what it reported, the JSON surface parses.
+- **Acceptance**: Dry run leaves the vault tree digest unchanged. Apply changes exactly
+ the reported set. Both surfaces parse under the JSON flag.
+- **Depends on**: Tasks 8, 10
+
+### Task 24: Documentation and version
+
+- **Files**: `CHANGELOG.md`, `README.md`, `docs/cli-reference.md`, `docs/mcp.md`,
+ `docs/architecture.md`, `package.json`, the mirrored manifests
+- **What**: One CHANGELOG entry under the new version. A README paragraph on the new
+ capability with the previous release compressed to a pointer. Reference entries for
+ every new flag, argument and configuration key. Bump the version in the single source
+ of truth and propagate with the sync script, inside this pull request, per the
+ repository rule.
+- **Acceptance**: The sync check passes. The CHANGELOG heading and the package version
+ agree. Every new surface introduced by tasks 1 through 23 appears in exactly one
+ reference document.
+- **Depends on**: all
diff --git a/docs/brainstorm/no-dead-ends/variants.md b/docs/brainstorm/no-dead-ends/variants.md
new file mode 100644
index 00000000..f52e8d79
--- /dev/null
+++ b/docs/brainstorm/no-dead-ends/variants.md
@@ -0,0 +1,103 @@
+# No dead ends - variant selection
+
+**Consultant:** Claude Code CLI (`claude -p`), primary consultant per the
+feature-release-playbook. Invoked once; the fallback consultant was not needed
+because the primary returned three parseable variants and a recommendation.
+
+**Prompt:** [`cli-output/prompt.md`](cli-output/prompt.md). The prompt carries the
+CORRECTED problem statement produced by seven parallel reconnaissance passes over
+the real code, not the kanban ticket text. Eight of the ten units had at least one
+premise invalidated before the consultant saw them.
+
+---
+
+## Consultant output, verbatim
+
+### Variant 1: Registry as the spine
+
+- **Approach**: Promote `DiagnosticSignal`/`DIAGNOSTIC_SIGNALS` to the single next-step source of truth and demote the other three shapes to projections of it — `RuntimeNotice` drops its prose command and resolves by code, `OnboardingStep.command` and `CheckResult.fix` render from the registry, and `o2b brain doctor` (text and `--json`) emits `nextCommand` for every code it raises. The registry entry additionally names its fixer (replacing `coversDoctorCode`) so `Fixer.plan` consumes detector findings instead of re-scanning, and a shared base is extracted across the 15 finding record types to carry `{code, identity, severity, path, line}`. Units C/D/E/F/H/I/J then each register their exits as registry codes rather than inventing local hints.
+- **Trade-offs**:
+ - Pro: one vocabulary, one place to add a code, and the diagnosis→exit contract is structurally impossible to skip once the registry is the only carrier.
+ - Pro: kills the `Fixer.plan` double-scan outright, which is the one undisputed defect in Unit B, and makes blast-radius guards (`assertExpectedCount`) uniform across all three appliers.
+ - Pro: the "refuse by name" half becomes a registry field, so frontmatter drops, semantic-health `needs-review`, and the coupled dream phases all refuse from the same table as the ones that fix.
+ - Con: a shared finding base collides head-on with `DegradationCode`'s deliberate closure and with three incompatible severity unions; widening them is exactly the reversal the brief forbids without explicit justification.
+ - Con: `DoctorIssue.code` is an unenumerated `string` with ~35 literals inline across 1754 lines — enumerating it is a large mechanical refactor with real risk to the byte-identical constraint on `--json` consumers.
+ - Con: consumes most of the release on Units A and B, leaving C/D/G/H/I/J as thin follow-ons or deferred; the stale command manifest must also be repaired first or terminal-state enumeration silently misses a third of the surface.
+ - Con: three `RuntimeNotice` surfaces (onboarding, SessionStart hook, `vault_health`) change shape at once, so a regression lands in agent context injection rather than in a CLI nobody scripts.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: One advisory rail, four shapes preserved
+
+- **Approach**: Leave all four record types and all 15 finding types alone; unify the *emission point* instead. Add a single advisory-output seam that every next-step line must pass through — it resolves payloads by code from the existing `DIAGNOSTIC_SIGNALS` registry, and it is the one place that knows whether advisory chrome is legal on the current stdout (fixing `wantsJsonFlag`'s raw-argv scan and honouring the `COMMANDS_WITH_INTERNAL_JSON` split). Each existing shape gets a thin adapter into that rail, each of the three appliers publishes a capability descriptor (`mechanical` with a fixer id, or a named refusal), and a census test enumerated from the dispatchers — not the stale manifest — fails until every terminal state is classified as *has exit*, *has named refusal*, or *deliberately silent*.
+- **Trade-offs**:
+ - Pro: gets the whole thesis (machine-readable exit, mechanical fix, named refusal) without touching a single closed vocabulary; `DegradationCode` stays closed and the three severity unions stay separate.
+ - Pro: byte-identical-when-absent is cheap to guarantee, because the rail is additive and the existing prose messages remain the fallback until each code is migrated.
+ - Pro: leaves budget for the smaller units, which are where most of the verified defects actually live — the `lint-consolidate` guard misplacement on a read path, `createProfile`'s silent overwrite and lock-free write, `pending apply`'s missing dry-run, the `null`-ranks-below-`0` defect on the two topK surfaces, dedup counters persisted as a `ContinuityRecord` kind, `project` on the session summary, skill-acceptance frontmatter joined to `recordProceduralOutcome`, `install --check` expected-output blocks with Windows/WSL2 named as an unsupported-path error rather than an unconditional POSIX assumption.
+ - Pro: the census test is the enforcement artifact and matches established precedent, so next release's new verbs cannot silently reintroduce dead ends.
+ - Con: four shapes remain four shapes; the registry becomes the source of truth for *content* but not for *structure*, so a fifth shape is still possible.
+ - Con: `Fixer.plan`'s independent re-scan is corrected only by making the detector's findings the input to the capability lookup, not by a full findings-contract merge — the double-scan shrinks rather than disappears.
+ - Con: the manifest repair is a prerequisite with its own surface (7 missing `search` subverbs, 55 missing `brain` labels, absent `secrets`/`partner`), and it changes shell completions and `o2b help --json` output for real users.
+ - Con: adapters are a per-shape cost, so the cheapest-looking unification is not free.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Conformance obligation only — correct each mechanism in place
+
+- **Approach**: Introduce no shared type and no shared emitter; the only new artifact is a conformance census asserting that every diagnosis-emitting site either names a structural exit, names a refusal, or is listed as deliberately silent with written justification. Each unit is then repaired at its own site under that obligation — `doctor` prints the registry's `nextCommand` for codes it already shares, `RuntimeNotice` gains an optional `command?` field and its stale self-heal text is corrected, `DEFAULT_BRAIN_CONFIG_YAML` is generated from the resolver default tables so the 16-key gap cannot recur, `dream --only` accepts the two provably self-contained steps and refuses the mutually-coupled ones by name, and Unit J refuses both proposed fixes by name while fixing the ranking defect and pointing at the existing `low-evidence-confirmed` signpost.
+- **Trade-offs**:
+ - Pro: lowest risk against the byte-identical and no-silent-fallback constraints; almost every change is additive at one call site with a local test.
+ - Pro: the honest answer to the units where the ticket premise collapsed (D's non-existent phase functions, E's non-existent semantic drop, I's non-existent profile artifact, J's non-existent de-prioritization) is a named refusal, and this variant makes refusal the default posture rather than an exception.
+ - Pro: fits comfortably in one release with room for the two missing CLI-level tests (`brain lint`, `brain hygiene`) and the dream checkpoint honesty fix.
+ - Con: the four incompatible next-step shapes survive intact, so the drift that produced them continues; the next wave inherits the identical Unit A.
+ - Con: a census that permits "named refusal" can be satisfied by writing refusals everywhere, which technically passes the thesis while delivering little forward motion.
+ - Con: `Fixer.plan`'s re-scan and the three divergent write-guard placements go unaddressed, leaving Unit B's genuine architectural defect for later.
+ - Con: without a shared emitter, the JSON-discipline hazard remains per-verb, so a future advisory line on an internal-`--json` verb still breaks `JSON.parse`.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 2
+
+**Rationale**: The verified state says the well-shaped mechanism already exists — `DiagnosticSignal.nextCommand` with a ~20-code registry — and the defect is delivery, not modelling, so unifying the emission point buys the entire thesis while Variant 1 pays for a 15-type findings merge that collides with `DegradationCode`'s deliberate closure and with the byte-identical constraint on three context-injection surfaces. Variant 2 also keeps enough budget for the units where the real, verified bugs are small and local (the read-path vault-identity throw, the silent profile overwrite, the `null`-below-`0` ranking defect, the missing `pending apply` dry-run), which Variant 1 would starve. Variant 3 is safest but leaves Unit A structurally unchanged and lets a census of refusals stand in for the wiring the release is actually about.
+
+---
+
+## Orchestrator decision
+
+**Accepted: Variant 2 (one advisory rail, four shapes preserved), with two grafts.**
+
+The consultant's reasoning holds against the evidence. The well-shaped mechanism
+already exists - `DiagnosticSignal.nextCommand` with a populated registry - and the
+defect is delivery, not modelling. Variant 1 pays for a fifteen-type findings merge
+that collides head-on with the deliberate closure of `DegradationCode` and would put
+a shape change into three context-injection surfaces at once; that is a large risk
+bought for a small gain, since nothing downstream needs the fifteen types to share a
+base in order for a caller to learn its next command. Variant 3 is the safest but
+leaves Unit A structurally untouched, and its census would be satisfiable by writing
+refusals everywhere - a conformance artifact that passes while delivering nothing.
+
+Two elements are grafted in, because Variant 2 under-serves them:
+
+**Graft 1, from Variant 3: generate the config template from the resolver default
+tables.** Variant 2 leaves Unit C as an ordinary repair. But the sixteen-key gap is
+not a bug that was introduced once - it is accumulated drift between a hand-written
+string constant and a set of resolver default tables that nothing keeps in sync. A
+repair that re-syncs them by hand re-arms the same drift. Generating the template
+from the tables, with a ratchet test asserting every key the resolver understands is
+represented, removes the drift mechanism rather than its current output.
+
+**Graft 2, from Variant 1: the repair planner consumes the doctor's findings instead
+of re-scanning.** Variant 2 shrinks this defect; Variant 1 removes it but only as
+part of the expensive merge. The removal does not actually require the merge. The
+doctor already produces its findings, and `planRepair` already calls it - for counts
+only. Passing those findings into the fixers is a narrow change confined to one
+module, and it is the difference between an applier that consumes the finding
+contract and one that merely shares vocabulary with it. Since "the applier is not
+keyed off the findings shape" is the single verified true statement in the whole of
+Unit B's ticket, leaving it half-fixed would mean the one real defect survives the
+release that was named after it.
+
+**Explicitly not adopted from Variant 1:** a shared base across the fifteen finding
+record types, and enumerating `DoctorIssue.code`. Both are real debts. Neither is
+required by this release's thesis, and the first reverses a stated policy. They are
+recorded in "Out of scope" with the reason.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 5fbaf7a5..e2eb7e11 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -105,8 +105,20 @@ o2b brain context-pack Bounded-token vault slice for priming an agent's c
o2b brain synthesise Concept-scoped JSON envelope: target node + linkers + optional unlinked mentions
o2b brain moc-audit Per-MOC coverage audit: classify cluster members into well-covered / fragile / candidate-missing
o2b brain unlinked Raw-text mentions outside `[[...]]` (Unicode-aware boundaries)
+o2b brain skill-proposals recover [--discard-unreadable]
+ Resolve accept sequences a crash abandoned, rolling each back to its pending draft or forward to rebuilt projections. Refuses by name, naming the exact file, on a held `Brain/skill-proposals/accept.lock` (nothing breaks a lock - a live writer cannot be told from a crashed one) and on an accept-journal marker that cannot be parsed; `--discard-unreadable` removes those markers, which unblocks accepting without claiming the sequence each marked was resolved
```
+Recovery is a vault-wide sweep, not a per-slug one: `recover` - and every
+`accept`, which runs the same sweep first - resolves EVERY outstanding
+journal it finds, so accepting one proposal can roll another slug's
+abandoned sequence back. That is deliberate. The sweep and the accept
+share one vault-wide lock, which is what makes it safe, and leaving a
+crashed sequence unresolved would let the next accept build on a
+duplicate. It writes only under `Brain/skill-proposals/` and
+`Brain/procedures/`, and only files the abandoned sequence itself
+created - the journal records whether each target pre-existed.
+
### Context continuity and receipts (since v0.29.0)
```text
@@ -454,6 +466,8 @@ exits 2 on an un-initialized vault where it previously exited 0.
```text
o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> | discard <run-id> | list - staged lifecycle over a persisted proposal bundle; validate/apply exit 1 on drift
+o2b brain dream --step S run ONE independently-runnable step instead of the full pass: `scan` (pure read) or `heal-enrich` (asking for it is the opt-in, so the config gate is not consulted). Any other token - including a dream reporting phase - exits 2 with the specific reason that step cannot run alone and the runnable set. Returns a partial result marked `partial: true`, never a run summary. Mirrors MCP `brain_dream` `step`
+o2b brain dream --gate N=V override one phase gate for THIS RUN ONLY (`--gate heal_enrich=true|false`); repeatable, never written back to `Brain/_brain.yaml`, so a targeted pass needs no config edit and no revert. An unknown gate or a non-boolean value exits 2 naming the known gates. Mirrors MCP `brain_dream` `gates: {heal_enrich: bool}`
o2b brain doctor gains the removed-tool-reference warning: vault notes, root instruction files, and installed skills naming a tool removed in 1.0.0 are flagged with the replacement
o2b brain doctor opt-in `entity-alias-candidate` lint (off by default): with `entity_semantic_dedup_enabled: true` surfaces lexical entity-name variants ("Google LLC" vs "Google Inc") as PROPOSAL-ONLY alias-merge candidates via a deterministic jaccard layer (`entity_semantic_dedup_lexical_threshold`, default 0.8); never auto-merges or rewrites the identity key. The embedding-cosine layer (`entity_semantic_dedup_threshold`, default 0.92, reuses the configured embedding provider) is exposed as a library reader for apply plans
o2b brain daily | weekly | monthly | morning-brief | timeline
@@ -462,6 +476,14 @@ o2b brain digest | daily | weekly
with report_snapshots_enabled persist Brain/reports/<surface>/<date>.json and report a deterministic Since-last-run delta
```
+### Forward pointers (`next:` / `next_command`)
+
+A verb that succeeds and leaves the caller with somewhere to go names that place through one mechanism. On a human stream it prints one `next: <command>` line; under `--json` the same command arrives as an additive `next_command` string field in the payload, and the key is **absent** whenever no exit resolves. The command is always a structural `o2b` invocation resolved from the diagnostics registry - never prose - so a caller can execute it verbatim.
+
+Verbs that carry it today: `o2b status`, `o2b brain init`, `bridges list|discover`, `clusters list|run`, `dream list`, `git status|mine`, `inbox-drain`, `intention list`, `intent-review`, `tune status`, `o2b search index|reindex|status`. `o2b brain tiers check` deliberately carries none under `--json`: that state has two exits (restore or accept), the wire key is singular, and naming one would tell a machine caller the other does not exist.
+
+**When there is no command.** About two thirds of the doctor's issue codes resolve to none, because the repair is a judgement over content or an edit whose target shape the finding cannot supply. Those are not silent: `o2b brain doctor` prints `no exit: <code> - <reason>` once per reported code, and `--json` (and MCP `brain_doctor`) carries the same reasons in an additive `no_exit` object beside the issue streams - once per code rather than repeated on each record, because a reason is about a class. Every doctor code is one or the other; `tests/core/brain/doctor-exit-census.test.ts` enumerates them from the detector and fails on a code that is neither, so an unregistered code can no longer mean "nobody got round to it". The key and the lines are absent whenever every reported code has an exit, and on a clean vault.
+
Long-running operations (dream, `o2b search index | reindex`, bridges discover, clusters run, the maintenance lane) run under a cooperative safeguard deadline: `safeguard_timeout_seconds` (default 600, `0` disables, env `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) with per-operation overrides like `safeguard_timeout_dream_seconds`. A tripped deadline aborts at the next checkpoint - between atomic writes - and reports `{ok:false, timed_out:true}` on exit 1; maintenance-lane task results carry `timed_out` per task. The frozen-surface policy lives in `docs/stability.md`; the 0.x to 1.0.0 migration table in `docs/updating.md`.
## Vault scope
diff --git a/docs/mcp.md b/docs/mcp.md
index 952a14ba..650cbce2 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -43,7 +43,7 @@ flags for a narrower per-process full server.
| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — |
| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |
-| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis`. | `view` |
+| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |
| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, and a selectable recall `profile` (`fast \| balanced \| thorough`). | `query` |
| `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` |
| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores`, also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag over the gate-telemetry relevance scores plus the epistemic mix; thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. | `prompt` |
@@ -138,7 +138,15 @@ deterministic media/base64 sanitization. `brain_session_grep`,
recall DAG populated by CLI `import-session --recall` or the core API.
`brain_session_summary` accepts `operation: "write"|"get"|"list"` (write takes
`session_id` plus any of `request`, `decisions`, `learnings`, `next_steps`,
-`source_turn_ids`, `host`). `brain_idea_lineage` accepts `id` and optional
+`source_turn_ids`, `host`, `project_scope`). `project_scope` is the same
+project axis `brain_search` filters on, normalized to the same `[a-z0-9-]` slug:
+on `write` it files the digest under that project and folds it into the dedupe
+key, so the same content under two projects is two digests; on `list` it returns
+only that project's digests. Omitted, the digest and its dedupe key are
+byte-identical to the pre-project shape. A value with no alphanumeric is an
+`INVALID_PARAMS` error naming the argument, never a silent drop to unscoped.
+This is unrelated to the `o2b brain project` verb, which links a code directory
+to its owning vault at the configuration level. `brain_idea_lineage` accepts `id` and optional
`max_depth`. `brain_note_history` accepts `path` and optional `gap_hours` /
`max_count`.
`brain_recall_gate` accepts optional `previous_prompt` and
@@ -607,3 +615,39 @@ Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default
reason when a cached pack is refused because the vault state it was
built from has moved or its validity window has expired, instead of
silently serving or silently rebuilding.
+- Since v1.40.0 `brain_doctor` additively carries `next_command` on each
+ reported issue whose code has a registered exit, and a `no_exit` object
+ giving, once per code, the reason a class has no single command. The
+ two are complementary: a caller can tell a class it can act on from one
+ that needs a human judgement over content, and neither is silent. Both
+ keys are absent when every reported code has an exit, so the payload is
+ byte-identical for a vault whose findings all resolve.
+- Since v1.40.0 `vault_health` notices carry the same `next_command`
+ field, resolved from the same registry, so the notice channel no longer
+ requires a consumer to match the command out of an English sentence.
+- Since v1.40.0 `brain_dream` accepts `step` and `gates`. `step` runs one
+ independently-runnable step; any other value, including the five phase
+ labels, is refused with the coupling named rather than silently running
+ more than was asked. `gates` overrides a dream gate for that run only
+ and never writes to `_brain.yaml`. `step` is deliberately not a schema
+ enum, because an enum would swallow the per-step refusal reason, which
+ is the deliverable for the steps that cannot run alone.
+- Since v1.40.0 `brain_skill_proposals` accepts a `recover` operation and
+ four contract arguments on `accept` (`prerequisites`, `rollback`,
+ `side_effects`, `verification`), plus an `evidence` operation that
+ reports a proposal's self-declared support beside the independently
+ recorded procedural outcomes. Three states stay distinct: recorded
+ successes, recorded failures, and no recorded outcome at all - the last
+ is never reported as a zero success rate. `recover` is the operator
+ surface for an accept sequence a crash left outstanding.
+- Since v1.40.0 `brain_procedural_memory` entries carry the four contract
+ fields back on `list`, so a contract written at acceptance is readable
+ rather than write-only.
+- Since v1.40.0 `brain_session_summary` accepts an optional
+ `project_scope`, normalized by the same slug rule as the session axis.
+ A digest written without one keeps its existing dedupe key byte for
+ byte, so deduplication of pre-existing digests is unaffected.
+- Since v1.40.0 `brain_analytics` accepts `view: dedup`, folding the new
+ `ingest_dedup` continuity records into a trend. The counts are exact-hash
+ drops only; the semantic layers nominate candidates and never drop, so
+ nothing in this view may be read as a semantic discard.
diff --git a/docs/observability.md b/docs/observability.md
index 1a858e38..998a7eda 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -41,11 +41,12 @@ Every continuity record shares one envelope: `schema`, `id`, `kind`, `createdAt`
| `token_impact` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `record` (`emitTokenImpact` in `src/core/brain/token-impact.ts`) - one sample per context pack; payload carries the tokenizer-exact prompt-token counts (`baseline_tokens`, `packed_tokens`, signed `delta_tokens`), the `method` label (`exact`/`fallback`), an optional opaque `pack_id`, and the optional modeled inference-avoidance estimate - never raw prompts or recalled text |
| `token_impact_outcome` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `outcome` (`recordTokenImpactOutcome`) - one first-pass/repair/retry post used only to calibrate the modeled ledger |
| `context_pack_outcome` | config key `context_pack_outcome_enabled` (default off) | `brain_context_pack_outcome` action `post` (`emitContextPackOutcome` in `src/core/brain/context-pack-outcome.ts`) - one compact per-sample outcome row for a carried context-pack quality-sample id: first-pass/repair/retry counters plus three STRICTLY SEPARATE token signals (`exact_prompt_token_savings`, `modeled_inference_avoidance`, `observed_provider_tokens`), never merged; also composes a matching `token_impact_outcome` calibration post; payload carries counters + an opaque `sample_id` only, never raw prompts or recalled text, and a caller-omitted field is not invented |
+| `ingest_dedup` | always-on, fail-open; written ONLY by a run that actually dropped something | the three ingest runs that drop an item on an exact sha-256 `dedup_hash` collision: `captureSessionLifecycleEvent`, `scanInline`, `importSession` (`emitIngestDedupReport` in `src/core/brain/dedup-telemetry.ts`) - one record per run, payload carries the `surface`, the run's `exact_deduped` total, and a `by_source` map keyed by the session id or vault-relative note path being re-ingested. A run that deduped nothing writes NO record, so a real zero stays distinguishable from an absent measurement. Every count is an EXACT-hash drop; the semantic detectors nominate merge candidates and never drop, so no semantic figure appears here |
| `session_turn`, `session_summary_node` | always-on within its operation | session-recall import (`src/core/brain/session-recall.ts`) - the write IS the operation |
| `pre_compact_extract` | always-on within its operation | explicit pre-compact extraction (`src/core/brain/pre-compact-extract.ts`) |
| `source_invalidation` | always-on within its operation | source drift detection (`appendContinuitySourceInvalidation`) |
-Session lifecycle capture (`captureSessionLifecycleEvent`) writes audit rows and Brain log events but ZERO continuity records - that boundary is pinned by a regression test (`tests/core/brain/continuity-emit.test.ts`).
+Session lifecycle capture (`captureSessionLifecycleEvent`) writes audit rows and Brain log events, and no continuity record at all unless the event actually dropped a repeat - in which case it writes exactly one `ingest_dedup` record. Both halves of that boundary are pinned by regression tests (`tests/core/brain/continuity-emit.test.ts` for the silent path, `tests/core/brain/dedup-telemetry.test.ts` for the dedup path).
## Schema version and evolution rule
diff --git a/install/aider.md b/install/aider.md
index 2eb9e301..4bbd2aba 100644
--- a/install/aider.md
+++ b/install/aider.md
@@ -34,6 +34,21 @@ o2b install --check --target aider
Confirms both the managed block and the sidecar context file are
on disk.
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target aider -->
+
+```text
+o2b install --check
+--------------------
+ aider ok $HOME/.aider.conf.yml: managed block present; sidecar ok
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/copilot-cli.md b/install/copilot-cli.md
index 4eaffb91..ebe8bf22 100644
--- a/install/copilot-cli.md
+++ b/install/copilot-cli.md
@@ -26,6 +26,21 @@ o2b install --check --target copilot-cli
Verify queries `copilot mcp list` when the CLI is available, or
inspects the fallback file otherwise.
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target copilot-cli -->
+
+```text
+o2b install --check
+--------------------
+ copilot-cli ok both OSB names registered with copilot CLI
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/cursor.md b/install/cursor.md
index 9fb54d34..6f01a6ee 100644
--- a/install/cursor.md
+++ b/install/cursor.md
@@ -25,6 +25,27 @@ After install, **restart the Cursor app** for the new MCP servers
to load. `o2b install --check --target cursor` confirms the file
state regardless of whether Cursor has reloaded yet.
+## Verify
+
+```bash
+o2b install --check --target cursor
+```
+
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target cursor -->
+
+```text
+o2b install --check
+--------------------
+ cursor ok $HOME/.cursor/mcp.json: both OSB keys present
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/gemini-cli.md b/install/gemini-cli.md
index c948e685..3f0eb2e6 100644
--- a/install/gemini-cli.md
+++ b/install/gemini-cli.md
@@ -18,6 +18,21 @@ o2b install --target gemini-cli --apply
o2b install --check --target gemini-cli
```
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target gemini-cli -->
+
+```text
+o2b install --check
+--------------------
+ gemini-cli ok $HOME/.gemini/settings.json: both OSB keys present
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/generic.md b/install/generic.md
index b37a55c7..c79f245c 100644
--- a/install/generic.md
+++ b/install/generic.md
@@ -48,6 +48,27 @@ file — the consuming runtime may still depend on it. The
uninstall step prints the path so the operator can clean it up by
hand.
+## Verify
+
+```bash
+o2b install --check --target generic
+```
+
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target generic -->
+
+```text
+o2b install --check
+--------------------
+ generic ok generic: payload written to $HOME/osb-mcp.json (runtime wiring is operator-managed)
+```
+
+`$HOME/osb-mcp.json` is whatever path `--out` was given. This block
+is asserted against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Notes
- Detection always reports `not-installed` (there is no canonical
diff --git a/install/grok.md b/install/grok.md
index 4d001570..620d4217 100644
--- a/install/grok.md
+++ b/install/grok.md
@@ -82,6 +82,20 @@ Reports drift when the `config.toml` MCP tables or the hooks file differ from
canonical (for example after an Open Second Brain upgrade, or if `bun`/the repo
moved - re-run apply to refresh the absolute paths).
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target grok -->
+
+```text
+o2b install --check
+--------------------
+ grok ok
+```
+
+This block is asserted against the adapter's real `verify()` output
+by `tests/docs/install-verify-conformance.test.ts`, so it cannot
+drift from the code.
+
## Uninstall
```bash
diff --git a/install/kiro.md b/install/kiro.md
index 0ec41329..3591bbe2 100644
--- a/install/kiro.md
+++ b/install/kiro.md
@@ -18,6 +18,21 @@ Restart kiro to load the new servers.
o2b install --check --target kiro
```
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target kiro -->
+
+```text
+o2b install --check
+--------------------
+ kiro ok $HOME/.kiro/settings.json: both OSB keys present
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/opencode.md b/install/opencode.md
index 10d01a8d..09a62fa2 100644
--- a/install/opencode.md
+++ b/install/opencode.md
@@ -71,6 +71,21 @@ Reports drift when the MCP entries differ from canonical or the
installed plugin copy differs from the bundled version (for example
after an Open Second Brain upgrade - re-run apply to refresh it).
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target opencode -->
+
+```text
+o2b install --check
+--------------------
+ opencode ok $HOME/.config/opencode/opencode.json: both OSB keys present
+```
+
+`$HOME` stands in for your home directory. This block is asserted
+against the adapter's real `verify()` output by
+`tests/docs/install-verify-conformance.test.ts`, so it cannot drift
+from the code.
+
## Uninstall
```bash
diff --git a/install/pi.md b/install/pi.md
index d0a56d11..958fdfbe 100644
--- a/install/pi.md
+++ b/install/pi.md
@@ -24,6 +24,21 @@ o2b install --check --target pi
Confirms the symlink is valid and the source `SKILL.md` is
readable.
+A successful check prints:
+
+<!-- expected-output: o2b install --check --target pi -->
+
+```text
+o2b install --check
+--------------------
+ pi ok $HOME/.pi/skills/brain-memory → <plugin>/skills/brain-memory
+```
+
+`$HOME` is your home directory and `<plugin>` the plugin checkout.
+This block is asserted against the adapter's real `verify()` output
+by `tests/docs/install-verify-conformance.test.ts`, so it cannot
+drift from the code.
+
## Uninstall
```bash
diff --git a/install/prerequisites.md b/install/prerequisites.md
index df66f15d..e4f2df07 100644
--- a/install/prerequisites.md
+++ b/install/prerequisites.md
@@ -13,6 +13,27 @@ If you cannot install Bun (locked-down environment, unsupported
architecture), the plugin will not function on that host. No Python
fallback exists.
+## Supported platforms
+
+Linux, macOS and the other POSIX hosts Bun runs on. The default
+configuration path is `$HOME/.config/open-second-brain/config.yaml`,
+a POSIX convention; **Windows is not supported** and the resolver
+refuses by name there (`UnsupportedPlatformError`) rather than
+returning a path that no part of this build would look in. WSL is a
+Linux host and works normally.
+
+To run on an unsupported platform anyway, name the file yourself:
+
+```bash
+export OPEN_SECOND_BRAIN_CONFIG=/explicit/path/to/config.yaml
+# or point the whole configuration root somewhere:
+export XDG_CONFIG_HOME=/explicit/config/root
+```
+
+Both are honoured before the platform check, so nothing else in the
+CLI changes. Everything beyond the config path — path handling, the
+lifecycle hooks, the install adapters — is untested on Windows.
+
## Identity (agent name + timezone)
`o2b init` persists two values into `~/.config/open-second-brain/config.yaml`:
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 28979c52..77a41a35 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.39.0",
+ "version": "1.40.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index e44bbcbd..ac57bdfd 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.39.0",
+ "version": "1.40.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 898c21c5..96e2411b 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.39.0"
+version: "1.40.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 46b6a2c5..d4fa3125 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.39.0",
+ "version": "1.40.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/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 898c21c5..96e2411b 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.39.0"
+version: "1.40.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 ccf59457..bd0ab564 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.39.0"
+version = "1.40.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/advisory-rail.ts b/src/cli/advisory-rail.ts
new file mode 100644
index 00000000..89a4668c
--- /dev/null
+++ b/src/cli/advisory-rail.ts
@@ -0,0 +1,161 @@
+/**
+ * The advisory emission rail (no-dead-ends, task 2).
+ *
+ * Every forward-pointer line the CLI prints - "here is the command that
+ * moves this forward" - passes through this module, and through nothing
+ * else. It exists because that line is two decisions, and both were
+ * previously taken per verb, differently:
+ *
+ * 1. WHAT to say. The rail takes a diagnostic CODE and resolves it
+ * through `resolveNextStep`, so the command is the registry's
+ * structural CLI string. There is deliberately no parameter through
+ * which a caller can supply a command or a sentence: prose cannot
+ * enter this surface, and an unregistered code produces an explicit
+ * absent result rather than an invented hint.
+ * 2. WHETHER it is legal to say it here. Twelve top-level commands
+ * render their own JSON, and their stdout is a payload a caller
+ * parses; one stray advisory line breaks it. Everything else is
+ * wrapped by `withJsonFallback`, whose envelope buffers stdout, so a
+ * line there is harmless. The rail asks `ownsInternalJson` rather
+ * than leaving each verb to remember which family it is in.
+ *
+ * The caller supplies `jsonRequested` from its own PARSED flags, never
+ * from a raw-argv scan: a positional whose text happens to contain the
+ * flag would otherwise silence a legitimate human-path advisory.
+ *
+ * Suppression is not a drop. A suppressed emission still returns the
+ * resolved `NextStep`, so a JSON verb carries it as a field in its own
+ * payload - which is where it belongs on that stream.
+ */
+
+import { resolveNextStep, type NextStep } from "../core/brain/next-step.ts";
+
+import { ownsInternalJson } from "./json-helpers.ts";
+import { info } from "./output.ts";
+
+/** Structural label prefixed to every advisory line. */
+const NEXT_STEP_LABEL = "next:";
+
+/** The output stream an emission is being considered for. */
+export interface AdvisoryStream {
+ /** Top-level `o2b` command, e.g. `brain`. */
+ readonly command: string;
+ /** Argv tail after the top-level command, as `main` dispatched it. */
+ readonly argv: ReadonlyArray<string>;
+ /**
+ * Whether the caller asked for JSON, read from the verb's PARSED flags.
+ * Never a raw-argv scan - see the module docblock.
+ */
+ readonly jsonRequested: boolean;
+}
+
+/** Why an emission did or did not reach stdout. Every case is named. */
+export const ADVISORY_OUTCOME = Object.freeze({
+ /** The line was written to stdout. */
+ emitted: "emitted",
+ /** Stdout is a machine-parsed payload; the line stayed off it. */
+ suppressedMachineStream: "suppressed-machine-stream",
+ /** No signal is registered for the code, so there is no command to name. */
+ unregisteredCode: "unregistered-code",
+} as const);
+
+export type AdvisoryOutcome = (typeof ADVISORY_OUTCOME)[keyof typeof ADVISORY_OUTCOME];
+
+/** What one rail call did, in full. */
+export interface AdvisoryEmission {
+ /**
+ * The code this call was made for, echoed back. Load-bearing for the
+ * unregistered outcome: without it a caller learns that one of its
+ * codes has no exit but not WHICH, and the batch form's contract of
+ * reporting such codes "by name" would be unmeetable.
+ */
+ readonly code: string;
+ readonly outcome: AdvisoryOutcome;
+ /** The resolved step, or `null` iff the code is unregistered. */
+ readonly nextStep: NextStep | null;
+ /** The exact line written, or `null` when nothing was written. */
+ readonly line: string | null;
+}
+
+/**
+ * True when an advisory line may be written to stdout for `stream`. False
+ * only when the caller asked for JSON from a command that renders its own:
+ * the envelope-wrapped family buffers stdout, so a line there is safe.
+ */
+export function advisoryIsLegal(stream: AdvisoryStream): boolean {
+ if (!stream.jsonRequested) return true;
+ return !ownsInternalJson(stream.command, stream.argv);
+}
+
+/** Render `step` as the one-line form the human surfaces print. */
+export function renderNextStepLine(step: NextStep): string {
+ return `${NEXT_STEP_LABEL} ${step.nextCommand}`;
+}
+
+/**
+ * Resolve `code` and, if the stream allows it, print its next-step line.
+ *
+ * Never throws: an unregistered code is a caller that has not registered
+ * its diagnostic yet, not a crash, and the doctor surfaces must be able to
+ * report such an issue without inventing a command for it. The outcome
+ * distinguishes that case from a suppressed one, so neither is silent.
+ */
+export function emitNextStep(code: string, stream: AdvisoryStream): AdvisoryEmission {
+ const nextStep = resolveNextStep(code);
+ if (nextStep === null) {
+ return Object.freeze({
+ code,
+ outcome: ADVISORY_OUTCOME.unregisteredCode,
+ nextStep: null,
+ line: null,
+ });
+ }
+ if (!advisoryIsLegal(stream)) {
+ return Object.freeze({
+ code,
+ outcome: ADVISORY_OUTCOME.suppressedMachineStream,
+ nextStep,
+ line: null,
+ });
+ }
+ const line = renderNextStepLine(nextStep);
+ info(line);
+ return Object.freeze({ code, outcome: ADVISORY_OUTCOME.emitted, nextStep, line });
+}
+
+/**
+ * Batch form: emit the DISTINCT next steps for `codes`, in the order
+ * their commands first appear.
+ *
+ * A diagnosis surface reports issues, not exits, and the two are not one
+ * to one: two hundred broken wikilinks share a single repair command,
+ * and two different codes can share one too. Emitting per issue would
+ * bury the answer in repetition, so the de-duplication rule lives here
+ * rather than in each verb that reports a batch - the rail already owns
+ * what reaches stdout, and one rule cannot drift from itself.
+ *
+ * De-duplication is keyed on the resolved COMMAND, not on the code,
+ * because the caller acts on commands. Unregistered codes are returned
+ * once each so the caller can still see, by name, which of its issues
+ * has no registered exit; they never print.
+ */
+export function emitNextSteps(
+ codes: Iterable<string>,
+ stream: AdvisoryStream,
+): ReadonlyArray<AdvisoryEmission> {
+ const seenCommands = new Set<string>();
+ const seenUnregistered = new Set<string>();
+ const emissions: AdvisoryEmission[] = [];
+ for (const code of codes) {
+ const resolved = resolveNextStep(code);
+ if (resolved === null) {
+ if (seenUnregistered.has(code)) continue;
+ seenUnregistered.add(code);
+ } else {
+ if (seenCommands.has(resolved.nextCommand)) continue;
+ seenCommands.add(resolved.nextCommand);
+ }
+ emissions.push(emitNextStep(code, stream));
+ }
+ return Object.freeze(emissions);
+}
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 05cf8b78..d2618bf3 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -726,12 +726,15 @@ export const VERB_HELP: Record<string, string> = {
" o2b brain generation-reports show <report-id> [--vault <path>] [--json]\n" +
"Inbound, opt-in LLM generation tracing. record is gated (default off) by --enable or generation_trace_enabled; only prompt_hash + counts are stored, never the prompt.\n",
"skill-proposals":
- "usage: o2b brain skill-proposals <learn|list|accept|reject> [args]\n" +
+ "usage: o2b brain skill-proposals <learn|list|accept|reject|recover|usage> [args]\n" +
"Deterministic proposal queue lifecycle.\n" +
" learn [--min-support <n>] [--vault <path>] [--json]\n" +
" list [--vault <path>] [--json]\n" +
" accept <slug> [--note <text>] [--vault <path>] [--json]\n" +
- " reject <slug> --note <text> [--vault <path>] [--json]\n",
+ " reject <slug> --note <text> [--vault <path>] [--json]\n" +
+ " recover [--discard-unreadable] [--vault <path>] [--json]\n" +
+ " usage [--vault <path>] [--json]\n" +
+ "recover resolves accept sequences a crash abandoned. It refuses, naming the file, on a held accept lock and on an unreadable journal marker; --discard-unreadable removes those markers.\n",
"procedural-memory":
"usage: o2b brain procedural-memory <reconcile|list|mark-used> [args]\n" +
"Procedural index reconciliation and usage tracking sidecar.\n" +
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index 727d0b06..f5048307 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -95,7 +95,7 @@ export function parse(
// ── Re-exports (the barrel that verb handlers import from) ──────────────────
export { CliError } from "../argparse.ts";
-export { fail, info, ok, okJson } from "../output.ts";
+export { fail, failWith, info, ok, okJson } from "../output.ts";
/**
* Usage / argument error: plain message to stderr, exit code 2. Distinct
diff --git a/src/cli/brain/verbs/bridges.ts b/src/cli/brain/verbs/bridges.ts
index b284a44a..74509b32 100644
--- a/src/cli/brain/verbs/bridges.ts
+++ b/src/cli/brain/verbs/bridges.ts
@@ -36,6 +36,8 @@ import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { SearchError } from "../../../core/search/types.ts";
import { parseFrontmatter } from "../../../core/vault.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
@@ -50,6 +52,10 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
json: { type: "boolean" },
});
const asJson = flags["json"] === true;
+ // no-dead-ends, task 5: both fail-soft exits below used to carry their
+ // own `- run: <command>` tail inside the status line. They resolve
+ // through the registry now, so the command is written down once.
+ const stream: AdvisoryStream = { command: "brain", argv, jsonRequested: asJson };
const action = positional[0];
if (
action === undefined ||
@@ -84,8 +90,13 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
if (action === "list") {
const path = join(vault, "Brain", "proposals", "bridges.md");
if (!existsSync(path)) {
- if (asJson) okJson({ exists: false, proposals: 0 });
- else ok("no proposals artifact yet - run: o2b brain bridges discover");
+ // no-dead-ends, phase 3: the rail suppresses its line here and
+ // returns the step so this payload can carry it. Nothing did.
+ if (asJson) {
+ okJson({ exists: false, proposals: 0, ...nextCommandField("bridge-proposals-absent") });
+ } else ok("no proposals artifact yet");
+ // no-dead-ends, task 5: the exit is this verb's own producer.
+ emitNextStep("bridge-proposals-absent", stream);
return 0;
}
const [meta, body] = parseFrontmatter(path);
@@ -119,8 +130,16 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {
exc instanceof SearchError &&
(exc.code === "INDEX_MISSING" || exc.code === "SCHEMA_MISMATCH")
) {
- if (asJson) okJson({ vec_available: false, proposals: [], reason: "index not built" });
- else ok("bridges discover: search index not initialised - run: o2b search index");
+ if (asJson) {
+ okJson({
+ vec_available: false,
+ proposals: [],
+ reason: "index not built",
+ ...nextCommandField("search-index-missing"),
+ });
+ } else ok("bridges discover: search index not initialised");
+ // no-dead-ends, task 5: fail-soft, but not silent about the fix.
+ emitNextStep("search-index-missing", stream);
return 0;
}
throw exc;
diff --git a/src/cli/brain/verbs/clusters.ts b/src/cli/brain/verbs/clusters.ts
index 4baaa37f..f8156aa7 100644
--- a/src/cli/brain/verbs/clusters.ts
+++ b/src/cli/brain/verbs/clusters.ts
@@ -31,6 +31,8 @@ import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { SearchError } from "../../../core/search/types.ts";
import { listVaultPages, parseFrontmatter } from "../../../core/vault.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
@@ -66,6 +68,10 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
json: { type: "boolean" },
});
const asJson = flags["json"] === true;
+ // no-dead-ends, task 5: the fail-soft "no index" exit below shares its
+ // registry code with the identical branch in `bridges`, so the two
+ // cannot drift on what an operator is told to run.
+ const stream: AdvisoryStream = { command: "brain", argv, jsonRequested: asJson };
const action = positional[0];
if ((action !== "run" && action !== "list") || positional.length !== 1) {
process.stderr.write(`${USAGE}\n`);
@@ -78,8 +84,12 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
if (action === "list") {
const dir = join(vault, "Brain", "clusters");
if (!existsSync(dir)) {
- if (asJson) okJson({ clusters: [] });
- else ok("no cluster notes yet - run: o2b brain clusters run");
+ if (asJson) okJson({ clusters: [], ...nextCommandField("cluster-notes-absent") });
+ else ok("no cluster notes yet");
+ // no-dead-ends, phase 3: this pointer was hand-written in the
+ // same file as a migrated one, so `list` printed `- run: ...`
+ // while `run` printed `next: ...`.
+ emitNextStep("cluster-notes-absent", stream);
return 0;
}
const clusters = readdirSync(dir)
@@ -98,9 +108,18 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
: null;
})
.filter((c) => c !== null);
- if (asJson) okJson({ clusters });
- else if (clusters.length === 0) ok("no generated cluster notes");
- else {
+ if (asJson) {
+ okJson({
+ clusters,
+ ...(clusters.length === 0 ? nextCommandField("cluster-notes-absent") : {}),
+ });
+ } else if (clusters.length === 0) {
+ // The directory exists but holds nothing this verb generated -
+ // the SAME state as the missing-directory branch above, which
+ // previously said nothing forward at all.
+ ok("no generated cluster notes");
+ emitNextStep("cluster-notes-absent", stream);
+ } else {
for (const c of clusters) {
ok(`${c.cluster}: ${c.size} notes, density ${c.density} (${c.path})`);
}
@@ -154,8 +173,14 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {
exc instanceof SearchError &&
(exc.code === "INDEX_MISSING" || exc.code === "SCHEMA_MISMATCH")
) {
- if (asJson) okJson({ communities: 0, reason: "index not built" });
- else ok("clusters run: search index not initialised - run: o2b search index");
+ if (asJson) {
+ okJson({
+ communities: 0,
+ reason: "index not built",
+ ...nextCommandField("search-index-missing"),
+ });
+ } else ok("clusters run: search index not initialised");
+ emitNextStep("search-index-missing", stream);
return 0;
}
throw exc;
diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.ts
index 93972714..8dcb3703 100644
--- a/src/cli/brain/verbs/doctor.ts
+++ b/src/cli/brain/verbs/doctor.ts
@@ -8,7 +8,67 @@ import {
planRemediation,
} from "../../../core/brain/health/remediation.ts";
import { loadBrainConfigDetailed, resolveHealth } from "../../../core/brain/policy.ts";
-import { brainVerbContext, fail, ok, parse, resolveBrainAgent, usageError } from "../helpers.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { NO_EXIT_KEY, noExitReasons } from "../../../core/brain/doctor-exits.ts";
+import type { DoctorIssue } from "../../../core/brain/types.ts";
+import { advisoryIsLegal, emitNextSteps, type AdvisoryStream } from "../../advisory-rail.ts";
+import {
+ brainVerbContext,
+ fail,
+ info,
+ ok,
+ parse,
+ resolveBrainAgent,
+ usageError,
+} from "../helpers.ts";
+
+/**
+ * One reported issue, machine-readable: the record the doctor produced
+ * plus the structural next command when its code is registered.
+ *
+ * The key is spread LAST so the pre-existing field order is untouched
+ * and an unregistered code produces byte-identical JSON. The builder is
+ * shared with the `brain_doctor` MCP tool through `nextCommandField`, so
+ * the two surfaces cannot disagree on the spelling or on which codes
+ * resolve.
+ */
+function withNextCommand<T extends Pick<DoctorIssue, "code">>(issue: T): Record<string, unknown> {
+ return { ...issue, ...nextCommandField(issue.code) };
+}
+
+/**
+ * One reported issue, human-readable. `label` carries its own trailing
+ * padding because the three streams have never been column-aligned and
+ * this task does not change a byte of what they print; the renderer
+ * exists so the three call sites stop repeating the same template.
+ */
+function renderIssueLine(
+ label: string,
+ issue: Pick<DoctorIssue, "code" | "message"> & { readonly path?: string },
+): string {
+ return `${label} ${issue.code}: ${issue.message}${issue.path ? ` (${issue.path})` : ""}\n`;
+}
+
+/**
+ * The other half of the rail's answer: why a reported code named no
+ * command.
+ *
+ * `emitNextSteps` prints one line per exit and nothing for a code with
+ * none, which left two different situations looking identical - a class
+ * no single command resolves, and a class nobody has registered yet.
+ * `doctor-exits.ts` publishes the first as a written reason, and this
+ * prints it once per code, after the exits.
+ *
+ * It follows the rail's own stream discipline rather than deciding for
+ * itself: on a machine stream the reasons ride in the payload instead.
+ * The limit, stated: only codes the table publishes produce a line, so a
+ * code forwarded into `uncertain` from another module's vocabulary stays
+ * as quiet as it was - those are classified in `applier-capability.ts`.
+ */
+function explainMissingExits(codes: Iterable<string>, stream: AdvisoryStream): void {
+ if (!advisoryIsLegal(stream)) return;
+ for (const [code, reason] of noExitReasons(codes)) info(`no exit: ${code} - ${reason}`);
+}
export async function cmdBrainDoctor(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -60,13 +120,24 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {
return fail(`doctor failed: ${(exc as Error).message ?? exc}`);
}
+ // Where an advisory line may legally go. `brain` renders its own JSON,
+ // so under `--json` the rail suppresses every line and the pointer
+ // travels as a payload field instead. The verb never decides this for
+ // itself - see `advisory-rail.ts`.
+ const stream: AdvisoryStream = {
+ command: "brain",
+ argv,
+ jsonRequested: Boolean(flags["json"]),
+ };
+
if (flags["remediate"]) {
// Never auto-repair a vault that has structural errors - those need
// an operator, and remediation assumes a parseable tree.
if (result.errors.length > 0) {
- for (const e of result.errors) {
- process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);
- }
+ for (const e of result.errors) process.stdout.write(renderIssueLine("[ERROR]", e));
+ const errorCodes = result.errors.map((e) => e.code);
+ emitNextSteps(errorCodes, stream);
+ explainMissingExits(errorCodes, stream);
return fail("doctor found errors; remediation aborted");
}
try {
@@ -85,30 +156,53 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {
// field into a broken build.
const uncertain = result.uncertain ?? [];
+ // Every code the three streams reported, in the order an operator reads
+ // them. Feeds both the rail and the explanation of what the rail could
+ // not name, so the two can never disagree about which codes have an exit.
+ const reportedCodes = [...result.errors, ...result.warnings, ...uncertain].map(
+ (issue) => issue.code,
+ );
+ // Published reasons for the reported codes that resolve to no command.
+ // Empty - hence the key absent, hence byte-identical output - whenever
+ // every reported code has an exit, and on a clean vault.
+ const noExit = noExitReasons(reportedCodes);
+
if (flags["json"]) {
process.stdout.write(
JSON.stringify(
{
- warnings: result.warnings,
- errors: result.errors,
- ...(uncertain.length > 0 ? { uncertain } : {}),
+ warnings: result.warnings.map(withNextCommand),
+ errors: result.errors.map(withNextCommand),
+ ...(uncertain.length > 0 ? { uncertain: uncertain.map(withNextCommand) } : {}),
+ // Beside the streams, once per code, rather than repeated on
+ // every issue record: a reason is about a CLASS, unlike a next
+ // command, and two hundred malformed timestamps share one.
+ ...(noExit.size > 0 ? { [NO_EXIT_KEY]: Object.fromEntries(noExit) } : {}),
},
null,
2,
) + "\n",
);
} else {
- for (const e of result.errors)
- process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);
- for (const w of result.warnings)
- process.stdout.write(`[WARN] ${w.code}: ${w.message}${w.path ? ` (${w.path})` : ""}\n`);
- for (const u of uncertain)
- process.stdout.write(`[UNSURE] ${u.code}: ${u.message}${u.path ? ` (${u.path})` : ""}\n`);
+ for (const e of result.errors) process.stdout.write(renderIssueLine("[ERROR]", e));
+ for (const w of result.warnings) process.stdout.write(renderIssueLine("[WARN] ", w));
+ for (const u of uncertain) process.stdout.write(renderIssueLine("[UNSURE]", u));
if (result.errors.length === 0 && result.warnings.length === 0 && uncertain.length === 0) {
ok("brain doctor: clean");
}
}
+ // no-dead-ends, task 4: the exits, after the diagnosis. Errors first,
+ // then warnings, then the uncertain stream - the order an operator
+ // reads them in. The rail prints nothing under `--json` (the pointer
+ // rode out as `next_command` above) and nothing for a code with no
+ // registered signal.
+ emitNextSteps(reportedCodes, stream);
+ // ...and, after them, why the codes that named none have none. Without
+ // this a finding with no exit and a finding whose exit nobody
+ // registered read identically.
+ explainMissingExits(reportedCodes, stream);
+
if (result.errors.length > 0) return 1;
if (result.warnings.length > 0 && flags["strict"]) return 2;
return 0;
diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.ts
index 1af668da..a567b866 100644
--- a/src/cli/brain/verbs/dream.ts
+++ b/src/cli/brain/verbs/dream.ts
@@ -1,19 +1,41 @@
/**
- * `o2b brain dream [run] [--dry-run] | stage | validate <run-id> |
- * apply <run-id> | discard <run-id> | list` - the learning pass plus
- * the staged lifecycle (t_ae8a8ec0). `run` (the default, kept
- * positional-free for back-compat) promotes inline; `stage` persists
- * a reviewable proposal bundle; `validate` proves the vault has not
- * drifted; `apply` re-validates and runs the same engine live;
- * `discard` drops the bundle.
+ * `o2b brain dream [run] [--dry-run] [--step S] [--gate N=V] | stage |
+ * validate <run-id> | apply <run-id> | discard <run-id> | list` - the
+ * learning pass plus the staged lifecycle (t_ae8a8ec0). `run` (the
+ * default, kept positional-free for back-compat) promotes inline;
+ * `stage` persists a reviewable proposal bundle; `validate` proves the
+ * vault has not drifted; `apply` re-validates and runs the same engine
+ * live; `discard` drops the bundle.
+ *
+ * `--step` and `--gate` (no-dead-ends, Unit E - operator surface) are
+ * the shell reach for the two capabilities that previously existed only
+ * as TypeScript arguments: `runDreamStep` and `DreamOptions.gates`.
+ * Both belong to the default `run` action and both refuse by name -
+ * `--step` through `DreamStepNotRunnableError`, which carries the
+ * specific reason and the runnable set, and `--gate` through
+ * `DreamGateOverrideError`. Neither writes anything back to
+ * `Brain/_brain.yaml`; with both absent the verb is byte-identical.
*
* Exit codes: 0 on success, 1 on operational failure (including a
- * failed validation - scripts gate on it), 2 on usage errors.
+ * failed validation - scripts gate on it), 2 on usage errors, which is
+ * where a refused step or gate lands: the request was understood and
+ * declined, not attempted and broken.
*/
import { resolveAgentName } from "../../../core/config.ts";
-import { dream } from "../../../core/brain/dream.ts";
+import { dream, type DreamGateOverrides } from "../../../core/brain/dream.ts";
import { CountGuardError, assertExpectedCount } from "../../../core/brain/count-guard.ts";
+import {
+ DREAM_GATE_NAMES,
+ DreamGateOverrideError,
+ parseDreamGateOverrides,
+} from "../../../core/brain/dream-gates.ts";
+import {
+ DREAM_STEP_RUNNABLE,
+ DreamStepNotRunnableError,
+ runDreamStep,
+ type DreamStepResult,
+} from "../../../core/brain/dream-step.ts";
import {
applyDreamBundle,
discardDreamBundle,
@@ -26,14 +48,50 @@ import {
resolveSafeguardTimeoutMs,
SafeguardTimeoutError,
} from "../../../core/brain/safeguard.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep } from "../../advisory-rail.ts";
import { brainVerbContext, fail, ok, okJson, parse, parseOptionalIsoDate } from "../helpers.ts";
+// The runnable set is read from the step registry, never retyped: a
+// usage line that advertises a step the pass refuses is its own dead end.
const USAGE =
- "usage: o2b brain dream [run] [--dry-run] | stage | validate <run-id> | " +
- "apply <run-id> | discard <run-id> | list [--now ISO] [--agent A] [--vault <path>] [--json]";
+ `usage: o2b brain dream [run] [--dry-run] [--step <${DREAM_STEP_RUNNABLE.join("|")}>] ` +
+ `[--gate <${DREAM_GATE_NAMES.join("|")}>=<true|false>] | ` +
+ "stage | validate <run-id> | apply <run-id> | discard <run-id> | list " +
+ "[--now ISO] [--agent A] [--vault <path>] [--json]";
const ACTIONS = new Set(["run", "stage", "validate", "apply", "discard", "list"]);
+/**
+ * Refuse a request this verb understood and declined. Exit 2, with the
+ * reason on stderr for a human and as a payload for a machine - never a
+ * stray line on a stream a caller parses.
+ */
+function refuse(message: string, asJson: boolean, payload: Record<string, unknown> = {}): number {
+ if (asJson) {
+ okJson({ ok: false, ...payload, message });
+ return 2;
+ }
+ process.stderr.write(`error: ${message}\n`);
+ return 2;
+}
+
+/** Render one partial step result as the verb's human line format. */
+function printStepResult(result: DreamStepResult): void {
+ ok(`step: ${result.step}`);
+ if (result.step === "scan") {
+ ok(`active_signals: ${result.active_signals}`);
+ ok(`processed_signals: ${result.processed_signals}`);
+ ok(`preferences: ${result.preferences}`);
+ ok(`retired: ${result.retired}`);
+ if (result.corrupted.length > 0) ok(`corrupted: ${result.corrupted.join(", ")}`);
+ return;
+ }
+ ok(`scanned: ${result.scanned}`);
+ ok(`enriched: ${result.enriched}`);
+ if (result.pages.length > 0) ok(`pages: ${result.pages.join(", ")}`);
+}
+
export async function cmdBrainDream(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
vault: { type: "string" },
@@ -42,6 +100,8 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
agent: { type: "string" },
expect: { type: "string" },
strict: { type: "boolean" },
+ step: { type: "string" },
+ gate: { type: "string-array" },
json: { type: "boolean" },
});
const asJson = flags["json"] === true;
@@ -55,6 +115,74 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
process.stderr.write(`${USAGE}\n`);
return 2;
}
+
+ // --- Operator-surface argument checks (no-dead-ends, Unit E) --------
+ // Both live on the default `run` action and each is refused by name
+ // where it would otherwise be accepted and quietly ignored.
+ const stepRequest = flags["step"];
+ const gateEntries = (flags["gate"] as string[] | undefined) ?? [];
+ const wantsStep = typeof stepRequest === "string";
+ if ((wantsStep || gateEntries.length > 0) && action !== "run") {
+ return refuse(
+ `brain dream: --step and --gate steer the default 'run' action; ` +
+ `'${action}' drives the staged lifecycle, which has neither a single step nor a gate to override`,
+ asJson,
+ { action },
+ );
+ }
+ if (wantsStep) {
+ // Every flag below configures work a single step does not do, so
+ // accepting one alongside --step would silently drop it.
+ const conflict =
+ gateEntries.length > 0
+ ? {
+ flag: "--gate",
+ reason:
+ "a gate steers a full pass; the 'heal-enrich' step IS the opt-in and the 'scan' step reads no gate, so an override would have nothing to apply to",
+ }
+ : flags["dry-run"] === true
+ ? {
+ flag: "--dry-run",
+ reason:
+ "runDreamStep has no preview path - 'scan' already writes nothing and 'heal-enrich' has no plan-only mode, so a dry run would be either a no-op dressed as a preview or a write",
+ }
+ : flags["expect"] !== undefined
+ ? {
+ flag: "--expect",
+ reason:
+ "the count guard asserts over the preferences a full pass creates, confirms, retires or moves, and a single step produces none of those counters",
+ }
+ : flags["strict"] === true
+ ? {
+ flag: "--strict",
+ reason:
+ "it demands a count guard over the preferences a full pass changes, and a single step changes none of them",
+ }
+ : null;
+ if (conflict !== null) {
+ return refuse(
+ `brain dream: --step cannot be combined with ${conflict.flag}: ${conflict.reason}`,
+ asJson,
+ { step: stepRequest, conflicting_flag: conflict.flag },
+ );
+ }
+ }
+
+ let gates: DreamGateOverrides | null = null;
+ if (gateEntries.length > 0) {
+ try {
+ gates = parseDreamGateOverrides(gateEntries);
+ } catch (exc) {
+ if (exc instanceof DreamGateOverrideError) {
+ return refuse(`brain dream: ${exc.message}`, asJson, {
+ entry: exc.entry,
+ known_gates: [...exc.known],
+ });
+ }
+ throw exc;
+ }
+ }
+
const { config, vault } = brainVerbContext(flags);
const agentFlag = flags["agent"];
@@ -78,6 +206,33 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
timeoutMs: resolveSafeguardTimeoutMs("dream", config ?? undefined),
});
+ if (wantsStep) {
+ let result: DreamStepResult;
+ try {
+ result = runDreamStep(vault, stepRequest);
+ } catch (exc) {
+ if (exc instanceof DreamStepNotRunnableError) {
+ return refuse(exc.message, asJson, {
+ step: exc.requested,
+ runnable: [...exc.runnable],
+ reason: exc.reason,
+ });
+ }
+ const message = `dream step ${stepRequest} failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, step: stepRequest, message });
+ return 1;
+ }
+ return fail(message);
+ }
+ if (asJson) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+ printStepResult(result);
+ return 0;
+ }
+
try {
if (action === "stage") {
const bundle = stageDream(vault, {
@@ -158,9 +313,13 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
proposals: b.proposals,
sources: b.sources,
})),
+ ...(bundles.length === 0 ? nextCommandField("dream-bundles-absent") : {}),
});
} else if (bundles.length === 0) {
- ok("no dream bundles - run: o2b brain dream stage");
+ ok("no dream bundles");
+ // no-dead-ends, phase 3: this pointer was hand-written beside
+ // the rail. One mechanism, one line format.
+ emitNextStep("dream-bundles-absent", { command: "brain", argv, jsonRequested: asJson });
} else {
for (const b of bundles) {
ok(`${b.runId} ${b.status} staged ${b.stagedAt} ${b.proposals} proposal(s)`);
@@ -197,6 +356,9 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
...(now !== null ? { now } : {}),
dryRun: true,
...(agent ? { agentName: agent } : {}),
+ // The guard must preview the run it is guarding, overrides and
+ // all, or it asserts a count for a pass that will not happen.
+ ...(gates !== null ? { gates } : {}),
});
const matchList = [
...preview.new_unconfirmed,
@@ -224,6 +386,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
dryRun: Boolean(flags["dry-run"]),
...(agent ? { agentName: agent } : {}),
safeguard: guard(),
+ ...(gates !== null ? { gates } : {}),
});
} catch (exc) {
if (exc instanceof SafeguardTimeoutError && asJson) {
diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.ts
index 8931e891..a776ecb0 100644
--- a/src/cli/brain/verbs/feedback.ts
+++ b/src/cli/brain/verbs/feedback.ts
@@ -133,6 +133,16 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
confirmed_at: now.toISOString(),
status: BRAIN_PREFERENCE_STATUS.confirmed,
evidenced_by: [`[[${sigResult.id}]]`],
+ // Issue #149: an explicit zero, not an absent value. The
+ // on-disk encoding of "absent" is the literal `null`, and two
+ // ranking surfaces (`pre-compress-pack`, `morning-brief`) map
+ // `null` to negative infinity before sorting - so a rule
+ // force-confirmed a second ago would sort BELOW every rule
+ // that has a number, including one measured at zero. Zero is
+ // also the true Wilson lower bound on no evidence, which is
+ // why the dream pass already pre-seeds it for new
+ // preferences. This writer now matches it.
+ confidence_value: 0,
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
},
{ overwrite: false },
diff --git a/src/cli/brain/verbs/git.ts b/src/cli/brain/verbs/git.ts
index ed35fe70..c5decc9a 100644
--- a/src/cli/brain/verbs/git.ts
+++ b/src/cli/brain/verbs/git.ts
@@ -11,12 +11,24 @@ import { mineCommitDecisions } from "../../../core/brain/git/decisions.ts";
import { GitIngestError, ingestGitHistory } from "../../../core/brain/git/ingest.ts";
import { listGitCommits, listGitRepos, listGitTags } from "../../../core/brain/git/store.ts";
import type { GitCommitFilter, GitCommitRecord } from "../../../core/brain/git/store.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE = "usage: o2b brain git <ingest|status|find|mine> [args] [--vault V] [--json]";
const FIND_DEFAULT_LIMIT = 20;
+/**
+ * Advisory stream for this verb (no-dead-ends, task 5). Two subverbs
+ * reach the same "nothing ingested yet" state, and both used to carry
+ * their own `(run: o2b brain git ingest <repo-path>)` parenthetical
+ * inside the status line. One registry code, one rail, one shape.
+ */
+function gitAdvisoryStream(argv: ReadonlyArray<string>, jsonRequested: boolean): AdvisoryStream {
+ return { command: "brain", argv, jsonRequested };
+}
+
export async function cmdBrainGit(argv: string[]): Promise<number> {
const action = argv[0];
if (action === "ingest") return cmdIngest(argv.slice(1));
@@ -53,11 +65,17 @@ async function cmdMine(argv: string[]): Promise<number> {
skipped_existing: res.skippedExisting,
notes: res.notes,
})),
+ // no-dead-ends, phase 3: the rail returns the resolved step when
+ // it suppresses the line; this payload carries it.
+ ...(results.length === 0 ? nextCommandField("git-history-absent") : {}),
});
return 0;
}
if (results.length === 0) {
- ok("no git history ingested yet (run: o2b brain git ingest <repo-path>)");
+ ok("no git history ingested yet");
+ // The `--json` branch above returned, so this stream is provably
+ // a human one.
+ emitNextStep("git-history-absent", gitAdvisoryStream(argv, false));
return 0;
}
for (const res of results) {
@@ -135,11 +153,17 @@ async function cmdStatus(argv: string[]): Promise<number> {
tags: listGitTags(vault, entry.key).length,
}));
if (flags["json"] === true) {
- okJson({ ok: true, repos });
+ okJson({
+ ok: true,
+ repos,
+ ...(repos.length === 0 ? nextCommandField("git-history-absent") : {}),
+ });
return 0;
}
if (repos.length === 0) {
- ok("no git history ingested yet (run: o2b brain git ingest <repo-path>)");
+ ok("no git history ingested yet");
+ // The `--json` branch above returned; this stream is human.
+ emitNextStep("git-history-absent", gitAdvisoryStream(argv, false));
return 0;
}
for (const repo of repos) {
diff --git a/src/cli/brain/verbs/inbox-drain.ts b/src/cli/brain/verbs/inbox-drain.ts
index cdc2df3e..f1a8681f 100644
--- a/src/cli/brain/verbs/inbox-drain.ts
+++ b/src/cli/brain/verbs/inbox-drain.ts
@@ -14,6 +14,8 @@ import {
type DrainItem,
type DrainReport,
} from "../../../core/brain/capture/inbox-drain.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep } from "../../advisory-rail.ts";
import { brainVerbContext, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
function itemJson(item: DrainItem): Record<string, unknown> {
@@ -49,8 +51,15 @@ export async function cmdBrainInboxDrain(argv: string[]): Promise<number> {
const agent = resolveBrainAgent(flags, config);
const report = drainInbox(vault, { apply: flags["apply"] === true, agent, now: new Date() });
+ const pending = flags["apply"] !== true && report.items.length > 0;
+
if (flags["json"] === true) {
- okJson(reportJson(report));
+ // no-dead-ends, phase 3: the exit was computed on the human path and
+ // discarded here.
+ okJson({
+ ...reportJson(report),
+ ...(pending ? nextCommandField("staged-captures-pending") : {}),
+ });
return 0;
}
@@ -62,8 +71,12 @@ export async function cmdBrainInboxDrain(argv: string[]): Promise<number> {
ok(
` routed ${report.routed}, unroutable ${report.unroutable}, archive-failed ${report.archiveFailed}`,
);
- if (!flags["apply"] && report.items.length > 0) {
- ok(" re-run with --apply to route and archive");
+ if (pending) {
+ // no-dead-ends, task 7: the terminal-state census found this
+ // hand-written pointer, which the rail-detection could not see. One
+ // mechanism, one line format. The `--json` branch above returned, so
+ // this stream is provably a human one.
+ emitNextStep("staged-captures-pending", { command: "brain", argv, jsonRequested: false });
}
return 0;
}
diff --git a/src/cli/brain/verbs/init.ts b/src/cli/brain/verbs/init.ts
index a24ad3fe..22f783b9 100644
--- a/src/cli/brain/verbs/init.ts
+++ b/src/cli/brain/verbs/init.ts
@@ -1,5 +1,8 @@
import { defaultConfigPath } from "../../../core/config.ts";
import { bootstrapBrain } from "../../../core/brain/init.ts";
+import { computeBrainStatus } from "../../../core/brain/status.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { parse, fail, ok, info, okJson, resolveBrainVault } from "../helpers.ts";
export async function cmdBrainInit(argv: string[]): Promise<number> {
@@ -47,18 +50,57 @@ export async function cmdBrainInit(argv: string[]): Promise<number> {
return fail(`failed to initialize Brain: ${(exc as Error).message ?? exc}`);
}
+ const stream: AdvisoryStream = {
+ command: "brain",
+ argv,
+ jsonRequested: Boolean(flags["json"]),
+ };
+
+ // Resolved once, ahead of both renderers: the human stream prints it
+ // as a rail line and the machine stream carries it as a field, and a
+ // second evaluation could disagree with the first.
+ const empty = brainHasNothingRecorded(vault);
+
if (flags["json"]) {
okJson({
vault,
created: result.created,
overwritten: result.overwritten,
skipped: result.skipped,
+ ...(empty ? nextCommandField("brain-empty") : {}),
});
- return 0;
+ } else {
+ ok(`brain initialized: ${vault}`);
+ for (const p of result.created) info(` created: ${p}`);
+ for (const p of result.overwritten) info(` overwritten: ${p}`);
+ for (const p of result.skipped) info(` exists: ${p}`);
}
- ok(`brain initialized: ${vault}`);
- for (const p of result.created) info(` created: ${p}`);
- for (const p of result.overwritten) info(` overwritten: ${p}`);
- for (const p of result.skipped) info(` exists: ${p}`);
+
+ // no-dead-ends, task 5. This verb creates the tree and then says
+ // nothing about what goes in it, which is the archetypal dead end:
+ // the whole point of a Brain is the first recorded signal. The rail
+ // keeps the line off the `--json` payload.
+ //
+ // phase 3: fired UNCONDITIONALLY until now, so a re-run over a Brain
+ // full of preferences - every path in `result.skipped` - still
+ // asserted `brain-empty`, whose registered class reads "Brain with
+ // nothing recorded in it". The claim is about content, not about
+ // whether this run created anything, so the condition is the content.
+ if (empty) emitNextStep("brain-empty", stream);
return 0;
}
+
+/**
+ * True when the Brain holds no signal, preference or retired record.
+ *
+ * Counted through the shared status snapshot rather than a private
+ * walk: `computeBrainStatus` is already this codebase's answer to "what
+ * is in this Brain", and a second counter here would be a second thing
+ * to keep in step with the directory layout. Processed signals count as
+ * recorded - a Brain whose inbox has been drained into `processed/` has
+ * a history, and telling its operator it is empty would be false.
+ */
+function brainHasNothingRecorded(vault: string): boolean {
+ const { counts } = computeBrainStatus(vault);
+ return counts.inbox + counts.inbox_processed + counts.preferences + counts.retired === 0;
+}
diff --git a/src/cli/brain/verbs/intent-review.ts b/src/cli/brain/verbs/intent-review.ts
index 25eeb749..4496f0f6 100644
--- a/src/cli/brain/verbs/intent-review.ts
+++ b/src/cli/brain/verbs/intent-review.ts
@@ -1,4 +1,6 @@
import { buildIntentReview } from "../../../core/brain/intent-review.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { CliError, brainVerbContext, parse } from "../helpers.ts";
/**
@@ -17,7 +19,13 @@ export async function cmdBrainIntentReview(argv: string[]): Promise<number> {
const report = buildIntentReview(vault, now ? { now } : {});
if (flags["json"]) {
- process.stdout.write(JSON.stringify(report, null, 2) + "\n");
+ // no-dead-ends, phase 3: the exit was computed on the human path and
+ // discarded here. Additive - absent when a review resolved.
+ const payload =
+ report.reviews.length === 0
+ ? { ...report, ...nextCommandField("signal-clusters-absent") }
+ : report;
+ process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
return 0;
}
@@ -29,6 +37,13 @@ export async function cmdBrainIntentReview(argv: string[]): Promise<number> {
}
if (report.reviews.length === 0) {
process.stdout.write(" no active signal clusters\n");
+ // no-dead-ends, task 5: clusters are built from the signals in
+ // `Brain/inbox/`, so an empty review means there is nothing to
+ // review yet - the exit is recording one. The `--json` branch above
+ // returned, so this stream is provably a human one; the payload
+ // carries the same exit as a field.
+ const stream: AdvisoryStream = { command: "brain", argv, jsonRequested: false };
+ emitNextStep("signal-clusters-absent", stream);
}
return 0;
}
diff --git a/src/cli/brain/verbs/intention.ts b/src/cli/brain/verbs/intention.ts
index 3d789d80..7651776b 100644
--- a/src/cli/brain/verbs/intention.ts
+++ b/src/cli/brain/verbs/intention.ts
@@ -11,6 +11,8 @@ import {
setIntention,
showIntention,
} from "../../../core/brain/intentions.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
export async function cmdBrainIntention(argv: string[]): Promise<number> {
@@ -44,11 +46,18 @@ export async function cmdBrainIntention(argv: string[]): Promise<number> {
updated_at: c.updatedAt,
text: c.text,
})),
+ // no-dead-ends, phase 3: the exit the human stream prints as a
+ // rail line, carried here as a field.
+ ...(intentions.length === 0 ? nextCommandField("intentions-absent") : {}),
});
return 0;
}
if (intentions.length === 0) {
ok("no active intentions");
+ // no-dead-ends, task 5: the exit is this verb's own setter.
+ // The `--json` branch above returned; this stream is human.
+ const stream: AdvisoryStream = { command: "brain", argv, jsonRequested: false };
+ emitNextStep("intentions-absent", stream);
return 0;
}
for (const c of intentions) ok(`${c.scope} v${c.version} (${c.updatedAt}): ${c.text}`);
diff --git a/src/cli/brain/verbs/pending.ts b/src/cli/brain/verbs/pending.ts
index 5ca9f469..5b28960c 100644
--- a/src/cli/brain/verbs/pending.ts
+++ b/src/cli/brain/verbs/pending.ts
@@ -4,7 +4,8 @@
*
* When `write_approval.enabled` is on, extracted signals are staged into
* `Brain/pending/`; these verbs let an operator review the queue: `list` shows
- * the staged signals, `apply <id>` moves one into `Brain/inbox/` unchanged, and
+ * the staged signals, `apply <id>` moves one into `Brain/inbox/` unchanged
+ * (`--dry-run` reports the move and writes nothing), and
* `reject <id> --reason <text>` moves it to `Brain/retired/`. A missing id is a
* typed error surfaced as exit 2 (not a silent no-op).
*/
@@ -80,16 +81,20 @@ function pendingList(argv: string[]): number {
function pendingApply(argv: string[]): number {
const { flags, positional } = parse(argv, {
vault: { type: "string" },
+ "dry-run": { type: "boolean" },
json: { type: "boolean" },
});
if (positional.length < 1) return usageError("brain pending apply requires an <id> argument");
const { vault } = brainVerbContext(flags);
+ const dryRun = flags["dry-run"] === true;
try {
- const res = applyPending(vault, positional[0]!);
+ const res = applyPending(vault, positional[0]!, { dryRun });
+ // `status` is the one field that distinguishes the preview from the
+ // move, so a caller reading JSON cannot mistake one for the other.
if (flags["json"]) {
- okJson({ id: res.id, path: res.path, status: "applied" });
+ okJson({ id: res.id, path: res.path, status: dryRun ? "would-apply" : "applied" });
} else {
- ok(`applied: ${res.id}`);
+ ok(`${dryRun ? "would apply" : "applied"}: ${res.id}`);
}
return 0;
} catch (exc) {
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
index 8132f3d8..290fc7ad 100644
--- a/src/cli/brain/verbs/skill-proposals.ts
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -1,11 +1,13 @@
import {
acceptSkillProposal,
+ discardUnreadableSkillAcceptJournals,
learnSkillProposals,
listPendingSkillProposals,
+ recoverSkillProposalAccepts,
rejectSkillProposal,
} from "../../../core/brain/skill-proposals.ts";
import { deriveSkillUsage } from "../../../core/brain/skill-usage.ts";
-import { CliError, brainVerbContext, parse } from "../helpers.ts";
+import { CliError, brainVerbContext, failWith, parse } from "../helpers.ts";
export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -14,8 +16,59 @@ export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
if (sub === "list") return list(rest);
if (sub === "accept") return accept(rest);
if (sub === "reject") return reject(rest);
+ if (sub === "recover") return recover(rest);
if (sub === "usage") return usage(rest);
- throw new CliError("brain skill-proposals: expected learn, list, accept, reject, or usage");
+ throw new CliError(
+ "brain skill-proposals: expected learn, list, accept, reject, recover, or usage",
+ );
+}
+
+/**
+ * Resolve the accept sequences a crash abandoned.
+ *
+ * The accept transaction's write-ahead journal was recoverable in the
+ * library and reachable from nowhere: an operator whose accept broke had
+ * no command to run. This is that command.
+ *
+ * Both hazards it can meet refuse rather than guess, and the refusal
+ * carries the message the core error composed - naming the exact file and
+ * the exit - so the two surfaces cannot word it differently. `--discard-
+ * unreadable` is the only destructive part and it is opt-in for the reason
+ * stated on `discardUnreadableSkillAcceptJournals`: an unparseable marker
+ * names no phase, so removing it unblocks accepting without claiming the
+ * sequence it marked was resolved.
+ */
+function recover(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "discard-unreadable": { type: "boolean" },
+ });
+ const vault = brainVerbContext(flags).vault;
+
+ let discarded: ReadonlyArray<string>;
+ let recovered: ReadonlyArray<{ slug: string; action: string }>;
+ try {
+ discarded = flags["discard-unreadable"] ? discardUnreadableSkillAcceptJournals(vault) : [];
+ recovered = recoverSkillProposalAccepts(vault);
+ } catch (exc) {
+ return failWith("recover skill-proposal accepts", exc);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ discarded, recovered, total: recovered.length }, null, 2) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `skill-proposals recover: ${recovered.length} sequence(s) resolved, ` +
+ `${discarded.length} unreadable marker(s) discarded\n`,
+ );
+ for (const path of discarded) process.stdout.write(` discarded ${path}\n`);
+ for (const item of recovered) process.stdout.write(` ${item.action} ${item.slug}\n`);
+ return 0;
}
function usage(argv: string[]): number {
diff --git a/src/cli/brain/verbs/tiers.ts b/src/cli/brain/verbs/tiers.ts
index f7401632..f0c62ec1 100644
--- a/src/cli/brain/verbs/tiers.ts
+++ b/src/cli/brain/verbs/tiers.ts
@@ -17,6 +17,7 @@ import { resolveSearchConfig } from "../../../core/search/index.ts";
import { Store } from "../../../core/search/store.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../../core/vault.ts";
import type { FrontmatterMap } from "../../../core/types.ts";
+import { emitNextSteps } from "../../advisory-rail.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
@@ -60,6 +61,11 @@ export async function cmdBrainTiers(argv: string[]): Promise<number> {
try {
const findings = store.listTierDrift();
if (asJson) {
+ // Deliberately carries no next command. `nextCommandField` is
+ // singular by construction - one wire key, one string - and
+ // this state has TWO exits, restore and accept. Emitting one
+ // would tell a machine caller that the other does not exist,
+ // which is worse than the human stream's two rail lines.
okJson({ findings });
} else {
ok(`tier drift: ${findings.length} open finding(s)`);
@@ -69,7 +75,17 @@ export async function cmdBrainTiers(argv: string[]): Promise<number> {
);
}
if (findings.length > 0) {
- ok("resolve with: o2b brain tiers restore <path> --apply (or accept <path>)");
+ // no-dead-ends, phase 3. One finding, two readings: the
+ // indexed value is authoritative (restore) or the note's is
+ // (accept). The rail's batch form prints one line per
+ // distinct command, so both exits survive the migration -
+ // collapsing them into a single code would have dropped the
+ // half the operator did not happen to want.
+ emitNextSteps(["tier-drift-restore", "tier-drift-accept"], {
+ command: "brain",
+ argv,
+ jsonRequested: asJson,
+ });
}
}
return 0;
diff --git a/src/cli/brain/verbs/tune.ts b/src/cli/brain/verbs/tune.ts
index 2a58c959..c17af724 100644
--- a/src/cli/brain/verbs/tune.ts
+++ b/src/cli/brain/verbs/tune.ts
@@ -19,6 +19,8 @@ import { appendMetric } from "../../../core/brain/metrics.ts";
import { isoSecond } from "../../../core/brain/time.ts";
import { resolveSearchConfig } from "../../../core/search/index.ts";
import { SearchError } from "../../../core/search/types.ts";
+import { nextCommandField } from "../../../core/brain/next-step.ts";
+import { emitNextStep } from "../../advisory-rail.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
const USAGE =
@@ -49,9 +51,16 @@ export async function cmdBrainTune(argv: string[]): Promise<number> {
const tuned = loadTunedParameters(vault);
const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
if (asJson) {
- okJson({ enabled: searchConfig.recall.selfTuningEnabled, tuned });
+ okJson({
+ enabled: searchConfig.recall.selfTuningEnabled,
+ tuned,
+ ...(tuned === null ? nextCommandField("recall-tuning-absent") : {}),
+ });
} else if (tuned === null) {
- ok("tune: no valid tuned parameters persisted - run: o2b brain tune run --dataset <path>");
+ ok("tune: no valid tuned parameters persisted");
+ // no-dead-ends, phase 3: this pointer was hand-written beside
+ // the rail. One mechanism, one line format.
+ emitNextStep("recall-tuning-absent", { command: "brain", argv, jsonRequested: asJson });
} else {
ok(
`tune: pool x${tuned.poolMultiplier}, depth ${tuned.traversalDepth}, ` +
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 29fc8299..9c3aedf8 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -84,6 +84,19 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("vault", "string"),
flag("tool-arg", "string-array"),
]),
+ command(
+ "secrets",
+ "Inspect $secret:NAME references without printing values",
+ [],
+ [
+ command("list", "List $secret:NAME references found in the config", [
+ flag("config", "string"),
+ ]),
+ command("status", "Report whether each referenced secret resolves", [
+ flag("config", "string"),
+ ]),
+ ],
+ ),
command(
"aider",
"Session-bracketing memory wrapper for Aider",
@@ -107,7 +120,9 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("feedback", "Record a taste signal"),
command(
"dream",
- "Run deterministic consolidation; staged lifecycle via stage/validate/apply",
+ "Run deterministic consolidation; staged lifecycle via stage/validate/apply; " +
+ "--step runs one independently-runnable step, --gate overrides a phase gate for one run",
+ [flag("step", "string"), flag("gate", "string-array")],
),
command("apply-evidence", "Record preference evidence"),
command("note", "Append a narrative milestone"),
@@ -265,6 +280,149 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("entity", "Canonical entity registry: set, get, list, relate, archive"),
command("session-hook", "Capture runtime lifecycle hook payloads"),
command("import-claude-memory", "Import Claude memory feedback"),
+ // no-dead-ends, task 6: the fifty-five brain cases the manifest
+ // never modelled, so neither shell completions nor `o2b help
+ // --json` could name them. Listed in dispatcher order; the
+ // ratchet in `tests/cli/manifest-completeness.test.ts` reads the
+ // dispatcher, so a fifty-sixth cannot land unlisted.
+ command(
+ "lifecycle",
+ "Tombstone or supersede a memory, resolve chain tips, list curator slices",
+ ),
+ command(
+ "claims",
+ "Claim-graph query: current truth, truth at an instant, replaced-by, contested-by",
+ ),
+ command(
+ "decision",
+ "Decision records: record, outcome, rate, show, list, compare, similar, history, recall",
+ ),
+ command(
+ "tension",
+ "Detect and triage persisted contradictions: detect, list, show, confirm, dismiss, resolve",
+ ),
+ command("state", "Overwrite-only exact-state lane keyed by aspect: set, get, list, clear"),
+ command(
+ "health-baseline",
+ "Acknowledge-before watermark for health advisories: set, get, clear",
+ ),
+ command(
+ "vitals",
+ "Governance scorecard: domain diversity, connectivity, orphans, gap pressure",
+ ),
+ command(
+ "bank-export",
+ "Serialise a whole-vault bank bundle: preferences, graph, pages, sources",
+ ),
+ command("bank-import", "Reconstruct the page graph from a bank bundle"),
+ command(
+ "authored-at-backfill",
+ "Backfill authored_at on session-imported signals (dry-run by default)",
+ ),
+ command(
+ "distill",
+ "Condense a source into agent-supplied atomic claims with block provenance",
+ ),
+ command("session-summary", "Session-scoped structured digest: write, get, list"),
+ command(
+ "idea-lineage",
+ "Trace how a derived artifact was reached: observation, synthesis, conclusion",
+ ),
+ command("note-history", "Decompose a note's git history into episodic phases"),
+ command(
+ "diarize",
+ "Subject profile: document set, stated-versus-evidenced gap, needs-LLM skeleton",
+ ),
+ command("okf-export", "Write a portable Open Knowledge Format bundle"),
+ command(
+ "okf-import",
+ "Import an Open Knowledge Format bundle (staged for review by default)",
+ ),
+ command("page-dedup", "Detect, and optionally merge, near-duplicate vault pages"),
+ command("token-footprint", "Report per-category vault token size against a warn threshold"),
+ command("context-pack", "Return a tier-then-recency vault slice under a token budget"),
+ command("context-receipts", "List or show prompt context receipt records"),
+ command(
+ "event-trace",
+ "Join logged events to the continuity records sharing their correlation ids",
+ ),
+ command("context-presets", "Show, suggest, or diff read-only context budget presets"),
+ command(
+ "pre-compact-extract",
+ "Extract typed continuity records from bounded session text",
+ ),
+ command(
+ "post-compact-audit",
+ "Audit pinned-anchor survival after a compaction and re-assert drifted anchors",
+ ),
+ command("recall-telemetry", "List, summarize, or cost opt-in recall telemetry records"),
+ command("knowledge-gaps", "Rank recurring queries the vault answers poorly"),
+ command(
+ "skill-proposals",
+ "Learn, list, review, and recover deterministic skill proposals",
+ ),
+ command("procedural-memory", "Reconcile or list the procedural memory index and its usage"),
+ command("procedural-graph", "Rebuild or show the procedural graph and hint projections"),
+ command("recurrence", "Inspect and update recurrence and support diagnostics"),
+ command("attention-flows", "Declarative attention recipes over open loops and learnings"),
+ command("obligation", "Recurring obligations with cadence-driven next-due dates"),
+ command("agenda", "Synthesize agenda conflicts and focus blocks from provided events"),
+ command("today", "Today dashboard: due obligations, open loops, recent activity, totals"),
+ command("apply-markers", "Apply @osb set frontmatter write-backs (report by default)"),
+ command(
+ "pending",
+ "Review the write-approval queue: list, apply, reject",
+ [],
+ [
+ command("list", "List the staged signals awaiting approval", [flag("vault", "string")]),
+ command("apply", "Move one staged signal into the inbox unchanged", [
+ flag("vault", "string"),
+ flag("dry-run", "boolean"),
+ ]),
+ command("reject", "Retire one staged signal with a recorded reason", [
+ flag("vault", "string"),
+ flag("reason", "string"),
+ ]),
+ ],
+ ),
+ command("signal", "Fact signal lifecycle: retire a signal with a reason"),
+ command("telegram-capture", "Inbound Telegram capture bot: long-poll run or catchup"),
+ command("inbox-drain", "Classify and route staged captures (dry-run by default)"),
+ command("repair-lane", "Propose memory-graph edges (dry-run by default)"),
+ command("session-grep", "Search imported session recall turns and summaries"),
+ command("session-describe", "Describe an imported session recall DAG"),
+ command("session-expand", "Expand a session recall node to its source turns"),
+ command("lint", "Self-healing structural checks; --consolidate --apply writes the fixes", [
+ flag("vault", "string"),
+ flag("consolidate", "boolean"),
+ flag("apply", "boolean"),
+ flag("yes", "boolean"),
+ ]),
+ command(
+ "actions",
+ "Ranked maintenance action list over dedup, lint, and footprint findings",
+ ),
+ command("summary", "Operator dashboard: trust verdict, doctor and dream counts, actions"),
+ command(
+ "unlinked",
+ "Raw-text mentions of an artifact's title or aliases outside wikilinks",
+ ),
+ command(
+ "synthesise",
+ "Concept cluster: a target plus its depth-1 linkers, optionally mentions",
+ ),
+ command("moc-audit", "Per-MOC coverage audit: well-covered, fragile, candidate-missing"),
+ command(
+ "timeline",
+ "Chronological event list filtered by preference, topic, kind, or date",
+ ),
+ command(
+ "evolution",
+ "Per-preference or per-topic story: status transitions, evidence, retire",
+ ),
+ command("stale", "Stale preferences, signals, and log files against configured thresholds"),
+ command("daily", "Daily brief: events by kind, status transitions, vault delta"),
+ command("weekly", "Seven-day synthesis: transitions, retired, contradictions, vault delta"),
],
),
command(
@@ -279,6 +437,13 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("status", "Print search index status"),
command("check", "Run search pre-flight diagnostics"),
command("provider", "Manage embedding provider profiles"),
+ command("expand", "Drill a search card into the fuller note and its raw chunk transcript"),
+ command("focus", "Set, show, or clear the session recall focus bias"),
+ command("feedback", "Record a relevance verdict for one recall result"),
+ command("weights", "Show or reset the learned hybrid ranking weights"),
+ command("rerank-provider", "Manage reranker provider profiles"),
+ command("rerank-fit", "Diagnose whether the configured reranker fits this vault's queries"),
+ command("plan", "Preview the should-read shortlist for a query without reading the notes"),
],
),
command(
@@ -302,6 +467,23 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("uninstall", "Remove discipline cron"),
],
),
+ command(
+ "partner",
+ "Read-only reports on external code-project partners",
+ [],
+ [
+ command(
+ "codegraph",
+ "Codegraph partner reports",
+ [],
+ [
+ command("report", "Report codegraph index status and workspace members", [
+ flag("vault", "string"),
+ ]),
+ ],
+ ),
+ ],
+ ),
],
});
diff --git a/src/cli/help-render.ts b/src/cli/help-render.ts
new file mode 100644
index 00000000..3e1d450d
--- /dev/null
+++ b/src/cli/help-render.ts
@@ -0,0 +1,129 @@
+/**
+ * The human help surface, rendered FROM the command manifest
+ * (no-dead-ends, phase 3, item 1).
+ *
+ * `o2b help --json` has always serialised {@link CLI_COMMAND_MANIFEST};
+ * `o2b help` printed a hand-written constant beside it. Two lists meant
+ * two truths, and the manifest repair that added sixty-four entries
+ * widened the gap until the human surface named twelve `brain` verbs out
+ * of a hundred and thirty. An operator reading the only surface written
+ * for them could not reach most of this tool - a discoverability dead end
+ * of exactly the kind this release removes.
+ *
+ * So the human text is derived here rather than maintained. There is no
+ * second list to drift: a verb reaches both surfaces by existing in the
+ * manifest, and `tests/cli/help-surface-parity.test.ts` parses this
+ * output back and requires it to equal the manifest exactly, so a
+ * renderer that truncated or wrapped could not pass by claiming shared
+ * provenance.
+ *
+ * Two forms, because they answer different questions:
+ *
+ * - {@link renderHelp} is the COMPLETE index - every command at every
+ * level, with the summary and the flags the manifest declares. It is
+ * what `o2b help` and `o2b --help` print.
+ * - {@link renderUsage} is the terse banner for an invocation that named
+ * no command or an unknown one. It lists the top level and names the
+ * complete index, so the short form is a signpost rather than a
+ * truncation.
+ *
+ * The inherited `--json` flag is stated once in the banner instead of
+ * being repeated on two hundred entries; per-command `flags:` lines carry
+ * what a command DECLARES. This is a rendering choice, not a claim about
+ * the manifest, and the parity test compares against declared flags for
+ * that reason.
+ *
+ * On the forward-pointer ratchet: the strings this module writes name
+ * `o2b help` as a usage grammar - the index telling a reader where the
+ * rest of the index is - not as a diagnostic's structural exit. Those
+ * belong to the advisory rail, which resolves a registered code and never
+ * takes text from a caller. The two mechanisms do not overlap.
+ */
+
+import {
+ manifestForJson,
+ type CliCommandManifest,
+ type CliFlagManifest,
+ type CliRootManifest,
+} from "./command-manifest.ts";
+
+/** Indent of an entry line; the parity parser keys on it. */
+const ENTRY_INDENT = " ";
+/** Indent of the flags continuation line, deeper so it cannot be an entry. */
+const FLAGS_INDENT = " ";
+/** Minimum gutter between a command path and its summary. */
+const GUTTER = 2;
+
+const USAGE_LINE = "usage: o2b <command> [args...]";
+
+/** Names the machine surface and the inherited flag, once. */
+const BANNER =
+ "Every command accepts --json; `o2b help --json` prints this same manifest\n" +
+ "as machine-readable JSON, which is what shell completions are built from.";
+
+/** Where the rest of the index is, for the terse form. */
+const COMPLETE_INDEX_LINE =
+ "Run `o2b help` for every command at every level with its summary and flags.";
+
+/** The declared (non-inherited) flags of `item`, as `--name` tokens. */
+function declaredFlags(item: CliCommandManifest): ReadonlyArray<string> {
+ return (item.flags ?? [])
+ .filter((f: CliFlagManifest) => f.inherited !== true)
+ .map((f) => `--${f.name}`);
+}
+
+/** One `<heading>:` block listing `items` under the path prefix `prefix`. */
+function renderSection(
+ heading: string,
+ items: ReadonlyArray<CliCommandManifest>,
+ prefix: string,
+): string {
+ const paths = items.map((item) => `${prefix}${item.name}`);
+ const width = Math.max(...paths.map((p) => p.length));
+ const lines = [`${heading}:`];
+ for (const [index, item] of items.entries()) {
+ lines.push(`${ENTRY_INDENT}${paths[index]!.padEnd(width)}${" ".repeat(GUTTER)}${item.summary}`);
+ const flags = declaredFlags(item);
+ if (flags.length > 0) lines.push(`${FLAGS_INDENT}flags: ${flags.join(" ")}`);
+ }
+ return lines.join("\n");
+}
+
+/**
+ * Every section, depth first: the parent's own list, then a section per
+ * child that has children of its own. Depth-first keeps a group's
+ * sub-groups (`brain schema`, `brain pending`) adjacent to it rather than
+ * collected at the end, which is the order a reader scans in.
+ */
+function subSections(items: ReadonlyArray<CliCommandManifest>, prefix: string): string[] {
+ const out: string[] = [];
+ for (const item of items) {
+ if (item.commands === undefined || item.commands.length === 0) continue;
+ const path = `${prefix}${item.name}`;
+ out.push(renderSection(`o2b ${path} - ${item.summary}`, item.commands, `${path} `));
+ out.push(...subSections(item.commands, `${path} `));
+ }
+ return out;
+}
+
+/** The complete index: every command, at every level, with its summary. */
+export function renderHelp(root: CliRootManifest = manifestForJson()): string {
+ const blocks = [
+ USAGE_LINE,
+ BANNER,
+ renderSection("Commands", root.commands, ""),
+ ...subSections(root.commands, ""),
+ ];
+ return `${blocks.join("\n\n")}\n`;
+}
+
+/**
+ * The terse banner: the top-level verbs on one line, plus where the rest
+ * of the index is. Used when the caller named no command or an unknown
+ * one - cases where the complete two-hundred-line index would bury the
+ * error that prompted it.
+ */
+export function renderUsage(root: CliRootManifest = manifestForJson()): string {
+ const names = root.commands.map((item) => item.name).join(", ");
+ return `${USAGE_LINE}\n\nCommands: ${names}\n\n${COMPLETE_INDEX_LINE}\n`;
+}
diff --git a/src/cli/json-helpers.ts b/src/cli/json-helpers.ts
index 2e4ce495..2b4d644a 100644
--- a/src/cli/json-helpers.ts
+++ b/src/cli/json-helpers.ts
@@ -2,8 +2,74 @@ const SECRET_KEY_RE = /(?:api[_-]?key|token|secret|password|crypt[_-]?password)/
const SECRET_ASSIGNMENT_RE =
/((?:api[_-]?key|token|secret|password|crypt[_-]?password)\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s]+)/gi;
+/** The long flag every verb accepts to request machine-readable output. */
+const JSON_FLAG = "--json";
+const JSON_FLAG_ASSIGNMENT = `${JSON_FLAG}=`;
+
+/**
+ * Argv terminator. `parseFlags` treats every token after it as positional,
+ * so nothing past it can be a flag.
+ */
+const ARGV_TERMINATOR = "--";
+
+/**
+ * True when `argv` requests JSON output as a FLAG rather than as literal
+ * content.
+ *
+ * The scan is faithful to `parseFlags` on the one part of the grammar that
+ * needs no per-verb schema: it stops at `--`, after which `o2b brain note
+ * -- "--json"` is a note whose text is the flag, not a JSON request.
+ *
+ * The remaining ambiguity - a `--json` token sitting in the value position
+ * of a value-taking flag - is undecidable here, because the two `main.ts`
+ * call sites run before per-verb parsing and so have no schema. It stays
+ * conservative: the token counts as a flag, which at worst adds a buffered
+ * envelope. It is NOT resolved by guessing which flags take values, because
+ * guessing wrong in the other direction would drop a real `--json`.
+ * Consumers that need the authoritative answer must read their own parsed
+ * flag - which is exactly what `advisory-rail.ts` requires of its callers.
+ */
export function wantsJsonFlag(argv: ReadonlyArray<string>): boolean {
- return argv.some((arg) => arg === "--json" || arg.startsWith("--json="));
+ for (const arg of argv) {
+ if (arg === ARGV_TERMINATOR) return false;
+ if (arg === JSON_FLAG || arg.startsWith(JSON_FLAG_ASSIGNMENT)) return true;
+ }
+ return false;
+}
+
+/**
+ * Top-level commands that render their own JSON under `--json`. Their
+ * stdout is a payload a caller parses, so it is never wrapped by
+ * {@link withJsonFallback} and never safe for advisory chrome.
+ */
+export const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set([
+ "status",
+ "install",
+ "update",
+ "tool-call",
+ "secrets",
+ "brain",
+ "search",
+ "vault",
+ "discipline",
+ "partner",
+ "doctor",
+ "onboarding",
+]);
+
+/**
+ * True when `command` owns its JSON output rather than being wrapped in the
+ * {@link withJsonFallback} envelope. This is the single fact table behind
+ * two questions: which invocations `main` must wrap, and - via
+ * `advisory-rail.ts` - which stdout streams advisory chrome would corrupt.
+ * It answers the structural question only; whether the caller actually
+ * asked for JSON is the caller's to supply.
+ */
+export function ownsInternalJson(command: string, rest: ReadonlyArray<string>): boolean {
+ if (COMMANDS_WITH_INTERNAL_JSON.has(command)) return true;
+ // `mcp` prints JSON only for the probe; `help` renders the manifest.
+ if (command === "mcp" && rest.includes("--probe")) return true;
+ return command === "help";
}
export function redactSecrets(value: unknown): unknown {
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 9b5248b9..31e66eee 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -39,7 +39,10 @@ import {
resolveSemanticConfigState,
sortedReplacer,
} from "./helpers.ts";
-import { wantsJsonFlag, withJsonFallback } from "./json-helpers.ts";
+import { nextCommandField } from "../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "./advisory-rail.ts";
+import { renderHelp, renderUsage } from "./help-render.ts";
+import { ownsInternalJson, wantsJsonFlag, withJsonFallback } from "./json-helpers.ts";
import {
installCli,
renderInstallResult,
@@ -51,7 +54,11 @@ import { planUninstall, renderPlan } from "./uninstall.ts";
import { cmdInstall } from "./install/install.ts";
import { cmdUninstallTarget } from "./install/uninstall-target.ts";
import { cmdInitInteractive } from "./install/init-interactive.ts";
-import { buildOnboardingChecklist, renderOnboardingChecklist } from "./onboarding.ts";
+import {
+ buildOnboardingChecklist,
+ renderOnboardingChecklist,
+ searchIndexExists,
+} from "./onboarding.ts";
import { CLI_COMMAND_MANIFEST, manifestForJson } from "./command-manifest.ts";
import { COMPLETION_SHELLS, isCompletionShell, renderCompletions } from "./completions.ts";
import { MCPServer } from "../mcp/server.ts";
@@ -87,6 +94,9 @@ async function cmdStatus(argv: string[]): Promise<number> {
output["config_keys"] = Object.keys(result.data).toSorted();
}
if (flags["vault"]) output["vault"] = String(flags["vault"]);
+ // no-dead-ends, phase 3: the human stream prints this exit as a rail
+ // line; the machine stream carried nothing at all until now.
+ if (!result.exists) Object.assign(output, nextCommandField("cli-config-absent"));
process.stdout.write(JSON.stringify(output, sortedReplacer, 2) + "\n");
} else {
process.stdout.write(`config_path: ${result.path}\n`);
@@ -101,6 +111,17 @@ async function cmdStatus(argv: string[]): Promise<number> {
process.stdout.write(`semantic: off (${semantic.hint})\n`);
}
}
+ // no-dead-ends, task 7: the terminal-state census found this one. With
+ // no configuration file there is nothing else this verb can report and
+ // nothing the caller can do with the report, so it names the command
+ // that creates one. With a config present it stays byte-identical.
+ if (!result.exists) {
+ emitNextStep("cli-config-absent", {
+ command: "status",
+ argv,
+ jsonRequested: Boolean(flags["json"]),
+ });
+ }
return 0;
}
@@ -162,7 +183,11 @@ async function cmdInit(argv: string[]): Promise<number> {
process.stdout.write(`timezone registered: ${timezone}\n`);
process.stdout.write(`timezone persisted to: ${configPath}\n`);
}
- writeSearchInitBlock(configPath);
+ writeSearchInitBlock(resolvedVault, configPath, {
+ command: "init",
+ argv,
+ jsonRequested: flags["json"] === true,
+ });
// Guided first-run onboarding: turn the bare init into a walked-through
// checklist of state-aware next steps (t_84500f39). Additive - the search
// block above is unchanged. Best-effort: a checklist failure must never fail
@@ -196,15 +221,24 @@ async function cmdOnboarding(argv: string[]): Promise<number> {
/**
* Print the post-init search-onboarding block (design §10).
*
- * Always advertises `o2b search index`. When the user has already
- * flipped `search_semantic_enabled` to true but no embedding key is
- * resolvable, the detailed configuration template is appended. The
- * block prints once, only during `o2b init` — no nagging on other
- * CLI invocations (the dedicated diagnostic is `o2b search check`).
+ * Advertises `o2b search index` when the vault has no index. When the
+ * user has already flipped `search_semantic_enabled` to true but no
+ * embedding key is resolvable, the detailed configuration template is
+ * appended. The block prints once, only during `o2b init` — no nagging
+ * on other CLI invocations (the dedicated diagnostic is
+ * `o2b search check`).
*/
-function writeSearchInitBlock(configPath: string): void {
+function writeSearchInitBlock(vault: string, configPath: string, stream: AdvisoryStream): void {
process.stdout.write("\nSearch:\n");
- process.stdout.write(" next: o2b search index # build the vault search index\n");
+ // no-dead-ends, phase 3. Two defects at one line. It hand-wrote the
+ // rail's own `next: <command>` format, which is the second mechanism
+ // the rail exists to prevent; and it advertised the indexer
+ // unconditionally, so on a vault that already had an index this block
+ // asserted `search-index-missing` two lines above the onboarding
+ // checklist reporting that same step as done. One command, two
+ // contradictory answers. The predicate is shared with the checklist so
+ // they cannot disagree again.
+ if (!searchIndexExists(vault, configPath)) emitNextStep("search-index-missing", stream);
const data = discoverConfig(configPath).data;
// v0.10.10 — share the truthy / key-present logic with `o2b status`
@@ -764,7 +798,7 @@ function cmdHelp(argv: ReadonlyArray<string>): number {
if (flags["json"]) {
process.stdout.write(JSON.stringify(manifestForJson(), null, 2) + "\n");
} else {
- process.stdout.write(HELP);
+ process.stdout.write(renderHelp());
}
return 0;
}
@@ -786,63 +820,17 @@ function cmdCompletions(argv: ReadonlyArray<string>): number {
return 0;
}
-const HELP = `usage: o2b <command> [args...]
-
-Commands:
- status Show Open Second Brain configuration status
- init Initialize a vault profile with required files
- doctor Run health checks on vault, config, and plugins
- export-config Write a redacted config snapshot
- index Regenerate the vault index from discovered pages
- mcp Run the optional MCP tool server (stdio or HTTP JSON-RPC)
- install-cli Create symlinks for o2b and vault-log in ~/.local/bin
- install Multi-runtime install orchestrator (v0.10.11) — detect / plan / apply / --check (see install/)
- update Update OSB installation across all detected runtimes
- uninstall Print an uninstall plan; --target X removes a per-runtime install
- tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout
- secrets Inspect $secret:NAME references without printing values
- help Print this help text; --json prints command metadata
- completions Print shell completions for bash, zsh, fish, elvish, nushell, powershell
-
-Aider (session-bracketing memory wrapper):
- aider wrap Run Aider bracketed with live memory load + write-back
-
-Brain (observing memory):
- brain init Bootstrap <vault>/Brain/ skeleton (idempotent)
- brain feedback Record a taste signal into Brain/inbox/
- brain dream Run the deterministic dreaming pass (idempotent)
- brain apply-evidence Log a real-work application of a preference
- brain note Append a one-line narrative milestone to Brain/log/today
- brain digest Render the recent-changes digest (markdown or --json)
- brain query Read by --preference, --topic, or --since
- brain reject Move a preference to retired/ (user-rejected)
- brain pin Mark a preference exempt from automatic retire
- brain unpin Clear the pinned flag
- brain rollback Restore Brain/ from a snapshot (--list / <run_id>)
- brain doctor Validate Brain invariants (--strict promotes warnings)
-
-Discipline:
- discipline report Render the daily discipline report block (Telegram-safe)
-
-Search:
- search "<query>" Search the vault index (default verb is 'query')
- search index Incrementally update the index from the vault
- search reindex Rebuild the index atomically (.new -> rename -> .bak)
- search status Print index summary (counts, model, vec extension)
- search check Pre-flight diagnostics (SQLite, FTS5, vec, provider)
-
-Vault scope:
- vault status Show how many files/dirs the active policy includes and which rules excluded
- vault inspect <relpath> Point-check one vault-relative path against the policy
-
-Partner (read-only):
- partner codegraph report Report codegraph index status + structural Cargo workspace members (--json)
-`;
-
export async function main(argv: ReadonlyArray<string>): Promise<number> {
- if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
- process.stdout.write(HELP);
- return argv.length === 0 ? 2 : 0;
+ if (argv.length === 0) {
+ // No command named: the terse banner, not the complete index. The
+ // index is two hundred lines and would bury the fact that nothing
+ // was asked for; the banner names where the index is.
+ process.stdout.write(renderUsage());
+ return 2;
+ }
+ if (argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(renderHelp());
+ return 0;
}
const command = argv[0]!;
const rest = argv.slice(1);
@@ -872,37 +860,12 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
}
const run = () => dispatchCommand(command, rest);
- if (wantsJsonFlag(rest) && !commandHasSemanticJson(command, rest)) {
+ if (wantsJsonFlag(rest) && !ownsInternalJson(command, rest)) {
return await withJsonFallback(command, run);
}
return await run();
}
-function commandHasSemanticJson(command: string, rest: ReadonlyArray<string>): boolean {
- if (!wantsJsonFlag(rest)) return false;
- if (COMMANDS_WITH_INTERNAL_JSON.has(command)) {
- return true;
- }
- if (command === "mcp" && rest.includes("--probe")) return true;
- if (command === "help") return true;
- return false;
-}
-
-const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set([
- "status",
- "install",
- "update",
- "tool-call",
- "secrets",
- "brain",
- "search",
- "vault",
- "discipline",
- "partner",
- "doctor",
- "onboarding",
-]);
-
async function dispatchCommand(command: string, rest: string[]): Promise<number> {
try {
switch (command) {
@@ -950,7 +913,7 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>
return await handlePartnerSubcommand(rest);
default:
process.stderr.write(`error: unknown command: ${command}\n`);
- process.stderr.write(HELP);
+ process.stderr.write(renderUsage());
return 2;
}
} catch (exc) {
diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.ts
index cde4c325..d8d7da5f 100644
--- a/src/cli/onboarding.ts
+++ b/src/cli/onboarding.ts
@@ -57,6 +57,19 @@ function countMarkdown(dir: string): number {
}
}
+/**
+ * True when this vault's search index has been built.
+ *
+ * Exported because `o2b init` prints its search block immediately above
+ * this checklist and must reach the same answer: the block used to
+ * advertise the indexer unconditionally, so one command's output said
+ * "build the index" and "[x] Build the search index" two lines apart.
+ * One predicate, one answer.
+ */
+export function searchIndexExists(vault: string, configPath?: string): boolean {
+ return existsSync(resolveSearchConfig({ vault, configPath }).dbPath);
+}
+
/**
* Compute the onboarding checklist from the vault's real on-disk + config
* state. Pure read: never writes, never calls the network or an LLM.
@@ -70,7 +83,7 @@ export function buildOnboardingChecklist(
const vaultConfigured = typeof config["vault"] === "string" && config["vault"].length > 0;
const brainScaffolded = existsSync(join(vault, "Brain"));
- const indexBuilt = existsSync(search.dbPath);
+ const indexBuilt = searchIndexExists(vault, opts.configPath);
const agentNamed =
(typeof config["agent_name"] === "string" && config["agent_name"].length > 0) ||
(typeof config["agentName"] === "string" && config["agentName"].length > 0);
diff --git a/src/cli/search.ts b/src/cli/search.ts
index fe060c91..8109b018 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -81,6 +81,8 @@ import { IndexWatchRunner } from "../core/search/watch-runner.ts";
import { SafeguardAbortError } from "../core/brain/safeguard.ts";
import { canonicalNotePath } from "../core/path-safety.ts";
import { watch, type FSWatcher } from "node:fs";
+import { nextCommandField } from "../core/brain/next-step.ts";
+import { emitNextStep, type AdvisoryStream } from "./advisory-rail.ts";
import { CliError, parseFlags } from "./argparse.ts";
import { CronTemplateError, renderCronTemplate } from "./search-cron-template.ts";
@@ -1016,6 +1018,43 @@ async function cmdSearchExpand(argv: ReadonlyArray<string>): Promise<number> {
// ─── index ────────────────────────────────────────────────────────────────────
+/**
+ * Advisory stream for the two index builders (no-dead-ends, task 5).
+ * `index` and `reindex` reach the same terminal state - an index that
+ * now exists and has not been queried - so they name the same exit
+ * through the same registry code.
+ *
+ * The read path is deliberately NOT covered: `search query` self-heals a
+ * missing index by building it, and pointing an operator at the indexer
+ * there would describe a world that self-heal removed.
+ */
+function indexAdvisoryStream(argv: ReadonlyArray<string>, jsonRequested: boolean): AdvisoryStream {
+ return { command: "search", argv, jsonRequested };
+}
+
+/**
+ * True when the run this `stats` describes left the index covering every
+ * document, which is what the `search-index-built` class ("search index
+ * up to date") asserts.
+ *
+ * `stats.errors` means, per its own declaration, "this file did not
+ * index". Emitting the class with entries in it would tell the operator
+ * the index is current while the tool knows documents are missing from
+ * it, and would point at `o2b search query` as though a query over it
+ * were complete. Re-labelling the class instead was considered and
+ * rejected: a truthful label for the failed case would have to be
+ * vacuous, and it would leave the misleading COMMAND in place.
+ *
+ * A run with errors is left deliberately without a rail line. The errors
+ * block already names every affected path and message, and what repairs
+ * an unreadable or malformed note is a judgement over that file's
+ * content - there is no `o2b` command that performs it, and naming the
+ * indexer again would advise repeating the run that just failed.
+ */
+function indexIsComplete(stats: IndexStats): boolean {
+ return stats.errors.length === 0;
+}
+
async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<number> {
const { flags } = parseFlags(argv, {
vault: { type: "string" },
@@ -1049,11 +1088,23 @@ async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<number> {
},
});
+ const complete = indexIsComplete(stats);
if (flags["json"]) {
- process.stdout.write(JSON.stringify(jsonForStats(stats, cfg)) + "\n");
- return 0;
+ // no-dead-ends, phase 3: the rail suppresses its line on this stream
+ // and returns the resolved step precisely so the payload can carry
+ // it. Absent whenever the run left the index incomplete.
+ process.stdout.write(
+ JSON.stringify({
+ ...(jsonForStats(stats, cfg) as Record<string, unknown>),
+ ...(complete ? nextCommandField("search-index-built") : {}),
+ }) + "\n",
+ );
+ } else {
+ process.stdout.write(renderStatsHuman(stats, cfg));
+ }
+ if (complete) {
+ emitNextStep("search-index-built", indexAdvisoryStream(argv, flags["json"] === true));
}
- process.stdout.write(renderStatsHuman(stats, cfg));
return 0;
}
@@ -1254,11 +1305,23 @@ async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {
forceCost: flags["force-cost"] === true,
onFile: flags["verbose"] ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`) : undefined,
});
+ const complete = indexIsComplete(stats);
if (flags["json"]) {
- process.stdout.write(JSON.stringify(jsonForStats(stats, cfg)) + "\n");
- return 0;
+ // no-dead-ends, phase 3: the rail suppresses its line on this stream
+ // and returns the resolved step precisely so the payload can carry
+ // it. Absent whenever the run left the index incomplete.
+ process.stdout.write(
+ JSON.stringify({
+ ...(jsonForStats(stats, cfg) as Record<string, unknown>),
+ ...(complete ? nextCommandField("search-index-built") : {}),
+ }) + "\n",
+ );
+ } else {
+ process.stdout.write(renderStatsHuman(stats, cfg));
+ }
+ if (complete) {
+ emitNextStep("search-index-built", indexAdvisoryStream(argv, flags["json"] === true));
}
- process.stdout.write(renderStatsHuman(stats, cfg));
return 0;
}
@@ -1274,16 +1337,32 @@ async function cmdSearchStatus(argv: ReadonlyArray<string>): Promise<number> {
const cfg = resolveConfig(flags);
const status = await indexStatus(cfg);
if (flags["json"]) {
- process.stdout.write(JSON.stringify(serializeIndexStatus(status)) + "\n");
+ process.stdout.write(
+ JSON.stringify({
+ ...(serializeIndexStatus(status) as Record<string, unknown>),
+ // Same polarity as the human twin below, so the two conditions
+ // read as one rule rather than as each other's negation.
+ ...(!status.exists ? nextCommandField("search-index-missing") : {}),
+ }) + "\n",
+ );
return 0;
}
process.stdout.write(renderStatusHuman(status));
+ // no-dead-ends, phase 3: the pointer used to be spliced into the
+ // renderer's first line, which is a second emission mechanism AND
+ // beyond the reach of a scan over writer call sites. The rail decides
+ // the format; the condition is the one the claim rests on.
+ if (!status.exists) {
+ // The `--json` branch above returned, so this stream is provably a
+ // human one; the JSON payload carries the same exit as a field.
+ emitNextStep("search-index-missing", indexAdvisoryStream(argv, false));
+ }
return 0;
}
function renderStatusHuman(s: IndexStatusSnapshot): string {
if (!s.exists) {
- return `index: not initialised. Run: o2b search index\n path: ${s.indexPath}\n`;
+ return `index: not initialised\n path: ${s.indexPath}\n`;
}
const lines: string[] = [];
lines.push(`index: ${s.indexPath}`);
diff --git a/src/core/brain/applier-capability.ts b/src/core/brain/applier-capability.ts
new file mode 100644
index 00000000..19cd1721
--- /dev/null
+++ b/src/core/brain/applier-capability.ts
@@ -0,0 +1,334 @@
+/**
+ * The applier capability table (no-dead-ends, task 8).
+ *
+ * Three Finding-to-apply pipelines ship in this codebase - `applyRepair`
+ * (`diagnostics.ts`), `applyHygienePlan` (`hygiene/apply.ts`) and
+ * `applyRemediation` (`health/remediation.ts`) - plus the self-healing
+ * consolidation pass in `lint-consolidate.ts`. Each one used to decide
+ * privately what it could repair, so the question "is this finding
+ * mechanically fixable, and if not why not?" had four partial answers and
+ * no single one. This module is that answer: per finding code, either
+ * MECHANICAL (naming the fixer that performs the repair) or REFUSED
+ * (naming the reason it is not attempted).
+ *
+ * A refusal is a deliverable here. Every entry below that declines a
+ * repair states why in a non-empty reason, because a finding whose exit
+ * is "nothing happens" is exactly the dead end this release removes.
+ *
+ * ## Why this is its own module, and why it imports nothing
+ *
+ * The design left the placement open, to be decided by import surface.
+ * The table's consumers are the three appliers plus `hygiene/plan.ts`,
+ * and its natural alternative home - `diagnostics.ts`, beside the fixer
+ * registry - transitively pulls in `doctor.ts`, the whole detection pass.
+ * Hosting the table there would make `health/remediation.ts` and
+ * `hygiene/plan.ts` import the detector in order to ask a question about
+ * repair, and would make the dependency circular the moment
+ * `diagnostics.ts` consulted the table itself.
+ *
+ * So this module is a plain-data leaf with NO imports, and every code in
+ * it is written as a literal rather than referenced from the constant
+ * that also spells it. The literals are bound to their sources by
+ * `tests/core/brain/applier-capability.test.ts`, which re-derives the
+ * same population from the fixer registry, the remediation planner, the
+ * hygiene plan builder and the lint fix kinds, and fails on any
+ * disagreement in either direction. The binding is a test rather than an
+ * import on purpose: it is the only form that also catches a fixer added
+ * without a table entry.
+ *
+ * ## Write-guard placement: the one rule
+ *
+ * The three appliers used to place `assertVaultIdentityForWrite` three
+ * different ways - hygiene after its dry-run return, repair before it and
+ * conditional on it, remediation unconditionally including on dry runs.
+ * The unified rule, which all four write paths now follow:
+ *
+ * ASSERT AT THE APPLIER'S ENTRY POINT, BEFORE ANY OTHER WORK, AND ONLY
+ * WHEN THE CALL WILL WRITE.
+ *
+ * Both halves carry a reason and both come from a placement that already
+ * existed.
+ *
+ * - "Before any other work" is hygiene's rationale, generalised. Its
+ * per-finding loop is fail-soft, so an assertion reached from inside
+ * an executor would be recorded as one finding's error instead of
+ * refusing the run; and more generally a refusal that arrives after
+ * the first byte is on disk has already materialized the wrong store.
+ * - "Only when the call will write" is the repair path's rationale, and
+ * it is what the guard's own contract says: it is a WRITE guard. A
+ * dry run writes nothing, so gating it turns a preview - the very
+ * thing an operator reaches for to find out what is wrong - into a
+ * refusal. Remediation's unconditional placement was the outlier and
+ * is the behaviour that changed.
+ *
+ * `lint-consolidate.ts` follows the same rule (task 10): it used to
+ * assert unconditionally, which let the read-only `o2b brain actions`
+ * verb fail with a write-path error.
+ */
+
+/** Whether a finding code has a mechanical repair, or a stated refusal. */
+export const REPAIR_VERDICT = Object.freeze({
+ mechanical: "mechanical",
+ refused: "refused",
+} as const);
+
+export type RepairVerdict = (typeof REPAIR_VERDICT)[keyof typeof REPAIR_VERDICT];
+
+/**
+ * The module that owns the repair (or the refusal). `detectorOnly` is for
+ * codes a detector reports and no applier claims - those can only ever be
+ * refusals, asserted by the capability test.
+ */
+export const REPAIR_SURFACE = Object.freeze({
+ diagnostics: "diagnostics",
+ healthRemediation: "health/remediation",
+ hygieneApply: "hygiene/apply",
+ lintConsolidate: "lint-consolidate",
+ detectorOnly: "detector-only",
+} as const);
+
+export type RepairSurface = (typeof REPAIR_SURFACE)[keyof typeof REPAIR_SURFACE];
+
+interface RepairCapabilityBase {
+ /** The finding code, exactly as the detecting surface emits it. */
+ readonly code: string;
+ readonly surface: RepairSurface;
+}
+
+/** A code a named fixer repairs safely, deterministically and idempotently. */
+export interface MechanicalRepair extends RepairCapabilityBase {
+ readonly verdict: typeof REPAIR_VERDICT.mechanical;
+ /** The function that performs the repair, named so the claim is checkable. */
+ readonly fixer: string;
+}
+
+/** A code no applier will repair, with the reason it will not. */
+export interface RefusedRepair extends RepairCapabilityBase {
+ readonly verdict: typeof REPAIR_VERDICT.refused;
+ /** Why the repair is not attempted. Never empty. */
+ readonly reason: string;
+}
+
+export type RepairCapability = MechanicalRepair | RefusedRepair;
+
+/** A code that appears in no table entry. Never resolved to a guess. */
+export class UnclassifiedRepairCodeError extends Error {
+ readonly code: string;
+ constructor(code: string) {
+ super(
+ `no applier capability is published for finding code ${JSON.stringify(code)}; ` +
+ "add an entry to APPLIER_CAPABILITY declaring it mechanical or refused",
+ );
+ this.name = "UnclassifiedRepairCodeError";
+ this.code = code;
+ }
+}
+
+/** A mechanical repair was demanded for a code the table refuses. */
+export class RefusedRepairError extends Error {
+ readonly code: string;
+ readonly reason: string;
+ constructor(entry: RefusedRepair) {
+ super(`finding code ${JSON.stringify(entry.code)} has no mechanical repair: ${entry.reason}`);
+ this.name = "RefusedRepairError";
+ this.code = entry.code;
+ this.reason = entry.reason;
+ }
+}
+
+/** Two entries claimed the same code - the table would silently lose one. */
+export class DuplicateRepairCodeError extends Error {
+ constructor(code: string) {
+ super(`APPLIER_CAPABILITY declares finding code ${JSON.stringify(code)} more than once`);
+ this.name = "DuplicateRepairCodeError";
+ }
+}
+
+const ENTRIES: ReadonlyArray<RepairCapability> = [
+ // --- diagnostics: the two guarded doctor fixers -------------------------
+ {
+ code: "wal-gap",
+ surface: REPAIR_SURFACE.diagnostics,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "diagnostics.walGapFixer",
+ },
+ {
+ code: "orphaned-reference",
+ surface: REPAIR_SURFACE.diagnostics,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "diagnostics.orphanedReferenceFixer",
+ },
+
+ // --- health/remediation: bookkeeping repairs, semantic review -----------
+ {
+ code: "content-hash-drift",
+ surface: REPAIR_SURFACE.healthRemediation,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "health/remediation.restampContentHash",
+ },
+ {
+ code: "wide-permissions",
+ surface: REPAIR_SURFACE.healthRemediation,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "health/remediation.hardenPermissions",
+ },
+ {
+ code: "contradictory-preferences",
+ surface: REPAIR_SURFACE.healthRemediation,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "which of the two rules survives is a judgment about what the operator " +
+ "currently believes; an applier picking one would retire a rule nobody " +
+ "decided to retire",
+ },
+ {
+ code: "stale-claim",
+ surface: REPAIR_SURFACE.healthRemediation,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "age is evidence that a claim needs re-confirming, not evidence that it " +
+ "is wrong; only the operator can tell an obsolete rule from a durable one " +
+ "that simply has not come up",
+ },
+ {
+ code: "concept-gap",
+ surface: REPAIR_SURFACE.healthRemediation,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "the repair is to write a preference that does not exist yet, which is " +
+ "authoring content rather than repairing a record",
+ },
+
+ // --- hygiene/apply: one executor per proposed action --------------------
+ {
+ code: "merge",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "hygiene/apply.executeFinding -> mergePreferences",
+ },
+ {
+ code: "supersede",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "hygiene/apply.executeFinding -> appendClaimEvent",
+ },
+ {
+ code: "recompile",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "hygiene/apply.executeFinding -> executeRecompile",
+ },
+ {
+ code: "archive",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "hygiene/apply.executeFinding -> archivePage",
+ },
+ {
+ code: "forget",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "hygiene/apply.executeFinding -> archivePage",
+ },
+ {
+ code: "review",
+ surface: REPAIR_SURFACE.hygieneApply,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "the closed action vocabulary's safe default: a detector routes a finding " +
+ "here precisely when it cannot name an executor for it, so there is nothing " +
+ "to run",
+ },
+
+ // --- lint-consolidate: the self-healing structural pass -----------------
+ {
+ code: "fix-merged-link",
+ surface: REPAIR_SURFACE.lintConsolidate,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "lint-consolidate.scanFileForMergedLinks",
+ },
+ {
+ code: "demote-stale-stable",
+ surface: REPAIR_SURFACE.lintConsolidate,
+ verdict: REPAIR_VERDICT.mechanical,
+ fixer: "lint-consolidate.applyDemotion",
+ },
+
+ // --- detector-only: reported, deliberately never repaired ---------------
+ {
+ code: "stale-lock",
+ surface: REPAIR_SURFACE.detectorOnly,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "the lock primitive is a single-attempt exclusive create with no breaker, " +
+ "so no timeout distinguishes a crashed writer from a slow live one; " +
+ "removing a live writer's lock corrupts what it protects",
+ },
+ {
+ code: "vault-marker-absent",
+ surface: REPAIR_SURFACE.detectorOnly,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "an absent marker is ambiguous by construction - a fresh directory, a vault " +
+ "predating markers and a mis-resolved root are indistinguishable - so " +
+ "stamping one would name whichever root the typo produced",
+ },
+ {
+ code: "frontmatter-line-dropped",
+ surface: REPAIR_SURFACE.detectorOnly,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "the frontmatter scanner is line-based, so a dropped line is by definition " +
+ "grammar it has no branch for; repairing it means choosing a target shape " +
+ "per case, which is a policy decision rather than a mechanical fix",
+ },
+ {
+ code: "link_integrity",
+ surface: REPAIR_SURFACE.detectorOnly,
+ verdict: REPAIR_VERDICT.refused,
+ reason:
+ "the ratchet measurement yields scalar counts over the search index and no " +
+ "per-link rows, so there is no individual finding for an applier to act on",
+ },
+];
+
+/**
+ * The published table, keyed by finding code. Built eagerly so a
+ * duplicate code fails at import rather than silently losing an entry.
+ */
+export const APPLIER_CAPABILITY: ReadonlyMap<string, RepairCapability> = (() => {
+ const table = new Map<string, RepairCapability>();
+ for (const entry of ENTRIES) {
+ if (table.has(entry.code)) throw new DuplicateRepairCodeError(entry.code);
+ table.set(entry.code, Object.freeze(entry));
+ }
+ return table;
+})();
+
+/** The published capability for `code`, or `null` when none is published. */
+export function repairCapability(code: string): RepairCapability | null {
+ return APPLIER_CAPABILITY.get(code) ?? null;
+}
+
+/**
+ * The published capability for `code`, or {@link UnclassifiedRepairCodeError}.
+ * Callers that must route a finding use this rather than defaulting: an
+ * unpublished code means the table and the applier have drifted, and
+ * guessing a route is how a finding gets silently dropped.
+ */
+export function requireRepairCapability(code: string): RepairCapability {
+ const entry = APPLIER_CAPABILITY.get(code);
+ if (entry === undefined) throw new UnclassifiedRepairCodeError(code);
+ return entry;
+}
+
+/**
+ * The mechanical repair for `code`. Raises {@link RefusedRepairError}
+ * (carrying the published reason) when the table refuses the code, and
+ * {@link UnclassifiedRepairCodeError} when it does not know it.
+ */
+export function requireMechanicalRepair(code: string): MechanicalRepair {
+ const entry = requireRepairCapability(code);
+ if (entry.verdict === REPAIR_VERDICT.refused) throw new RefusedRepairError(entry);
+ return entry;
+}
diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.ts
new file mode 100644
index 00000000..7d70032e
--- /dev/null
+++ b/src/core/brain/config-template.ts
@@ -0,0 +1,556 @@
+/**
+ * Generator for the `Brain/_brain.yaml` bootstrap template.
+ *
+ * ## Why a generator
+ *
+ * The template used to be a hand-written string constant. The validator
+ * in `policy.ts` branches on 23 top-level keys; the constant emitted 7.
+ * Nothing connected the two, so sixteen keys resolved silently from
+ * their defaults and never appeared in the file an operator reads - a
+ * gap that grew by one block per release. Deriving the text from the
+ * resolver default tables removes the drift mechanism itself; the
+ * ratchet in `tests/core/brain/config-template-ratchet.test.ts` fails if
+ * a key is added to the resolver without landing here.
+ *
+ * ## Commented, not live: the judgement call
+ *
+ * Previously-hidden keys are emitted as COMMENTED defaults rather than
+ * live ones. Both options are defensible and the trade is real:
+ *
+ * - Live is more discoverable to a reader skimming the file, but it
+ * writes today's default value into every newly-created vault. A
+ * later release that changes a default would then be silently inert
+ * for those vaults, because an explicit value always wins over the
+ * table - the operator never chose the number, the template did. On
+ * a config the bootstrap writes once and never migrates, that is a
+ * one-way door.
+ * - Commented keeps the resolver default authoritative (the key is
+ * absent, so the table still decides) while still showing the reader
+ * the exact key name and its current value. Uncommenting is a
+ * deliberate act that records intent.
+ *
+ * Commented wins: this repository's stated contract is "byte-identical
+ * when absent", and a bootstrap template that pins sixteen defaults into
+ * every new vault is the opposite of that. The seven blocks that were
+ * already live stay live - grandfathered, because they are the
+ * established tuning surface and un-writing them would change what an
+ * existing operator's file looks like on the next `brain upgrade`.
+ *
+ * The ratchet enforces the rule in both directions: nothing new becomes
+ * live, and the live surface stays byte-identical to the pre-generation
+ * template.
+ */
+
+import {
+ BRAIN_GUARDRAIL_DEFAULTS,
+ BRAIN_HEALTH_DEFAULTS,
+ BRAIN_INTEGRITY_DEFAULTS,
+ BRAIN_LINK_GRAPH_DEFAULTS,
+ BRAIN_NOTES_DEFAULTS,
+ BRAIN_SESSIONS_DEFAULTS,
+ BRAIN_TEMPORAL_DEFAULTS,
+ DEFAULT_BRAIN_CONFIG,
+ INJECT_BUDGET_CHARS_DEFAULT,
+ LESSONS_CORROBORATION_MIN_DEFAULT,
+ LESSONS_HALF_LIFE_DAYS_DEFAULT,
+ LESSONS_LIMIT_DEFAULT,
+ MOST_APPLIED_LIMIT_DEFAULT,
+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,
+} from "./policy.ts";
+import {
+ DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ DEFAULT_ANTICIPATORY_TTL_SECONDS,
+} from "./anticipatory-cache.ts";
+import {
+ DEFAULT_FACT_ROLLUP_THRESHOLD,
+ DEFAULT_ROLLUP_IDENTITY_THRESHOLD,
+} from "./rollup-ladder.ts";
+import { SCHEMA_VOCAB_CATEGORIES } from "./schema-vocab.ts";
+
+/**
+ * How one key is emitted.
+ *
+ * - `live` — written uncommented; the value lands in the file.
+ * - `commented-default` — written commented AT the resolver default,
+ * so uncommenting it is a no-op until the operator edits the value.
+ * - `commented-example` — the resolver default is "absent" (the key
+ * has no default at all), so the value shown is an illustration, not
+ * a default. Excluded from the all-defaults rendering because
+ * writing it would change behaviour.
+ */
+export type BrainTemplateEmission = "live" | "commented-default" | "commented-example";
+
+export type BrainTemplateValue = number | string | boolean | null | ReadonlyArray<string>;
+
+export interface BrainTemplateKey {
+ readonly key: string;
+ /** Comment lines rendered above the key, without the leading `#`. */
+ readonly doc: ReadonlyArray<string>;
+ readonly emit: BrainTemplateEmission;
+ readonly value: BrainTemplateValue;
+ /**
+ * Rendered form, when it differs from the default formatting of
+ * `value` (`confidence.medium_min` has always been written `0.40`).
+ */
+ readonly text?: string;
+}
+
+export interface BrainTemplateBlock {
+ readonly key: string;
+ readonly doc: ReadonlyArray<string>;
+ readonly emit: BrainTemplateEmission;
+ /** Present for a top-level scalar (`schema_version`, `primary_agent`). */
+ readonly scalar?: BrainTemplateValue;
+ readonly keys: ReadonlyArray<BrainTemplateKey>;
+}
+
+/** A resolver key deliberately left out of the template. */
+export interface BrainTemplateOmission {
+ /** `block` or `block.sub_key`. */
+ readonly key: string;
+ readonly reason: string;
+}
+
+const G = BRAIN_GUARDRAIL_DEFAULTS;
+const T = BRAIN_TEMPORAL_DEFAULTS;
+const H = BRAIN_HEALTH_DEFAULTS;
+const I = BRAIN_INTEGRITY_DEFAULTS;
+const L = BRAIN_LINK_GRAPH_DEFAULTS;
+
+/** Every sub-key of a `commented-default` block that holds an empty list. */
+const EMPTY_LIST: ReadonlyArray<string> = Object.freeze([]);
+
+function live(
+ key: string,
+ value: BrainTemplateValue,
+ doc: ReadonlyArray<string> = [],
+ text?: string,
+): BrainTemplateKey {
+ return { key, doc, emit: "live", value, ...(text !== undefined ? { text } : {}) };
+}
+
+function def(
+ key: string,
+ value: BrainTemplateValue,
+ doc: ReadonlyArray<string> = [],
+): BrainTemplateKey {
+ return { key, doc, emit: "commented-default", value };
+}
+
+function example(
+ key: string,
+ value: BrainTemplateValue,
+ doc: ReadonlyArray<string>,
+): BrainTemplateKey {
+ return { key, doc, emit: "commented-example", value };
+}
+
+/**
+ * The template, block by block, in emission order. Values come from the
+ * resolver default tables - never from a literal repeated here - so the
+ * file and the resolver cannot disagree about what a default is.
+ */
+export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.freeze([
+ {
+ key: "schema_version",
+ doc: [],
+ emit: "live",
+ scalar: DEFAULT_BRAIN_CONFIG.schema_version,
+ keys: [],
+ },
+ {
+ key: "primary_agent",
+ doc: [
+ "Optional. When set, dream runs from a different agent emit a stderr",
+ "warning and a non_primary_agent payload row. The vault should have a",
+ "single dream-running runtime even when it is shared across devices",
+ "via Syncthing.",
+ ],
+ emit: "live",
+ scalar: DEFAULT_BRAIN_CONFIG.primary_agent,
+ keys: [],
+ },
+ {
+ key: "dream",
+ doc: [],
+ emit: "live",
+ keys: [
+ live("candidate_threshold", DEFAULT_BRAIN_CONFIG.dream.candidate_threshold),
+ live("unconfirmed_window_days", DEFAULT_BRAIN_CONFIG.dream.unconfirmed_window_days),
+ live("contradiction_window_days", DEFAULT_BRAIN_CONFIG.dream.contradiction_window_days),
+ def("heal_enrich_enabled", DEFAULT_BRAIN_CONFIG.dream.heal_enrich_enabled === true, [
+ "Opt-in heal-phase enrichment. Left off, the heal phase is a",
+ "checkpoint-only no-op.",
+ ]),
+ ],
+ },
+ {
+ key: "retire",
+ doc: [],
+ emit: "live",
+ keys: [
+ live("stale_evidence_days", DEFAULT_BRAIN_CONFIG.retire.stale_evidence_days),
+ example("confirmed_evidence_min_threshold", 3, [
+ "Unset by default, which leaves the destructive-from-confirmed gate",
+ "off. Set a positive integer to refuse retiring a confirmed, unpinned",
+ "preference whose applied+violated count is below it; skipped retires",
+ "surface as gated_retires in the dream summary.",
+ ]),
+ ],
+ },
+ {
+ key: "confidence",
+ doc: [],
+ emit: "live",
+ keys: [
+ live("low_max_applied", DEFAULT_BRAIN_CONFIG.confidence.low_max_applied, [
+ 'low_max_applied gates the "low-evidence-confirmed" doctor warning',
+ "and the auto-promotion of unconfirmed preferences to confirmed.",
+ ]),
+ live(
+ "medium_min",
+ DEFAULT_BRAIN_CONFIG.confidence.medium_min,
+ [
+ "Band thresholds on the numeric confidence_value (Wilson lower",
+ "bound times freshness decay). value >= high_min ⇒ high;",
+ "value >= medium_min ⇒ medium; else low.",
+ ],
+ DEFAULT_BRAIN_CONFIG.confidence.medium_min.toFixed(2),
+ ),
+ live("high_min", DEFAULT_BRAIN_CONFIG.confidence.high_min),
+ ],
+ },
+ {
+ key: "snapshots",
+ doc: [],
+ emit: "live",
+ keys: [live("retention_count", DEFAULT_BRAIN_CONFIG.snapshots.retention_count)],
+ },
+ {
+ key: "vault",
+ doc: [
+ "Vault-wide exclusion policy. Single source of truth for every",
+ "vault walker (search indexer, scan-inline, future scanners).",
+ "Entries without a slash match a directory name anywhere in the",
+ "tree; entries with a slash match a vault-relative POSIX path",
+ "exactly. Remove the block to fall back to the built-in defaults;",
+ "set ignore_paths to an empty list to disable exclusions entirely.",
+ ],
+ emit: "live",
+ keys: [live("ignore_paths", DEFAULT_BRAIN_CONFIG.vault?.ignore_paths ?? EMPTY_LIST)],
+ },
+
+ // ----- Below here: every remaining key the resolver understands. ------
+ // Commented at its default (see the module docblock for why).
+
+ {
+ key: "active",
+ doc: ["Tuning for the active.md body injected at SessionStart."],
+ emit: "commented-default",
+ keys: [
+ def("most_applied_window_days", MOST_APPLIED_WINDOW_DAYS_DEFAULT),
+ def("most_applied_limit", MOST_APPLIED_LIMIT_DEFAULT),
+ def("inject_budget_chars", INJECT_BUDGET_CHARS_DEFAULT),
+ ],
+ },
+ {
+ key: "anticipatory",
+ doc: ["Anticipatory context cache: freshness window and size cap."],
+ emit: "commented-default",
+ keys: [
+ def("ttl_seconds", DEFAULT_ANTICIPATORY_TTL_SECONDS),
+ def("max_tokens", DEFAULT_ANTICIPATORY_MAX_TOKENS),
+ ],
+ },
+ {
+ key: "discipline_report",
+ doc: [
+ "`o2b discipline report`. No defaults: the block is all-or-nothing,",
+ "and an absent block means the report is disabled. The values below",
+ "are an illustration, not defaults - every field must be supplied.",
+ ],
+ emit: "commented-example",
+ keys: [
+ example("enabled", false, []),
+ example("timezone", "UTC", []),
+ example("watched_paths", EMPTY_LIST, []),
+ example("known_agents", EMPTY_LIST, []),
+ ],
+ },
+ {
+ key: "feedback",
+ doc: [
+ "Vault-default scope stamped on feedback signals that omit one.",
+ "Unset by default, which leaves signals scope-less.",
+ ],
+ emit: "commented-example",
+ keys: [example("default_scope", "coding", [])],
+ },
+ {
+ key: "guardrails",
+ doc: [
+ "Promotion floors and opt-in provenance features. The three",
+ "promotion floors default strictly looser than every dream-pass",
+ "gate, so they cannot block a promotion that already succeeded.",
+ ],
+ emit: "commented-default",
+ keys: [
+ def("promotion_min_signals", G.promotion_min_signals),
+ def("promotion_min_distinct_agents", G.promotion_min_distinct_agents),
+ def("promotion_min_age_days", G.promotion_min_age_days),
+ def("instruction_file_max_lines", G.instruction_file_max_lines),
+ def("untrusted_source_delimiting", G.untrusted_source_delimiting),
+ def("derived_fact_synthesis", G.derived_fact_synthesis),
+ def("provenance_trust_ordering", G.provenance_trust_ordering),
+ def("owner_scoped_facts", G.owner_scoped_facts),
+ def("marker_writeback", G.marker_writeback),
+ ],
+ },
+ {
+ key: "health",
+ doc: ["Semantic-health detectors and the remediation step cap."],
+ emit: "commented-default",
+ keys: [
+ def("contradiction_jaccard", H.contradiction_jaccard),
+ def("concept_gap_min_frequency", H.concept_gap_min_frequency),
+ def("stale_claim_max_age_days", H.stale_claim_max_age_days),
+ def("remediation_step_cap", H.remediation_step_cap),
+ example("silence_before", "2026-01-01", [
+ "Baseline watermark: findings older than this instant are silenced.",
+ "Unset by default; `o2b brain health --silence-before` writes it.",
+ ]),
+ ],
+ },
+ {
+ key: "hygiene",
+ doc: ["Continuity-hygiene pass."],
+ emit: "commented-example",
+ keys: [
+ example("resolver_cmd", "echo", [
+ "External resolver invoked for hygiene conflicts. Unset by default,",
+ "which leaves conflicts for the operator.",
+ ]),
+ ],
+ },
+ {
+ key: "integrity",
+ doc: [
+ "Context-integrity gates. Each gate is off | warn | fail.",
+ "pack_validity_seconds bounds how long a built context pack stays",
+ "servable; the provenance stamp is the primary invalidator.",
+ ],
+ emit: "commented-default",
+ keys: [
+ def("owner_scope_delivery", I.owner_scope_delivery),
+ def("embedding_abi", I.embedding_abi),
+ def("pack_validity_seconds", I.pack_validity_seconds),
+ ],
+ },
+ {
+ key: "lessons",
+ doc: ["Signed, recency-scored lessons digest (Brain/lessons.md)."],
+ emit: "commented-default",
+ keys: [
+ def("half_life_days", LESSONS_HALF_LIFE_DAYS_DEFAULT),
+ def("corroboration_min", LESSONS_CORROBORATION_MIN_DEFAULT),
+ def("limit", LESSONS_LIMIT_DEFAULT),
+ ],
+ },
+ {
+ key: "link_graph",
+ doc: [
+ "MOC-detection thresholds (purely structural - link counts and",
+ "character ratios, never vocabulary) and the vault-root instruction",
+ "file brain_context surfaces when present.",
+ ],
+ emit: "commented-default",
+ keys: [
+ def("moc_min_outbound_links", L.moc_min_outbound_links),
+ def("moc_min_link_ratio", L.moc_min_link_ratio),
+ def("vault_instruction_file", L.vault_instruction_file),
+ ],
+ },
+ {
+ key: "notes",
+ doc: [
+ "User-authored folders the agent may READ. Empty means it reads",
+ "none; the agent never writes to these paths.",
+ ],
+ emit: "commented-default",
+ keys: [def("read_paths", BRAIN_NOTES_DEFAULTS.read_paths)],
+ },
+ {
+ key: "recall",
+ doc: [
+ "Per-entry trim strategy when a recall budget is exceeded.",
+ "hard-cut keeps the historical mid-sentence cut; staged walks a",
+ "sentence -> whole-lines -> hard ladder.",
+ ],
+ emit: "commented-default",
+ keys: [def("degradation", "hard-cut")],
+ },
+ {
+ key: "rollup",
+ doc: ["Fact rollup-ladder thresholds."],
+ emit: "commented-default",
+ keys: [
+ def("fact_threshold", DEFAULT_FACT_ROLLUP_THRESHOLD),
+ def("identity_threshold", DEFAULT_ROLLUP_IDENTITY_THRESHOLD),
+ ],
+ },
+ {
+ key: "schema",
+ doc: [
+ "Runtime schema-pack declarations. Every list is additive on top of",
+ "the built-in vocabulary, so an empty list declares nothing - the",
+ "default. Use `o2b schema` to inspect what is already in force",
+ "before adding tokens here.",
+ ],
+ emit: "commented-default",
+ keys: [
+ ...SCHEMA_VOCAB_CATEGORIES.map((category) => def(category, EMPTY_LIST)),
+ def("aliases", EMPTY_LIST),
+ def("prefixes", EMPTY_LIST),
+ def("link_types", EMPTY_LIST),
+ def("extractable", EMPTY_LIST),
+ def("expert_routing", EMPTY_LIST),
+ ],
+ },
+ {
+ key: "sessions",
+ doc: [
+ "Session-capture filters. Session patterns are anchored globs;",
+ "message patterns are regexes. Empty lists capture everything.",
+ ],
+ emit: "commented-default",
+ keys: [
+ def("ignore_patterns", BRAIN_SESSIONS_DEFAULTS.ignore_patterns),
+ def("stateless_patterns", BRAIN_SESSIONS_DEFAULTS.stateless_patterns),
+ def("ignore_message_patterns", BRAIN_SESSIONS_DEFAULTS.ignore_message_patterns),
+ ],
+ },
+ {
+ key: "temporal",
+ doc: [
+ "Staleness windows and calendar alignment. weekly_start_dow is an",
+ "ISO-8601 weekday number (1 = Monday, 7 = Sunday).",
+ ],
+ emit: "commented-default",
+ keys: [
+ def("stale_pref_days", T.stale_pref_days),
+ def("stale_signal_days", T.stale_signal_days),
+ def("stale_log_days", T.stale_log_days),
+ def("weekly_start_dow", T.weekly_start_dow),
+ def("daily_window_offset_hours", T.daily_window_offset_hours),
+ ],
+ },
+]) as ReadonlyArray<BrainTemplateBlock>;
+
+/**
+ * Resolver keys deliberately absent from the template, each with the
+ * reason. The ratchet accepts an omission only when the reason is
+ * non-empty - "we forgot" is not expressible here.
+ */
+export const BRAIN_CONFIG_TEMPLATE_OMISSIONS: ReadonlyArray<BrainTemplateOmission> = Object.freeze([
+ {
+ key: "hygiene.dedup_threshold",
+ reason:
+ "Validated by the loader but read by no consumer: no code path reads " +
+ "hygiene.dedup_threshold, so templating it would advertise a knob that " +
+ "does nothing. Wire a reader (or drop the validation) before documenting it.",
+ },
+]) as ReadonlyArray<BrainTemplateOmission>;
+
+export interface RenderBrainConfigTemplateOptions {
+ /**
+ * Render every `commented-default` key as a live one. Used by the
+ * ratchet to prove that the commented defaults are exactly the
+ * resolver's defaults: the resulting config must resolve identically
+ * to an empty one. `commented-example` keys stay out - they have no
+ * default, so writing them WOULD change behaviour.
+ */
+ readonly allDefaultsLive?: boolean;
+}
+
+/** Render one scalar in the `_brain.yaml` subset. */
+function formatScalar(value: BrainTemplateValue, text?: string): string {
+ if (text !== undefined) return text;
+ if (value === null) return "null";
+ if (typeof value === "string") return JSON.stringify(value);
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
+ return "[]";
+}
+
+/**
+ * Line prefixes. A commented BLOCK carries its marker at column 0 (the
+ * whole block is inert); a commented KEY inside a live block keeps the
+ * block's indentation and carries the marker after it, so it still reads
+ * as part of the block it belongs to.
+ */
+const LIVE_KEY_INDENT = " ";
+const LIVE_LIST_INDENT = " ";
+const BLOCK_COMMENT = "# ";
+const KEY_COMMENT = " # ";
+const KEY_COMMENT_LIST = " # - ";
+
+function renderKeyLines(entry: BrainTemplateKey, keyIsLive: boolean): string[] {
+ const out: string[] = [];
+ for (const doc of entry.doc) out.push(`${KEY_COMMENT}${doc}`);
+ const list = Array.isArray(entry.value) ? (entry.value as ReadonlyArray<string>) : null;
+ const header = keyIsLive ? `${LIVE_KEY_INDENT}${entry.key}` : `${KEY_COMMENT}${entry.key}`;
+ if (list !== null && list.length > 0) {
+ out.push(`${header}:`);
+ for (const item of list) {
+ out.push(keyIsLive ? `${LIVE_LIST_INDENT}- ${item}` : `${KEY_COMMENT_LIST}${item}`);
+ }
+ return out;
+ }
+ out.push(`${header}: ${formatScalar(entry.value, entry.text)}`);
+ return out;
+}
+
+/** Comment out an already-rendered live block, line by line. */
+function commentOutBlock(lines: ReadonlyArray<string>): string[] {
+ return lines.map((line) => (line === "" ? "#" : `${BLOCK_COMMENT}${line}`));
+}
+
+/**
+ * Render the canonical `Brain/_brain.yaml` body.
+ *
+ * Deterministic and pure: same inputs, same bytes, every call.
+ */
+export function renderBrainConfigTemplate(options: RenderBrainConfigTemplateOptions = {}): string {
+ const allDefaultsLive = options.allDefaultsLive === true;
+ const chunks: string[] = [];
+ for (const block of BRAIN_CONFIG_TEMPLATE) {
+ const blockIsLive =
+ block.emit === "live" || (allDefaultsLive && block.emit !== "commented-example");
+ if (allDefaultsLive && !blockIsLive) continue;
+ const entries = block.keys.filter(
+ (entry) => !(allDefaultsLive && entry.emit === "commented-example"),
+ );
+ if (block.keys.length > 0 && entries.length === 0) continue;
+ const body: string[] = [];
+ if (block.scalar !== undefined || block.keys.length === 0) {
+ body.push(`${block.key}: ${formatScalar(block.scalar ?? null)}`);
+ } else {
+ body.push(`${block.key}:`);
+ for (const entry of entries) {
+ const keyIsLive = entry.emit === "live" || allDefaultsLive;
+ body.push(...renderKeyLines(entry, keyIsLive));
+ }
+ }
+ const rendered = blockIsLive ? body : commentOutBlock(body);
+ const doc = block.doc.map((line) => `${BLOCK_COMMENT}${line}`);
+ chunks.push([...doc, ...rendered].join("\n"));
+ }
+ return `${chunks.join("\n\n")}\n`;
+}
+
+/**
+ * Default `_brain.yaml` content written by `o2b brain init`.
+ *
+ * Generated, not hand-written: see the module docblock. The LIVE keys
+ * are byte-identical to the constant this replaced.
+ */
+export const DEFAULT_BRAIN_CONFIG_YAML = renderBrainConfigTemplate();
diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.ts
index 207536fb..314a9cec 100644
--- a/src/core/brain/continuity/types.ts
+++ b/src/core/brain/continuity/types.ts
@@ -38,6 +38,7 @@ export type ContinuityRecordKind =
| "session_summary_node"
| "session_summary_digest"
| "generation_report"
+ | "ingest_dedup"
| "mcp_route_latency"
| "token_impact"
| "token_impact_outcome"
diff --git a/src/core/brain/dedup-telemetry.ts b/src/core/brain/dedup-telemetry.ts
new file mode 100644
index 00000000..6950b50c
--- /dev/null
+++ b/src/core/brain/dedup-telemetry.ts
@@ -0,0 +1,294 @@
+/**
+ * Ingest dedup observability (no-dead-ends, Unit F).
+ *
+ * The three ingest paths that DROP an item on a repeat -
+ * `captureSessionLifecycleEvent`, `scanInline`, `importSession` - each
+ * already counted the drops and returned the count in a CLI/JSON/MCP
+ * response. That count then died one call deep: nothing persisted it, so
+ * a spike in re-ingest pressure could not be observed over time. This
+ * module is the missing persistence: one append-only `ingest_dedup`
+ * continuity record per ingest RUN, read back by {@link
+ * summarizeIngestDedup} on the analytics surface. It follows the
+ * `generation_report` model (emit / list / summarize over the continuity
+ * store) rather than inventing a shape.
+ *
+ * EXACT HASH ONLY. Every count here comes from a sha-256 `dedup_hash`
+ * collision - the only mechanism in this codebase that actually drops an
+ * ingested item. The two semantic layers (`detectSemanticDedup`,
+ * `detectEntityAliasCandidates`) are opt-in, proposal-only NOMINATION
+ * systems: they nominate merge candidates and never drop anything. So no
+ * field here reports a semantic figure, and every field that counts drops
+ * carries `exact` in its name, so nothing this module writes can be read
+ * as "semantically dropped".
+ *
+ * The per-source dimension answers the operator question "which source is
+ * being re-ingested". It is taken from the identity each call site already
+ * keys its provenance by: the session id for the two session paths, and
+ * the vault-relative note path for the inline scan. Those are exactly the
+ * units an operator can act on (stop replaying that session; fix that
+ * note).
+ *
+ * Error discipline. A caller bug (an unknown surface, a negative or
+ * fractional count, a blank ref) raises {@link IngestDedupTelemetryError}
+ * eagerly, BEFORE the gate - a miscounted telemetry row is worse than a
+ * loud failure, and those inputs are computed locally so they are
+ * deterministic. Only the disk write runs inside `emitGatedTelemetry`,
+ * which keeps the fail-open guarantee that telemetry can never fail the
+ * ingest it observes.
+ */
+
+import { emitGatedTelemetry } from "./continuity/emit.ts";
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+
+/** Continuity record kind this module owns. */
+export const INGEST_DEDUP_RECORD_KIND = "ingest_dedup";
+
+/** The ingest runs that can drop an item on an exact-hash collision. */
+export const INGEST_DEDUP_SURFACES = Object.freeze([
+ "session_lifecycle",
+ "scan_inline",
+ "session_import",
+] as const);
+
+export type IngestDedupSurface = (typeof INGEST_DEDUP_SURFACES)[number];
+
+/**
+ * Largest per-source map a single record carries. A vault-wide re-scan can
+ * touch thousands of notes; the map keeps the heaviest re-ingest offenders
+ * (which is the operator question) and names how many refs it dropped
+ * rather than growing an unbounded payload. The run TOTAL is a separate
+ * field and stays exact regardless of the clip.
+ */
+export const MAX_TRACKED_DEDUP_SOURCES = 50;
+
+export class IngestDedupTelemetryError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "IngestDedupTelemetryError";
+ }
+}
+
+/** One ingest source and how many of its items collided on an exact hash. */
+export interface IngestDedupSourceCount {
+ /** Session id, or vault-relative note path - whatever the run keys provenance by. */
+ readonly ref: string;
+ readonly exactDeduped: number;
+}
+
+export interface IngestDedupReportInput {
+ readonly surface: IngestDedupSurface;
+ /** Every source the run considered; a zero-count source is legal and contributes nothing. */
+ readonly sources: ReadonlyArray<IngestDedupSourceCount>;
+ readonly createdAt?: string;
+}
+
+/**
+ * Persist one run's exact-hash dedup counts.
+ *
+ * Returns `null` - writing NOTHING - when the run deduped nothing. A zero
+ * row would make a real measured zero indistinguishable from an absent
+ * measurement, so absence is the honest encoding of "nothing collided".
+ * Also returns `null` when the write itself fails, so telemetry never
+ * fails the ingest.
+ */
+export function emitIngestDedupReport(
+ vault: string,
+ input: IngestDedupReportInput,
+): ContinuityRecord | null {
+ assertKnownSurface(input.surface);
+ const totals = mergeSources(input.sources);
+
+ let exactDeduped = 0;
+ for (const count of totals.values()) exactDeduped += count;
+ if (exactDeduped === 0) return null;
+
+ const ranked = [...totals.entries()]
+ .filter(([, count]) => count > 0)
+ .toSorted(([leftRef, leftCount], [rightRef, rightCount]) =>
+ rightCount === leftCount ? leftRef.localeCompare(rightRef) : rightCount - leftCount,
+ );
+ const tracked = ranked.slice(0, MAX_TRACKED_DEDUP_SOURCES);
+ const omitted = ranked.length - tracked.length;
+ const createdAt = input.createdAt ?? new Date().toISOString();
+
+ return emitGatedTelemetry(INGEST_DEDUP_GATE, () =>
+ appendContinuityRecord(vault, {
+ kind: INGEST_DEDUP_RECORD_KIND,
+ createdAt,
+ sourceRefs: buildSourceRefs(input.surface, tracked),
+ payload: {
+ surface: input.surface,
+ exact_deduped: exactDeduped,
+ by_source: Object.fromEntries(tracked),
+ ...(omitted > 0 ? { by_source_omitted: omitted } : {}),
+ },
+ }),
+ );
+}
+
+/**
+ * The gate is permanently open: unlike the opt-in traces, the dedup count
+ * is a first-class observability surface whose whole point is that a spike
+ * is visible without the operator having enabled anything in advance. The
+ * emit still routes through `emitGatedTelemetry` for the second guarantee
+ * that helper provides - fail-open, so a broken continuity store degrades
+ * observability instead of breaking ingest.
+ */
+const INGEST_DEDUP_GATE = true;
+
+function assertKnownSurface(surface: IngestDedupSurface): void {
+ if (!(INGEST_DEDUP_SURFACES as ReadonlyArray<string>).includes(surface)) {
+ throw new IngestDedupTelemetryError(
+ `unknown ingest dedup surface ${JSON.stringify(surface)}; ` +
+ `expected one of ${INGEST_DEDUP_SURFACES.join(", ")}`,
+ );
+ }
+}
+
+/** Collapse repeated refs into one count each, validating as it goes. */
+function mergeSources(sources: ReadonlyArray<IngestDedupSourceCount>): Map<string, number> {
+ const totals = new Map<string, number>();
+ for (const source of sources) {
+ const ref = typeof source.ref === "string" ? source.ref.trim() : "";
+ if (ref.length === 0) {
+ throw new IngestDedupTelemetryError(
+ `ingest dedup source ref must be a non-empty string; got ${JSON.stringify(source.ref)}`,
+ );
+ }
+ const count = source.exactDeduped;
+ if (!Number.isInteger(count) || count < 0) {
+ throw new IngestDedupTelemetryError(
+ `ingest dedup count for ${JSON.stringify(ref)} must be a non-negative integer; ` +
+ `got ${JSON.stringify(count)}`,
+ );
+ }
+ totals.set(ref, (totals.get(ref) ?? 0) + count);
+ }
+ return totals;
+}
+
+function buildSourceRefs(
+ surface: IngestDedupSurface,
+ tracked: ReadonlyArray<readonly [string, number]>,
+): ReadonlyArray<ContinuitySourceRef> {
+ return Object.freeze(tracked.map(([ref]) => Object.freeze({ id: ref, kind: surface })));
+}
+
+export interface IngestDedupFilter {
+ readonly surface?: IngestDedupSurface;
+ readonly since?: string;
+ readonly until?: string;
+ readonly limit?: number;
+}
+
+/** List `ingest_dedup` records newest-first, after applying filters. */
+export function listIngestDedupReports(
+ vault: string,
+ filter: IngestDedupFilter = {},
+): ReadonlyArray<ContinuityRecord> {
+ let records = listContinuityRecords(vault, {
+ kind: INGEST_DEDUP_RECORD_KIND,
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ }).filter(
+ (record) => filter.surface === undefined || record.payload["surface"] === filter.surface,
+ );
+ records = records.toReversed();
+ if (filter.limit !== undefined) records = records.slice(0, Math.max(0, Math.floor(filter.limit)));
+ return Object.freeze(records);
+}
+
+/** One point of the re-ingest trend: a single run's exact-hash drop count. */
+export interface IngestDedupTrendPoint {
+ readonly at: string;
+ readonly surface: string;
+ readonly exact_deduped: number;
+}
+
+/** How much re-ingest pressure one source accounts for, across runs. */
+export interface IngestDedupSourceRollup {
+ readonly ref: string;
+ readonly surface: string;
+ readonly exact_deduped: number;
+ readonly records: number;
+}
+
+export interface IngestDedupSummary {
+ readonly total_records: number;
+ /** Items dropped on an exact sha-256 collision. Never a semantic figure. */
+ readonly total_exact_deduped: number;
+ readonly by_surface: Readonly<Record<string, number>>;
+ /** Heaviest re-ingested sources first - the "which source" answer. */
+ readonly by_source: ReadonlyArray<IngestDedupSourceRollup>;
+ /** One point per run, oldest first, so a spike is visible over time. */
+ readonly trend: ReadonlyArray<IngestDedupTrendPoint>;
+}
+
+/** Aggregate the persisted dedup records into a trend plus a per-source ranking. */
+export function summarizeIngestDedup(
+ vault: string,
+ filter: IngestDedupFilter = {},
+): IngestDedupSummary {
+ const records = listIngestDedupReports(vault, filter).toSorted(
+ (left, right) =>
+ left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
+ );
+ const bySurface: Record<string, number> = {};
+ const bySource = new Map<string, { rollup: IngestDedupSourceRollup }>();
+ const trend: IngestDedupTrendPoint[] = [];
+ let totalExact = 0;
+
+ for (const record of records) {
+ const payload = record.payload;
+ const surface = typeof payload["surface"] === "string" ? payload["surface"] : "unknown";
+ const exact = numberOr0(payload["exact_deduped"]);
+ totalExact += exact;
+ bySurface[surface] = (bySurface[surface] ?? 0) + exact;
+ trend.push(Object.freeze({ at: record.createdAt, surface, exact_deduped: exact }));
+
+ for (const [ref, count] of readSourceMap(payload["by_source"])) {
+ // Axis label folded into the key so the same ref on two surfaces
+ // never merges into one misleading rollup.
+ const key = `${surface}${ref}`;
+ const previous = bySource.get(key)?.rollup;
+ bySource.set(key, {
+ rollup: Object.freeze({
+ ref,
+ surface,
+ exact_deduped: (previous?.exact_deduped ?? 0) + count,
+ records: (previous?.records ?? 0) + 1,
+ }),
+ });
+ }
+ }
+
+ const ranked = [...bySource.values()]
+ .map((entry) => entry.rollup)
+ .toSorted((left, right) =>
+ right.exact_deduped === left.exact_deduped
+ ? left.ref.localeCompare(right.ref)
+ : right.exact_deduped - left.exact_deduped,
+ );
+
+ return Object.freeze({
+ total_records: records.length,
+ total_exact_deduped: totalExact,
+ by_surface: Object.freeze(bySurface),
+ by_source: Object.freeze(ranked),
+ trend: Object.freeze(trend),
+ });
+}
+
+function readSourceMap(value: unknown): ReadonlyArray<readonly [string, number]> {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return [];
+ const out: Array<readonly [string, number]> = [];
+ for (const [ref, count] of Object.entries(value as Record<string, unknown>)) {
+ if (typeof count === "number" && Number.isFinite(count)) out.push([ref, count] as const);
+ }
+ return out;
+}
+
+function numberOr0(value: unknown): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
+}
diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.ts
index 9b549560..9e6e8c7f 100644
--- a/src/core/brain/diagnostics.ts
+++ b/src/core/brain/diagnostics.ts
@@ -14,7 +14,13 @@
* Repair contract:
* - `doctor.ts` (plain / `--strict`) is read-only and byte-identical;
* nothing here runs unless the operator opts in with `--repair`.
- * - `planRepair` is a pure read: it previews what `--apply` would do.
+ * - `planRepair` is a pure read: it previews what `--apply` would do,
+ * DERIVED FROM the doctor's findings rather than from a scan of its
+ * own (no-dead-ends, task 9). Each fixer receives exactly the
+ * findings carrying the doctor code it covers. Neither fixer keeps a
+ * private detector: the doctor reports `dangling-workrun` from the
+ * same scan the WAL fixer used to run, and `broken-wikilink` is a
+ * superset of the orphaned-reference population.
* - `applyRepair({ dryRun: true })` is the preview surface (writes
* nothing); `{ dryRun: false }` performs the fixes and appends ONE
* typed `doctor-repair` event per applied fix.
@@ -37,7 +43,7 @@
* lifecycle provenance or break a required field.
*/
-import { appendFileSync, existsSync, readdirSync, readFileSync } from "node:fs";
+import { appendFileSync, existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { normalizeAgentArgument } from "../agent-identity.ts";
@@ -45,14 +51,14 @@ import { resolveAgentName } from "../config.ts";
import { vaultRelative } from "../path-safety.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { UnclassifiedRepairCodeError, requireMechanicalRepair } from "./applier-capability.ts";
+
import { collectAllBasenames, runDoctor } from "./doctor.ts";
import { scanDanglingWorkruns, WORKRUN_PHASE } from "./dream-workrun.ts";
import { appendLogEvent } from "./log.ts";
-import { brainDirs } from "./paths.ts";
-import { parsePreference, parseRetired } from "./preference.ts";
import { acquireLockSync } from "./sync-lockfile.ts";
import { isoSecond } from "./time.ts";
-import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { BRAIN_LOG_EVENT_KIND, type DoctorIssue } from "./types.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
@@ -84,6 +90,13 @@ export const REPAIR_CODE = Object.freeze({
* Registry: the single home for every issue class this wave surfaces and
* its next-command hint. Doctor codes, fixer codes, and the O3 snapshot
* source codes all resolve here so a hint is defined exactly once.
+ *
+ * no-dead-ends (task 5) widened the population from "issue" to "state a
+ * caller can be left in": a verb that succeeded and printed nothing
+ * forward is the same defect from the caller's side, and giving those
+ * states a code here is what stops the command being retyped inside an
+ * `ok()` string. Nothing iterates this map expecting only faults; every
+ * consumer resolves by code.
*/
export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map(
(
@@ -181,6 +194,17 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map
nextCommand: "o2b brain stale",
autoRepairable: false,
},
+ {
+ // Issue #149. The detector has existed since the hygiene lints
+ // shipped; what it never had was an exit. Recording real use is
+ // the only thing that moves a cold-start rule, and the reporter
+ // reached for a synthetic confidence value precisely because no
+ // surface said so.
+ code: "low-evidence-confirmed",
+ issueClass: "confirmed rule with no recorded use",
+ nextCommand: "o2b brain apply-evidence --pref <id> --artifact <artifact> --result=applied",
+ autoRepairable: false,
+ },
// --- O3 operator-snapshot source classes ---
{
code: "doctor-errors",
@@ -224,14 +248,194 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map
nextCommand: "o2b brain init",
autoRepairable: false,
},
+ // --- Terminal states (no-dead-ends, task 5) ---
+ // A verb that succeeded and left the caller with nowhere to go.
+ // These are not defects, so `issueClass` reads as the STATE the
+ // caller is in rather than a fault; the field is otherwise the
+ // same short label every other entry carries, and the registry
+ // stays the single place a structural command is written down.
+ {
+ code: "brain-empty",
+ issueClass: "Brain with nothing recorded in it",
+ nextCommand: "o2b brain feedback --topic <topic> --signal=positive --principle <principle>",
+ autoRepairable: false,
+ },
+ {
+ code: "signal-clusters-absent",
+ issueClass: "no active signal clusters to review",
+ nextCommand: "o2b brain feedback --topic <topic> --signal=positive --principle <principle>",
+ autoRepairable: false,
+ },
+ {
+ code: "intentions-absent",
+ issueClass: "no active intention chains",
+ nextCommand: "o2b brain intention set --scope <scope> --text <text>",
+ autoRepairable: false,
+ },
+ {
+ code: "search-index-built",
+ issueClass: "search index up to date",
+ nextCommand: "o2b search query <text>",
+ autoRepairable: false,
+ },
+ {
+ code: "search-index-missing",
+ issueClass: "search index not built",
+ nextCommand: "o2b search index",
+ autoRepairable: false,
+ },
+ {
+ code: "git-history-absent",
+ issueClass: "no ingested git history",
+ nextCommand: "o2b brain git ingest <repo-path>",
+ autoRepairable: false,
+ },
+ {
+ code: "bridge-proposals-absent",
+ issueClass: "no bridge-proposal artifact yet",
+ nextCommand: "o2b brain bridges discover",
+ autoRepairable: false,
+ },
+ {
+ code: "cli-config-absent",
+ issueClass: "no machine configuration file",
+ nextCommand: "o2b init --vault <path> --name <name>",
+ autoRepairable: false,
+ },
+ {
+ code: "staged-captures-pending",
+ issueClass: "staged captures previewed but not routed",
+ nextCommand: "o2b brain inbox-drain --apply",
+ autoRepairable: false,
+ },
+ // The five states whose exits used to be retyped inside an `ok()`
+ // string beside the rail rather than resolved through it.
+ {
+ code: "dream-bundles-absent",
+ issueClass: "no staged dream bundles",
+ nextCommand: "o2b brain dream stage",
+ autoRepairable: false,
+ },
+ {
+ code: "cluster-notes-absent",
+ issueClass: "no materialized cluster notes",
+ nextCommand: "o2b brain clusters run",
+ autoRepairable: false,
+ },
+ {
+ code: "recall-tuning-absent",
+ issueClass: "no persisted recall tuning",
+ nextCommand: "o2b brain tune run --dataset <path>",
+ autoRepairable: false,
+ },
+ // One finding, two readings, so two codes rather than one code
+ // carrying two commands: which value is authoritative - the
+ // indexed one or the note's - is the operator's call, and the
+ // rail's batch form prints both exits for the one state.
+ {
+ code: "tier-drift-restore",
+ issueClass: "tier drift, indexed value authoritative",
+ nextCommand: "o2b brain tiers restore <path> --apply",
+ autoRepairable: false,
+ },
+ {
+ code: "tier-drift-accept",
+ issueClass: "tier drift, note value authoritative",
+ nextCommand: "o2b brain tiers accept <path>",
+ autoRepairable: false,
+ },
+ // --- Doctor classes the exit census found unregistered ---
+ // The census (`tests/core/brain/doctor-exit-census.test.ts`) forced
+ // every doctor code into one of two buckets. These three turned out
+ // to have a genuine single command; the other twenty-four are
+ // recorded as having none, with the reason, in `doctor-exits.ts`.
+ {
+ code: "brain-root-absent",
+ issueClass: "resolved root carries no Brain layer",
+ nextCommand: "o2b brain init",
+ autoRepairable: false,
+ },
+ {
+ // The exit is the REVIEW, not the repair: what follows it is
+ // `tier-drift-restore` or `tier-drift-accept`, registered above,
+ // and which of the two applies is per drifted note.
+ code: "tier-drift",
+ issueClass: "identity-field hand-edits staged",
+ nextCommand: "o2b brain tiers check",
+ autoRepairable: false,
+ },
+ {
+ code: "entity-label-malformed",
+ issueClass: "entity label fails the quality gate",
+ nextCommand: "o2b brain entity prune",
+ autoRepairable: false,
+ },
+ // --- Skill-accept transaction refusals (no-dead-ends, phase 3) ---
+ // Both are states the accept transaction itself can leave an
+ // operator in, and both used to refuse without naming a way out.
+ // They are registered here rather than spelled inside the two
+ // error messages so the messages resolve one structural command
+ // from the same registry every other surface reads.
+ {
+ code: "skill-accept-journal-unreadable",
+ issueClass: "unreadable skill-accept journal marker",
+ nextCommand: "o2b brain skill-proposals recover --discard-unreadable",
+ autoRepairable: false,
+ },
+ {
+ // The exit is the INSPECTION, not a repair: nothing breaks a
+ // lock automatically, so what the operator needs first is the
+ // full list of locks under the Brain tree with their paths.
+ // Removing the file stays a human judgement - see the
+ // `stale-lock` refusal in `applier-capability.ts`.
+ code: "skill-accept-locked",
+ issueClass: "skill-accept lock held",
+ nextCommand: "o2b brain doctor",
+ autoRepairable: false,
+ },
+ // --- Runtime-notice conditions (no-dead-ends, task 3) ---
+ // The notice channel pushes a transient condition at the agent
+ // (SessionStart injection, `vault_health`, the onboarding
+ // checklist) rather than waiting to be polled, and it spells its
+ // codes in the snake case its wire records use. Registering them
+ // here is what lets a notice carry a structural command instead of
+ // an English "Run: ..." tail a consumer has to regex.
+ //
+ // `search_index_missing` is the same condition the kebab-cased
+ // `search-index-missing` terminal state reports from `o2b search
+ // check`, and deliberately resolves to the same command: two
+ // emitters, two code vocabularies, one exit. Only the codes with a
+ // genuine single exit are listed - `vault_read_only`,
+ // `vault_marker_absent`, `brain_config_unreadable` and
+ // `reindex_in_progress` have none, each for a reason written down
+ // beside the notice that raises it.
+ {
+ code: "search_index_missing",
+ issueClass: "search index not built",
+ nextCommand: "o2b search index",
+ autoRepairable: false,
+ },
+ {
+ code: "semantic_degraded",
+ issueClass: "semantic search fell back to lexical",
+ nextCommand: "o2b search check",
+ autoRepairable: false,
+ },
] satisfies ReadonlyArray<DiagnosticSignal>
).map((s) => [s.code, Object.freeze(s)]),
);
/**
- * Resolve a signal by code. Unknown codes fall back to a generic
- * doctor-run hint so a newly-added lint still renders a next command
- * without a formatter having to invent one.
+ * Resolve a signal by code, LENIENTLY. An unregistered code does not
+ * resolve: this function fabricates a generic `o2b brain doctor` signal
+ * whose `issueClass` is the raw code. That value is invented here, it is
+ * not a registry entry, and it does not mean the code is known.
+ *
+ * Kept for its two existing consumers (the O3 operator snapshot and the
+ * repair planner's unfixable aggregation), whose output shape predates
+ * this release. New consumers MUST use `resolveNextStep` in
+ * `next-step.ts`, which returns an explicit absent result instead of a
+ * guessed command.
*/
export function resolveSignal(code: string): DiagnosticSignal {
const known = DIAGNOSTIC_SIGNALS.get(code);
@@ -277,20 +481,56 @@ export interface RepairPlan {
// ----- Fixers ---------------------------------------------------------------
+/**
+ * A doctor finding did not carry the data its fixer needs to plan from.
+ *
+ * Raised, not skipped (no-dead-ends, task 9). A `dangling-workrun` with
+ * no path, or a `broken-wikilink` with no field or target, means the
+ * detector and this module disagree about the finding contract; dropping
+ * the item would report a complete plan that had silently omitted a
+ * detected defect.
+ */
+export class MalformedDoctorFindingError extends Error {
+ readonly code: string;
+ readonly missingField: string;
+
+ constructor(code: string, missingField: string) {
+ super(
+ `doctor finding ${JSON.stringify(code)} carries no ${JSON.stringify(missingField)}, ` +
+ "so the fixer for it cannot derive a repair target",
+ );
+ this.name = "MalformedDoctorFindingError";
+ this.code = code;
+ this.missingField = missingField;
+ }
+}
+
/**
* A fixer owns one auto-repairable class. `coversDoctorCode` is the
- * doctor issue code the fixer represents, so the planner can exclude that
- * code from the needs-a-different-tool `unfixable` list without parsing
- * doctor messages.
+ * doctor issue code the fixer represents: the planner hands it exactly
+ * the findings carrying that code, and excludes the code from the
+ * needs-a-different-tool `unfixable` list.
+ *
+ * `plan` receives those findings rather than the vault alone. Both
+ * fixers' classes are reported in FULL by the doctor - `dangling-workrun`
+ * comes from the same `scanDanglingWorkruns` the fixer used to call, and
+ * `broken-wikilink` is a superset of the orphaned-reference population
+ * (it also reports targets outside the Brain id space, which this fixer
+ * skips) - so neither retains an independent scan. `vault` is still
+ * passed because a repair target is vault-relative; it is not a licence
+ * to look for work the findings did not name.
*/
interface Fixer {
readonly code: string;
readonly coversDoctorCode: string;
- plan(vault: string): RepairItem[];
+ plan(vault: string, findings: ReadonlyArray<DoctorIssue>): RepairItem[];
/** Apply one applicable item. Returns null on an idempotent no-op. */
apply(vault: string, item: RepairItem): AppliedFix | null;
}
+/** Doctor field name for the evidence list; its raw key is `_evidenced_by`. */
+const DOCTOR_EVIDENCE_FIELD = "evidenced_by";
+
/** Separator between the parts of an `orphaned-reference` target id. */
const TARGET_SEP = "::";
/** Raw frontmatter key for the derived evidence list. */
@@ -309,9 +549,10 @@ function isBrokenBrainRef(raw: string, known: ReadonlySet<string>): string | nul
const walGapFixer: Fixer = {
code: REPAIR_CODE.walGap,
coversDoctorCode: "dangling-workrun",
- plan(vault: string): RepairItem[] {
- return scanDanglingWorkruns(vault).map((path) => {
- const rel = vaultRelative(path, vault);
+ plan(vault: string, findings: ReadonlyArray<DoctorIssue>): RepairItem[] {
+ return findings.map((issue) => {
+ if (issue.path === undefined) throw new MalformedDoctorFindingError(issue.code, "path");
+ const rel = vaultRelative(issue.path, vault);
return {
code: REPAIR_CODE.walGap,
target: rel,
@@ -359,39 +600,23 @@ const walGapFixer: Fixer = {
const orphanedReferenceFixer: Fixer = {
code: REPAIR_CODE.orphanedReference,
coversDoctorCode: "broken-wikilink",
- plan(vault: string): RepairItem[] {
- const known = collectAllBasenames(vault);
+ plan(vault: string, findings: ReadonlyArray<DoctorIssue>): RepairItem[] {
const items: RepairItem[] = [];
- const dirs = brainDirs(vault);
-
- walkBrainRecords(dirs.preferences, "pref-", (path) => {
- const pref = parsePreference(path);
- const rel = vaultRelative(path, vault);
- for (const raw of pref.evidenced_by) {
- const dead = isBrokenBrainRef(raw, known);
- if (dead) items.push(evidencePrune(rel, dead));
- }
- if (pref.supersedes) {
- const dead = isBrokenBrainRef(pref.supersedes, known);
- if (dead) items.push(structuralReview(rel, "supersedes", dead));
- }
- });
-
- walkBrainRecords(dirs.retired, "ret-", (path) => {
- const ret = parseRetired(path);
- const rel = vaultRelative(path, vault);
- for (const raw of ret.evidenced_by) {
- const dead = isBrokenBrainRef(raw, known);
- if (dead) items.push(evidencePrune(rel, dead));
- }
- const retiredBy = isBrokenBrainRef(ret.retired_by, known);
- if (retiredBy) items.push(structuralReview(rel, "retired_by", retiredBy));
- if (ret.superseded_by) {
- const dead = isBrokenBrainRef(ret.superseded_by, known);
- if (dead) items.push(structuralReview(rel, "superseded_by", dead));
- }
- });
-
+ for (const issue of findings) {
+ if (issue.path === undefined) throw new MalformedDoctorFindingError(issue.code, "path");
+ if (issue.field === undefined) throw new MalformedDoctorFindingError(issue.code, "field");
+ if (issue.target === undefined) throw new MalformedDoctorFindingError(issue.code, "target");
+ // The doctor reports every unresolvable basename; only Brain-managed
+ // ids are this fixer's business. An external / non-Brain link is
+ // left exactly where it is, as it always was.
+ if (!BRAIN_ID_RE.test(issue.target)) continue;
+ const rel = vaultRelative(issue.path, vault);
+ items.push(
+ issue.field === DOCTOR_EVIDENCE_FIELD
+ ? evidencePrune(rel, issue.target)
+ : structuralReview(rel, issue.field, issue.target),
+ );
+ }
return items;
},
apply(vault: string, item: RepairItem): AppliedFix | null {
@@ -475,37 +700,65 @@ function removeOriginBullet(body: string, dead: string): string {
return kept.join("\n");
}
-/** Iterate `<prefix>*.md` records under `dir`, skipping unparseable files. */
-function walkBrainRecords(dir: string, prefix: string, cb: (path: string) => void): void {
- if (!existsSync(dir)) return;
- for (const name of readdirSync(dir)) {
- if (!name.endsWith(".md") || !name.startsWith(prefix)) continue;
- try {
- cb(join(dir, name));
- } catch {
- // schema error - surfaced by the doctor, not this fixer's concern
- }
- }
-}
-
const FIXERS: ReadonlyArray<Fixer> = Object.freeze([walGapFixer, orphanedReferenceFixer]);
const FIXER_BY_CODE: ReadonlyMap<string, Fixer> = new Map(FIXERS.map((f) => [f.code, f]));
const COVERED_DOCTOR_CODES: ReadonlySet<string> = new Set(FIXERS.map((f) => f.coversDoctorCode));
+/**
+ * The classes this module's fixers repair, as a read-only set. Exported
+ * so the applier capability table can be checked against the registry
+ * that actually decides (no-dead-ends, task 8) rather than against a
+ * hand-maintained copy of it.
+ */
+export const REPAIR_FIXER_CODES: ReadonlySet<string> = Object.freeze(
+ new Set(FIXERS.map((f) => f.code)),
+);
+
// ----- Planner --------------------------------------------------------------
+export interface PlanRepairOptions {
+ /**
+ * The doctor findings to derive the plan from. Omitted, `planRepair`
+ * runs the doctor itself, which is what every production caller does.
+ *
+ * Supplying them is how a caller that has ALREADY run the doctor avoids
+ * a second full pass, and it is the seam that makes the derivation
+ * observable: hand in findings that do not match the disk and the plan
+ * follows the findings, which is the property a re-scanning planner
+ * cannot have.
+ */
+ readonly issues?: ReadonlyArray<DoctorIssue>;
+}
+
/**
- * Preview what a repair would do. Pure read: runs the doctor to enumerate
- * detected classes, gathers every fixer's findings, and aggregates the
- * classes no fixer addresses (each with its next-command hint).
+ * Preview what a repair would do. Pure read.
+ *
+ * The plan is DERIVED FROM the doctor's findings (no-dead-ends, task 9).
+ * Each fixer is handed exactly the findings carrying the doctor code it
+ * covers and derives its items from those; it does not scan for work of
+ * its own. Before this, every fixer re-scanned the vault independently
+ * while the doctor's findings sat beside them consulted only for counts,
+ * so the applier shared the detector's vocabulary without consuming its
+ * output and nothing forced the two to agree.
+ *
+ * The remaining classes - the ones no fixer covers - are aggregated from
+ * the same findings, each with its next-command hint.
*/
-export function planRepair(vault: string): RepairPlan {
+export function planRepair(vault: string, opts: PlanRepairOptions = {}): RepairPlan {
+ const issues = opts.issues ?? collectDoctorIssues(vault);
+
const fixes: RepairItem[] = [];
- for (const fixer of FIXERS) fixes.push(...fixer.plan(vault));
+ for (const fixer of FIXERS) {
+ fixes.push(
+ ...fixer.plan(
+ vault,
+ issues.filter((i) => i.code === fixer.coversDoctorCode),
+ ),
+ );
+ }
- const doctor = runDoctor(vault);
const counts = new Map<string, number>();
- for (const issue of [...doctor.errors, ...doctor.warnings]) {
+ for (const issue of issues) {
if (COVERED_DOCTOR_CODES.has(issue.code)) continue;
counts.set(issue.code, (counts.get(issue.code) ?? 0) + 1);
}
@@ -524,6 +777,12 @@ export function planRepair(vault: string): RepairPlan {
return Object.freeze({ fixes: Object.freeze(fixes), unfixable: Object.freeze(unfixable) });
}
+/** The doctor's errors and warnings as one stream, in report order. */
+function collectDoctorIssues(vault: string): ReadonlyArray<DoctorIssue> {
+ const doctor = runDoctor(vault);
+ return [...doctor.errors, ...doctor.warnings];
+}
+
// ----- Apply ----------------------------------------------------------------
export interface AppliedFix {
@@ -562,8 +821,11 @@ export interface ApplyRepairOptions {
* changed disk. Idempotent: a second non-dry-run call finds nothing to do.
*/
export function applyRepair(vault: string, opts: ApplyRepairOptions): RepairOutcome {
- // Vault-identity write guard (context-integrity-gates, Unit J).
- // A dry run previews and writes nothing, so it stays ungated.
+ // Vault-identity write guard (context-integrity-gates, Unit J), placed
+ // per the one rule the three appliers now share: at the entry point,
+ // before any other work, and only when the call will write. A dry run
+ // previews and writes nothing, so it stays ungated. See the write-guard
+ // section of `applier-capability.ts`.
if (opts.dryRun !== true) assertVaultIdentityForWrite(vault);
const plan = planRepair(vault);
const needsReview = plan.fixes.filter((f) => !f.applicable);
@@ -583,8 +845,15 @@ export function applyRepair(vault: string, opts: ApplyRepairOptions): RepairOutc
const timestamp = isoSecond(opts.now ?? new Date());
const applied: AppliedFix[] = [];
for (const item of applicable) {
+ // The capability table is the published statement that this code has
+ // a mechanical repair; the registry is the thing that performs it.
+ // Consulting the table first turns a disagreement between the two
+ // into a named error instead of the silent `continue` that used to
+ // stand here - which would have dropped an applicable item on the
+ // floor and still reported success.
+ requireMechanicalRepair(item.code);
const fixer = FIXER_BY_CODE.get(item.code);
- if (!fixer) continue;
+ if (fixer === undefined) throw new UnclassifiedRepairCodeError(item.code);
const result = fixer.apply(vault, item);
if (!result) continue; // idempotent no-op: nothing changed, no event
const res = appendLogEvent(vault, {
diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.ts
new file mode 100644
index 00000000..8461eca7
--- /dev/null
+++ b/src/core/brain/doctor-exits.ts
@@ -0,0 +1,286 @@
+/**
+ * Why a doctor finding has no next command (no-dead-ends, phase 3).
+ *
+ * `o2b brain doctor` resolves each reported code through the diagnostics
+ * registry and prints `next: <command>` when one is registered. About two
+ * thirds of its codes are not, and nothing said why - so an operator
+ * reading a finding with no exit could not tell "no command resolves
+ * this" from "someone forgot to register it". Silence carried both
+ * meanings, which makes it worth nothing.
+ *
+ * This table removes the second meaning. Every code the doctor spells is
+ * either in `DIAGNOSTIC_SIGNALS` with a structural command, or here with
+ * the reason there is none. `tests/core/brain/doctor-exit-census.test.ts`
+ * enumerates the population out of `doctor.ts` and fails on a code in
+ * neither table, or in both.
+ *
+ * ## What earns an entry here rather than a registration
+ *
+ * Two shapes, and only these two:
+ *
+ * - the repair is a JUDGEMENT over content - which of two contradicting
+ * rules survives, which of two files keeps a duplicated id, whether a
+ * pin is still intended. A command that picked one would be making
+ * the operator's decision and recording it as a repair.
+ * - the repair is an EDIT to a file whose target shape is not derivable
+ * from the finding - a malformed timestamp does not say what instant
+ * it meant, a failed regular expression does not say what it was
+ * meant to match. Writing a plausible value would turn an unreadable
+ * record into a confidently wrong one.
+ *
+ * A code with a real single command belongs in the registry instead, and
+ * the census enforces that direction too: a reason here may not name an
+ * `o2b` invocation. If one fits, it is a registration, not an excuse.
+ *
+ * ## Related, and deliberately separate
+ *
+ * `applier-capability.ts` answers a different question - whether a
+ * MECHANICAL repair exists - and the answers do not coincide. A finding
+ * can have no automatic fixer and still have an exact next command
+ * (`contradictory-preferences` has both a refusal there and a command in
+ * the registry), so folding the two tables together would force one
+ * verdict onto two independent axes.
+ */
+
+import { resolveNextStep } from "./next-step.ts";
+
+/** One doctor code with no single command, and the reason it has none. */
+export interface DoctorExitExclusion {
+ readonly code: string;
+ /** Why no one command resolves the finding. Never empty. */
+ readonly reason: string;
+}
+
+const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [
+ // --- Judgements over content -------------------------------------------
+ {
+ code: "active-budget-pressure",
+ reason:
+ "active.md is rendered from the preference set, so it shrinks by retiring, merging or " +
+ "unpinning rules rather than by editing the file; which rule to drop is a statement about " +
+ "what the operator still believes, and the finding already ranks the candidates",
+ },
+ {
+ code: "batch-concept-inflation",
+ reason:
+ "the finding is that a batch was confirmed together without a dedup pass, not that any " +
+ "particular pair duplicates. Whether two principles say the same thing is a reading of " +
+ "their content, and merging the wrong pair destroys a rule nobody decided to drop",
+ },
+ {
+ code: "broken-entity-relation",
+ reason:
+ "the edge names an entity id the registry does not hold. Repairing it means either " +
+ "creating that entity or correcting the edge, and which was intended is only in the " +
+ "author's head - the two produce different graphs",
+ },
+ {
+ code: "concept-gap",
+ reason:
+ "the repair is to write a preference that does not exist yet, which is authoring content " +
+ "rather than repairing a record; the same reason applier-capability.ts refuses it a fixer",
+ },
+ {
+ code: "duplicate-entity",
+ reason:
+ "two entity files claim one identity, and lookups already resolve to the first claimant. " +
+ "Merging them or archiving one decides which history survives, which needs both files " +
+ "read rather than a rule applied",
+ },
+ {
+ code: "duplicate-id",
+ reason:
+ "two records carry the same id and either could be the one that keeps it. Renaming a file " +
+ "breaks every wikilink that resolved to it, so the choice is a judgement about which " +
+ "record the rest of the vault means",
+ },
+ {
+ code: "entity-alias-candidate",
+ reason:
+ "a nomination, never a drop: the finding is that two names MIGHT denote one entity. " +
+ "Confirming it means adding an alias to the surviving entity, which is a claim about the " +
+ "world the lexical detector is not entitled to make",
+ },
+ {
+ code: "id-filename-mismatch",
+ reason:
+ "the id and the basename disagree and neither is authoritative. Renaming the file breaks " +
+ "inbound wikilinks, rewriting the id breaks outbound ones, and the finding cannot tell " +
+ "which of the two was the typo",
+ },
+ {
+ code: "pinned-without-recent-evidence",
+ reason:
+ "the pin is doing exactly what a pin does - holding a rule back from automatic retire. " +
+ "Whether that is still intended is the operator's call, and asking the question is the " +
+ "entire content of the warning",
+ },
+ {
+ code: "removed-tool-reference",
+ reason:
+ "the reference sits in prose an operator or another tool wrote, and the replacement " +
+ "mapping is already printed in the finding. Rewriting someone else's note is an edit to " +
+ "their content, not a repair of a record this store owns",
+ },
+ {
+ code: "stale-lock",
+ reason:
+ "the lock primitive is a single-attempt exclusive create, so no timeout distinguishes a " +
+ "crashed writer from a slow live one and nothing may remove the file automatically. The " +
+ "exit is the operator's judgement followed by a manual deletion",
+ },
+ {
+ code: "status-folder-mismatch",
+ reason:
+ "the status field and the containing folder disagree, and either could be the true one. " +
+ "Moving the file and rewriting the field are different repairs with different lifecycle " +
+ "consequences, and the record does not say which happened",
+ },
+ {
+ code: "symlink-escape",
+ reason:
+ "a link leaving the vault is removed or repointed depending on what it was for, and " +
+ "following it to find out is exactly what this check refuses to do - a reader that " +
+ "follows it has already left the store",
+ },
+ {
+ code: "vault-ignore-missing-path",
+ reason:
+ "the ignore rule names a path that is not in this vault. It is usually a typo, but it can " +
+ "also be a path not created yet, and silently deleting a rule the operator wrote is worse " +
+ "than reporting that it currently matches nothing",
+ },
+
+ // --- Edits whose target shape the finding cannot supply ------------------
+ {
+ code: "config-warning",
+ reason:
+ "the resolver reports a key in Brain/_brain.yaml it could not honour. The repair is an " +
+ "edit to that file and the value to write is a policy choice; the resolver fell back to " +
+ "a default rather than guessing, and so does this",
+ },
+ {
+ code: "invalid-capture-pattern",
+ reason:
+ "a regular expression in the capture configuration failed to compile. What it was meant " +
+ "to match is not recoverable from a pattern that does not parse, so the repair is an edit " +
+ "by whoever wrote it",
+ },
+ {
+ code: "iso-invalid",
+ reason:
+ "a timestamp field is not ISO-8601. The instant it meant is not recoverable from the " +
+ "malformed text, and writing today's date would make a record that lost its time look " +
+ "like one that was written now",
+ },
+ {
+ code: "log-malformed",
+ reason:
+ "a log line the parser has no branch for. The log is append-only history, so rewriting a " +
+ "line to fit the grammar changes what was recorded - the finding names the file and the " +
+ "line number precisely so a human can read the original",
+ },
+ {
+ code: "malformed-evidence-range",
+ reason:
+ "the line range on a logged artifact reference does not parse. The range the author meant " +
+ "is not derivable from the malformed text, and the event itself stays valid, so nothing " +
+ "is lost by leaving it reported",
+ },
+ {
+ code: "preference-missing-field",
+ reason:
+ "a required frontmatter field is absent and its value is not recoverable from the rest of " +
+ "the record. Writing a placeholder would make an unreadable preference read as a true " +
+ "one, which is worse than a record the doctor keeps naming",
+ },
+ {
+ code: "preference-invalid",
+ reason:
+ "the preference could not be parsed, for a reason the parser reports verbatim in the " +
+ "finding. The repair is an edit whose target shape depends on which part of the grammar " +
+ "broke, so there is no one command that covers the class",
+ },
+ {
+ code: "retired-missing-field",
+ reason:
+ "a required frontmatter field is absent from a retired record and its value is not " +
+ "recoverable from the rest of the file. A placeholder would fabricate lifecycle " +
+ "provenance, which is the one thing a retired record exists to hold",
+ },
+ {
+ code: "retired-invalid",
+ reason:
+ "the retired record could not be parsed, for a reason the parser reports verbatim in the " +
+ "finding. As with its preference twin, the repair is an edit whose shape depends on which " +
+ "part of the grammar broke",
+ },
+ {
+ code: "signal-invalid",
+ reason:
+ "the signal file could not be parsed. A signal is a captured observation, so what it was " +
+ "meant to say exists only in the source it was captured from - reconstructing it here " +
+ "would be inventing the observation",
+ },
+];
+
+/** Two entries claimed one code - the table would silently lose one. */
+export class DuplicateDoctorExitExclusionError extends Error {
+ constructor(code: string) {
+ super(`DOCTOR_EXIT_EXCLUSIONS declares doctor code ${JSON.stringify(code)} more than once`);
+ this.name = "DuplicateDoctorExitExclusionError";
+ }
+}
+
+/**
+ * The published table, code to reason. Built eagerly so a duplicate fails
+ * at import rather than silently losing an entry.
+ */
+export const DOCTOR_EXIT_EXCLUSIONS: ReadonlyMap<string, string> = (() => {
+ const table = new Map<string, string>();
+ for (const entry of EXCLUSIONS) {
+ if (table.has(entry.code)) throw new DuplicateDoctorExitExclusionError(entry.code);
+ table.set(entry.code, entry.reason);
+ }
+ return table;
+})();
+
+/**
+ * The published reason `code` has no next command, or `null` when the
+ * table publishes none. `null` is also what a code WITH a registered
+ * command yields: the two questions are asked in that order by every
+ * caller, and a code cannot honestly answer both.
+ */
+export function doctorExitReason(code: string): string | null {
+ if (resolveNextStep(code) !== null) return null;
+ return DOCTOR_EXIT_EXCLUSIONS.get(code) ?? null;
+}
+
+/**
+ * The additive JSON key a machine-readable surface carries the reasons
+ * in. Named once here for the same reason `NEXT_COMMAND_KEY` is: the CLI
+ * `--json` renderer and its MCP twin must not drift on the spelling.
+ */
+export const NO_EXIT_KEY = "no_exit";
+
+/**
+ * The published reasons for `codes`, deduplicated, in the order the codes
+ * were reported.
+ *
+ * Deduplicated by code rather than by reason, because unlike a next
+ * command - which two codes can share - a reason is about one class. A
+ * registered code contributes nothing, and neither does one the table
+ * does not know: an empty result is what a report whose every code has an
+ * exit produces, which is what keeps both surfaces byte-identical on the
+ * vaults that had no gap to explain.
+ */
+export function noExitReasons(codes: Iterable<string>): ReadonlyMap<string, string> {
+ const out = new Map<string, string>();
+ for (const code of codes) {
+ if (out.has(code)) continue;
+ const reason = doctorExitReason(code);
+ if (reason === null) continue;
+ out.set(code, reason);
+ }
+ return out;
+}
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index f306bac2..c91047c9 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -1087,6 +1087,44 @@ function forEachBrainFile(
}
}
+/** Record kinds whose parse failures this module classifies. */
+type ParsedRecordKind = "preference" | "retired";
+
+const PREFERENCE_MISSING_FIELD_CODE = "preference-missing-field";
+const PREFERENCE_INVALID_CODE = "preference-invalid";
+const RETIRED_MISSING_FIELD_CODE = "retired-missing-field";
+const RETIRED_INVALID_CODE = "retired-invalid";
+const ISO_INVALID_CODE = "iso-invalid";
+
+/**
+ * The parse-failure codes, per record kind, written out.
+ *
+ * These four used to be built by concatenating the kind onto a suffix,
+ * which meant they appeared nowhere in this module as readable strings -
+ * so the doctor's own code population could not be enumerated from its
+ * source, and the exit census (`tests/core/brain/doctor-exit-census.test.ts`)
+ * could not see them to demand a classification.
+ */
+const PARSE_ERROR_CODES: Readonly<
+ Record<ParsedRecordKind, { readonly missingField: string; readonly invalid: string }>
+> = Object.freeze({
+ preference: Object.freeze({
+ missingField: PREFERENCE_MISSING_FIELD_CODE,
+ invalid: PREFERENCE_INVALID_CODE,
+ }),
+ retired: Object.freeze({
+ missingField: RETIRED_MISSING_FIELD_CODE,
+ invalid: RETIRED_INVALID_CODE,
+ }),
+});
+
+/** Which of the three parse-failure codes `msg` from `kind` reports. */
+function parseErrorCode(kind: ParsedRecordKind, msg: string): string {
+ if (/missing field/.test(msg)) return PARSE_ERROR_CODES[kind].missingField;
+ if (/ISO-8601/i.test(msg)) return ISO_INVALID_CODE;
+ return PARSE_ERROR_CODES[kind].invalid;
+}
+
/**
* Classify a parse-time error into a `DoctorIssue` and push it. Shared by
* `checkPreferences` and `checkRetired`, which previously carried
@@ -1097,7 +1135,7 @@ function forEachBrainFile(
function classifyParseError(
err: unknown,
path: string,
- kindPrefix: string,
+ kindPrefix: ParsedRecordKind,
issues: DoctorIssue[],
): void {
if (err instanceof BrainStatusFolderMismatchError) {
@@ -1110,15 +1148,9 @@ function classifyParseError(
return;
}
const msg = (err as Error).message ?? String(err);
- const isMissingField = /missing field/.test(msg);
- const isInvalidIso = /ISO-8601/i.test(msg);
issues.push({
severity: "error",
- code: isMissingField
- ? `${kindPrefix}-missing-field`
- : isInvalidIso
- ? "iso-invalid"
- : `${kindPrefix}-invalid`,
+ code: parseErrorCode(kindPrefix, msg),
path,
message: msg,
});
@@ -1133,7 +1165,7 @@ function checkIso(path: string, field: string, value: string, issues: DoctorIssu
if (!ISO_RE.test(value)) {
issues.push({
severity: "error",
- code: "iso-invalid",
+ code: ISO_INVALID_CODE,
path,
message: `field '${field}' is not a valid ISO-8601 timestamp: ${JSON.stringify(value)}`,
});
@@ -1174,6 +1206,12 @@ function checkWikilinks(
severity: "warning",
code: "broken-wikilink",
path,
+ // no-dead-ends, task 12: the field and the target ride as
+ // fields as well as inside the sentence, so a consumer acts on
+ // values rather than on a regex over prose. The message is
+ // unchanged - the human surface still reads it.
+ field,
+ target,
message: `field '${field}' references missing basename '${target}'`,
});
}
@@ -1210,6 +1248,13 @@ function checkBrokenBacklinks(
issues.push({
severity: "warning",
code: "broken-backlinks",
+ // no-dead-ends, task 12. This issue has no `path` - the whole
+ // finding is that no file with this basename exists - so before
+ // these fields the referencing sources were reachable only by
+ // splitting the tail of the sentence on ", ". The message keeps
+ // them too; the human surface is unchanged.
+ target,
+ sources,
message:
`[[${target}]] is referenced by ${sources.length} source(s) but no file with that ` +
`basename exists under Brain/: ${sources.join(", ")}`,
diff --git a/src/core/brain/dream-gates.ts b/src/core/brain/dream-gates.ts
new file mode 100644
index 00000000..696d5aaf
--- /dev/null
+++ b/src/core/brain/dream-gates.ts
@@ -0,0 +1,155 @@
+/**
+ * The operator-facing vocabulary for {@link DreamGateOverrides}
+ * (no-dead-ends, Unit E - operator surface).
+ *
+ * `DreamOptions.gates` shipped as a TypeScript field with no way to reach
+ * it from a shell or from MCP, which is not the capability the unit asked
+ * for: the point of a per-run override is that an operator can steer one
+ * pass WITHOUT editing `Brain/_brain.yaml` and remembering to revert it.
+ * This module is the one place that maps what an operator types onto that
+ * field, so the CLI flag and the MCP argument cannot drift apart.
+ *
+ * ## Why the gate names are spelled in snake case
+ *
+ * A gate name is not a CLI flag - it is the VALUE of one (`--gate
+ * heal_enrich=true`), and it names a key an operator would otherwise edit
+ * in `_brain.yaml` (`dream.heal_enrich_enabled`). Spelling it the way the
+ * configuration spells it means there is exactly one gate vocabulary
+ * across the flag, the MCP argument, the override field and the config
+ * key, and no translation table anyone can get wrong. The kebab-cased
+ * `heal-enrich` token belongs to {@link DREAM_STEP}, which is a different
+ * vocabulary (units of work, not switches).
+ *
+ * ## Why every malformed entry throws
+ *
+ * An override that cannot be understood must never resolve to "leave the
+ * configured value alone": that is a silent no-op wearing the costume of
+ * an applied setting, and the operator would read the run's behaviour as
+ * evidence that the gate did nothing. Every rejection names the entry,
+ * the reason, and the accepted vocabulary.
+ */
+
+import type { DreamGateOverrides } from "./dream.ts";
+
+/**
+ * Gate names an operator may override, keyed by the field they set on
+ * {@link DreamGateOverrides}. Deliberately closed: a general config
+ * overlay would let any resolved key be replaced for one run, which is
+ * far more surface than the single boolean switch that motivated this.
+ */
+export const DREAM_GATE = Object.freeze({
+ healEnrich: "heal_enrich",
+} as const);
+
+export type DreamGateName = (typeof DREAM_GATE)[keyof typeof DREAM_GATE];
+
+/** Canonical order every refusal lists the known gates in. */
+export const DREAM_GATE_NAMES: ReadonlyArray<DreamGateName> = Object.freeze([
+ DREAM_GATE.healEnrich,
+]);
+
+/**
+ * Accepted boolean tokens, in the spelling `_brain.yaml` itself uses.
+ * No looser vocabulary (`on`, `yes`, `1`) is accepted: two ways to write
+ * one value is two things to keep in step for no gain.
+ */
+const GATE_TOKENS: Readonly<Record<string, boolean>> = Object.freeze({
+ true: true,
+ false: false,
+});
+
+/** The separator in a `<name>=<value>` command-line entry. */
+const ENTRY_SEPARATOR = "=";
+
+/**
+ * Raised when a gate override cannot be honoured exactly as written.
+ * Carries the offending entry and the known gate names so a caller
+ * reading only the error knows what it may ask for instead.
+ */
+export class DreamGateOverrideError extends Error {
+ /** The entry the caller supplied, verbatim. */
+ readonly entry: string;
+ /** The gate names this build understands. */
+ readonly known: ReadonlyArray<DreamGateName>;
+
+ constructor(entry: string, reason: string) {
+ super(
+ `dream gate override '${entry}' cannot be applied: ${reason}. ` +
+ `Known gates: ${DREAM_GATE_NAMES.join(", ")}.`,
+ );
+ this.name = "DreamGateOverrideError";
+ this.entry = entry;
+ this.known = DREAM_GATE_NAMES;
+ }
+}
+
+const isKnownGate = (name: string): name is DreamGateName =>
+ (DREAM_GATE_NAMES as ReadonlyArray<string>).includes(name);
+
+/**
+ * Validate an already-typed `{ gate: boolean }` record - the shape a JSON
+ * caller (MCP) sends - into {@link DreamGateOverrides}.
+ *
+ * An empty record yields an empty override set, which is meaningful: the
+ * caller asked for no override and every gate resolves from the vault
+ * configuration, exactly as it does today.
+ */
+export function validateDreamGateOverrides(
+ record: Readonly<Record<string, unknown>>,
+): DreamGateOverrides {
+ const overrides: { -readonly [K in keyof DreamGateOverrides]: DreamGateOverrides[K] } = {};
+ for (const [name, value] of Object.entries(record)) {
+ if (!isKnownGate(name)) {
+ throw new DreamGateOverrideError(name, "it is not a gate this dream pass resolves");
+ }
+ if (typeof value !== "boolean") {
+ throw new DreamGateOverrideError(
+ name,
+ `its value must be a boolean, not ${typeof value === "object" ? "an object" : `a ${typeof value}`}`,
+ );
+ }
+ overrides[name] = value;
+ }
+ return Object.freeze(overrides);
+}
+
+/**
+ * Parse repeated `<name>=<value>` command-line entries into
+ * {@link DreamGateOverrides}.
+ *
+ * Two entries naming the same gate are a contradiction, not a
+ * last-one-wins: an operator who typed both did not mean either, and
+ * silently picking one would apply a setting they never asked for.
+ */
+export function parseDreamGateOverrides(entries: ReadonlyArray<string>): DreamGateOverrides {
+ const record: Record<string, boolean> = {};
+ for (const entry of entries) {
+ const separator = entry.indexOf(ENTRY_SEPARATOR);
+ if (separator === -1) {
+ throw new DreamGateOverrideError(
+ entry,
+ `it carries no '${ENTRY_SEPARATOR}' - the form is <name>${ENTRY_SEPARATOR}<${Object.keys(GATE_TOKENS).join("|")}>`,
+ );
+ }
+ const name = entry.slice(0, separator);
+ const token = entry.slice(separator + 1);
+ if (!isKnownGate(name)) {
+ throw new DreamGateOverrideError(entry, `'${name}' is not a gate this dream pass resolves`);
+ }
+ if (!Object.hasOwn(GATE_TOKENS, token)) {
+ throw new DreamGateOverrideError(
+ entry,
+ `'${token}' is not a boolean - accepted values are ${Object.keys(GATE_TOKENS).join(" and ")}`,
+ );
+ }
+ const value = GATE_TOKENS[token]!;
+ if (Object.hasOwn(record, name) && record[name] !== value) {
+ throw new DreamGateOverrideError(
+ entry,
+ `'${name}' was already overridden to ${String(record[name])} in this invocation`,
+ );
+ }
+ record[name] = value;
+ }
+ return validateDreamGateOverrides(record);
+}
diff --git a/src/core/brain/dream-phases.ts b/src/core/brain/dream-phases.ts
index b4ce2719..ee1a42c5 100644
--- a/src/core/brain/dream-phases.ts
+++ b/src/core/brain/dream-phases.ts
@@ -25,7 +25,11 @@ export const DREAM_PHASE = {
} as const;
export type DreamPhase = (typeof DREAM_PHASE)[keyof typeof DREAM_PHASE];
-/** Canonical phase order. Readers MUST tolerate unknown future phases. */
+/**
+ * Canonical REPORTING order of `DreamRunSummary.phases`. Readers MUST
+ * tolerate unknown future phases. The workrun journal emits its markers in
+ * execution order instead, which differs: see `WORKRUN_PHASE`.
+ */
export const DREAM_PHASE_ORDER: ReadonlyArray<DreamPhase> = Object.freeze([
DREAM_PHASE.close,
DREAM_PHASE.reconcile,
diff --git a/src/core/brain/dream-step.ts b/src/core/brain/dream-step.ts
new file mode 100644
index 00000000..8928adb0
--- /dev/null
+++ b/src/core/brain/dream-step.ts
@@ -0,0 +1,189 @@
+/**
+ * Single-step dream requests (no-dead-ends, Unit E).
+ *
+ * An operator sometimes wants one piece of the dream pass rather than the
+ * whole thing. Most of the pass cannot serve that request, and the honest
+ * answer is a named refusal rather than a partial run:
+ *
+ * - The five `DREAM_PHASE` labels are a REPORTING layer. Their metrics
+ * are assembled after all work completes, from counters produced by
+ * different functions; there is no function named `close`,
+ * `reconcile`, `synthesize`, `heal` or `log` to call.
+ * - `planRefresh` and `planAutoRetires` are two-way mutably coupled:
+ * `planRefresh` pushes into `plan.retires`, and `planAutoRetires`
+ * deletes those slugs out of `refresh.updated`, precisely so that a
+ * preference is never both refreshed and retired in one pass. Running
+ * either alone with writes enabled is a data-correctness bug, not a
+ * missing feature.
+ *
+ * Exactly two units of work are provably independent, and this module
+ * offers those two and refuses everything else by name:
+ *
+ * - `scan` - {@link scanBrain}, a pure read of the `Brain/` tree. It
+ * opens no writer, takes no clock and mutates nothing.
+ * - `heal-enrich` - {@link runHealEnrichment}, the opt-in deterministic
+ * vault enrichment. It reads and rewrites user pages outside the Brain
+ * root and shares no accumulator with the planning steps. Asking for
+ * it IS the opt-in, so it runs regardless of
+ * `dream.heal_enrich_enabled`; that config key gates the automatic
+ * pass, and `DreamOptions.gates` overrides it for one full run.
+ *
+ * ## What a partial run returns
+ *
+ * NOT a `DreamRunSummary`. Almost every field of that record is
+ * produced by steps a single-step request does not run, so returning one
+ * would assert `retired: []` and `changed: false` about work that never
+ * happened - a misleading fallback of exactly the kind this release
+ * removes. Each step returns its own shape instead, discriminated by
+ * `step` and marked `partial: true`, carrying only what that step actually
+ * observed or did.
+ */
+
+import { scanBrain } from "./dream.ts";
+import { DREAM_PHASE, type DreamPhase } from "./dream-phases.ts";
+import { runHealEnrichment } from "./heal-run.ts";
+import { vaultRelative } from "./paths.ts";
+
+/** The units of dream work that are provably runnable on their own. */
+export const DREAM_STEP = Object.freeze({
+ scan: "scan",
+ healEnrich: "heal-enrich",
+} as const);
+
+export type DreamStep = (typeof DREAM_STEP)[keyof typeof DREAM_STEP];
+
+/** Canonical order the refusal message lists the runnable steps in. */
+export const DREAM_STEP_RUNNABLE: ReadonlyArray<DreamStep> = Object.freeze([
+ DREAM_STEP.scan,
+ DREAM_STEP.healEnrich,
+]);
+
+/**
+ * Why each reporting label cannot be honoured on its own. One entry per
+ * `DREAM_PHASE` member: a caller asking for a phase gets the reason for
+ * THAT phase, never a generic "unsupported" line.
+ */
+const PHASE_REFUSAL: Readonly<Record<DreamPhase, string>> = Object.freeze({
+ [DREAM_PHASE.close]:
+ `it labels both the read scan and the pre-run snapshot that the mutating pass rolls back to, ` +
+ `and a snapshot outside a run has nothing to protect; its read half is the '${DREAM_STEP.scan}' step`,
+ [DREAM_PHASE.reconcile]:
+ `it classifies contradictions over the plan that planTopics builds in the same pass, and records ` +
+ `the outcome as run-log events; it owns no state of its own to run against`,
+ [DREAM_PHASE.synthesize]:
+ `planRefresh and planAutoRetires mutate each other's accumulators - planRefresh pushes into ` +
+ `plan.retires and planAutoRetires deletes those slugs out of refresh.updated - so that a ` +
+ `preference is never both refreshed and retired; running the refresh half alone with writes ` +
+ `enabled would write a preference that the same pass had decided to retire`,
+ [DREAM_PHASE.heal]:
+ `its retire half is the other side of the planRefresh/planAutoRetires accumulator coupling ` +
+ `(planAutoRetires deletes from refresh.updated the slugs planRefresh queued into plan.retires), ` +
+ `so retiring alone would drop a refresh the same pass computed; its enrichment half is ` +
+ `available on its own as the '${DREAM_STEP.healEnrich}' step`,
+ [DREAM_PHASE.log]:
+ `it writes the run summary and audit events describing work that a single-step request did not ` +
+ `perform, so running it alone would record a pass that never happened`,
+});
+
+/** Reason given for a token that is not even a reporting label. */
+const UNKNOWN_STEP_REFUSAL =
+ "it is neither a runnable dream step nor one of the dream reporting phases";
+
+/**
+ * Raised when a caller asks for a step the dream pass cannot perform in
+ * isolation. Carries the requested token, the steps that ARE runnable, and
+ * the specific reason - so an agent reading only the error knows both why
+ * it was refused and what it may ask for instead.
+ */
+export class DreamStepNotRunnableError extends Error {
+ /** The token the caller asked for, verbatim. */
+ readonly requested: string;
+ /** The steps {@link runDreamStep} does honour. */
+ readonly runnable: ReadonlyArray<DreamStep>;
+ /** Why {@link requested} specifically cannot be run alone. */
+ readonly reason: string;
+
+ constructor(requested: string, reason: string) {
+ super(
+ `dream step '${requested}' is not independently runnable: ${reason}. ` +
+ `Independently runnable steps: ${DREAM_STEP_RUNNABLE.join(", ")}. ` +
+ `Everything else runs only as part of a full dream() pass.`,
+ );
+ this.name = "DreamStepNotRunnableError";
+ this.requested = requested;
+ this.runnable = DREAM_STEP_RUNNABLE;
+ this.reason = reason;
+ }
+}
+
+/** Result of the `scan` step: what the read saw, and nothing more. */
+export interface DreamScanStepResult {
+ readonly step: typeof DREAM_STEP.scan;
+ /** Always true: this is one step of the pass, not a run summary. */
+ readonly partial: true;
+ /** Signals still in `inbox/`. */
+ readonly active_signals: number;
+ /** Signals already in `inbox/processed/`. */
+ readonly processed_signals: number;
+ readonly preferences: number;
+ readonly retired: number;
+ /** Vault-relative paths whose frontmatter would not parse. */
+ readonly corrupted: ReadonlyArray<string>;
+}
+
+/** Result of the `heal-enrich` step: what the enrichment rewrote. */
+export interface DreamHealEnrichStepResult {
+ readonly step: typeof DREAM_STEP.healEnrich;
+ /** Always true: this is one step of the pass, not a run summary. */
+ readonly partial: true;
+ /** User pages considered (the Brain root is never touched). */
+ readonly scanned: number;
+ readonly enriched: number;
+ /** Paths actually rewritten, sorted. */
+ readonly pages: ReadonlyArray<string>;
+}
+
+export type DreamStepResult = DreamScanStepResult | DreamHealEnrichStepResult;
+
+/**
+ * Run exactly one dream step, or refuse by name.
+ *
+ * Never runs more than was asked and never runs less: a request this
+ * function cannot honour in full throws {@link DreamStepNotRunnableError}
+ * and writes nothing.
+ */
+export function runDreamStep(vault: string, step: string): DreamStepResult {
+ switch (step) {
+ case DREAM_STEP.scan: {
+ const scan = scanBrain(vault);
+ return Object.freeze({
+ step: DREAM_STEP.scan,
+ partial: true,
+ active_signals: scan.signals.filter((s) => s.active).length,
+ processed_signals: scan.signals.filter((s) => !s.active).length,
+ preferences: scan.preferences.length,
+ retired: scan.retired.length,
+ corrupted: Object.freeze(scan.corrupted.map((c) => vaultRelative(c.path, vault))),
+ } satisfies DreamScanStepResult);
+ }
+ case DREAM_STEP.healEnrich: {
+ const result = runHealEnrichment(vault);
+ return Object.freeze({
+ step: DREAM_STEP.healEnrich,
+ partial: true,
+ scanned: result.scanned,
+ enriched: result.enriched,
+ pages: Object.freeze([...result.pages]),
+ } satisfies DreamHealEnrichStepResult);
+ }
+ default:
+ throw new DreamStepNotRunnableError(step, refusalReason(step));
+ }
+}
+
+/** The specific reason for a refused token. */
+function refusalReason(step: string): string {
+ return Object.hasOwn(PHASE_REFUSAL, step)
+ ? PHASE_REFUSAL[step as DreamPhase]
+ : UNKNOWN_STEP_REFUSAL;
+}
diff --git a/src/core/brain/dream-workrun.ts b/src/core/brain/dream-workrun.ts
index adcf24b2..f9d43ee1 100644
--- a/src/core/brain/dream-workrun.ts
+++ b/src/core/brain/dream-workrun.ts
@@ -36,9 +36,16 @@ import { dreamRunsDir, dreamWorkrunPath } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/**
- * Canonical phase identifiers. Five forward-progress phases plus the
- * sticky `interrupted` terminal. The dream pass emits them in the
- * order declared; readers MUST tolerate unknown future phases.
+ * Canonical phase identifiers. Nine forward-progress phases plus the
+ * sticky `interrupted` terminal. Readers MUST tolerate unknown future
+ * phases.
+ *
+ * Emission order is EXECUTION order, not the order declared here and not
+ * `DREAM_PHASE_ORDER` (which is the reporting order of the summary). A
+ * marker is written at the point where that phase's durable output has
+ * landed, so `reconcile_complete` trails `heal_complete`: reconcile's only
+ * artifacts are audit events written in the log phase. See the emission
+ * notes in `dream.ts`.
*/
export const WORKRUN_PHASE = Object.freeze({
started: "started",
@@ -48,8 +55,8 @@ export const WORKRUN_PHASE = Object.freeze({
finalized: "finalized",
interrupted: "interrupted",
// Brain lifecycle suite (Feature 2): multi-phase dream checkpoints.
- // Emitted in order between `started` and `finalized`. Readers tolerate
- // unknown phases, so adding these is backward-compatible.
+ // Emitted between `started` and `finalized`, each where its phase's
+ // writes land. Readers tolerate unknown phases.
closeComplete: "close_complete",
reconcileComplete: "reconcile_complete",
synthesizeComplete: "synthesize_complete",
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 683eb7ea..0948eb8c 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -255,6 +255,32 @@ export interface DreamRunSummary {
readonly dry_run?: boolean;
}
+/**
+ * Per-run overrides for the dream gates that otherwise live in
+ * `Brain/_brain.yaml` (no-dead-ends, Unit E). An override applies to the
+ * one run it is passed to and is NEVER written back, so a targeted pass
+ * needs no config edit and no remembering to revert: the stored
+ * configuration is byte-identical after a run that overrode it.
+ *
+ * Deliberately a named field per gate rather than a general config
+ * overlay. An audit of the `dream:` and `retire:` blocks found exactly one
+ * boolean gate an operator flips to steer a pass
+ * (`dream.heal_enrich_enabled`); `retire.confirmed_evidence_min_threshold`
+ * is a numeric evidence floor, not a phase switch, and is deliberately
+ * absent. A general overlay would let any resolved key be replaced for one
+ * run - far more surface than the one switch that motivated this - and the
+ * design doc records the narrow form as the default choice.
+ */
+export interface DreamGateOverrides {
+ /**
+ * Overrides `dream.heal_enrich_enabled` for this run only. `true` runs
+ * the opt-in heal enrichment on a vault whose config leaves it off;
+ * `false` skips it on a vault whose config turns it on. Omitted: the
+ * configured value decides, exactly as before.
+ */
+ readonly heal_enrich?: boolean;
+}
+
export interface DreamOptions {
/** Wall clock for the run. Defaults to `new Date()`. */
readonly now?: Date;
@@ -270,13 +296,22 @@ export interface DreamOptions {
*/
readonly agentName?: string;
/**
- * Cooperative deadline (t_06784b8d): checkpointed at entry and at
- * the phase seams (pre-mutation, post-promote, pre-finalize). A
- * tripped guard on the mutation path leaves the durable workrun
+ * Cooperative deadline (t_06784b8d). Checkpointed at exactly five
+ * points, in order: entry, before the pre-run snapshot, before the
+ * first mutation, after the mutation writes, and immediately before
+ * the workrun is finalised. The last one (no-dead-ends, Unit E) covers
+ * the tail that used to run unguarded - the log events, the rollup
+ * ledger write, snapshot pruning and the active/lessons regeneration.
+ * A tripped guard on the mutation path leaves the durable workrun
* dangling, which is exactly the integrity contract - the next
* pass spots and reports it.
*/
readonly safeguard?: import("./safeguard.ts").Safeguard;
+ /**
+ * Per-run gate overrides (no-dead-ends, Unit E). Additive: omitted, the
+ * run reads every gate from `Brain/_brain.yaml` exactly as before.
+ */
+ readonly gates?: DreamGateOverrides;
}
// ----- Internal scan types ------------------------------------------------
@@ -288,6 +323,11 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
const dryRun = opts.dryRun === true;
opts.safeguard?.checkpoint();
const cfg = loadBrainConfig(vault);
+ // Per-run gate resolution (no-dead-ends, Unit E): the override wins for
+ // this run, the configured value decides when it is absent. Resolved
+ // once, here, so the heal branch below has a single source of truth and
+ // nothing writes the decision back to `_brain.yaml`.
+ const healEnrichEnabled = opts.gates?.heal_enrich ?? cfg.dream.heal_enrich_enabled === true;
let runId = formatRunId(now);
const wikilinkToRun = `[[Brain/log/${isoDate(now)}]]`;
@@ -447,7 +487,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// skip-corrupted-frontmatter, dream summary).
const moved: string[] = [];
// F6: count of user pages the opt-in heal phase enriched (0 unless
- // dream.heal_enrich_enabled).
+ // the heal gate resolved on - see `healEnrichEnabled`).
let healEnriched = 0;
// v0.12.0 Brain Integrity Suite: declined retires accumulate here.
// Always declared (even when no gate is configured) so the eventual
@@ -462,13 +502,16 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
opts.safeguard?.checkpoint();
if (!dryRun) {
workrun = openWorkrun(vault, runId);
+ // Truthful checkpoints (no-dead-ends, Unit E). A marker means every
+ // durable effect attributed to that phase is already on disk, so a
+ // crash leaves a journal whose last marker names work that genuinely
+ // finished. Cluster and close are the only two phases whose work
+ // provably ends here: clustering is pure planning that produces no
+ // file at all, and close's single artifact - the pre-run snapshot -
+ // was written just above. Every other marker moved down to the point
+ // where that phase's writes land; see the emission notes there.
workrun.checkpoint(WORKRUN_PHASE.clusterComplete);
- // Multi-phase dream (F2): close + reconcile are complete by the time
- // we reach the mutation path - the scan and contradiction planning
- // both ran before the `changed` gate. Emit their checkpoints here in
- // order; synthesize + heal follow the write loops below.
workrun.checkpoint(WORKRUN_PHASE.closeComplete);
- workrun.checkpoint(WORKRUN_PHASE.reconcileComplete);
}
if (!dryRun) {
@@ -583,6 +626,14 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
}
}
+ // Synthesize is durable here and nowhere earlier: every new
+ // unconfirmed preference, every refreshed preference and every
+ // confidence receipt has landed. `promote_complete` is the pre-F2
+ // name for the same writes, so it moves with it rather than being
+ // left behind claiming a batch that had not started.
+ workrun?.checkpoint(WORKRUN_PHASE.promoteComplete);
+ workrun?.checkpoint(WORKRUN_PHASE.synthesizeComplete);
+
for (const r of plan.retires) {
const fromPath = preferencePath(vault, r.slug);
if (!existsSync(fromPath)) continue;
@@ -642,6 +693,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
}
}
+ // Every planned retire has been moved (or explicitly gated) by here.
+ workrun?.checkpoint(WORKRUN_PHASE.retireComplete);
+
for (const sig of plan.signalsToMove.values()) {
const dest = processedSignalPath(vault, sig.date, sig.slug);
try {
@@ -660,34 +714,27 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// the retire/move mutations (heal-after-mutations). Off by default so
// the default install stays byte-identical; a failure is a warning,
// never fatal to the dream pass.
- if (cfg.dream.heal_enrich_enabled === true) {
+ if (healEnrichEnabled) {
try {
healEnriched = runHealEnrichment(vault).enriched;
} catch (err) {
process.stderr.write(`warning: heal enrichment failed: ${(err as Error).message}\n`);
}
}
+ // Heal's second half (the optional enrichment) is durable here; its
+ // first half was the retire loop above. The marker sits at the later
+ // of the two, so it is never a claim about work still to come.
+ workrun?.checkpoint(WORKRUN_PHASE.healComplete);
} else {
// Dry-run still reports the move list so the caller's summary is
// accurate, but it does not touch disk.
for (const sig of plan.signalsToMove.values()) moved.push(sig.id);
}
- // v0.12.0 Brain Integrity Suite: mark promote + retire phases. The
- // dream.ts execution loop runs promote (writePreference) then retire
- // (moveToRetired) sequentially; one checkpoint covers both
- // mutations so the workrun stays compact yet recovery-meaningful.
+ // Post-mutation safeguard checkpoint: every state-changing write for
+ // this run is on disk, so a deadline that has passed stops the run here
+ // rather than part-way through the audit tail.
opts.safeguard?.checkpoint();
- if (workrun !== null) {
- workrun.checkpoint(WORKRUN_PHASE.promoteComplete);
- // Multi-phase dream (F2): synthesize = the promote/confirm writes
- // just completed; heal = the retire (and, when enabled, enrichment)
- // writes. Emit the phase checkpoints in order alongside the legacy
- // promote/retire markers (readers tolerate the extra phases).
- workrun.checkpoint(WORKRUN_PHASE.synthesizeComplete);
- workrun.checkpoint(WORKRUN_PHASE.retireComplete);
- workrun.checkpoint(WORKRUN_PHASE.healComplete);
- }
// v0.12.0 Brain Integrity Suite: build the gated-slug set once so the
// log body and the DreamRunSummary stay consistent — both views must
@@ -758,6 +805,14 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
},
});
}
+ // Reconcile's only durable artifact is the pair of event loops just
+ // above: the classification itself is in-memory and vanishes with the
+ // process. The pre-mutation burst used to claim this phase complete
+ // before a single preference had been written, which is precisely the
+ // journal-lies failure this release removes. The marker therefore
+ // trails `heal_complete` in the file - emission order is execution
+ // order, not the reporting order of DREAM_PHASE_ORDER.
+ workrun?.checkpoint(WORKRUN_PHASE.reconcileComplete);
for (const suppressed of plan.signalsSuppressed) {
writeEvent(vault, {
@@ -882,6 +937,14 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
regenerateLessonsQuiet(vault, { now });
}
+ // Pre-finalize safeguard checkpoint (no-dead-ends, Unit E). Everything
+ // between the post-mutation checkpoint and this line - the log events,
+ // the rollup ledger write, snapshot pruning, the active/lessons
+ // regeneration - used to run with no deadline check at all, so a run
+ // already past its budget still reached `finalized`. Tripping here
+ // leaves the workrun dangling, which is the documented contract.
+ opts.safeguard?.checkpoint();
+
// v0.12.0 Brain Integrity Suite: finalise the durable workrun
// immediately before constructing the summary. Any crash building
// the summary leaves the workrun dangling for the next pass to
@@ -972,7 +1035,12 @@ export function shouldGateRetireFromConfirmed(
// ----- Scan ---------------------------------------------------------------
-function scanBrain(vault: string): ScanResult {
+/**
+ * Read the whole `Brain/` tree into memory. Pure: it opens no writer, takes
+ * no clock and touches nothing on disk, which is why it is the one part of
+ * the pass that is provably runnable on its own (see `dream-step.ts`).
+ */
+export function scanBrain(vault: string): ScanResult {
const dirs = brainDirs(vault);
const signals: SignalRecord[] = [];
const preferences: PreferenceRecord[] = [];
diff --git a/src/core/brain/git/reader.ts b/src/core/brain/git/reader.ts
index 1f9b41eb..2335c4da 100644
--- a/src/core/brain/git/reader.ts
+++ b/src/core/brain/git/reader.ts
@@ -330,6 +330,35 @@ function canonicalRemotePath(pathname: string): string | null {
return path.length === 0 || path === "/" ? null : path;
}
+/**
+ * Resolve the probe's wall-clock budget from an optional caller value.
+ *
+ * Three cases, each stated rather than approximated:
+ *
+ * - absent: the module default, which is what every production caller
+ * takes today;
+ * - a finite number at or below zero: the budget is ALREADY spent, so
+ * no git runs at all. This is the only way to express an exhausted
+ * budget; passing a small positive number instead leaves the first
+ * invocation that much budget and so asserts something about how
+ * fast the host's git is, not about the probe.
+ * - anything else finite: floored to whole milliseconds.
+ *
+ * A non-finite value is a caller bug and raises. Substituting the
+ * default there would hand a two-second probe to a caller who believes
+ * it asked for something else, inside a lifecycle hook whose own
+ * process ceiling this must never consume.
+ */
+function resolveProbeBudgetMs(timeoutMs: number | undefined): number {
+ if (timeoutMs === undefined) return GIT_PROBE_TIMEOUT_MS;
+ if (!Number.isFinite(timeoutMs)) {
+ throw new TypeError(
+ `readGitWorkspaceIdentity: timeoutMs must be a finite number, got ${timeoutMs}`,
+ );
+ }
+ return timeoutMs <= 0 ? 0 : Math.floor(timeoutMs);
+}
+
/**
* Probe `repoPath` for its workspace identity, or `null` when it is not
* inside a git repository (or the probe's budget ran out).
@@ -350,10 +379,7 @@ export function readGitWorkspaceIdentity(
repoPath: string,
opts: { readonly timeoutMs?: number } = {},
): GitWorkspaceIdentity | null {
- const budgetMs =
- typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
- ? Math.floor(opts.timeoutMs)
- : GIT_PROBE_TIMEOUT_MS;
+ const budgetMs = resolveProbeBudgetMs(opts.timeoutMs);
const deadline = Date.now() + budgetMs;
const probe = (args: ReadonlyArray<string>): string => {
const remaining = deadline - Date.now();
diff --git a/src/core/brain/health/remediation.ts b/src/core/brain/health/remediation.ts
index d8fc92f6..908dbc4e 100644
--- a/src/core/brain/health/remediation.ts
+++ b/src/core/brain/health/remediation.ts
@@ -23,6 +23,7 @@ import { join } from "node:path";
import { ensureInsideVault, vaultRelative } from "../../path-safety.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
+import { REPAIR_VERDICT, requireRepairCapability } from "../applier-capability.ts";
import { computeContentHash, verifyContentHash } from "../content-hash.ts";
import { brainDirs, preferencePath } from "../paths.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
@@ -92,17 +93,41 @@ export interface RemediationOutcome {
readonly dryRun: boolean;
}
+/** The finding codes this planner emits, spelled once. */
+const REMEDIATION_CODE = Object.freeze({
+ widePermissions: "wide-permissions",
+ contentHashDrift: "content-hash-drift",
+ contradictoryPreferences: "contradictory-preferences",
+ staleClaim: "stale-claim",
+ conceptGap: "concept-gap",
+} as const);
+
// Fixed dependency order: bookkeeping repairs first, then semantic
// review steps. Pinned explicitly so the plan is identical on every
// Syncthing peer.
const CODE_ORDER: ReadonlyMap<string, number> = new Map([
- ["wide-permissions", 0],
- ["content-hash-drift", 1],
- ["contradictory-preferences", 2],
- ["stale-claim", 3],
- ["concept-gap", 4],
+ [REMEDIATION_CODE.widePermissions, 0],
+ [REMEDIATION_CODE.contentHashDrift, 1],
+ [REMEDIATION_CODE.contradictoryPreferences, 2],
+ [REMEDIATION_CODE.staleClaim, 3],
+ [REMEDIATION_CODE.conceptGap, 4],
]);
+/**
+ * The step classification for a finding code, read from the published
+ * applier capability table rather than decided here (no-dead-ends, task
+ * 8). Before that table existed each applier carried its own private
+ * verdict, so "is this auto-fixable?" had three answers that nothing kept
+ * in agreement. A code the table does not classify raises
+ * `UnclassifiedRepairCodeError` - defaulting it to needs-review would
+ * quietly hide a planner and table that had drifted apart.
+ */
+function classify(code: string): RemediationClass {
+ return requireRepairCapability(code).verdict === REPAIR_VERDICT.mechanical
+ ? "auto-safe"
+ : "needs-review";
+}
+
/**
* Scan `Brain/preferences/` for confirmed preferences whose stored
* `_content_hash` no longer matches their live (principle, scope) -
@@ -206,10 +231,10 @@ export function planRemediation(
for (const perm of findings.widePermissions ?? []) {
steps.push({
- code: "wide-permissions",
+ code: REMEDIATION_CODE.widePermissions,
action: "harden-permissions",
target: perm.path,
- classification: "auto-safe",
+ classification: classify(REMEDIATION_CODE.widePermissions),
detail:
`chmod ${perm.isDir ? "0700" : "0600"} ${perm.path} ` +
`(currently ${perm.mode.toString(8).padStart(3, "0")})`,
@@ -218,37 +243,37 @@ export function planRemediation(
for (const slug of findings.driftedSlugs) {
steps.push({
- code: "content-hash-drift",
+ code: REMEDIATION_CODE.contentHashDrift,
action: "restamp-content-hash",
target: slug,
- classification: "auto-safe",
+ classification: classify(REMEDIATION_CODE.contentHashDrift),
detail: `re-stamp _content_hash for pref-${slug} from its current content`,
});
}
for (const c of findings.contradictions) {
steps.push({
- code: "contradictory-preferences",
+ code: REMEDIATION_CODE.contradictoryPreferences,
action: "review",
target: `${c.aId}|${c.bId}`,
- classification: "needs-review",
+ classification: classify(REMEDIATION_CODE.contradictoryPreferences),
detail: `reconcile or retire one of [[${c.aId}]] / [[${c.bId}]]`,
});
}
for (const s of findings.staleClaims) {
steps.push({
- code: "stale-claim",
+ code: REMEDIATION_CODE.staleClaim,
action: "review",
target: s.id,
- classification: "needs-review",
+ classification: classify(REMEDIATION_CODE.staleClaim),
detail: `re-confirm or retire [[${s.id}]]`,
});
}
for (const g of findings.conceptGaps) {
steps.push({
- code: "concept-gap",
+ code: REMEDIATION_CODE.conceptGap,
action: "review",
target: g.term,
- classification: "needs-review",
+ classification: classify(REMEDIATION_CODE.conceptGap),
detail: `capture a dedicated preference for '${g.term}'`,
});
}
@@ -338,8 +363,14 @@ export function applyRemediation(
plan: RemediationPlan,
opts: ApplyRemediationOptions,
): RemediationOutcome {
- // Vault-identity write guard (context-integrity-gates, Unit J).
- assertVaultIdentityForWrite(vault);
+ // Vault-identity write guard (context-integrity-gates, Unit J), placed
+ // per the one rule the three appliers now share: at the entry point,
+ // before any other work, and only when the call will write. See the
+ // write-guard section of `applier-capability.ts`. This applier used to
+ // assert unconditionally, so a preview - the surface an operator
+ // reaches for to find out what is wrong - was refused on a root where
+ // nothing would have been written.
+ if (!opts.dryRun) assertVaultIdentityForWrite(vault);
const applied: RemediationStep[] = [];
const skipped: RemediationStep[] = [];
let budget = plan.stepCap;
diff --git a/src/core/brain/hygiene/apply.ts b/src/core/brain/hygiene/apply.ts
index eaf52bce..a069b70e 100644
--- a/src/core/brain/hygiene/apply.ts
+++ b/src/core/brain/hygiene/apply.ts
@@ -140,6 +140,15 @@ export async function applyHygienePlan(
opts: HygieneApplyOptions,
): Promise<HygieneApplyResult> {
const dryRun = opts.dryRun === true;
+ // Vault-identity write guard (context-integrity-gates, Unit J), placed
+ // per the one rule the three appliers now share: at the entry point,
+ // before any other work, and only when the call will write. See the
+ // write-guard section of `applier-capability.ts` for why. The "before
+ // any other work" half is this applier's own rationale - the per-finding
+ // loop below is fail-soft, so an assertion reached from inside an
+ // executor would be filed as one finding's error instead of refusing.
+ if (!dryRun) assertVaultIdentityForWrite(vault);
+
if (dryRun) {
return Object.freeze({
dry_run: true,
@@ -149,12 +158,6 @@ export async function applyHygienePlan(
});
}
- // Vault-identity write guard (context-integrity-gates, Unit J), after
- // the dry-run early return and before the first executor. The per-
- // finding loop is fail-soft, so an assertion reached only from inside
- // an executor would be filed as a finding error instead of refusing.
- assertVaultIdentityForWrite(vault);
-
const applied: HygieneAppliedAction[] = [];
const errors: { finding_id: string; message: string }[] = [];
for (const finding of plan.selected) {
diff --git a/src/core/brain/hygiene/plan.ts b/src/core/brain/hygiene/plan.ts
index c38e64b4..c07297e3 100644
--- a/src/core/brain/hygiene/plan.ts
+++ b/src/core/brain/hygiene/plan.ts
@@ -3,11 +3,17 @@
* (continuity-hygiene-freshness suite; kanban t_698db8f7).
*
* `apply` never acts on a raw scan: the operator (or a surface acting
- * for them) selects finding ids out of a scan report, and `review`
- * findings are structurally excluded - they have no automated
- * remediation by definition.
+ * for them) selects finding ids out of a scan report, and findings whose
+ * proposed action the applier capability table refuses are structurally
+ * excluded - they have no automated remediation by definition.
+ *
+ * Which actions those are is not decided here (no-dead-ends, task 8): the
+ * table is the one published statement of what each applier can repair,
+ * and an action it does not classify raises rather than being routed to a
+ * default.
*/
+import { REPAIR_VERDICT, requireRepairCapability } from "../applier-capability.ts";
import type { HygieneFinding, HygieneScanReport } from "./types.ts";
export interface HygienePlan {
@@ -40,7 +46,7 @@ export function buildHygienePlan(
unknown.push(id);
continue;
}
- if (finding.proposed_action === "review") {
+ if (requireRepairCapability(finding.proposed_action).verdict === REPAIR_VERDICT.refused) {
excludedReview.push(id);
continue;
}
diff --git a/src/core/brain/hygiene/types.ts b/src/core/brain/hygiene/types.ts
index 02facfa6..06ffe0cc 100644
--- a/src/core/brain/hygiene/types.ts
+++ b/src/core/brain/hygiene/types.ts
@@ -18,14 +18,21 @@ export type HygieneSeverity = "info" | "warning" | "action";
/**
* Closed action vocabulary. `review` is the universal safe default -
* anything an automated remediation should not touch lands there.
+ *
+ * Declared as a runtime tuple, like {@link HYGIENE_DETECTOR_IDS} above,
+ * so the applier capability table can be checked against the whole
+ * vocabulary rather than against whichever members a test remembered.
*/
-export type HygieneProposedAction =
- | "merge"
- | "supersede"
- | "archive"
- | "recompile"
- | "forget"
- | "review";
+export const HYGIENE_PROPOSED_ACTIONS = [
+ "merge",
+ "supersede",
+ "archive",
+ "recompile",
+ "forget",
+ "review",
+] as const;
+
+export type HygieneProposedAction = (typeof HYGIENE_PROPOSED_ACTIONS)[number];
export interface HygieneFinding {
/** Deterministic id: `<detector>:<sha256-prefix of targets>`. */
diff --git a/src/core/brain/index.ts b/src/core/brain/index.ts
index 854c2697..6ab32e74 100644
--- a/src/core/brain/index.ts
+++ b/src/core/brain/index.ts
@@ -71,6 +71,33 @@ export {
vaultRelative,
} from "./paths.ts";
+// ----- Dream: single-step requests and per-run gate overrides ---------------
+// The two capabilities Unit E shipped. They are on the barrel because the
+// CLI verb and the MCP tool are both adapters over them, and an adapter
+// that has to reach past this surface is how a capability ends up with no
+// operator reach at all.
+export {
+ DREAM_STEP,
+ DREAM_STEP_RUNNABLE,
+ DreamStepNotRunnableError,
+ runDreamStep,
+} from "./dream-step.ts";
+export type {
+ DreamStep,
+ DreamStepResult,
+ DreamScanStepResult,
+ DreamHealEnrichStepResult,
+} from "./dream-step.ts";
+export {
+ DREAM_GATE,
+ DREAM_GATE_NAMES,
+ DreamGateOverrideError,
+ parseDreamGateOverrides,
+ validateDreamGateOverrides,
+} from "./dream-gates.ts";
+export type { DreamGateName } from "./dream-gates.ts";
+export type { DreamGateOverrides, DreamOptions } from "./dream.ts";
+
// ----- Active-preferences digest --------------------------------------------
export { regenerateActive, regenerateActiveQuiet } from "./active.ts";
export type { RegenerateActiveOptions, RegenerateActiveResult } from "./active.ts";
@@ -107,9 +134,9 @@ export type {
export type { BrainDirs, AllocateSlugOptions, AllocateSlugResult } from "./paths.ts";
// ----- Configuration --------------------------------------------------------
+export { DEFAULT_BRAIN_CONFIG_YAML, renderBrainConfigTemplate } from "./config-template.ts";
export {
DEFAULT_BRAIN_CONFIG,
- DEFAULT_BRAIN_CONFIG_YAML,
BRAIN_CONFIG_SUPPORTED_VERSIONS,
BrainConfigError,
loadBrainConfig,
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index e47f5aa7..459cc11d 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -35,7 +35,8 @@ import {
vaultRelative,
} from "./paths.ts";
import { vaultIdentityPath, writeVaultIdentity } from "./vault-identity.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML, formatPrimaryAgentYamlValue } from "./policy.ts";
+import { formatPrimaryAgentYamlValue } from "./policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";
import { BASE_TEMPLATE_FILES, BASES_TEMPLATE_DIR, renderBrainManual } from "./templates.ts";
const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;
@@ -228,17 +229,15 @@ export function bootstrapBrain(
// 1. Directories. mkdirSync({ recursive: true }) is idempotent and
// does not throw on existing paths, so we do not track create
// counts for directories — only files end up in the report.
+ //
+ // Enumerated from `brainDirs` rather than from a list repeated
+ // here: a hand-written list is how `pending` and `entities` came to
+ // be DECLARED by `brainDirs` and never created (their writers made
+ // them lazily, so a freshly-bootstrapped vault was missing two of
+ // the ten directories it advertises). Iterating the struct makes
+ // "declared but not created" unrepresentable.
const dirs = brainDirs(vault);
- for (const dir of [
- dirs.brain,
- dirs.inbox,
- dirs.processed,
- dirs.preferences,
- dirs.retired,
- dirs.log,
- dirs.bases,
- dirs.snapshots,
- ]) {
+ for (const dir of Object.values(dirs)) {
mkdirSync(dir, { recursive: true });
}
diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.ts
index 82746eaf..1d170f18 100644
--- a/src/core/brain/inline-scan.ts
+++ b/src/core/brain/inline-scan.ts
@@ -28,6 +28,7 @@
import { readFileSync } from "node:fs";
import { relative, sep } from "node:path";
+import { emitIngestDedupReport, type IngestDedupSourceCount } from "./dedup-telemetry.ts";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";
import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
@@ -78,6 +79,8 @@ export async function scanInline(
const now = opts.now ?? new Date();
const errors: ScanInlineErrorEntry[] = [];
const filesWithMarkers: ScanInlineFileSummary[] = [];
+ /** Per-file exact-hash drop counts, persisted once at the end of the run. */
+ const dedupBySource: IngestDedupSourceCount[] = [];
let scanned = 0;
let found = 0;
@@ -148,6 +151,7 @@ export async function scanInline(
filesWithMarkers.push({ path: filePath, markers: markers.length });
const rewriteOps: RewriteOp[] = [];
+ let fileDeduped = 0;
for (const marker of markers) {
const hash = computeDedupHash({
topic: marker.topic,
@@ -158,6 +162,7 @@ export async function scanInline(
const existing = dedupIndex.get(hash);
if (existing) {
deduped++;
+ fileDeduped++;
if (!opts.dryRun) {
rewriteOps.push({ marker, signalId: existing.id });
}
@@ -195,6 +200,13 @@ export async function scanInline(
}
}
+ if (fileDeduped > 0) {
+ dedupBySource.push({
+ ref: relative(vault, filePath).split(sep).join("/"),
+ exactDeduped: fileDeduped,
+ });
+ }
+
if (rewriteOps.length > 0 && !opts.dryRun) {
try {
await rewriteMarkers(filePath, rewriteOps);
@@ -207,6 +219,17 @@ export async function scanInline(
}
}
+ // Dedup observability (Unit F): one record per run that actually
+ // dropped something, keyed by the note being re-ingested. A dry run
+ // reports its count but writes nothing, here as everywhere else.
+ if (!opts.dryRun) {
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: dedupBySource,
+ createdAt: now.toISOString(),
+ });
+ }
+
return Object.freeze({
scanned,
found,
diff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.ts
index e21c507b..330f76ea 100644
--- a/src/core/brain/lint-consolidate.ts
+++ b/src/core/brain/lint-consolidate.ts
@@ -34,15 +34,25 @@ import {
import { readMergedInto } from "./page-meta/page-id.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+/**
+ * The two structural repairs this pass performs, spelled once. They are
+ * also the codes the applier capability table publishes for this module,
+ * and the capability test binds the two together.
+ */
+export const LINT_CONSOLIDATE_KIND = Object.freeze({
+ mergedLink: "fix-merged-link",
+ staleStableDemotion: "demote-stale-stable",
+} as const);
+
export interface LintFix {
- readonly kind: "fix-merged-link";
+ readonly kind: typeof LINT_CONSOLIDATE_KIND.mergedLink;
readonly path: string;
readonly from: string;
readonly to: string;
}
export interface LintDemotion {
- readonly kind: "demote-stale-stable";
+ readonly kind: typeof LINT_CONSOLIDATE_KIND.staleStableDemotion;
readonly id: string;
readonly path: string;
readonly ageDays: number;
@@ -99,7 +109,12 @@ function scanFileForMergedLinks(
const rewritten = raw.replace(WIKILINK_TARGET_RE, (match, target, suffix) => {
const canonical = merge.forward.get(target);
if (!canonical) return match;
- fixes.push({ kind: "fix-merged-link", path, from: target, to: canonical });
+ fixes.push({
+ kind: LINT_CONSOLIDATE_KIND.mergedLink,
+ path,
+ from: target,
+ to: canonical,
+ });
return `[[${canonical}${suffix ?? ""}]]`;
});
return { fixes, rewritten };
@@ -135,7 +150,7 @@ function detectStaleStable(vault: string, now: Date, staleDays: number): LintDem
if (age < staleDays) continue;
const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");
out.push({
- kind: "demote-stale-stable",
+ kind: LINT_CONSOLIDATE_KIND.staleStableDemotion,
id,
path,
ageDays: Math.floor(age),
@@ -168,8 +183,16 @@ function applyDemotion(path: string): boolean {
}
export function lintConsolidate(vault: string, opts: LintOptions): LintReport {
- // Vault-identity write guard (context-integrity-gates, Unit J).
- assertVaultIdentityForWrite(vault);
+ // Vault-identity write guard (context-integrity-gates, Unit J), placed
+ // per the one rule the appliers share: at the entry point, before any
+ // other work, and only when the call will write. See the write-guard
+ // section of `applier-capability.ts`.
+ //
+ // It used to run unconditionally, ahead of this branch. The read-only
+ // `o2b brain actions` verb calls this function in report mode, so a
+ // root the guard refuses took down a ranking command that never
+ // intended to write a byte - the guard's own contract inverted.
+ if (opts.apply) assertVaultIdentityForWrite(vault);
const now = opts.now ?? new Date();
const staleDays = opts.staleDays ?? PAGE_STALE_DAYS_DEFAULT;
const merge = buildMergeMap(vault);
diff --git a/src/core/brain/next-step.ts b/src/core/brain/next-step.ts
new file mode 100644
index 00000000..651c208d
--- /dev/null
+++ b/src/core/brain/next-step.ts
@@ -0,0 +1,99 @@
+/**
+ * Strict next-step resolution over {@link DIAGNOSTIC_SIGNALS} (no-dead-ends,
+ * task 1).
+ *
+ * This module is the read surface every NEW forward-pointer consumer uses.
+ * It exists because `resolveSignal` is deliberately lenient: for an
+ * unregistered code it fabricates a generic `o2b brain doctor` hint, which
+ * is exactly the "plausible value invented to keep a code path quiet" this
+ * release removes. The strict lookup here never invents a command - an
+ * unregistered code is absent, and the caller decides what to do about it.
+ *
+ * There is NO second registry: {@link DIAGNOSTIC_SIGNALS} already models an
+ * issue class plus its structural CLI string, so this module only narrows
+ * that record to what a next-step renderer needs and refuses to guess.
+ */
+
+import { DIAGNOSTIC_SIGNALS, type DiagnosticSignal } from "./diagnostics.ts";
+
+/**
+ * A resolved forward pointer: the code that produced it, its human label,
+ * and the exact structural command to run next. Derived from
+ * {@link DiagnosticSignal} rather than redeclared, so the two shapes cannot
+ * drift; `autoRepairable` is deliberately excluded because rendering a next
+ * step never depends on whether a fixer exists.
+ */
+export type NextStep = Readonly<Pick<DiagnosticSignal, "code" | "issueClass" | "nextCommand">>;
+
+/**
+ * Resolve `code` to its registered next step, or `null` when no signal is
+ * registered for it. `null` is the absent result rather than a sentinel
+ * record because that is this codebase's established "nothing to report"
+ * return (see the write-conflict advisory and the profile lookups), and
+ * because any record-shaped absent value would have to carry a command
+ * field - the one thing this function must never invent.
+ */
+export function resolveNextStep(code: string): NextStep | null {
+ const signal = DIAGNOSTIC_SIGNALS.get(code);
+ if (signal === undefined) return null;
+ return Object.freeze({
+ code: signal.code,
+ issueClass: signal.issueClass,
+ nextCommand: signal.nextCommand,
+ });
+}
+
+/** A code whose next step a caller requires, but which is unregistered. */
+export class UnregisteredNextStepError extends Error {
+ readonly code: string;
+ constructor(code: string) {
+ super(
+ `no diagnostic signal is registered for code ${JSON.stringify(code)}; ` +
+ "add an entry to DIAGNOSTIC_SIGNALS naming the command that resolves it",
+ );
+ this.name = "UnregisteredNextStepError";
+ this.code = code;
+ }
+}
+
+/**
+ * The registered next step for `code`, or {@link UnregisteredNextStepError}.
+ *
+ * For the callers that must NAME a command - a refusal whose whole value is
+ * telling the operator what to run - absence is not a case to handle, it is
+ * a registry that has drifted. Those callers resolve at module scope, so the
+ * drift fails at import rather than inside the failure path it was meant to
+ * explain. Mirrors `requireRepairCapability` in `applier-capability.ts`.
+ */
+export function requireNextStep(code: string): NextStep {
+ const step = resolveNextStep(code);
+ if (step === null) throw new UnregisteredNextStepError(code);
+ return step;
+}
+
+/**
+ * The additive JSON key every machine-readable surface carries a next
+ * step in. Named once here because the CLI `--json` renderers and their
+ * MCP twins must not drift on the spelling: a consumer that learns the
+ * key from one surface reads it on the other.
+ */
+export const NEXT_COMMAND_KEY = "next_command";
+
+/** The field a resolved code contributes, spread into an issue record. */
+export type NextCommandField = { readonly [NEXT_COMMAND_KEY]?: string };
+
+/** Absent case: an unregistered code contributes no key whatsoever. */
+const NO_NEXT_COMMAND: NextCommandField = Object.freeze({});
+
+/**
+ * Resolve `code` into the object to spread onto a machine-readable issue
+ * record. An unregistered code yields the empty object, so the key is
+ * ABSENT rather than present-and-null - a null would be a value a
+ * consumer has to interpret, and the honest statement is that this code
+ * has no registered exit.
+ */
+export function nextCommandField(code: string): NextCommandField {
+ const step = resolveNextStep(code);
+ if (step === null) return NO_NEXT_COMMAND;
+ return Object.freeze({ [NEXT_COMMAND_KEY]: step.nextCommand });
+}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 92685acc..2fca971f 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -52,6 +52,11 @@ export const BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-propo
export const BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");
export const BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");
export const BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");
+/** Write-ahead journal of in-flight skill-proposal accepts (no-dead-ends, Unit I). */
+export const BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(
+ BRAIN_SKILL_PROPOSALS_REL,
+ "accept-journal",
+);
export const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");
export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");
export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
@@ -337,6 +342,12 @@ export function skillProposalRejectedPath(vault: string, slug: string): string {
return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REJECTED_REL, `prop-${s}.md`), vault);
}
+/** Accept-journal path: `Brain/skill-proposals/accept-journal/<slug>.json`. */
+export function skillAcceptJournalPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_SKILL_ACCEPT_JOURNAL_REL, `${s}.json`), vault);
+}
+
/** Accepted procedure reference path: `Brain/procedures/proc-<slug>.md`. */
export function procedurePath(vault: string, slug: string): string {
const s = validateSlug(slug);
diff --git a/src/core/brain/pending.ts b/src/core/brain/pending.ts
index 2be36d3e..3f3f4f70 100644
--- a/src/core/brain/pending.ts
+++ b/src/core/brain/pending.ts
@@ -9,7 +9,8 @@
* - {@link listPending} enumerate staged signals;
* - {@link applyPending} move a staged file into `Brain/inbox/` UNCHANGED
* (entity anchors and dedup hash preserved verbatim -
- * they were resolved at extraction time);
+ * they were resolved at extraction time), or, with
+ * `dryRun`, report the move and write nothing;
* - {@link rejectPending} move a staged file into `Brain/retired/` with
* retire-shaped frontmatter (`_status`, `retired_at`,
* `retired_reason`), following the retire conventions.
@@ -73,6 +74,27 @@ export class InvalidPendingIdError extends Error {
}
}
+/**
+ * The inbox slot this id would move into is already occupied.
+ *
+ * The exclusive create in {@link applyPending} has always refused this,
+ * as a raw filesystem error. It is a named error now because the dry run
+ * added in no-dead-ends task 11 has to refuse it too: a preview that
+ * reported a move the apply would then reject would be a preview that
+ * lied, which is the defect class this release exists to remove. The
+ * exclusive create stays as the actual race gate.
+ */
+export class PendingApplyConflictError extends Error {
+ readonly id: string;
+ readonly path: string;
+ constructor(id: string, path: string) {
+ super(`inbox already holds a signal named ${JSON.stringify(id)}: ${path}`);
+ this.name = "PendingApplyConflictError";
+ this.id = id;
+ this.path = path;
+ }
+}
+
/** One staged signal: its id, absolute path, and parsed frontmatter. */
export interface PendingEntry {
readonly id: string;
@@ -95,10 +117,21 @@ export function stagePendingSignal(vault: string, input: WriteSignalInput): Stag
return { id: res.id, path: res.path };
}
-/** Validate a pending id and resolve its absolute path inside `Brain/pending/`. */
-function pendingFilePath(vault: string, id: string): string {
+/**
+ * Validate a pending id and resolve its absolute path inside
+ * `Brain/pending/`.
+ *
+ * `forWrite` selects the guarded directory resolver, following the one
+ * rule the appliers share: the vault-identity assertion runs only when
+ * the call will write (see the write-guard section of
+ * `applier-capability.ts`). A dry run resolves the same paths ungated,
+ * because gating a preview refuses the surface an operator reaches for
+ * to find out what is wrong.
+ */
+function pendingFilePath(vault: string, id: string, forWrite: boolean): string {
if (!SIGNAL_ID_RE.test(id)) throw new InvalidPendingIdError(id);
- return ensureInsideVault(join(brainDirsForWrite(vault).pending, `${id}.md`), vault);
+ const dirs = forWrite ? brainDirsForWrite(vault) : brainDirs(vault);
+ return ensureInsideVault(join(dirs.pending, `${id}.md`), vault);
}
/** List the staged signals in `Brain/pending/`, sorted by id. */
@@ -118,20 +151,49 @@ export function listPending(vault: string): PendingEntry[] {
return out;
}
+export interface PendingApplyOptions {
+ /** True previews the move and writes nothing; false performs it. */
+ readonly dryRun?: boolean;
+}
+
+export interface PendingApplyResult extends StageResult {
+ /** True when this was a preview and nothing moved. */
+ readonly dryRun: boolean;
+}
+
/**
* Apply a staged signal: move it into `Brain/inbox/` UNCHANGED. The bytes are
* copied verbatim (anchors + dedup hash preserved) and the pending copy is
* removed only after the inbox copy lands. A missing id is a typed error.
+ *
+ * `dryRun` reports the move and writes nothing (no-dead-ends, task 11).
+ * This was the only applier in the codebase without a preview, so an
+ * operator working the approval queue could apply a staged signal but
+ * could not be told what applying would do first. The preview runs every
+ * check the apply runs - id shape, staged file present, destination free
+ * - and stops before the two calls that touch disk, so the report it
+ * gives is the move the apply would make rather than a guess at it.
*/
-export function applyPending(vault: string, id: string): StageResult {
- const src = pendingFilePath(vault, id);
+export function applyPending(
+ vault: string,
+ id: string,
+ opts: PendingApplyOptions = {},
+): PendingApplyResult {
+ const dryRun = opts.dryRun === true;
+ const src = pendingFilePath(vault, id, !dryRun);
if (!existsSync(src)) throw new PendingSignalNotFoundError(id);
+ const dirs = dryRun ? brainDirs(vault) : brainDirsForWrite(vault);
+ const dest = ensureInsideVault(join(dirs.inbox, `${id}.md`), vault);
+ if (existsSync(dest)) throw new PendingApplyConflictError(id, dest);
+ if (dryRun) return { id, path: dest, dryRun: true };
+
const contents = readFileSync(src, "utf8");
- const dest = ensureInsideVault(join(brainDirsForWrite(vault).inbox, `${id}.md`), vault);
- // Exclusive create: never clobber an existing inbox file with the same id.
+ // Exclusive create: never clobber an existing inbox file with the same
+ // id. This is the real gate - the check above makes the preview honest,
+ // it does not replace the atomic one.
atomicCreateFileSyncExclusive(dest, contents);
unlinkSync(src);
- return { id, path: dest };
+ return { id, path: dest, dryRun: false };
}
export interface RejectPendingOptions {
@@ -152,7 +214,7 @@ export function rejectPending(
reason: string,
opts: RejectPendingOptions = {},
): StageResult {
- const src = pendingFilePath(vault, id);
+ const src = pendingFilePath(vault, id, true);
if (!existsSync(src)) throw new PendingSignalNotFoundError(id);
const now = opts.now ?? new Date();
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index fab6faf9..7250a67c 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -307,6 +307,24 @@ export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {
*/
const INTEGRITY_GATE_KEYS = ["owner_scope_delivery", "embedding_abi"] as const;
+/**
+ * Sub-key vocabularies for the blocks whose validator branch does not
+ * derive them from a default table. Named once so the parser, the
+ * forward-compat unknown-key warning and the configuration-template
+ * ratchet all read the same list.
+ */
+const DISCIPLINE_REPORT_KEYS = ["enabled", "timezone", "watched_paths", "known_agents"] as const;
+const HYGIENE_KEYS = ["resolver_cmd", "dedup_threshold"] as const;
+const ANTICIPATORY_KEYS = ["ttl_seconds", "max_tokens"] as const;
+const RECALL_KEYS = ["degradation"] as const;
+
+/**
+ * Optional `retire:` sub-key with no default. Declared here because
+ * `mergeBlock` derives a block's vocabulary from its default table, and
+ * a key whose default is "absent" has no entry there.
+ */
+const RETIRE_OPTIONAL_KEYS = ["confirmed_evidence_min_threshold"] as const;
+
/**
* How long a context pack stays servable after it was built, when
* `_brain.yaml` omits `integrity.pack_validity_seconds`.
@@ -588,56 +606,11 @@ export const loadSnapshotRetentionSafe = makeSafeLoader(
DEFAULT_BRAIN_CONFIG.snapshots.retention_count,
);
-/**
- * Serialised default `_brain.yaml`. Hand-formatted to match the design
- * doc verbatim — `brain init` writes this byte string so the file the
- * user sees is the file the docs describe.
- */
-export const DEFAULT_BRAIN_CONFIG_YAML = `schema_version: 1
-
-# Optional. When set, dream runs from a different agent emit a stderr
-# warning and a non_primary_agent payload row. The vault should have a
-# single dream-running runtime even when it is shared across devices
-# via Syncthing.
-primary_agent: null
-
-dream:
- candidate_threshold: 3
- unconfirmed_window_days: 14
- contradiction_window_days: 14
-
-retire:
- stale_evidence_days: 90
-
-confidence:
- # low_max_applied gates the "low-evidence-confirmed" doctor warning
- # and the auto-promotion of unconfirmed preferences to confirmed.
- low_max_applied: 2
- # Band thresholds on the numeric confidence_value (Wilson lower
- # bound times freshness decay). value >= high_min ⇒ high;
- # value >= medium_min ⇒ medium; else low.
- medium_min: 0.40
- high_min: 0.75
-
-snapshots:
- retention_count: 10
-
-# Vault-wide exclusion policy. Single source of truth for every
-# vault walker (search indexer, scan-inline, future scanners).
-# Entries without a slash match a directory name anywhere in the
-# tree; entries with a slash match a vault-relative POSIX path
-# exactly. Remove the block to fall back to the built-in defaults;
-# set ignore_paths to an empty list to disable exclusions entirely.
-vault:
- ignore_paths:
- - .git
- - node_modules
- - .open-second-brain
- - .obsidian
- - .trash
- - .stversions
- - Brain/.snapshots
-`;
+// The serialised default `_brain.yaml` (`DEFAULT_BRAIN_CONFIG_YAML`) is
+// GENERATED from the default tables above and lives in
+// `config-template.ts`. It cannot live here: the generator reads these
+// tables, so importing it back would make `policy.ts` and
+// `config-template.ts` mutually dependent at module-evaluation time.
const YAML_STRING_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
@@ -780,6 +753,24 @@ export function validateBrainConfig(parsed: unknown, source: string | null = nul
export interface ValidateResult {
readonly config: BrainConfig;
readonly warnings: ReadonlyArray<BrainConfigLoadWarning>;
+ /**
+ * Every key this validation run branched on, top-level and per-block.
+ * Recorded by construction (see {@link KeyIndexCollector}) rather than
+ * from a hand-maintained list, so it can never disagree with what the
+ * validator actually understands. Consumed by the configuration-template
+ * ratchet.
+ */
+ readonly knownKeys: BrainConfigKeyIndex;
+}
+
+/**
+ * The set of configuration keys the validator understands, as observed
+ * during one validation run.
+ */
+export interface BrainConfigKeyIndex {
+ readonly topLevel: ReadonlySet<string>;
+ /** Block key → sub-keys that block declares. Scalar keys are absent. */
+ readonly subKeys: ReadonlyMap<string, ReadonlySet<string>>;
}
export function validateBrainConfigDetailed(
@@ -791,12 +782,14 @@ export function validateBrainConfigDetailed(
}
const obj = parsed as Record<string, unknown>;
const warnings: BrainConfigLoadWarning[] = [];
- // Populated by every `hasBlock`/`mergeBlock` call below; drives the
- // forward-compat "unknown top-level field" check at the end of this
- // function. `schema_version` is seeded directly since its presence is
- // checked by an inverted `if (!(... in obj))` immediately below, not
- // through either helper.
- const knownBlockKeys = new Set<string>(["schema_version"]);
+ // Populated by every `hasBlock`/`mergeBlock`/`warnUnknownKeys` call
+ // below; drives the forward-compat "unknown top-level field" check at
+ // the end of this function and the template ratchet.
+ // `schema_version` is seeded directly since its presence is checked by
+ // an inverted `if (!(... in obj))` immediately below, not through
+ // either helper.
+ const knownBlockKeys = new KeyIndexCollector();
+ knownBlockKeys.addTop("schema_version");
// schema_version is mandatory and must be in the supported set.
if (!("schema_version" in obj)) {
@@ -885,8 +878,19 @@ export function validateBrainConfigDetailed(
DEFAULT_BRAIN_CONFIG.retire as unknown as Readonly<Record<string, number>>,
source,
knownBlockKeys,
+ RETIRE_OPTIONAL_KEYS,
);
requirePositiveInteger("retire.stale_evidence_days", retire.stale_evidence_days, source);
+ // Optional destructive-from-confirmed gate (v0.12.0). Validated here
+ // and carried into the typed config below; an out-of-range value is a
+ // hard error rather than a silently ignored knob.
+ if (retire.confirmed_evidence_min_threshold !== undefined) {
+ requirePositiveInteger(
+ "retire.confirmed_evidence_min_threshold",
+ retire.confirmed_evidence_min_threshold,
+ source,
+ );
+ }
const confidence = mergeBlock(
"confidence",
@@ -989,7 +993,7 @@ export function validateBrainConfigDetailed(
vault = { ignore_paths: Object.freeze(validated) };
}
// Forward-compat: unknown sub-keys under `vault:` → warning.
- warnUnknownKeys(rawMap, ["ignore_paths"], "vault", source, warnings);
+ warnUnknownKeys(rawMap, ["ignore_paths"], "vault", source, warnings, knownBlockKeys);
}
// Optional `active.{most_applied_window_days, most_applied_limit}`
@@ -1065,6 +1069,7 @@ export function validateBrainConfigDetailed(
"active",
source,
warnings,
+ knownBlockKeys,
);
active = {
...(mostApplied !== undefined ? { most_applied: mostApplied } : {}),
@@ -1106,6 +1111,7 @@ export function validateBrainConfigDetailed(
"lessons",
source,
warnings,
+ knownBlockKeys,
);
lessons = {
...(halfLife !== undefined ? { half_life_days: halfLife } : {}),
@@ -1127,6 +1133,14 @@ export function validateBrainConfigDetailed(
});
} else {
const drObj = dr as Record<string, unknown>;
+ warnUnknownKeys(
+ drObj,
+ DISCIPLINE_REPORT_KEYS,
+ "discipline_report",
+ source,
+ warnings,
+ knownBlockKeys,
+ );
let ok = true;
// enabled: boolean
@@ -1306,6 +1320,7 @@ export function validateBrainConfigDetailed(
"guardrails",
source,
warnings,
+ knownBlockKeys,
);
if (Object.keys(partial).length > 0) {
@@ -1334,7 +1349,14 @@ export function validateBrainConfigDetailed(
requirePositiveInteger("rollup.identity_threshold", rawMap["identity_threshold"], source);
partial.identity_threshold = rawMap["identity_threshold"] as number;
}
- warnUnknownKeys(rawMap, ["fact_threshold", "identity_threshold"], "rollup", source, warnings);
+ warnUnknownKeys(
+ rawMap,
+ ["fact_threshold", "identity_threshold"],
+ "rollup",
+ source,
+ warnings,
+ knownBlockKeys,
+ );
rollup = partial;
}
@@ -1404,6 +1426,7 @@ export function validateBrainConfigDetailed(
"link_graph",
source,
warnings,
+ knownBlockKeys,
);
linkGraph = Object.keys(partialLg).length > 0 ? (partialLg as BrainLinkGraphConfig) : {};
}
@@ -1469,6 +1492,7 @@ export function validateBrainConfigDetailed(
"temporal",
source,
warnings,
+ knownBlockKeys,
);
temporal = Object.keys(partialTp).length > 0 ? (partialTp as BrainTemporalConfig) : {};
}
@@ -1533,6 +1557,7 @@ export function validateBrainConfigDetailed(
"health",
source,
warnings,
+ knownBlockKeys,
);
health = Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};
}
@@ -1579,6 +1604,7 @@ export function validateBrainConfigDetailed(
"integrity",
source,
warnings,
+ knownBlockKeys,
);
integrity = Object.keys(partialIt).length > 0 ? (partialIt as BrainIntegrityConfig) : {};
}
@@ -1642,7 +1668,7 @@ export function validateBrainConfigDetailed(
partialNotes["read_paths"] = cleaned;
}
// Forward-compat: unknown sub-keys under `notes:` → warning.
- warnUnknownKeys(notesObj, ["read_paths"], "notes", source, warnings);
+ warnUnknownKeys(notesObj, ["read_paths"], "notes", source, warnings, knownBlockKeys);
notes = Object.keys(partialNotes).length > 0 ? (partialNotes as BrainNotesConfig) : {};
}
@@ -1684,7 +1710,7 @@ export function validateBrainConfigDetailed(
});
partial[key] = cleaned;
}
- warnUnknownKeys(sessionsObj, LIST_KEYS, "sessions", source, warnings);
+ warnUnknownKeys(sessionsObj, LIST_KEYS, "sessions", source, warnings, knownBlockKeys);
sessions = partial as BrainSessionsConfig;
}
@@ -1760,6 +1786,7 @@ export function validateBrainConfigDetailed(
"schema",
source,
warnings,
+ knownBlockKeys,
);
try {
const declarations = validateSchemaDeclarations(partialSchema);
@@ -1810,6 +1837,7 @@ export function validateBrainConfigDetailed(
}
partial.dedup_threshold = threshold;
}
+ warnUnknownKeys(rawMap, HYGIENE_KEYS, "hygiene", source, warnings, knownBlockKeys);
hygiene = Object.freeze(partial);
}
@@ -1827,6 +1855,7 @@ export function validateBrainConfigDetailed(
requirePositiveInteger("anticipatory.max_tokens", rawMap["max_tokens"], source);
partial.max_tokens = rawMap["max_tokens"] as number;
}
+ warnUnknownKeys(rawMap, ANTICIPATORY_KEYS, "anticipatory", source, warnings, knownBlockKeys);
anticipatory = Object.freeze(partial);
}
@@ -1847,6 +1876,7 @@ export function validateBrainConfigDetailed(
}
partial.degradation = mode;
}
+ warnUnknownKeys(rawMap, RECALL_KEYS, "recall", source, warnings, knownBlockKeys);
recall = Object.freeze(partial);
}
@@ -1894,7 +1924,7 @@ export function validateBrainConfigDetailed(
partial.default_scope = trimmed;
}
// Forward-compat: unknown sub-keys under `feedback:` → warning.
- warnUnknownKeys(rawMap, ["default_scope"], "feedback", source, warnings);
+ warnUnknownKeys(rawMap, ["default_scope"], "feedback", source, warnings, knownBlockKeys);
feedback = Object.freeze(partial);
}
@@ -1905,7 +1935,7 @@ export function validateBrainConfigDetailed(
// its own message format (distinct from `warnUnknownKeys`'s
// `block.key: ...` shape), pinned by an existing test.
for (const key of Object.keys(obj)) {
- if (!knownBlockKeys.has(key)) {
+ if (!knownBlockKeys.topLevel.has(key)) {
warnings.push({
path: source ?? "<config>",
message: `unknown top-level field '${key}' ignored (forward-compat)`,
@@ -1927,6 +1957,13 @@ export function validateBrainConfigDetailed(
},
retire: {
stale_evidence_days: retire.stale_evidence_days as number,
+ // Absent stays absent: `undefined` is the documented "gate off"
+ // state the dream pass branches on, so spreading the key in
+ // unconditionally would change `retire` from omitting it to
+ // carrying an explicit undefined.
+ ...(retire.confirmed_evidence_min_threshold !== undefined
+ ? { confirmed_evidence_min_threshold: retire.confirmed_evidence_min_threshold as number }
+ : {}),
},
confidence: {
low_max_applied: confidence.low_max_applied as number,
@@ -1955,7 +1992,7 @@ export function validateBrainConfigDetailed(
...(feedback !== undefined ? { feedback } : {}),
};
- return { config, warnings };
+ return { config, warnings, knownKeys: knownBlockKeys };
}
// ----- Helpers --------------------------------------------------------------
@@ -1999,8 +2036,10 @@ function warnUnknownKeys(
blockName: string,
source: string | null,
warnings: BrainConfigLoadWarning[],
+ knownBlockKeys: KeyIndexCollector,
): void {
const knownSet = known instanceof Set ? known : new Set(known);
+ knownBlockKeys.addSub(blockName, knownSet);
for (const key of Object.keys(map)) {
if (!knownSet.has(key)) {
warnings.push({
@@ -2016,9 +2055,11 @@ function mergeBlock(
raw: unknown,
fallback: Readonly<Record<string, number>>,
source: string | null,
- knownBlockKeys: Set<string>,
+ knownBlockKeys: KeyIndexCollector,
+ optionalKeys: ReadonlyArray<string> = [],
): Record<string, unknown> {
- knownBlockKeys.add(blockKey);
+ knownBlockKeys.addTop(blockKey);
+ knownBlockKeys.addSub(blockKey, [...Object.keys(fallback), ...optionalKeys]);
if (raw === undefined) {
return { ...fallback };
}
@@ -2042,11 +2083,70 @@ function mergeBlock(
* warning). A key that is never checked can never be "known", by
* construction - there is no separate list to forget to update.
*/
-function hasBlock(obj: Record<string, unknown>, key: string, knownBlockKeys: Set<string>): boolean {
- knownBlockKeys.add(key);
+function hasBlock(
+ obj: Record<string, unknown>,
+ key: string,
+ knownBlockKeys: KeyIndexCollector,
+): boolean {
+ knownBlockKeys.addTop(key);
return key in obj;
}
+/**
+ * Mutable accumulator behind {@link BrainConfigKeyIndex}. Every helper
+ * that branches on a key registers it here, so the index is a
+ * by-construction record of what the validator understands rather than a
+ * second list that can drift from the first.
+ */
+class KeyIndexCollector implements BrainConfigKeyIndex {
+ readonly topLevel = new Set<string>();
+ readonly subKeys = new Map<string, ReadonlySet<string>>();
+
+ addTop(key: string): void {
+ this.topLevel.add(key);
+ }
+
+ addSub(block: string, keys: Iterable<string>): void {
+ const merged = new Set(this.subKeys.get(block) ?? []);
+ for (const key of keys) merged.add(key);
+ this.subKeys.set(block, merged);
+ }
+}
+
+/**
+ * Probe source label used by {@link brainConfigKnownKeys}. Never reaches
+ * a user-visible surface: the probe discards its warnings.
+ */
+const KEY_INDEX_PROBE_SOURCE = "<brain-config-key-index>";
+
+/**
+ * Every configuration key {@link validateBrainConfigDetailed} branches
+ * on, enumerated by running the validator rather than by reading a list.
+ *
+ * Two passes are needed because a block's sub-key vocabulary is only
+ * declared inside the branch that parses the block: pass one discovers
+ * the top-level keys against a minimal config, pass two re-runs with
+ * every discovered block present but empty so each block's sub-key
+ * registration executes. Scalar top-level keys keep their default value
+ * in pass two - handing `primary_agent` an empty map would (correctly)
+ * be rejected.
+ */
+export function brainConfigKnownKeys(): BrainConfigKeyIndex {
+ const minimal: Record<string, unknown> = {
+ schema_version: BRAIN_CONFIG_SUPPORTED_VERSIONS[0],
+ };
+ const firstPass = validateBrainConfigDetailed(minimal, KEY_INDEX_PROBE_SOURCE).knownKeys;
+ const defaults = DEFAULT_BRAIN_CONFIG as unknown as Record<string, unknown>;
+ const probe: Record<string, unknown> = { ...minimal };
+ for (const key of firstPass.topLevel) {
+ if (key in minimal) continue;
+ const fallback = defaults[key];
+ const isScalar = key in defaults && (fallback === null || typeof fallback !== "object");
+ probe[key] = isScalar ? fallback : {};
+ }
+ return validateBrainConfigDetailed(probe, KEY_INDEX_PROBE_SOURCE).knownKeys;
+}
+
function requirePositiveInteger(field: string, value: unknown, source: string | null): void {
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
throw new BrainConfigError(`must be a positive integer; got ${describe(value)}`, field, source);
diff --git a/src/core/brain/portability/profiles.ts b/src/core/brain/portability/profiles.ts
index 9c911be5..ea0d4120 100644
--- a/src/core/brain/portability/profiles.ts
+++ b/src/core/brain/portability/profiles.ts
@@ -15,8 +15,15 @@
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
+import lockfile from "proper-lockfile";
+
import { atomicWriteFileSync } from "../../fs-atomic.ts";
+/** Bounded-retry budget for the registry lock: 10 x 50ms ~ 500ms. */
+const LOCK_MAX_ATTEMPTS = 10;
+const LOCK_RETRY_MS = 50;
+const LOCK_STALE_MS = 10_000;
+
export interface VaultProfile {
readonly name: string;
readonly vault: string;
@@ -95,14 +102,77 @@ export function listProfiles(configPath: string): ProfilesListing {
return { profiles, active: data.active };
}
-/** Create (or update) a named profile pointing at a vault path. */
+/**
+ * Create a named profile pointing at a vault path.
+ *
+ * Refuses three things it used to accept:
+ *
+ * - an existing name. The assignment was a silent overwrite, so a typo'd
+ * `create` retargeted a live profile and the old path was gone with no
+ * record of it. Renaming or repointing is a deliberate act, not a
+ * side effect of `create`.
+ * - a target that is not a directory, with the same error shape
+ * {@link switchProfile} already uses. Checking only at switch time let
+ * a mistyped path sit in the registry until activation.
+ * - an unserialized mutation. Load-mutate-save over one JSON file loses
+ * an update when two processes (CLI plus MCP server, two agents)
+ * create at once, and the loser vanishes without an error.
+ *
+ * The exclusivity check is inside the lock, so it is a decision on the
+ * same bytes that are written back rather than a TOCTOU read.
+ */
export function createProfile(configPath: string, name: string, vault: string): void {
const trimmed = name.trim();
if (trimmed.length === 0) throw new Error("profile name must not be empty");
- if (vault.trim().length === 0) throw new Error("profile vault must not be empty");
- const data = load(configPath);
- data.profiles[trimmed] = { vault: vault.trim() };
- save(configPath, data);
+ const trimmedVault = vault.trim();
+ if (trimmedVault.length === 0) throw new Error("profile vault must not be empty");
+ assertVaultDirectory(trimmed, trimmedVault);
+
+ withRegistryLock(configPath, () => {
+ const data = load(configPath);
+ if (Object.hasOwn(data.profiles, trimmed)) {
+ throw new Error(`profile '${trimmed}' already exists`);
+ }
+ data.profiles[trimmed] = { vault: trimmedVault };
+ save(configPath, data);
+ });
+}
+
+/**
+ * Serialize a registry mutation on the directory that holds it - the same
+ * bounded-retry sync lock `resolveDeviceId` and the log writer take on
+ * their own directories. `proper-lockfile`'s sync API refuses the
+ * `retries` option, so the loop is spelled out; a lock still busy after
+ * the budget surfaces as ELOCKED rather than a lost update.
+ */
+function withRegistryLock<T>(configPath: string, mutate: () => T): T {
+ const dir = dirname(profilesPath(configPath));
+ mkdirSync(dir, { recursive: true });
+ let release: (() => void) | undefined;
+ let lastError: unknown;
+ for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt++) {
+ try {
+ release = lockfile.lockSync(dir, { stale: LOCK_STALE_MS, realpath: false });
+ break;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ELOCKED") throw err;
+ lastError = err;
+ if (attempt < LOCK_MAX_ATTEMPTS - 1) Bun.sleepSync(LOCK_RETRY_MS);
+ }
+ }
+ if (!release) throw lastError;
+ try {
+ return mutate();
+ } finally {
+ release();
+ }
+}
+
+/** Shared by create and switch so both refuse a bad target identically. */
+function assertVaultDirectory(name: string, vault: string): void {
+ if (!isDirectory(vault)) {
+ throw new Error(`profile '${name}' points at a path that is not a directory: ${vault}`);
+ }
}
/**
@@ -118,16 +188,16 @@ export function createProfile(configPath: string, name: string, vault: string):
* read-only and never throws.
*/
export function switchProfile(configPath: string, name: string): void {
- const data = load(configPath);
- const profile = data.profiles[name];
- if (!profile) {
- throw new Error(`unknown profile '${name}'`);
- }
- if (!isDirectory(profile.vault)) {
- throw new Error(`profile '${name}' points at a path that is not a directory: ${profile.vault}`);
- }
- data.active = name;
- save(configPath, data);
+ withRegistryLock(configPath, () => {
+ const data = load(configPath);
+ const profile = data.profiles[name];
+ if (!profile) {
+ throw new Error(`unknown profile '${name}'`);
+ }
+ assertVaultDirectory(name, profile.vault);
+ data.active = name;
+ save(configPath, data);
+ });
}
/** True when `path` exists and is a directory. Never throws. */
diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.ts
index b82ffab8..87e36d8a 100644
--- a/src/core/brain/procedural-memory.ts
+++ b/src/core/brain/procedural-memory.ts
@@ -81,14 +81,19 @@ export function listProceduralMemory(vault: string): ReadonlyArray<ProceduralMem
entries?: Array<ProceduralMemoryEntry>;
};
if (!Array.isArray(parsed.entries)) return Object.freeze([]);
- // Normalize additive outcome fields so a pre-outcome index (written
- // before t_703f7b18) reads with defaults instead of `undefined`.
+ // Normalize additive fields so an older index reads with defaults
+ // instead of `undefined`: the outcome counters (pre-t_703f7b18) and the
+ // four contract lists (pre no-dead-ends Unit I).
return Object.freeze(
parsed.entries.map((entry) =>
Object.freeze({
...entry,
successCount: typeof entry.successCount === "number" ? entry.successCount : 0,
failureCount: typeof entry.failureCount === "number" ? entry.failureCount : 0,
+ prerequisites: asStringArray(entry.prerequisites),
+ rollback: asStringArray(entry.rollback),
+ sideEffects: asStringArray(entry.sideEffects),
+ verification: asStringArray(entry.verification),
}),
),
);
@@ -222,7 +227,7 @@ function collectEntries(vault: string, roots: ReadonlyArray<string>): Procedural
const [fm, body] = parseFrontmatter(filePath);
const title = extractTitle(body, rel);
- const id = entryId(rel);
+ const id = proceduralEntryId(rel);
out.push({
id,
kind: detectedKind,
@@ -237,6 +242,14 @@ function collectEntries(vault: string, roots: ReadonlyArray<string>): Procedural
usedCount: 0,
successCount: 0,
failureCount: 0,
+ // Execution contract (no-dead-ends, Unit I). Same reader as the
+ // trigger/tag/permission lists above: absent frontmatter is an
+ // empty list, so a procedure written before the contract existed
+ // reads exactly as it did.
+ prerequisites: asStringArray(fm["prerequisites"]),
+ rollback: asStringArray(fm["rollback"]),
+ sideEffects: asStringArray(fm["side_effects"]),
+ verification: asStringArray(fm["verification"]),
});
}
}
@@ -293,7 +306,14 @@ function toVaultRelative(vault: string, absPath: string): string {
return rel;
}
-function entryId(sourcePath: string): string {
+/**
+ * Join key of a procedural-memory entry: `pmem-` plus the first 12 hex of
+ * the sha256 of its VAULT-RELATIVE source path. Pure and lookup-free, so a
+ * caller that knows a procedure's path (the skill-proposal accept path
+ * knows it from the slug) can address its outcome record without reading
+ * the index.
+ */
+export function proceduralEntryId(sourcePath: string): string {
const hash = createHash("sha256").update(sourcePath, "utf8").digest("hex").slice(0, 12);
return `pmem-${hash}`;
}
diff --git a/src/core/brain/runtime-notices.ts b/src/core/brain/runtime-notices.ts
index 2309f234..25a06214 100644
--- a/src/core/brain/runtime-notices.ts
+++ b/src/core/brain/runtime-notices.ts
@@ -14,6 +14,15 @@
* none and the injected context stays byte-identical. Scope is OSB's own
* subsystems (embeddings/index availability, read-only mode); it is not a
* third-party plugin notice bus and does not classify quota errors.
+ *
+ * The command a notice points at is a FIELD, not a sentence (no-dead-ends,
+ * task 3). It is resolved strictly through `next-step.ts`, so a condition
+ * whose code has no registered exit carries no key at all rather than a
+ * plausible command invented to make the shape uniform; four of the six
+ * conditions below are in exactly that position and say why at their own
+ * site. {@link renderRuntimeNotices} is the single place the command is
+ * rendered back into prose, for the two human surfaces (the SessionStart
+ * injection and the onboarding checklist) that share it.
*/
import { existsSync } from "node:fs";
@@ -23,18 +32,35 @@ import lockfile from "proper-lockfile";
import { resolveSearchConfig } from "../search/index.ts";
import { checkVaultWriteable } from "../doctor.ts";
+import { NEXT_COMMAND_KEY, nextCommandField, type NextCommandField } from "./next-step.ts";
import { BRAIN_ROOT_REL } from "./paths.ts";
import { brainConfigReadFailure } from "./policy.ts";
import { vaultMarkerAbsentNotice } from "./vault-identity.ts";
export type RuntimeNoticeSeverity = "info" | "warning";
-export interface RuntimeNotice {
+/**
+ * One transient condition. The optional next command is spelled with the
+ * shared machine-readable key rather than a camel-cased twin because this
+ * record IS the wire shape on two surfaces - `o2b onboarding --json`
+ * serializes it whole, and `vault_health` projects it field for field - so
+ * a second spelling would be a second contract.
+ */
+export interface RuntimeNotice extends NextCommandField {
readonly code: string;
readonly severity: RuntimeNoticeSeverity;
readonly message: string;
}
+/**
+ * Build one notice, resolving its next command from the diagnostics
+ * registry. Strict resolution: an unregistered code contributes no key,
+ * so the absence is visible instead of guessed at.
+ */
+function notice(code: string, severity: RuntimeNoticeSeverity, message: string): RuntimeNotice {
+ return { code, severity, message, ...nextCommandField(code) };
+}
+
export interface RuntimeNoticeOptions {
readonly configPath?: string;
readonly env?: Record<string, string | undefined>;
@@ -57,14 +83,22 @@ export function collectRuntimeNotices(
const notices: RuntimeNotice[] = [];
// Vault writability: a read-only vault means every memory write will fail.
+ //
+ // No registered command: the two exits are an OS permission change on
+ // this root and a different `VAULT_DIR`, neither of them an `o2b` verb,
+ // and which one is right depends on which vault the operator meant. The
+ // message names both branches; the field stays absent rather than
+ // picking one.
try {
const writeable = checkVaultWriteable(vault);
if (!writeable.ok) {
- notices.push({
- code: "vault_read_only",
- severity: "warning",
- message: `Vault is not writable, so memory writes will fail (${writeable.message}). Fix permissions on ${vault} or point VAULT_DIR at a writable vault.`,
- });
+ notices.push(
+ notice(
+ "vault_read_only",
+ "warning",
+ `Vault is not writable, so memory writes will fail (${writeable.message}). Fix permissions on ${vault} or point VAULT_DIR at a writable vault.`,
+ ),
+ );
}
} catch {
// best-effort
@@ -76,15 +110,21 @@ export function collectRuntimeNotices(
// existing, because a root nothing has written to yet is not a wrong
// store - it is a vault waiting for `o2b brain init`, and nagging before
// that command runs would make the notice noise instead of signal.
+ //
+ // No registered command, and this one is the reason the field is
+ // optional rather than uniform. An absent marker is ambiguous BY
+ // CONSTRUCTION: `vault-identity.ts` documents that a cold-start
+ // mis-resolution - a typo in `VAULT_DIR` - is indistinguishable from
+ // the intended vault, because nothing durable records which vault the
+ // process meant. `o2b brain init` is the exit for one reading and
+ // materializes the wrong store under the other, so the conditional
+ // sentence the guard already writes ("...if it is the intended vault")
+ // is the honest form and a structural command would not be.
try {
if (existsSync(join(vault, BRAIN_ROOT_REL))) {
const absent = vaultMarkerAbsentNotice(vault);
if (absent !== null) {
- notices.push({
- code: "vault_marker_absent",
- severity: "warning",
- message: `${absent.detail} (${absent.path})`,
- });
+ notices.push(notice("vault_marker_absent", "warning", `${absent.detail} (${absent.path})`));
}
}
} catch {
@@ -96,14 +136,21 @@ export function collectRuntimeNotices(
// one rather than the defaults. Either way the operator's settings are
// not the ones in force, so the condition has to be visible instead of
// inferable from a gate that suddenly refuses.
+ //
+ // No registered command: the repair is an edit to the YAML the parser
+ // just rejected, and no `o2b` verb performs it. The failure detail below
+ // is what the operator acts on; `o2b brain doctor` would only re-report
+ // the same line, which is a round-trip, not an exit.
try {
const failure = brainConfigReadFailure(vault);
if (failure !== null) {
- notices.push({
- code: "brain_config_unreadable",
- severity: "warning",
- message: `Brain/_brain.yaml could not be read, so configured settings are not in force and the integrity gates fall back to their strictest mode (${failure}). Fix the file, then re-run.`,
- });
+ notices.push(
+ notice(
+ "brain_config_unreadable",
+ "warning",
+ `Brain/_brain.yaml could not be read, so configured settings are not in force and the integrity gates fall back to their strictest mode (${failure}). Fix the file, then re-run.`,
+ ),
+ );
}
} catch {
// best-effort
@@ -116,28 +163,43 @@ export function collectRuntimeNotices(
const indexExists = existsSync(dbPath);
if (!indexExists) {
- notices.push({
- code: "search_index_missing",
- severity: "info",
- message: "Search index is not built yet, so recall returns nothing. Run: o2b search index",
- });
+ // The read path self-heals: `openReadOrSelfHeal` catches
+ // INDEX_MISSING, builds the index and retries, so recall does not
+ // come back empty - it comes back late. The notice said the
+ // opposite until no-dead-ends (task 3) corrected it; what the
+ // command buys is paying that build now rather than on the first
+ // query.
+ notices.push(
+ notice(
+ "search_index_missing",
+ "info",
+ "Search index is not built yet, so the first recall builds it before returning " +
+ "(that call pays the full index build).",
+ ),
+ );
} else if (reindexInProgress(dbPath)) {
- notices.push({
- code: "reindex_in_progress",
- severity: "info",
- message: "Search index is rebuilding; recent recall results may lag until it completes.",
- });
+ // No registered command: the condition clears itself when the
+ // running rebuild finishes, and nothing an operator can type makes
+ // it clear sooner.
+ notices.push(
+ notice(
+ "reindex_in_progress",
+ "info",
+ "Search index is rebuilding; recent recall results may lag until it completes.",
+ ),
+ );
}
const semantic = config.semantic;
const networked = semantic.provider !== "local" && semantic.provider !== "disabled";
if (semantic.enabled && networked && !semantic.apiKey) {
- notices.push({
- code: "semantic_degraded",
- severity: "warning",
- message:
- "Semantic search is enabled but no embedding key resolved, so search has fallen back to lexical. Run: o2b search check",
- });
+ notices.push(
+ notice(
+ "semantic_degraded",
+ "warning",
+ "Semantic search is enabled but no embedding key resolved, so search has fallen back to lexical.",
+ ),
+ );
}
} catch {
// best-effort
@@ -159,9 +221,32 @@ function reindexInProgress(dbPath: string): boolean {
}
}
-/** Render notices as a compact injectable block; empty string when clean. */
+/**
+ * Label the command is rendered behind on the human surfaces. The
+ * spelling is the one the prose used to carry, so a notice whose text did
+ * not change renders byte-for-byte what it rendered when the command was
+ * part of the sentence - which matters because this block lands in an
+ * agent's SessionStart context, not only in a terminal.
+ */
+const COMMAND_LABEL = "Run:";
+
+/** The ` Run: <command>` tail, or nothing when the code has no exit. */
+function commandTail(entry: RuntimeNotice): string {
+ const command = entry[NEXT_COMMAND_KEY];
+ return command === undefined ? "" : ` ${COMMAND_LABEL} ${command}`;
+}
+
+/**
+ * Render notices as a compact injectable block; empty string when clean.
+ *
+ * This is the ONE place a structured command becomes prose again. Both
+ * human surfaces - the SessionStart injection and the onboarding
+ * checklist - render through here, so the machine-readable field and the
+ * sentence a person reads cannot drift apart the way two hand-written
+ * copies did.
+ */
export function renderRuntimeNotices(notices: ReadonlyArray<RuntimeNotice>): string {
if (notices.length === 0) return "";
- const lines = notices.map((n) => `- [${n.severity}] ${n.message}`);
+ const lines = notices.map((n) => `- [${n.severity}] ${n.message}${commandTail(n)}`);
return `Runtime notices:\n${lines.join("\n")}`;
}
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index e7e2ce1a..26efe3c2 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -6,6 +6,7 @@ import { appendLogEvent } from "./log.ts";
import { brainDirsForWrite } from "./paths.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";
+import { emitIngestDedupReport } from "./dedup-telemetry.ts";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";
import { writeSignal } from "./signal.ts";
@@ -343,6 +344,20 @@ export async function captureSessionLifecycleEvent(
let logPath: string | undefined;
if (mayWrite && !opts.dryRun) {
logPath = appendLifecycleLog(vault, normalized, opts.agent, now, counters);
+ // Dedup observability (Unit F): persist the exact-hash drop counts
+ // this event produced, keyed by the session being re-ingested.
+ // Signals and facts are one count - both are items this event tried
+ // to ingest and dropped on a sha-256 collision.
+ emitIngestDedupReport(vault, {
+ surface: "session_lifecycle",
+ sources: [
+ {
+ ref: normalized.sessionId ?? UNKNOWN_SESSION_REF,
+ exactDeduped: counters.signals_deduped + counters.facts_deduped,
+ },
+ ],
+ createdAt: now.toISOString(),
+ });
}
const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "session-lifecycle"), {
@@ -647,8 +662,11 @@ function appendLifecycleLog(
}).logPath;
}
+/** Stand-in session identity when the host payload carries none. */
+const UNKNOWN_SESSION_REF = "unknown";
+
function sessionReference(payload: NormalizedPayload): string {
- return `session:${payload.sessionId ?? "unknown"}#${payload.event}`;
+ return `session:${payload.sessionId ?? UNKNOWN_SESSION_REF}#${payload.event}`;
}
function readNonEmptyString(value: unknown): string | undefined {
diff --git a/src/core/brain/session-summary.ts b/src/core/brain/session-summary.ts
index ca824710..7d25c097 100644
--- a/src/core/brain/session-summary.ts
+++ b/src/core/brain/session-summary.ts
@@ -15,12 +15,28 @@
* categories with a natural-language word list - that would break the
* language-agnostic guarantee. Absent agent extraction, no digest is
* written (no fabricated empty summary).
+ *
+ * Project scope. A digest may carry the `project` axis of the composite
+ * scope vocabulary (`src/core/scope-key.ts`), normalized by the SAME slug
+ * rule as the session axis and folded into the dedupe key through the
+ * canonical {@link compositeScopeKey}, so the same content under two
+ * projects is two digests. With the axis absent the key is byte-identical
+ * to the pre-project world - `compositeScopeKey` contributes the empty
+ * string - which is what keeps every digest already on disk deduping.
+ *
+ * NAMING CAUTION: this `project` is the retrieval/dedup scope axis that
+ * `brain_search` filters on as `project_scope`. It is NOT the unrelated
+ * `o2b brain project link|list|remove|status` verb, which links a code
+ * directory to its owning vault at the CONFIGURATION level. The two share
+ * a word and nothing else; do not wire one to the other.
*/
import { createHash } from "node:crypto";
+import { compositeScopeKey } from "../scope-key.ts";
import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+import { resolveSessionScope, SessionScopeError } from "./session-scope.ts";
export class SessionSummaryError extends Error {
constructor(message: string) {
@@ -40,6 +56,12 @@ export interface SessionSummaryInput {
readonly host?: string;
/** Turn ids the digest was distilled from; recorded as lineage edges. */
readonly sourceTurnIds?: ReadonlyArray<string>;
+ /**
+ * Raw project-scope value; normalized by the shared slug rule. A value
+ * with no alphanumeric is a caller error, never a silent drop to
+ * unscoped.
+ */
+ readonly project?: string;
readonly createdAt?: string;
}
@@ -52,10 +74,37 @@ export interface SessionSummaryDigest {
readonly nextSteps: ReadonlyArray<string>;
readonly createdAt: string;
readonly host?: string;
+ /** Normalized project-scope slug; absent when the digest is unscoped. */
+ readonly project?: string;
}
const KIND = "session_summary_digest";
+/** Name of the project axis, used in both the payload key and error text. */
+const PROJECT_FIELD = "project";
+
+/**
+ * Normalize a raw project value through the shared session-scope slug
+ * rule. Deliberately STRICT where {@link scopeFromFrontmatter} is
+ * tolerant: frontmatter is untrusted bulk input where an unusable value
+ * may contribute no scope, but this is an explicit caller argument, and
+ * silently normalizing it to "unscoped" would file the digest somewhere
+ * the caller never asked for.
+ */
+function normalizeProject(raw: string | undefined): string | undefined {
+ if (raw === undefined) return undefined;
+ try {
+ return resolveSessionScope(raw);
+ } catch (error) {
+ if (error instanceof SessionScopeError) {
+ throw new SessionSummaryError(
+ `session summary ${PROJECT_FIELD} requires at least one alphanumeric: ${JSON.stringify(raw)}`,
+ );
+ }
+ throw error;
+ }
+}
+
/**
* Validate the agent-supplied categories, dedupe by content hash, and
* append one digest record. Throws {@link SessionSummaryError} when
@@ -86,8 +135,16 @@ export function appendSessionSummary(
}
const host = input.host?.trim();
+ const project = normalizeProject(input.project);
const contentHash = hash(JSON.stringify([request ?? "", decisions, learnings, nextSteps]));
- const dedupeKey = [KIND, sessionId, contentHash].join(":");
+ // Canonical scope contribution: the empty string when the axis is
+ // absent, so an unscoped digest keys byte-identically to every digest
+ // written before the axis existed. A changed key would silently stop
+ // deduplicating the whole existing store.
+ const scopeKey = compositeScopeKey({ owner: null, session: null, project: project ?? null });
+ const dedupeKey = [KIND, sessionId, contentHash, ...(scopeKey.length > 0 ? [scopeKey] : [])].join(
+ ":",
+ );
const existing = findByDedupeKey(vault, dedupeKey);
if (existing !== null) return toDigest(existing);
@@ -104,6 +161,7 @@ export function appendSessionSummary(
learnings,
next_steps: nextSteps,
...(host !== undefined && host.length > 0 ? { host } : {}),
+ ...(project !== undefined ? { [PROJECT_FIELD]: project } : {}),
content_hash: contentHash,
dedupe_key: dedupeKey,
},
@@ -123,19 +181,33 @@ export function getSessionSummary(vault: string, sessionId: string): SessionSumm
export interface ListSessionSummariesOptions {
readonly sessionId?: string;
+ /** Raw project value; normalized by the same rule the write applies. */
+ readonly project?: string;
}
-/** All digests, oldest first; optionally scoped to one session. */
+/**
+ * All digests, oldest first; optionally scoped to one session and/or one
+ * project.
+ *
+ * The project filter is an exact match on the normalized slug, mirroring
+ * the sibling session filter. It deliberately does NOT use
+ * {@link scopeAxisReachable}: that helper governs RETRIEVAL, where an
+ * unscoped shared page must stay visible to every scoped request. This is
+ * an explicit narrowing of a list, so an unscoped digest is not in the
+ * asked-for project and is not returned.
+ */
export function listSessionSummaries(
vault: string,
opts: ListSessionSummariesOptions = {},
): ReadonlyArray<SessionSummaryDigest> {
const scope = opts.sessionId?.trim();
+ const project = normalizeProject(opts.project);
return Object.freeze(
sessionDigestRecords(vault)
.filter(
(record) => scope === undefined || String(record.payload["session_id"] ?? "") === scope,
)
+ .filter((record) => project === undefined || readProject(record.payload) === project)
.map(toDigest),
);
}
@@ -165,6 +237,7 @@ function buildSourceRefs(
function toDigest(record: ContinuityRecord): SessionSummaryDigest {
const payload = record.payload;
const host = typeof payload["host"] === "string" ? (payload["host"] as string) : undefined;
+ const project = readProject(payload);
return Object.freeze({
id: record.id,
sessionId: String(payload["session_id"] ?? ""),
@@ -174,9 +247,15 @@ function toDigest(record: ContinuityRecord): SessionSummaryDigest {
nextSteps: readList(payload["next_steps"]),
createdAt: record.createdAt,
...(host !== undefined ? { host } : {}),
+ ...(project !== undefined ? { [PROJECT_FIELD]: project } : {}),
});
}
+function readProject(payload: ContinuityRecord["payload"]): string | undefined {
+ const value = payload[PROJECT_FIELD];
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}
+
function findByDedupeKey(vault: string, dedupeKey: string): ContinuityRecord | null {
return (
listContinuityRecords(vault, { kind: KIND }).find(
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index f626a011..1ceb8f7c 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -45,6 +45,7 @@ import {
} from "./types.ts";
import { validateBrainFeedbackInput } from "./validate-feedback.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "../capture-boundary.ts";
+import { emitIngestDedupReport } from "../dedup-telemetry.ts";
import { extractFacts, routeExtractedFacts } from "../fact-extract.ts";
import { readLineageLedger } from "../lineage/ledger.ts";
import { resolveSessionLineage } from "../lineage/resolve.ts";
@@ -495,6 +496,18 @@ export async function importSession(
}
}
+ // Dedup observability (Unit F): one record per import run that actually
+ // dropped something, keyed by the portable session identity this import
+ // stamps on every signal it writes. A dry run reports its count and
+ // writes nothing.
+ if (opts.dryRun !== true) {
+ emitIngestDedupReport(vault, {
+ surface: "session_import",
+ sources: [{ ref: sessionKey, exactDeduped: signalsDeduped + factsDeduped }],
+ createdAt: now.toISOString(),
+ });
+ }
+
return Object.freeze({
file: absPath,
format: adapter.id,
diff --git a/src/core/brain/skill-accept-journal.ts b/src/core/brain/skill-accept-journal.ts
new file mode 100644
index 00000000..c644ef38
--- /dev/null
+++ b/src/core/brain/skill-accept-journal.ts
@@ -0,0 +1,218 @@
+/**
+ * Write-ahead journal for the skill-proposal accept sequence
+ * (no-dead-ends, Unit I).
+ *
+ * Accepting a proposal is four filesystem steps against three different
+ * trees: write the accepted archive, materialize the procedure, remove the
+ * pending copy, rebuild the procedural projections. Each individual write
+ * is already atomic and exclusive (`writeFrontmatterAtomic` over
+ * `atomicCreateFileSyncExclusive`), so the risk is never a torn file - it
+ * is a process that stops BETWEEN two of those steps and leaves a
+ * duplicate (pending plus accepted), an orphan (an accepted archive with
+ * no procedure) or a stale projection.
+ *
+ * An exception can be compensated in a `catch`; a crash cannot. So the
+ * sequence records its intent here BEFORE each step, and the next accept
+ * resolves whatever it finds. The journal states the step the writer was
+ * ABOUT to perform, never the one it completed - that is what makes a
+ * crash inside a step recoverable:
+ *
+ * - `archive` - about to write the accepted archive
+ * - `materialize` - about to write the procedure
+ * - `commit` - about to remove the pending copy, then reproject
+ *
+ * `acceptedExisted` / `procedureExisted` are captured before the sequence
+ * starts so a rollback never deletes a file the sequence did not create.
+ *
+ * The journal is a repair marker, not history: it is removed as soon as
+ * the sequence completes or is resolved. A journal left on disk means a
+ * sequence is still outstanding.
+ *
+ * A marker that cannot be READ is a third state, and it used to be a dead
+ * end: the sweep runs before every accept, so one unparseable file blocked
+ * the verb permanently and the refusal named no way out. There are now two
+ * readers - {@link readSkillAcceptJournals}, which reports unreadable
+ * markers as data for the diagnosis surface, and
+ * {@link listSkillAcceptJournals}, which still refuses, now by name and
+ * naming the command that clears them.
+ */
+
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import { requireNextStep } from "./next-step.ts";
+import { BRAIN_SKILL_ACCEPT_JOURNAL_REL, skillAcceptJournalPath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+/** Step the accept sequence was about to perform when the journal was stamped. */
+export type SkillAcceptPhase = "archive" | "materialize" | "commit";
+
+export interface SkillAcceptJournalEntry {
+ readonly slug: string;
+ readonly id: string;
+ readonly phase: SkillAcceptPhase;
+ readonly startedAt: string;
+ /** The accepted archive was already on disk before the sequence started. */
+ readonly acceptedExisted: boolean;
+ /** The procedure file was already on disk before the sequence started. */
+ readonly procedureExisted: boolean;
+}
+
+const JOURNAL_SCHEMA_VERSION = 1;
+const JOURNAL_SUFFIX = ".json";
+const PHASES: ReadonlySet<string> = new Set<SkillAcceptPhase>(["archive", "materialize", "commit"]);
+
+/** Stamp (or re-stamp) the journal for `entry.slug`. Overwrites by design. */
+export function writeSkillAcceptJournal(vault: string, entry: SkillAcceptJournalEntry): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const path = skillAcceptJournalPath(vault, entry.slug);
+ mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ const payload = {
+ schema_version: JOURNAL_SCHEMA_VERSION,
+ slug: entry.slug,
+ id: entry.id,
+ phase: entry.phase,
+ started_at: entry.startedAt,
+ accepted_existed: entry.acceptedExisted,
+ procedure_existed: entry.procedureExisted,
+ };
+ atomicWriteFileSync(path, `${JSON.stringify(payload, null, 2)}\n`);
+}
+
+/**
+ * Remove one marker file by path. Idempotent, vault-guarded and confined
+ * to the vault. Exists for the unreadable case, where the slug cannot be
+ * trusted to come from the file's own contents.
+ */
+export function removeSkillAcceptJournalFile(vault: string, path: string): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ rmSync(ensureInsideVault(path, vault), { force: true });
+}
+
+/** Remove the journal for `slug`. Idempotent. */
+export function clearSkillAcceptJournal(vault: string, slug: string): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ rmSync(skillAcceptJournalPath(vault, slug), { force: true });
+}
+
+/** Registry code for a marker file this module cannot parse. */
+export const SKILL_ACCEPT_JOURNAL_UNREADABLE_CODE = "skill-accept-journal-unreadable";
+
+/**
+ * Resolved once, at module scope, so a registry that lost the entry fails
+ * at import rather than inside the very refusal it is meant to explain.
+ */
+const UNREADABLE_EXIT = requireNextStep(SKILL_ACCEPT_JOURNAL_UNREADABLE_CODE).nextCommand;
+
+/** One marker file on disk that cannot be parsed back into an entry. */
+export interface UnreadableSkillAcceptJournal {
+ readonly path: string;
+ /** Why it could not be read - a parse failure or a missing field. */
+ readonly detail: string;
+}
+
+/** Outstanding markers, split into the ones that read and the ones that do not. */
+export interface SkillAcceptJournalState {
+ readonly entries: ReadonlyArray<SkillAcceptJournalEntry>;
+ readonly unreadable: ReadonlyArray<UnreadableSkillAcceptJournal>;
+}
+
+/**
+ * A marker file that cannot be parsed back into a complete entry.
+ *
+ * The write is atomic, so this shape never comes from a torn write of
+ * ours - it arrives by hand edit, a sync merge or media damage, and it
+ * blocks every accept until it is gone. The message therefore names both
+ * the file and the command that removes it; without that the operator's
+ * only route was reading this module.
+ */
+export class SkillAcceptJournalUnreadableError extends Error {
+ readonly path: string;
+ readonly detail: string;
+ constructor(entry: UnreadableSkillAcceptJournal) {
+ super(
+ `skill accept journal is unreadable: ${entry.path} (${entry.detail}). ` +
+ `Every accept is blocked until it is resolved: ${UNREADABLE_EXIT}`,
+ );
+ this.name = "SkillAcceptJournalUnreadableError";
+ this.path = entry.path;
+ this.detail = entry.detail;
+ }
+}
+
+/**
+ * Every outstanding journal, slug-ordered, partitioned by whether it
+ * parses.
+ *
+ * This is the DIAGNOSIS surface: it reports an unreadable marker as data
+ * so an operator can be shown what is wrong and act on it. The transaction
+ * paths use {@link listSkillAcceptJournals} instead, which refuses - a
+ * writer must never mistake an unreadable marker for "no outstanding work".
+ */
+export function readSkillAcceptJournals(vault: string): SkillAcceptJournalState {
+ const dir = ensureInsideVault(join(vault, BRAIN_SKILL_ACCEPT_JOURNAL_REL), vault);
+ if (!existsSync(dir)) {
+ return Object.freeze({ entries: Object.freeze([]), unreadable: Object.freeze([]) });
+ }
+ const entries: SkillAcceptJournalEntry[] = [];
+ const unreadable: UnreadableSkillAcceptJournal[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(JOURNAL_SUFFIX)) continue;
+ const path = join(dir, name);
+ const parsed = parseJournal(path);
+ if ("detail" in parsed) unreadable.push(parsed);
+ else entries.push(parsed);
+ }
+ return Object.freeze({ entries: Object.freeze(entries), unreadable: Object.freeze(unreadable) });
+}
+
+/**
+ * Every outstanding journal, slug-ordered. A file this module cannot parse
+ * back into a complete entry is a defect, not a soft skip: it is reported
+ * by throwing {@link SkillAcceptJournalUnreadableError} so the caller
+ * cannot mistake an unreadable marker for "no outstanding work".
+ */
+export function listSkillAcceptJournals(vault: string): ReadonlyArray<SkillAcceptJournalEntry> {
+ const state = readSkillAcceptJournals(vault);
+ const first = state.unreadable[0];
+ if (first !== undefined) throw new SkillAcceptJournalUnreadableError(first);
+ return state.entries;
+}
+
+function parseJournal(path: string): SkillAcceptJournalEntry | UnreadableSkillAcceptJournal {
+ let raw: Record<string, unknown>;
+ try {
+ raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
+ } catch (cause) {
+ return Object.freeze({
+ path,
+ detail: cause instanceof Error ? cause.message : String(cause),
+ });
+ }
+ const slug = raw["slug"];
+ const id = raw["id"];
+ const phase = raw["phase"];
+ const startedAt = raw["started_at"];
+ if (
+ typeof slug !== "string" ||
+ typeof id !== "string" ||
+ typeof phase !== "string" ||
+ !PHASES.has(phase) ||
+ typeof startedAt !== "string"
+ ) {
+ return Object.freeze({ path, detail: "a required field is missing or of the wrong type" });
+ }
+ return Object.freeze({
+ slug,
+ id,
+ phase: phase as SkillAcceptPhase,
+ startedAt,
+ acceptedExisted: raw["accepted_existed"] === true,
+ procedureExisted: raw["procedure_existed"] === true,
+ });
+}
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index 9cc8c084..f7eec510 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -5,9 +5,10 @@ import {
mkdirSync,
readdirSync,
readFileSync,
+ rmSync,
unlinkSync,
} from "node:fs";
-import { basename, dirname, join } from "node:path";
+import { basename, dirname, join, relative } from "node:path";
import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
@@ -15,11 +16,27 @@ import { ensureInsideVault } from "../path-safety.ts";
import { verifySkillProposalCandidate } from "./skill-proposal-verifier.ts";
import { rebuildProceduralHints } from "./procedural-hints.ts";
import { rebuildProceduralGraph } from "./procedural-graph.ts";
-import { reconcileProceduralMemory } from "./procedural-memory.ts";
+import {
+ listProceduralMemory,
+ proceduralEntryId,
+ proceduralSuccessRate,
+ reconcileProceduralMemory,
+} from "./procedural-memory.ts";
+import { requireNextStep } from "./next-step.ts";
+import {
+ clearSkillAcceptJournal,
+ listSkillAcceptJournals,
+ readSkillAcceptJournals,
+ removeSkillAcceptJournalFile,
+ writeSkillAcceptJournal,
+ type SkillAcceptJournalEntry,
+} from "./skill-accept-journal.ts";
+import { acquireLockSync, type LockHandle } from "./sync-lockfile.ts";
import {
BRAIN_SKILL_PROPOSALS_REL,
procedurePath,
proposalWatermarkPath,
+ skillAcceptJournalPath,
skillProposalAcceptedPath,
skillProposalPendingPath,
skillProposalRejectedPath,
@@ -58,6 +75,70 @@ export interface SkillProposalReviewResult {
readonly procedurePath?: string;
}
+/**
+ * Execution contract supplied at acceptance (no-dead-ends, Unit I). Each
+ * field is a list of structural steps; an absent field writes no key, so a
+ * contract-free acceptance is byte-identical to the pre-contract output.
+ */
+export interface SkillContractInput {
+ readonly prerequisites?: ReadonlyArray<string>;
+ readonly rollback?: ReadonlyArray<string>;
+ readonly sideEffects?: ReadonlyArray<string>;
+ readonly verification?: ReadonlyArray<string>;
+}
+
+export interface SkillProposalAcceptOptions {
+ readonly now?: Date;
+ readonly note?: string;
+ readonly contract?: SkillContractInput;
+}
+
+/** Contract field name -> frontmatter key, in the order they are written. */
+const SKILL_CONTRACT_FIELDS = Object.freeze([
+ ["prerequisites", "prerequisites"],
+ ["rollback", "rollback"],
+ ["sideEffects", "side_effects"],
+ ["verification", "verification"],
+] as const);
+
+/** What a resolved journal did to the sequence it was guarding. */
+export type SkillAcceptRecoveryAction = "rolled_back" | "completed";
+
+export interface SkillAcceptRecovery {
+ readonly slug: string;
+ readonly action: SkillAcceptRecoveryAction;
+}
+
+/**
+ * How a proposal's self-reported support compares with the independently
+ * recorded procedural outcome ledger.
+ *
+ * `unrecorded` is NOT "no failures": it is the absence of evidence either
+ * way, which is why {@link SkillProposalEvidence.recordedSuccessRate} is
+ * null rather than zero in that state. Failures, successes and silence stay
+ * three distinct answers; `mixed` is the honest fourth.
+ */
+export type SkillEvidenceOutcomeState = "unrecorded" | "successful" | "failing" | "mixed";
+
+export interface SkillProposalEvidence {
+ readonly slug: string;
+ readonly id: string;
+ readonly phase: "pending" | "accepted" | "rejected";
+ /** Support the proposal claims from its own pattern match - self-reported. */
+ readonly claimedEvidenceCount: number;
+ readonly claimedConfidence: number;
+ /** Ledger join key, derived from the slug with no lookup. */
+ readonly proceduralEntryId: string;
+ /** False when the procedure has no procedural-memory entry at all. */
+ readonly proceduralEntryPresent: boolean;
+ /** Host-recorded outcomes; null when there is no entry to read them from. */
+ readonly recordedSuccesses: number | null;
+ readonly recordedFailures: number | null;
+ /** null whenever nothing was recorded - never 0, which reads as total failure. */
+ readonly recordedSuccessRate: number | null;
+ readonly outcomeState: SkillEvidenceOutcomeState;
+}
+
interface ProposalCandidate {
readonly patternKind: SkillProposalPatternKind;
readonly key: string;
@@ -84,6 +165,9 @@ const DEFAULT_PROCEDURAL_ROOTS = ["Brain/procedures", "skills"] as const;
/** Version stamped on a freshly-drafted skill; increments on evolution. */
const SKILL_PROPOSAL_INITIAL_VERSION = 1;
+/** Lock basename guarding the accept sequence, inside the proposals root. */
+const ACCEPT_LOCK_NAME = "accept";
+
/** JSONL ledger of verifier rejections, relative to the vault. */
const VERIFIER_REJECTION_LEDGER_REL = join(BRAIN_SKILL_PROPOSALS_REL, "verifier-rejections.jsonl");
@@ -269,85 +353,396 @@ export function listPendingSkillProposals(vault: string): ReadonlyArray<{
return Object.freeze(out);
}
+/**
+ * Accept a pending proposal: archive it, materialize its procedure, drop
+ * the pending copy, reproject.
+ *
+ * The four steps are one compensating transaction. Every step is preceded
+ * by a write-ahead journal stamp (see `skill-accept-journal.ts`), so a
+ * CRASH - which no `catch` can compensate - is resolved by the next accept
+ * or by {@link recoverSkillProposalAccepts}; a thrown error is compensated
+ * inline through the same resolver. Removing the pending copy is the
+ * commit point: before it the sequence rolls back to the pending draft,
+ * after it the sequence rolls forward to rebuilt projections.
+ *
+ * The whole sequence runs under one vault-wide accept lock. That lock is
+ * what makes the sweep of OTHER slugs' journals safe: no second accept can
+ * be mid-sequence while this one resolves what it finds.
+ */
export function acceptSkillProposal(
vault: string,
slug: string,
- opts: { now?: Date; note?: string } = {},
+ opts: SkillProposalAcceptOptions = {},
): SkillProposalReviewResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
+ // Validated before anything touches disk: a malformed contract must not
+ // half-accept a proposal.
+ const contract = contractFrontmatter(opts.contract);
const now = (opts.now ?? new Date()).toISOString();
- const pendingPath = skillProposalPendingPath(vault, slug);
- if (!existsSync(pendingPath)) {
- throw new Error(`pending skill proposal not found: ${slug}`);
- }
- const [fm, body] = parseFrontmatter(pendingPath);
- if (fm["kind"] !== "brain-skill-proposal") {
- throw new Error(`invalid skill proposal file: ${pendingPath}`);
- }
- const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
- const version = parseVersion(fm["version"]);
- const acceptedPath = skillProposalAcceptedPath(vault, slug);
- const procPath = procedurePath(vault, slug);
+ const lock = acquireAcceptLock(vault);
+ try {
+ resolveOutstandingAccepts(vault);
- writeFrontmatterAtomic(
- acceptedPath,
- {
- ...fm,
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ if (!existsSync(pendingPath)) {
+ throw new Error(`pending skill proposal not found: ${slug}`);
+ }
+
+ const [fm, body] = parseFrontmatter(pendingPath);
+ if (fm["kind"] !== "brain-skill-proposal") {
+ throw new Error(`invalid skill proposal file: ${pendingPath}`);
+ }
+ const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
+ const version = parseVersion(fm["version"]);
+ const acceptedPath = skillProposalAcceptedPath(vault, slug);
+ const procPath = procedurePath(vault, slug);
+
+ let journal: SkillAcceptJournalEntry = {
+ slug,
+ id,
+ phase: "archive",
+ startedAt: now,
+ // Captured up front so a rollback never deletes a file this
+ // sequence did not create.
+ acceptedExisted: existsSync(acceptedPath),
+ procedureExisted: existsSync(procPath),
+ };
+ writeSkillAcceptJournal(vault, journal);
+
+ try {
+ writeFrontmatterAtomic(
+ acceptedPath,
+ {
+ ...fm,
+ status: "accepted",
+ version,
+ reviewed_at: now,
+ updated_at: now,
+ ...(opts.note ? { review_note: opts.note } : {}),
+ ...contract,
+ },
+ body,
+ {
+ overwrite: false,
+ existsErrorKind: "accepted skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ journal = { ...journal, phase: "materialize" };
+ writeSkillAcceptJournal(vault, journal);
+ writeFrontmatterAtomic(
+ procPath,
+ {
+ schema_version: 1,
+ kind: "brain-procedure",
+ id: `proc-${slug}`,
+ slug,
+ source_proposal: id,
+ version,
+ created_at: now,
+ updated_at: now,
+ status: "active",
+ ...contract,
+ },
+ renderAcceptedProcedureBody(id, body),
+ {
+ overwrite: false,
+ existsErrorKind: "procedure",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ journal = { ...journal, phase: "commit" };
+ writeSkillAcceptJournal(vault, journal);
+ unlinkSync(pendingPath);
+ rebuildProceduralProjections(vault);
+ } catch (error) {
+ compensateSkillAccept(vault, journal, error);
+ }
+
+ clearSkillAcceptJournal(vault, slug);
+ return {
+ id,
+ slug,
status: "accepted",
- version,
- reviewed_at: now,
- updated_at: now,
- ...(opts.note ? { review_note: opts.note } : {}),
- },
- body,
- {
- overwrite: false,
- existsErrorKind: "accepted skill proposal",
- vaultForRelativePath: vault,
- },
- );
+ proposalPath: acceptedPath,
+ procedurePath: procPath,
+ };
+ } finally {
+ lock.release();
+ }
+}
+/**
+ * Resolve every accept sequence a previous run abandoned. Returns what was
+ * done per slug; an empty array means there was nothing outstanding.
+ *
+ * This is the operator surface for a journal a crash left behind, reached
+ * through `o2b brain skill-proposals recover`. It refuses, by name, on the
+ * two states it must not paper over: a held lock
+ * ({@link SkillAcceptLockedError}) and an unreadable marker
+ * (`SkillAcceptJournalUnreadableError`).
+ */
+export function recoverSkillProposalAccepts(vault: string): ReadonlyArray<SkillAcceptRecovery> {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const lock = acquireAcceptLock(vault);
try {
- writeFrontmatterAtomic(
- procPath,
- {
- schema_version: 1,
- kind: "brain-procedure",
- id: `proc-${slug}`,
- slug,
- source_proposal: id,
- version,
- created_at: now,
- updated_at: now,
- status: "active",
- },
- renderAcceptedProcedureBody(id, body),
- {
- overwrite: false,
- existsErrorKind: "procedure",
- vaultForRelativePath: vault,
- },
+ return Object.freeze(resolveOutstandingAccepts(vault));
+ } finally {
+ lock.release();
+ }
+}
+
+/**
+ * Delete every accept-journal marker that cannot be parsed, returning the
+ * paths removed in the order they were found.
+ *
+ * This is the ONE mechanical exit in this pair, and it is deliberately not
+ * automatic: it runs when an operator asks for it, never inside an accept.
+ * What it gives up is stated rather than hidden - an unreadable marker
+ * names no phase, so the sequence it marked cannot be rolled back or
+ * forward, and removing it unblocks accepting without claiming that
+ * sequence was resolved. The marker's own contents are the only thing lost;
+ * every artifact the sequence may have written is still on disk, where
+ * `o2b brain doctor` reports duplicates and orphans.
+ */
+export function discardUnreadableSkillAcceptJournals(vault: string): ReadonlyArray<string> {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const lock = acquireAcceptLock(vault);
+ try {
+ const discarded = readSkillAcceptJournals(vault).unreadable.map((entry) => entry.path);
+ for (const path of discarded) removeSkillAcceptJournalFile(vault, path);
+ return Object.freeze(discarded);
+ } finally {
+ lock.release();
+ }
+}
+
+/** Registry code for the refusal a held accept lock produces. */
+export const SKILL_ACCEPT_LOCKED_CODE = "skill-accept-locked";
+
+/**
+ * Resolved at module scope so a registry that lost the entry fails at
+ * import rather than inside the refusal it is meant to explain.
+ */
+const LOCKED_EXIT = requireNextStep(SKILL_ACCEPT_LOCKED_CODE).nextCommand;
+
+/**
+ * The accept lock was already held.
+ *
+ * Deliberately NOT a breaker. The lock primitive is a single-attempt
+ * exclusive create, so no timeout distinguishes a crashed writer from a
+ * live one, and removing a live writer's lock corrupts what it protects -
+ * the same reason `applier-capability.ts` refuses `stale-lock`. What
+ * changes here is that the refusal names the exact file to judge and the
+ * command that lists every lock under the Brain tree, instead of leaving
+ * an `ELOCKED` errno for the operator to trace back to a path.
+ */
+export class SkillAcceptLockedError extends Error {
+ readonly path: string;
+ constructor(path: string, options?: { readonly cause?: unknown }) {
+ super(
+ `skill-proposal accept is locked by ${path}; every accept is refused while it is held. ` +
+ "Nothing breaks it automatically - a live writer cannot be told from a crashed one - " +
+ `so confirm no process owns it, then remove that file by hand: ${LOCKED_EXIT}`,
+ options,
);
+ this.name = "SkillAcceptLockedError";
+ this.path = path;
+ }
+}
+
+/** Path of the lock guarding the accept sequence and the journal sweep. */
+export function skillAcceptLockPath(vault: string): string {
+ return `${acceptLockTarget(vault)}.lock`;
+}
+
+/**
+ * Take the accept lock, mapping the primitive's `ELOCKED` errno onto the
+ * named refusal. One wrapper for all three entry points, so an operator
+ * meets the same message whichever one they reached.
+ */
+function acquireAcceptLock(vault: string): LockHandle {
+ try {
+ return acquireLockSync(acceptLockTarget(vault));
} catch (error) {
- if (existsSync(acceptedPath)) unlinkSync(acceptedPath);
+ if ((error as NodeJS.ErrnoException).code === "ELOCKED") {
+ throw new SkillAcceptLockedError(skillAcceptLockPath(vault), { cause: error });
+ }
throw error;
}
+}
- unlinkSync(pendingPath);
+/** Lock target guarding the accept sequence and the journal sweep. */
+function acceptLockTarget(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REL, ACCEPT_LOCK_NAME), vault);
+}
+
+/** Caller must already hold {@link acceptLockTarget}. */
+function resolveOutstandingAccepts(vault: string): SkillAcceptRecovery[] {
+ return listSkillAcceptJournals(vault).map((journal) => ({
+ slug: journal.slug,
+ action: resolveSkillAccept(vault, journal),
+ }));
+}
+
+/**
+ * Roll one journaled sequence back or forward.
+ *
+ * The pending copy is the commit witness: the sequence removes it only
+ * once both writes have landed, so its presence means nothing was
+ * committed and the draft must survive untouched.
+ */
+function resolveSkillAccept(
+ vault: string,
+ journal: SkillAcceptJournalEntry,
+): SkillAcceptRecoveryAction {
+ const committed =
+ journal.phase === "commit" && !existsSync(skillProposalPendingPath(vault, journal.slug));
+
+ if (!committed) {
+ if (!journal.acceptedExisted) {
+ rmSync(skillProposalAcceptedPath(vault, journal.slug), { force: true });
+ }
+ if (!journal.procedureExisted) {
+ rmSync(procedurePath(vault, journal.slug), { force: true });
+ }
+ clearSkillAcceptJournal(vault, journal.slug);
+ return "rolled_back";
+ }
+
+ rebuildProceduralProjections(vault);
+ clearSkillAcceptJournal(vault, journal.slug);
+ return "completed";
+}
+
+/**
+ * Inline compensation for a THROWN step. Always rethrows: either the
+ * original error once the sequence has been resolved, or - when the
+ * resolution itself fails - a named error saying the journal was retained
+ * so a later recovery pass can finish the job.
+ */
+function compensateSkillAccept(
+ vault: string,
+ journal: SkillAcceptJournalEntry,
+ error: unknown,
+): never {
+ let repairFailure: unknown = null;
+ try {
+ resolveSkillAccept(vault, journal);
+ } catch (repairError) {
+ repairFailure = repairError;
+ }
+ if (repairFailure !== null) {
+ // The step failure stays the `cause`; the repair failure is named in
+ // the message, and the journal on disk keeps the sequence recoverable.
+ throw new Error(
+ `skill proposal accept failed and could not be resolved (${errorMessage(repairFailure)}); ` +
+ `journal retained for recovery: ${skillAcceptJournalPath(vault, journal.slug)}`,
+ { cause: error },
+ );
+ }
+ throw error;
+}
+
+function errorMessage(value: unknown): string {
+ return value instanceof Error ? value.message : String(value);
+}
+
+/** Rebuild the three projections derived from the procedure tree. */
+function rebuildProceduralProjections(vault: string): void {
reconcileProceduralMemory(vault, {
roots: DEFAULT_PROCEDURAL_ROOTS.map((root) => join(vault, root)),
});
const graph = rebuildProceduralGraph(vault);
rebuildProceduralHints(vault, { graph });
- return {
- id,
+}
+
+/**
+ * Frontmatter fragment for the execution contract. An absent or empty
+ * field writes no key; a field holding a blank or non-string entry is a
+ * caller error and is refused by name rather than quietly dropped.
+ */
+function contractFrontmatter(
+ contract: SkillContractInput | undefined,
+): Record<string, ReadonlyArray<string>> {
+ if (!contract) return {};
+ const out: Record<string, ReadonlyArray<string>> = {};
+ for (const [field, key] of SKILL_CONTRACT_FIELDS) {
+ const values = contract[field];
+ if (values === undefined || values.length === 0) continue;
+ out[key] = values.map((value) => {
+ if (typeof value !== "string" || value.trim().length === 0) {
+ throw new Error(`skill contract field '${field}' must not contain an empty entry`);
+ }
+ return value.trim();
+ });
+ }
+ return out;
+}
+
+/**
+ * Resolve a proposal's SELF-REPORTED support against the independently
+ * recorded procedural outcome ledger.
+ *
+ * `evidence_count` and `confidence` come from the proposal's own pattern
+ * match, so on their own they corroborate nothing. The ledger written by
+ * `recordProceduralOutcome` is host-supplied and never inferred, and it is
+ * joined here by the entry id derived from the procedure path the accept
+ * path already causes to exist - no lookup table, no second registry.
+ */
+export function resolveSkillProposalEvidence(vault: string, slug: string): SkillProposalEvidence {
+ const found = findReviewedProposal(vault, slug);
+ const fm = found.fm;
+ const entryId = proceduralEntryId(vaultRelative(vault, procedurePath(vault, slug)));
+ const entry = listProceduralMemory(vault).find((candidate) => candidate.id === entryId) ?? null;
+
+ return Object.freeze({
slug,
- status: "accepted",
- proposalPath: acceptedPath,
- procedurePath: procPath,
- };
+ id: typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`,
+ phase: found.phase,
+ claimedEvidenceCount: Number.parseInt(String(fm["evidence_count"] ?? "0"), 10) || 0,
+ claimedConfidence: Number.parseFloat(String(fm["confidence"] ?? "0")) || 0,
+ proceduralEntryId: entryId,
+ proceduralEntryPresent: entry !== null,
+ recordedSuccesses: entry?.successCount ?? null,
+ recordedFailures: entry?.failureCount ?? null,
+ recordedSuccessRate: entry === null ? null : proceduralSuccessRate(entry),
+ outcomeState: outcomeState(entry?.successCount ?? 0, entry?.failureCount ?? 0),
+ });
+}
+
+function outcomeState(successes: number, failures: number): SkillEvidenceOutcomeState {
+ if (successes === 0 && failures === 0) return "unrecorded";
+ if (successes > 0 && failures > 0) return "mixed";
+ return failures > 0 ? "failing" : "successful";
+}
+
+/** Locate a proposal in whichever phase holds it, terminal phases first. */
+function findReviewedProposal(
+ vault: string,
+ slug: string,
+): { phase: "pending" | "accepted" | "rejected"; fm: Record<string, unknown> } {
+ const candidates = [
+ ["accepted", skillProposalAcceptedPath(vault, slug)],
+ ["rejected", skillProposalRejectedPath(vault, slug)],
+ ["pending", skillProposalPendingPath(vault, slug)],
+ ] as const;
+ for (const [phase, path] of candidates) {
+ if (!existsSync(path)) continue;
+ const [fm] = parseFrontmatter(path);
+ return { phase, fm: fm as Record<string, unknown> };
+ }
+ throw new Error(`skill proposal not found in any phase: ${slug}`);
+}
+
+function vaultRelative(vault: string, absolute: string): string {
+ return relative(vault, absolute).replaceAll("\\", "/");
}
export function rejectSkillProposal(
@@ -392,11 +787,7 @@ export function rejectSkillProposal(
);
unlinkSync(pendingPath);
- reconcileProceduralMemory(vault, {
- roots: DEFAULT_PROCEDURAL_ROOTS.map((root) => join(vault, root)),
- });
- const graph = rebuildProceduralGraph(vault);
- rebuildProceduralHints(vault, { graph });
+ rebuildProceduralProjections(vault);
return { id, slug, status: "rejected", proposalPath: rejectedPath };
}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index a90011f6..bde2e470 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -1081,6 +1081,18 @@ export interface ProceduralMemoryEntry {
*/
readonly successCount: number;
readonly failureCount: number;
+ /**
+ * Execution contract read back from the procedure's frontmatter
+ * (no-dead-ends, Unit I). Written by the skill-proposal accept path and
+ * surfaced here so the four fields are a contract a caller can act on
+ * rather than decoration on a file nobody parses. Same shape and reader
+ * as {@link ProceduralMemoryEntry.triggers}: absent frontmatter reads as
+ * an empty list, so a pre-contract vault is unaffected.
+ */
+ readonly prerequisites: ReadonlyArray<string>;
+ readonly rollback: ReadonlyArray<string>;
+ readonly sideEffects: ReadonlyArray<string>;
+ readonly verification: ReadonlyArray<string>;
}
// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------
@@ -1747,6 +1759,25 @@ export interface DoctorIssue {
readonly path?: string;
/** Human-readable description, suitable for `--text` rendering. */
readonly message: string;
+ /**
+ * Frontmatter field the broken reference sits in (`broken-wikilink`).
+ *
+ * no-dead-ends, task 12. The field name and the target below used to
+ * exist only inside `message`, so an applier deciding prune-versus-
+ * review had to regex the sentence - which is how a detector and an
+ * applier come to disagree about what was detected. Both are optional
+ * because only the link codes carry them; every other issue is
+ * byte-identical to what it was.
+ */
+ readonly field?: string;
+ /** Wikilink target that resolves to nothing (`broken-wikilink`, `broken-backlinks`). */
+ readonly target?: string;
+ /**
+ * Basenames of the artifacts that reference {@link target}
+ * (`broken-backlinks`). The dangling target has no file, so the issue
+ * carries no `path`; these sources are what an operator can act on.
+ */
+ readonly sources?: ReadonlyArray<string>;
}
/**
diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.ts
index 4e008fb2..b4b1a4ed 100644
--- a/src/core/brain/upgrade.ts
+++ b/src/core/brain/upgrade.ts
@@ -24,7 +24,8 @@ import { sanitisePrinciple } from "./text/sanitize-principle.ts";
import { defaultConfigPath, resolveAgentName } from "../config.ts";
import { appendLogEvent } from "./log.ts";
import { brainConfigPath, brainManualPath, vaultRelative } from "./paths.ts";
-import { BrainConfigError, DEFAULT_BRAIN_CONFIG_YAML, loadBrainConfig } from "./policy.ts";
+import { BrainConfigError, loadBrainConfig } from "./policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";
import { createSnapshot } from "./snapshot.ts";
import { renderBrainManual } from "./templates.ts";
import { isoSecond } from "./time.ts";
diff --git a/src/core/config.ts b/src/core/config.ts
index f2c5a8a1..7fa3c434 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -31,18 +31,82 @@ const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as
const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
/**
- * Resolve the location of the plugin config file.
+ * The one platform whose per-user configuration root is NOT
+ * `$HOME/.config`. Named rather than inferred: the list of platforms
+ * this build serves is a support decision, not a runtime discovery.
+ */
+const UNSUPPORTED_CONFIG_PLATFORMS: ReadonlyArray<string> = Object.freeze(["win32"]);
+
+/**
+ * Raised when the config path cannot be derived on the running
+ * platform. Named and specific because the alternative - returning
+ * `C:\Users\…\.config\open-second-brain\config.yaml` - is a
+ * plausible-looking answer to a question this build cannot answer: the
+ * layout is a POSIX convention, and nothing here (no adapter, no
+ * install document, no path handling) targets Windows.
+ */
+export class UnsupportedPlatformError extends Error {
+ readonly platform: string;
+
+ constructor(platform: string) {
+ super(
+ `open-second-brain has no configuration layout for platform '${platform}': ` +
+ "the default path $HOME/.config/open-second-brain/config.yaml is a POSIX " +
+ "convention and this build does not implement the Windows one. Set " +
+ "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " +
+ "to a configuration root, to choose the location yourself.",
+ );
+ this.name = "UnsupportedPlatformError";
+ this.platform = platform;
+ }
+}
+
+/** Injected view of the environment {@link resolveDefaultConfigPath} reads. */
+export interface ConfigPathEnv {
+ /** `process.platform` value. */
+ readonly platform: string;
+ /** `homedir()` value. */
+ readonly home: string;
+ readonly env: Readonly<Record<string, string | undefined>>;
+}
+
+/**
+ * Resolve the location of the plugin config file from an injected
+ * environment.
*
- * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, `~/.config/open-second-brain/config.yaml`.
+ * Order: `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, then
+ * `$HOME/.config/open-second-brain/config.yaml`. Only the last step is
+ * platform-bound, so an operator on an unsupported platform still has
+ * two ways to say where the file lives; the refusal fires exactly when
+ * they have said nothing and the convention does not apply.
+ *
+ * @throws {@link UnsupportedPlatformError} on a platform whose per-user
+ * configuration root is not `$HOME/.config`.
*/
-export function defaultConfigPath(): string {
- const override = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+export function resolveDefaultConfigPath(source: ConfigPathEnv): string {
+ const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
if (override) return expandTilde(override);
- const xdg = process.env["XDG_CONFIG_HOME"];
+ const xdg = source.env["XDG_CONFIG_HOME"];
if (xdg) return join(expandTilde(xdg), "open-second-brain", "config.yaml");
- return join(homedir(), ".config", "open-second-brain", "config.yaml");
+ if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
+ throw new UnsupportedPlatformError(source.platform);
+ }
+ return join(source.home, ".config", "open-second-brain", "config.yaml");
+}
+
+/**
+ * Resolve the location of the plugin config file for this process.
+ *
+ * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, `~/.config/open-second-brain/config.yaml`.
+ */
+export function defaultConfigPath(): string {
+ return resolveDefaultConfigPath({
+ platform: process.platform,
+ home: homedir(),
+ env: process.env,
+ });
}
/**
diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.ts
index 826eef5f..12537366 100644
--- a/src/mcp/brain/analytics-tools.ts
+++ b/src/mcp/brain/analytics-tools.ts
@@ -6,6 +6,11 @@
* BRAIN_TOOLS surface.
*/
+import {
+ INGEST_DEDUP_SURFACES,
+ summarizeIngestDedup,
+ type IngestDedupSurface,
+} from "../../core/brain/dedup-telemetry.ts";
import { buildConceptCluster } from "../../core/brain/link-graph/concept-cluster.ts";
import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
import { selectEvents } from "../../core/brain/temporal/select-events.ts";
@@ -188,6 +193,42 @@ async function toolBrainAttentionFlows(
);
}
+/**
+ * `view=dedup` - the persisted exact-hash ingest dedup trend.
+ *
+ * Every number here counts an item DROPPED on a sha-256 collision. The
+ * semantic dedup detectors are proposal-only nomination systems that never
+ * drop anything, so this lens deliberately publishes no semantic figure -
+ * see `src/core/brain/dedup-telemetry.ts`.
+ */
+async function toolBrainDedup(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const surface = args["surface"];
+ if (surface !== undefined && surface !== null) {
+ if (
+ typeof surface !== "string" ||
+ !(INGEST_DEDUP_SURFACES as ReadonlyArray<string>).includes(surface)
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_analytics view=dedup: surface must be one of ${INGEST_DEDUP_SURFACES.join(", ")}`,
+ );
+ }
+ }
+ const since = coerceIsoTimestampOrDate("brain_analytics", "since", args["since"]);
+ const until = coerceIsoTimestampOrDate("brain_analytics", "until", args["until"]);
+ return {
+ vault_path: ctx.vault,
+ ...summarizeIngestDedup(ctx.vault, {
+ ...(typeof surface === "string" ? { surface: surface as IngestDedupSurface } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ }),
+ };
+}
+
const ANALYTICS_VIEW_HANDLERS: Readonly<
Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>
> = Object.freeze({
@@ -195,6 +236,7 @@ const ANALYTICS_VIEW_HANDLERS: Readonly<
attention_flows: toolBrainAttentionFlows,
belief_evolution: toolBrainBeliefEvolution,
concept_synthesis: toolBrainConceptSynthesis,
+ dedup: toolBrainDedup,
});
async function toolBrainAnalytics(
@@ -212,13 +254,13 @@ export const ANALYTICS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
name: "brain_analytics",
previewBudget: MCP_PREVIEW_BUDGET,
description:
- "Read-only Brain analytics, one tool for every lens: view=timeline (event history), attention_flows, belief_evolution, or concept_synthesis. Replaces the per-lens analytics tools.",
+ "Read-only Brain analytics, one tool for every lens: view=timeline (event history), attention_flows, belief_evolution, concept_synthesis, or dedup (exact-hash ingest dedup trend). Replaces the per-lens analytics tools.",
inputSchema: {
type: "object",
properties: {
view: {
type: "string",
- enum: ["timeline", "attention_flows", "belief_evolution", "concept_synthesis"],
+ enum: ["timeline", "attention_flows", "belief_evolution", "concept_synthesis", "dedup"],
description: "Which analytics lens to run.",
},
pref_id: {
@@ -227,8 +269,13 @@ export const ANALYTICS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
topic: { type: "string", description: "timeline / belief_evolution: target topic slug." },
kind: { type: "string", description: "view=timeline: restrict to one event kind." },
- since: { type: "string", description: "view=timeline: inclusive ISO lower bound." },
- until: { type: "string", description: "view=timeline: exclusive ISO upper bound." },
+ since: { type: "string", description: "view=timeline / dedup: inclusive ISO lower bound." },
+ until: { type: "string", description: "view=timeline / dedup: exclusive ISO upper bound." },
+ surface: {
+ type: "string",
+ enum: ["session_lifecycle", "scan_inline", "session_import"],
+ description: "view=dedup: restrict the trend to one ingest surface.",
+ },
limit: { type: "integer", minimum: 1, description: "view=timeline: max events returned." },
id: { type: "string", description: "view=concept_synthesis: target id (e.g. pref-foo)." },
include_unlinked: {
diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.ts
index e2663a17..ee701176 100644
--- a/src/mcp/brain/feedback-tools.ts
+++ b/src/mcp/brain/feedback-tools.ts
@@ -13,7 +13,17 @@ import {
BrainPreferenceNotFoundError,
type AppendApplyEvidenceInput,
} from "../../core/brain/apply-evidence.ts";
-import { dream } from "../../core/brain/dream.ts";
+import { dream, type DreamGateOverrides } from "../../core/brain/dream.ts";
+import {
+ DREAM_GATE_NAMES,
+ DreamGateOverrideError,
+ validateDreamGateOverrides,
+} from "../../core/brain/dream-gates.ts";
+import {
+ DREAM_STEP_RUNNABLE,
+ DreamStepNotRunnableError,
+ runDreamStep,
+} from "../../core/brain/dream-step.ts";
import {
applyDreamBundle,
discardDreamBundle,
@@ -208,6 +218,16 @@ async function toolBrainFeedback(
status: BRAIN_PREFERENCE_STATUS.confirmed,
evidenced_by: [`[[${sigResult.id}]]`],
confirmed_at: createdAt,
+ // Issue #149: an explicit zero, not an absent value. The
+ // on-disk encoding of "absent" is the literal `null`, and two
+ // ranking surfaces (`pre-compress-pack`, `morning-brief`) map
+ // `null` to negative infinity before sorting - so a rule
+ // force-confirmed a second ago would sort BELOW every rule
+ // that has a number, including one measured at zero. Zero is
+ // also the true Wilson lower bound on no evidence, which is
+ // why the dream pass already pre-seeds it for new
+ // preferences. This writer now matches it.
+ confidence_value: 0,
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
});
try {
@@ -274,6 +294,32 @@ function dreamChangeList(summary: {
];
}
+/**
+ * Read the optional `gates` argument (no-dead-ends, Unit E - operator
+ * surface). JSON-RPC carries real objects and booleans, so the MCP form
+ * is the override record itself rather than the CLI's `name=value`
+ * strings; both go through the same validator in `dream-gates.ts`, so
+ * the accepted gate names cannot diverge between the two surfaces.
+ */
+function readDreamGates(args: Record<string, unknown>): DreamGateOverrides | undefined {
+ const raw = args["gates"];
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "object" || Array.isArray(raw)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_dream: gates must be an object of <gate>: <boolean>; known gates: ${DREAM_GATE_NAMES.join(", ")}`,
+ );
+ }
+ try {
+ return validateDreamGateOverrides(raw as Record<string, unknown>);
+ } catch (exc) {
+ if (exc instanceof DreamGateOverrideError) {
+ throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
async function toolBrainDream(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -296,8 +342,50 @@ async function toolBrainDream(
const nowDate = coerceIsoDate(args, "now");
const agentArg = coerceStr(args, "agent", false);
const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+ const gates = readDreamGates(args);
+ const stepArg = coerceStr(args, "step", false);
+
+ // Single-step requests (no-dead-ends, Unit E - operator surface).
+ // Deliberately checked before any environment work: a step the pass
+ // cannot honour is refused by name, carrying the specific reason and
+ // the runnable set, and nothing is read or written on that path.
+ if (stepArg) {
+ if (action !== "run") {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_dream: step applies to action=run; action=${action} drives the staged lifecycle, which has no single step`,
+ );
+ }
+ const conflicting = dryRun
+ ? "dry_run"
+ : gates !== undefined
+ ? "gates"
+ : "expect" in args || "strict" in args
+ ? "expect/strict"
+ : null;
+ if (conflicting !== null) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_dream: step cannot be combined with ${conflicting} - a single step has no preview path, reads no gate, and produces none of the preference counters the guard asserts over`,
+ );
+ }
+ try {
+ return { ...runDreamStep(ctx.vault, stepArg) };
+ } catch (exc) {
+ if (exc instanceof DreamStepNotRunnableError) {
+ throw new MCPError(INVALID_PARAMS, exc.message);
+ }
+ throw exc;
+ }
+ }
if (action !== "run") {
+ if (gates !== undefined) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_dream: gates apply to action=run; action=${action} drives the staged lifecycle, whose bundle records the gates its own run resolved`,
+ );
+ }
// Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a
// persisted bundle; dream() stays the only promotion engine.
const runIdArg = coerceStr(args, "run_id", false);
@@ -364,6 +452,8 @@ async function toolBrainDream(
dryRun: true,
...(nowDate ? { now: nowDate } : {}),
...(agent ? { agentName: agent } : {}),
+ // Preview the run being guarded, overrides and all.
+ ...(gates !== undefined ? { gates } : {}),
});
const previewList = dreamChangeList(preview);
enforceCountGuard({
@@ -379,6 +469,7 @@ async function toolBrainDream(
dryRun,
...(nowDate ? { now: nowDate } : {}),
...(agent ? { agentName: agent } : {}),
+ ...(gates !== undefined ? { gates } : {}),
});
const changeList = dreamChangeList(summary);
@@ -690,6 +781,30 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "boolean",
description: "action=run: refuse a guardless run (no `expect`). Default false.",
},
+ step: {
+ // Deliberately NOT an enum. A closed schema would reject a
+ // non-runnable step with a generic validation error, losing the
+ // specific reason `DreamStepNotRunnableError` carries - which
+ // is the whole deliverable for the steps that are refused.
+ type: "string",
+ description:
+ `action=run: run ONE step (${DREAM_STEP_RUNNABLE.join(", ")}) and return a partial ` +
+ `result, not a run summary. Any other token is refused with the reason it cannot run alone.`,
+ },
+ gates: {
+ type: "object",
+ description:
+ `action=run: override a phase gate for THIS RUN ONLY, never written back to ` +
+ `Brain/_brain.yaml. Known gates: ${DREAM_GATE_NAMES.join(", ")}.`,
+ properties: {
+ heal_enrich: {
+ type: "boolean",
+ description:
+ "Overrides dream.heal_enrich_enabled for this run. Omitted: the configured value decides.",
+ },
+ },
+ additionalProperties: false,
+ },
},
additionalProperties: false,
},
diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.ts
index f84457fb..4d7f8143 100644
--- a/src/mcp/brain/health-tools.ts
+++ b/src/mcp/brain/health-tools.ts
@@ -10,11 +10,41 @@ import { resolveSearchConfig } from "../../core/search/index.ts";
import { collectMaintenanceActions } from "../../core/brain/maintenance/collect.ts";
import { runDoctor } from "../../core/brain/doctor.ts";
import { applyRepair } from "../../core/brain/diagnostics.ts";
+import { nextCommandField } from "../../core/brain/next-step.ts";
+import { NO_EXIT_KEY, noExitReasons } from "../../core/brain/doctor-exits.ts";
import { buildOperatorSnapshot } from "../../core/brain/operator-snapshot.ts";
+import type { DoctorIssue } from "../../core/brain/types.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBool, coerceFormat } from "../coerce.ts";
import { vaultRelativeSafe } from "./shared.ts";
+/**
+ * One reported issue, as an MCP caller sees it.
+ *
+ * The projection is an explicit allowlist rather than a spread of the
+ * record, so a field added to `DoctorIssue` reaches this surface only
+ * when it is listed. `field` / `target` / `sources` (no-dead-ends, task
+ * 12) are listed for exactly that reason - the CLI's `--json` renderer
+ * carries them by spreading the record, and the two surfaces must not
+ * disagree about what a broken-link finding contains.
+ *
+ * Every added key is conditional on the value being present, so an issue
+ * that carries none of them produces the byte-identical payload it did
+ * before they existed.
+ */
+function issueView(ctx: ServerContext, issue: DoctorIssue): Record<string, unknown> {
+ return {
+ severity: issue.severity,
+ code: issue.code,
+ message: issue.message,
+ ...(issue.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, issue.path) } : {}),
+ ...(issue.field !== undefined ? { field: issue.field } : {}),
+ ...(issue.target !== undefined ? { target: issue.target } : {}),
+ ...(issue.sources !== undefined ? { sources: issue.sources } : {}),
+ ...nextCommandField(issue.code),
+ };
+}
+
async function toolBrainDoctor(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -53,22 +83,26 @@ async function toolBrainDoctor(
// to false. Errors always do.
const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);
+ // Why a reported code carries no `next_command`. Without it the field's
+ // absence has two readings - a class no single command resolves, and a
+ // class nobody has registered - and an agent cannot tell them apart.
+ // Resolved through the same table the CLI renderer reads.
+ const noExit = noExitReasons(
+ [...result.errors, ...result.warnings, ...(result.uncertain ?? [])].map((i) => i.code),
+ );
+
return {
format,
ok,
strict,
- errors: result.errors.map((i) => ({
- severity: i.severity,
- code: i.code,
- message: i.message,
- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
- })),
- warnings: result.warnings.map((i) => ({
- severity: i.severity,
- code: i.code,
- message: i.message,
- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),
- })),
+ // no-dead-ends, task 4: `next_command` is the structural CLI string
+ // the diagnostics registry holds for this code, resolved through the
+ // same `nextCommandField` the `o2b brain doctor --json` renderer
+ // uses so the two surfaces cannot drift. Absent - not null - for a
+ // code with no registered signal, because there is no honest command
+ // to name and a generic one would be invented.
+ errors: result.errors.map((i) => issueView(ctx, i)),
+ warnings: result.warnings.map((i) => issueView(ctx, i)),
// v0.10.15: ranked maintenance actions surfaced as a parallel
// signal to errors/warnings. The list is independent of `strict`
// because nothing here downgrades the `ok` flag - actions are
@@ -109,9 +143,15 @@ async function toolBrainDoctor(
code: u.code,
...(u.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, u.path) } : {}),
message: u.message,
+ ...nextCommandField(u.code),
})),
}
: {}),
+ // Once per code, beside the streams rather than on every issue: a
+ // reason is about a CLASS, unlike a next command, and two hundred
+ // malformed timestamps share one. Absent when every reported code has
+ // an exit, so a clean payload is byte-identical to the pre-task shape.
+ ...(noExit.size > 0 ? { [NO_EXIT_KEY]: Object.fromEntries(noExit) } : {}),
};
}
diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.ts
index 8cbd4aa3..b077795e 100644
--- a/src/mcp/brain/procedure-tools.ts
+++ b/src/mcp/brain/procedure-tools.ts
@@ -9,9 +9,13 @@
import { join } from "node:path";
import {
acceptSkillProposal,
+ discardUnreadableSkillAcceptJournals,
learnSkillProposals,
listPendingSkillProposals,
+ recoverSkillProposalAccepts,
rejectSkillProposal,
+ resolveSkillProposalEvidence,
+ type SkillContractInput,
} from "../../core/brain/skill-proposals.ts";
import { deriveSkillUsage } from "../../core/brain/skill-usage.ts";
import {
@@ -58,17 +62,35 @@ async function toolBrainSkillProposals(
if (operation === "accept") {
const slug = requiredStringArg("brain_skill_proposals", args, "slug");
const note = optionalStringArg("brain_skill_proposals", args, "note");
- const reviewed = note
- ? acceptSkillProposal(ctx.vault, slug, { note })
- : acceptSkillProposal(ctx.vault, slug);
+ const contract = readSkillContract(args);
+ const reviewed = acceptSkillProposal(ctx.vault, slug, {
+ ...(note ? { note } : {}),
+ ...(contract ? { contract } : {}),
+ });
return { ...reviewed };
}
+ if (operation === "evidence") {
+ const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ return { ...resolveSkillProposalEvidence(ctx.vault, slug) };
+ }
if (operation === "reject") {
const slug = requiredStringArg("brain_skill_proposals", args, "slug");
const note = requiredStringArg("brain_skill_proposals", args, "note");
const reviewed = rejectSkillProposal(ctx.vault, slug, { note });
return { ...reviewed };
}
+ if (operation === "recover") {
+ // The accept sequence's write-ahead journal was recoverable in the
+ // library and reachable from no tool, so an agent whose accept
+ // crashed had nothing to call. Both refusals it can raise carry the
+ // file and the exit in their message; they surface as errors here
+ // rather than as a result field, because neither is a state this
+ // operation completed.
+ const discarded =
+ args["discard_unreadable"] === true ? discardUnreadableSkillAcceptJournals(ctx.vault) : [];
+ const recovered = recoverSkillProposalAccepts(ctx.vault);
+ return { discarded, recovered, total: recovered.length };
+ }
if (operation === "usage") {
// Per-skill invocation telemetry (t_56a12bde): deterministic counts
// derived from skill_invoked continuity records, distinct from proposing
@@ -78,10 +100,31 @@ async function toolBrainSkillProposals(
}
throw new MCPError(
INVALID_PARAMS,
- "brain_skill_proposals: operation must be one of learn|list|accept|reject|usage",
+ "brain_skill_proposals: operation must be one of learn|list|accept|reject|recover|usage|evidence",
);
}
+/**
+ * Read the optional execution contract from an accept payload. Returns
+ * undefined when the caller supplied none, so the accept path stays
+ * byte-identical to a pre-contract acceptance.
+ */
+function readSkillContract(args: Record<string, unknown>): SkillContractInput | undefined {
+ const prerequisites = coerceStrList(args, "prerequisites");
+ const rollback = coerceStrList(args, "rollback");
+ const sideEffects = coerceStrList(args, "side_effects");
+ const verification = coerceStrList(args, "verification");
+ if (
+ prerequisites.length === 0 &&
+ rollback.length === 0 &&
+ sideEffects.length === 0 &&
+ verification.length === 0
+ ) {
+ return undefined;
+ }
+ return { prerequisites, rollback, sideEffects, verification };
+}
+
async function toolBrainProceduralMemory(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -221,15 +264,20 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_skill_proposals",
description:
- "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject), and read per-skill invocation usage counts (usage).",
+ "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject), resolve abandoned accept sequences (recover), read per-skill invocation counts (usage), and resolve a proposal's self-reported support against the recorded procedural outcome ledger (evidence).",
inputSchema: {
type: "object",
properties: {
operation: {
type: "string",
- enum: ["learn", "list", "accept", "reject", "usage"],
+ enum: ["learn", "list", "accept", "reject", "recover", "usage", "evidence"],
description: "Tool operation.",
},
+ discard_unreadable: {
+ type: "boolean",
+ description:
+ "recover only: delete accept-journal markers that cannot be parsed. Off by default: removing one unblocks accepting without resolving the sequence it marked.",
+ },
min_support: {
type: "integer",
minimum: 1,
@@ -237,12 +285,32 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
slug: {
type: "string",
- description: "Proposal slug for accept/reject.",
+ description: "Proposal slug for accept/reject/evidence.",
},
note: {
type: "string",
description: "Optional review note; required for reject.",
},
+ prerequisites: {
+ type: "array",
+ items: { type: "string" },
+ description: "accept only: conditions that must hold before the procedure runs.",
+ },
+ rollback: {
+ type: "array",
+ items: { type: "string" },
+ description: "accept only: steps that undo the procedure.",
+ },
+ side_effects: {
+ type: "array",
+ items: { type: "string" },
+ description: "accept only: state the procedure changes outside its own output.",
+ },
+ verification: {
+ type: "array",
+ items: { type: "string" },
+ description: "accept only: checks that confirm the procedure worked.",
+ },
},
required: ["operation"],
additionalProperties: false,
diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.ts
index a3eb823b..ce79fa39 100644
--- a/src/mcp/brain/synthesis-tools.ts
+++ b/src/mcp/brain/synthesis-tools.ts
@@ -29,6 +29,7 @@ import {
type IdeaLineageResult,
} from "../../core/brain/idea-lineage.ts";
import { decomposeNoteHistory } from "../../core/brain/note-history.ts";
+import { coerceStringOptional } from "../coerce.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
@@ -55,6 +56,18 @@ function stringArrayArg(
return value as ReadonlyArray<string>;
}
+/**
+ * Argument name for the project scope axis. Deliberately identical to the
+ * `brain_search` filter (`src/mcp/search-tools.ts`) so an agent that knows
+ * one knows the other; the core field it maps to is the `project` axis of
+ * `CompositeScope`. Not to be confused with `o2b brain project`, the
+ * unrelated configuration-level code-directory link.
+ */
+const PROJECT_SCOPE_ARG = "project_scope";
+
+/** Longest accepted raw project token, matching the `brain_search` filter. */
+const PROJECT_SCOPE_MAX_LEN = 128;
+
function serializeDigest(digest: SessionSummaryDigest): Record<string, unknown> {
return {
id: digest.id,
@@ -65,6 +78,7 @@ function serializeDigest(digest: SessionSummaryDigest): Record<string, unknown>
next_steps: digest.nextSteps,
created_at: digest.createdAt,
...(digest.host !== undefined ? { host: digest.host } : {}),
+ ...(digest.project !== undefined ? { project: digest.project } : {}),
};
}
@@ -85,6 +99,7 @@ async function toolBrainSessionSummary(
const nextSteps = stringArrayArg(args, "next_steps");
const host = args["host"];
const sourceTurnIds = stringArrayArg(args, "source_turn_ids");
+ const project = coerceStringOptional(args, PROJECT_SCOPE_ARG, PROJECT_SCOPE_MAX_LEN);
try {
const digest = appendSessionSummary(ctx.vault, {
sessionId,
@@ -94,6 +109,7 @@ async function toolBrainSessionSummary(
...(nextSteps !== undefined ? { nextSteps } : {}),
...(typeof host === "string" ? { host } : {}),
...(sourceTurnIds !== undefined ? { sourceTurnIds } : {}),
+ ...(project !== undefined ? { project } : {}),
});
return { written: true, digest: serializeDigest(digest) };
} catch (error) {
@@ -116,8 +132,19 @@ async function toolBrainSessionSummary(
typeof sessionIdRaw === "string" && sessionIdRaw.trim().length > 0
? sessionIdRaw.trim()
: undefined;
- const digests = listSessionSummaries(ctx.vault, sessionId !== undefined ? { sessionId } : {});
- return { count: digests.length, digests: digests.map(serializeDigest) };
+ const project = coerceStringOptional(args, PROJECT_SCOPE_ARG, PROJECT_SCOPE_MAX_LEN);
+ try {
+ const digests = listSessionSummaries(ctx.vault, {
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(project !== undefined ? { project } : {}),
+ });
+ return { count: digests.length, digests: digests.map(serializeDigest) };
+ } catch (error) {
+ if (error instanceof SessionSummaryError) {
+ throw new MCPError(INVALID_PARAMS, error.message);
+ }
+ throw error;
+ }
}
const CHECKPOINT_TOOL = "brain_session_checkpoint";
@@ -344,6 +371,11 @@ export const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description: "write: turn ids the digest was distilled from (lineage edges).",
},
host: { type: "string", description: "write: originating runtime (claude, codex, ...)." },
+ [PROJECT_SCOPE_ARG]: {
+ type: "string",
+ description:
+ "Project scope axis; same name and slug rule as the brain_search filter. write: scopes the digest and its dedupe key; list: filters by it. Unsluggable = error.",
+ },
},
required: ["operation"],
additionalProperties: false,
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index bd25490b..69de5b71 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -30,6 +30,7 @@ import {
import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
+import { nextCommandField } from "../core/brain/next-step.ts";
import { collectRuntimeNotices } from "../core/brain/runtime-notices.ts";
import { isDir } from "../core/fs-utils.ts";
import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";
@@ -221,9 +222,18 @@ async function toolVaultHealth(
}));
// Runtime-state notices (transient operational conditions) surfaced for
// pull consumers, mirroring the proactive SessionStart injection push.
+ // The projection carries the notice's structured next command when it has
+ // one, so a machine consumer reads the exit as a field instead of parsing
+ // it back out of `message`; a condition with no registered exit
+ // contributes no key at all.
const notices = collectRuntimeNotices(ctx.vault, {
configPath: ctx.configPath ?? undefined,
- }).map((n) => ({ code: n.code, severity: n.severity, message: n.message }));
+ }).map((n) => ({
+ code: n.code,
+ severity: n.severity,
+ message: n.message,
+ ...nextCommandField(n.code),
+ }));
return {
vault_path: vaultPathField(ctx),
diff --git a/tests/cli/advisory-claim-truth.test.ts b/tests/cli/advisory-claim-truth.test.ts
new file mode 100644
index 00000000..74e6524d
--- /dev/null
+++ b/tests/cli/advisory-claim-truth.test.ts
@@ -0,0 +1,246 @@
+/**
+ * A registered terminal state fires only where its claim holds
+ * (no-dead-ends, phase 3, item 3).
+ *
+ * The registry entry a rail emission resolves is not just a command - it
+ * is an assertion about the state the caller is in. `brain-empty` asserts
+ * "Brain with nothing recorded in it"; `search-index-built` asserts
+ * "search index up to date". Three emissions fired unconditionally and so
+ * made those assertions in cases where they were false, which is exactly
+ * the failure class this release exists to remove.
+ *
+ * Audited here, one test per emission that had to change, plus the
+ * negative case for each - because "fires when true" is only half the
+ * property and the half that regresses silently is the other one.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-claim-truth-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG", "VAULT_AGENT_NAME"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const FEEDBACK_EXIT = "next: o2b brain feedback";
+const QUERY_EXIT = "next: o2b search query <text>";
+const INDEX_EXIT = "next: o2b search index";
+
+function seedSignal(): void {
+ writeSignal(vault, {
+ topic: "already-recorded",
+ signal: "positive",
+ agent: "claude",
+ principle: "Something is already recorded here.",
+ created_at: "2026-05-20T10:00:00Z",
+ date: "2026-05-20",
+ slug: "already-recorded-1",
+ scope: "writing",
+ });
+}
+
+describe("brain-empty claims the Brain is empty", () => {
+ test("a first bootstrap does leave an empty Brain, so the exit fires", async () => {
+ const r = await runCli(["brain", "init", "--vault", vault, "--config", configPath]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(FEEDBACK_EXIT);
+ });
+
+ test("a re-run over a Brain that already holds a signal does not", async () => {
+ bootstrapBrain(vault, { configPath });
+ seedSignal();
+
+ const r = await runCli(["brain", "init", "--vault", vault, "--config", configPath]);
+
+ expect(r.returncode).toBe(0);
+ // Every path was skipped and the Brain is not empty; asserting it is
+ // would be a false claim.
+ expect(r.stdout).toContain("exists:");
+ expect(r.stdout).not.toContain(FEEDBACK_EXIT);
+ });
+
+ test("a re-run over a Brain that holds a preference does not", async () => {
+ bootstrapBrain(vault, { configPath });
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-recorded.md"),
+ "---\nid: pref-recorded\nstatus: confirmed\n---\n\nRecorded.\n",
+ "utf8",
+ );
+
+ const r = await runCli(["brain", "init", "--vault", vault, "--config", configPath]);
+
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain(FEEDBACK_EXIT);
+ });
+
+ test("a re-run over an empty Brain still fires - the claim is about content, not about a first run", async () => {
+ bootstrapBrain(vault, { configPath });
+
+ const r = await runCli(["brain", "init", "--vault", vault, "--config", configPath]);
+
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(FEEDBACK_EXIT);
+ });
+
+ test("the machine stream stays clean either way", async () => {
+ bootstrapBrain(vault, { configPath });
+ seedSignal();
+ const r = await runCli(["brain", "init", "--vault", vault, "--config", configPath, "--json"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ });
+});
+
+describe("search-index-built claims the index is up to date", () => {
+ const dbPath = (): string => join(tmp, "index.db");
+
+ function writeNote(name: string, body: string): void {
+ writeFileSync(join(vault, name), body, "utf8");
+ }
+
+ beforeEach(() => {
+ bootstrapBrain(vault, { configPath });
+ });
+
+ test("a clean run leaves it up to date, so the exit fires", async () => {
+ writeNote("good.md", "---\ntitle: Good\n---\n\nSome body text.\n");
+ const r = await runCli(["search", "index", "--vault", vault, "--db", dbPath()]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(QUERY_EXIT);
+ });
+
+ test("a run that could not index every file does not claim it is up to date", async () => {
+ writeNote("good.md", "---\ntitle: Good\n---\n\nSome body text.\n");
+ // Frontmatter with no closing fence: the chunker reports it and the
+ // run records the file under `errors`, meaning it did not index.
+ writeNote("broken.md", "---\ntitle: Broken\n\nBody without a closing fence.\n");
+
+ const r = await runCli(["search", "index", "--vault", vault, "--db", dbPath()]);
+
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("broken.md");
+ expect(r.stdout).not.toContain(QUERY_EXIT);
+ });
+
+ test("reindex holds the same property", async () => {
+ writeNote("good.md", "---\ntitle: Good\n---\n\nSome body text.\n");
+ const clean = await runCli(["search", "reindex", "--vault", vault, "--db", dbPath()]);
+ expect(clean.stdout).toContain(QUERY_EXIT);
+
+ writeNote("broken.md", "---\ntitle: Broken\n\nBody without a closing fence.\n");
+ const dirty = await runCli(["search", "reindex", "--vault", vault, "--db", dbPath()]);
+ expect(dirty.stdout).not.toContain(QUERY_EXIT);
+ });
+
+ test("the machine stream stays clean and parses in both cases", async () => {
+ writeNote("broken.md", "---\ntitle: Broken\n\nBody without a closing fence.\n");
+ const r = await runCli(["search", "index", "--vault", vault, "--db", dbPath(), "--json"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ });
+});
+
+describe("search-index-missing claims the index is not built", () => {
+ test("o2b init on a vault with no index names the indexer", async () => {
+ const r = await runCli(["init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(INDEX_EXIT);
+ });
+
+ test("o2b init on a vault that already has one does not", async () => {
+ // Build the index where the resolver will look for it, then re-init.
+ const built = await runCli(["search", "index", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(built.returncode).toBe(0);
+
+ const r = await runCli(["init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+
+ expect(r.returncode).toBe(0);
+ // The checklist below it already reports this step as done; the
+ // block above it must not contradict that in the same output.
+ expect(r.stdout).toContain("Search:");
+ expect(r.stdout).not.toContain(INDEX_EXIT);
+ });
+});
+
+describe("the audit of every other registered emission", () => {
+ /**
+ * The remaining rail call sites, and the condition each is guarded by.
+ * Read off the source at the time of this change and asserted rather
+ * than trusted: a site that loses its guard fails here.
+ */
+ const GUARDED: ReadonlyArray<readonly [string, string, string]> = [
+ ["src/cli/brain/verbs/bridges.ts", "bridge-proposals-absent", "!existsSync(path)"],
+ ["src/cli/brain/verbs/bridges.ts", "search-index-missing", "INDEX_MISSING"],
+ ["src/cli/brain/verbs/clusters.ts", "search-index-missing", "INDEX_MISSING"],
+ ["src/cli/brain/verbs/clusters.ts", "cluster-notes-absent", "!existsSync(dir)"],
+ ["src/cli/brain/verbs/dream.ts", "dream-bundles-absent", "bundles.length === 0"],
+ ["src/cli/brain/verbs/git.ts", "git-history-absent", "results.length === 0"],
+ ["src/cli/brain/verbs/git.ts", "git-history-absent", "repos.length === 0"],
+ ["src/cli/brain/verbs/inbox-drain.ts", "staged-captures-pending", "report.items.length > 0"],
+ ["src/cli/brain/verbs/intention.ts", "intentions-absent", "intentions.length === 0"],
+ [
+ "src/cli/brain/verbs/intent-review.ts",
+ "signal-clusters-absent",
+ "report.reviews.length === 0",
+ ],
+ ["src/cli/brain/verbs/tiers.ts", "tier-drift-restore", "findings.length > 0"],
+ ["src/cli/brain/verbs/tune.ts", "recall-tuning-absent", "tuned === null"],
+ ["src/cli/main.ts", "cli-config-absent", "!result.exists"],
+ ["src/cli/search.ts", "search-index-missing", "!status.exists"],
+ ];
+
+ test("every other emission sits under a guard naming its condition", () => {
+ const root = join(import.meta.dir, "..", "..");
+ const missing: string[] = [];
+ for (const [file, code, guard] of GUARDED) {
+ const text = readFileSync(join(root, file), "utf8");
+ // EVERY occurrence, not the first: a code is now named twice per
+ // site - once for the rail line and once for the JSON field - and
+ // checking only the first would let the second lose its guard.
+ const occurrences = [...text.matchAll(new RegExp(`"${code}"`, "g"))];
+ if (occurrences.length === 0) {
+ missing.push(`${file}: ${code} is not named at all`);
+ continue;
+ }
+ for (const occurrence of occurrences) {
+ if (!text.slice(0, occurrence.index!).includes(guard)) {
+ missing.push(`${file}: ${code} is not preceded by \`${guard}\``);
+ }
+ }
+ }
+ expect(missing.join("\n")).toBe("");
+ });
+});
diff --git a/tests/cli/advisory-rail.test.ts b/tests/cli/advisory-rail.test.ts
new file mode 100644
index 00000000..b97fce65
--- /dev/null
+++ b/tests/cli/advisory-rail.test.ts
@@ -0,0 +1,365 @@
+/**
+ * Tests for src/cli/advisory-rail.ts - the single emission point for
+ * forward-pointer lines (no-dead-ends, task 2).
+ *
+ * The rail owns two decisions and both are pinned here: WHAT to say (a
+ * payload resolved by code from the diagnostics registry, never a
+ * caller-supplied sentence) and WHETHER it is legal to say it on the
+ * current stream (a command that renders its own JSON must not receive
+ * advisory chrome on stdout; an envelope-wrapped command may, because the
+ * envelope buffers).
+ *
+ * `wantsJsonFlag` is tested alongside because the rail's legality question
+ * is the reason its raw-argv scan had to become grammar-faithful.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ ADVISORY_OUTCOME,
+ advisoryIsLegal,
+ type AdvisoryEmission,
+ emitNextStep,
+ emitNextSteps,
+ renderNextStepLine,
+} from "../../src/cli/advisory-rail.ts";
+import {
+ COMMANDS_WITH_INTERNAL_JSON,
+ ownsInternalJson,
+ wantsJsonFlag,
+ withJsonFallback,
+} from "../../src/cli/json-helpers.ts";
+import { parseFlags } from "../../src/cli/argparse.ts";
+import { writeJson } from "../../src/cli/output.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+/** A code the registry carries, with a multi-flag structural command. */
+const REGISTERED_CODE = "wal-gap";
+const REGISTERED_COMMAND = DIAGNOSTIC_SIGNALS.get(REGISTERED_CODE)!.nextCommand;
+
+/** Capture everything written to stdout while `run` executes. */
+async function captureStdout(run: () => Promise<void> | void): Promise<string> {
+ let captured = "";
+ const real = process.stdout.write;
+ process.stdout.write = ((chunk: unknown, ...rest: unknown[]) => {
+ captured += typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString();
+ const cb = rest[rest.length - 1];
+ if (typeof cb === "function") (cb as () => void)();
+ return true;
+ }) as typeof process.stdout.write;
+ try {
+ await run();
+ } finally {
+ process.stdout.write = real;
+ }
+ return captured;
+}
+
+describe("advisory rail - what to say", () => {
+ test("a human-path emission renders the structural command", async () => {
+ let result: AdvisoryEmission | undefined;
+ const out = await captureStdout(() => {
+ result = emitNextStep(REGISTERED_CODE, {
+ command: "brain",
+ argv: ["doctor"],
+ jsonRequested: false,
+ });
+ });
+ expect(out).toBe(`next: ${REGISTERED_COMMAND}\n`);
+ expect(result).toEqual({
+ code: REGISTERED_CODE,
+ outcome: ADVISORY_OUTCOME.emitted,
+ nextStep: {
+ code: REGISTERED_CODE,
+ issueClass: DIAGNOSTIC_SIGNALS.get(REGISTERED_CODE)!.issueClass,
+ nextCommand: REGISTERED_COMMAND,
+ },
+ line: `next: ${REGISTERED_COMMAND}`,
+ });
+ });
+
+ test("the rendered line is the label plus the registered command, nothing else", () => {
+ for (const signal of DIAGNOSTIC_SIGNALS.values()) {
+ expect(
+ renderNextStepLine({
+ code: signal.code,
+ issueClass: signal.issueClass,
+ nextCommand: signal.nextCommand,
+ }),
+ ).toBe(`next: ${signal.nextCommand}`);
+ }
+ });
+
+ test("an unregistered code emits nothing and reports the absence by name", async () => {
+ let result: AdvisoryEmission | undefined;
+ const out = await captureStdout(() => {
+ result = emitNextStep("no-such-diagnostic-code", {
+ command: "brain",
+ argv: ["doctor"],
+ jsonRequested: false,
+ });
+ });
+ expect(out).toBe("");
+ expect(result).toEqual({
+ code: "no-such-diagnostic-code",
+ outcome: ADVISORY_OUTCOME.unregisteredCode,
+ nextStep: null,
+ line: null,
+ });
+ });
+
+ test("a sentence passed where a code belongs resolves to nothing, never to itself", async () => {
+ let result: AdvisoryEmission | undefined;
+ const out = await captureStdout(() => {
+ result = emitNextStep("Run o2b brain doctor to repair this.", {
+ command: "brain",
+ argv: [],
+ jsonRequested: false,
+ });
+ });
+ expect(out).toBe("");
+ expect(result!.outcome).toBe(ADVISORY_OUTCOME.unregisteredCode);
+ expect(result!.line).toBeNull();
+ });
+});
+
+describe("advisory rail - whether it is legal here", () => {
+ test("a command that renders its own JSON gets no stdout contamination", async () => {
+ let result: AdvisoryEmission | undefined;
+ const out = await captureStdout(() => {
+ writeJson({ ok: true, issues: [] });
+ result = emitNextStep(REGISTERED_CODE, {
+ command: "brain",
+ argv: ["doctor", "--json"],
+ jsonRequested: true,
+ });
+ });
+ expect(out).toBe(`${JSON.stringify({ ok: true, issues: [] }, undefined, 2)}\n`);
+ expect(() => JSON.parse(out)).not.toThrow();
+ expect(result!.outcome).toBe(ADVISORY_OUTCOME.suppressedMachineStream);
+ expect(result!.line).toBeNull();
+ // The payload is still resolved, so the verb can carry it as a field.
+ expect(result!.nextStep!.nextCommand).toBe(REGISTERED_COMMAND);
+ });
+
+ test("the same command on the human path is not suppressed", () => {
+ expect(advisoryIsLegal({ command: "brain", argv: ["doctor"], jsonRequested: false })).toBe(
+ true,
+ );
+ expect(
+ advisoryIsLegal({ command: "brain", argv: ["doctor", "--json"], jsonRequested: true }),
+ ).toBe(false);
+ });
+
+ test("an envelope-wrapped command may emit: the envelope buffers the line", async () => {
+ const stream = { command: "completions", argv: ["bash", "--json"], jsonRequested: true };
+ expect(advisoryIsLegal(stream)).toBe(true);
+
+ const out = await captureStdout(async () => {
+ await withJsonFallback("completions", async () => {
+ writeJson({ shell: "bash" });
+ emitNextStep(REGISTERED_CODE, stream);
+ return 0;
+ });
+ });
+ const envelope = JSON.parse(out) as { ok: boolean; command: string; stdout: string };
+ expect(envelope.ok).toBe(true);
+ expect(envelope.command).toBe("completions");
+ expect(envelope.stdout).toContain(`next: ${REGISTERED_COMMAND}\n`);
+ });
+
+ test("mcp --probe and help are internal-JSON even though the set omits them", () => {
+ expect(COMMANDS_WITH_INTERNAL_JSON.has("mcp")).toBe(false);
+ expect(COMMANDS_WITH_INTERNAL_JSON.has("help")).toBe(false);
+ expect(ownsInternalJson("mcp", ["--probe", "--json"])).toBe(true);
+ expect(ownsInternalJson("mcp", ["--json"])).toBe(false);
+ expect(ownsInternalJson("help", ["--json"])).toBe(true);
+ expect(advisoryIsLegal({ command: "mcp", argv: ["--probe"], jsonRequested: true })).toBe(false);
+ });
+
+ test("every command owning an internal JSON branch is refused advisory chrome", () => {
+ for (const command of COMMANDS_WITH_INTERNAL_JSON) {
+ expect(`${command}: ${ownsInternalJson(command, ["--json"])}`).toBe(`${command}: true`);
+ expect(`${command}: ${advisoryIsLegal({ command, argv: [], jsonRequested: true })}`).toBe(
+ `${command}: false`,
+ );
+ expect(`${command}: ${advisoryIsLegal({ command, argv: [], jsonRequested: false })}`).toBe(
+ `${command}: true`,
+ );
+ }
+ });
+});
+
+describe("advisory rail - the batch form (no-dead-ends, task 4)", () => {
+ const HUMAN = { command: "brain", argv: ["doctor"], jsonRequested: false };
+
+ test("codes sharing one command print that command once", async () => {
+ // `broken-wikilink` and `dangling-workrun` are distinct issue
+ // classes with one repair verb between them.
+ const shared = DIAGNOSTIC_SIGNALS.get("broken-wikilink")!.nextCommand;
+ expect(DIAGNOSTIC_SIGNALS.get("dangling-workrun")!.nextCommand).toBe(shared);
+ let emissions: ReadonlyArray<AdvisoryEmission> = [];
+ const out = await captureStdout(() => {
+ emissions = emitNextSteps(
+ ["broken-wikilink", "dangling-workrun", "broken-wikilink", "broken-backlinks"],
+ HUMAN,
+ );
+ });
+ const backlinks = DIAGNOSTIC_SIGNALS.get("broken-backlinks")!.nextCommand;
+ expect(out).toBe(`next: ${shared}\nnext: ${backlinks}\n`);
+ expect(emissions.map((e) => e.outcome)).toEqual([
+ ADVISORY_OUTCOME.emitted,
+ ADVISORY_OUTCOME.emitted,
+ ]);
+ });
+
+ test("an unregistered code is reported once by name and never printed", async () => {
+ let emissions: ReadonlyArray<AdvisoryEmission> = [];
+ const out = await captureStdout(() => {
+ emissions = emitNextSteps(
+ ["no-such-diagnostic-code", "no-such-diagnostic-code", REGISTERED_CODE],
+ HUMAN,
+ );
+ });
+ expect(out).toBe(`next: ${REGISTERED_COMMAND}\n`);
+ expect(emissions.map((e) => e.outcome)).toEqual([
+ ADVISORY_OUTCOME.unregisteredCode,
+ ADVISORY_OUTCOME.emitted,
+ ]);
+ // "by name" is the whole point of returning an unregistered code at
+ // all: a caller batching codes must be able to say WHICH of its
+ // issues has no exit. Asserting only the outcome would let the
+ // record stop carrying the name without any test noticing.
+ expect(emissions.map((e) => e.code)).toEqual(["no-such-diagnostic-code", REGISTERED_CODE]);
+ });
+
+ test("no codes means no lines and no emissions", async () => {
+ let emissions: ReadonlyArray<AdvisoryEmission> = [];
+ const out = await captureStdout(() => {
+ emissions = emitNextSteps([], HUMAN);
+ });
+ expect(out).toBe("");
+ expect(emissions).toEqual([]);
+ });
+
+ test("a machine stream still resolves every distinct step, silently", async () => {
+ let emissions: ReadonlyArray<AdvisoryEmission> = [];
+ const out = await captureStdout(() => {
+ emissions = emitNextSteps([REGISTERED_CODE, REGISTERED_CODE], {
+ command: "brain",
+ argv: ["doctor", "--json"],
+ jsonRequested: true,
+ });
+ });
+ expect(out).toBe("");
+ expect(emissions).toHaveLength(1);
+ expect(emissions[0]!.outcome).toBe(ADVISORY_OUTCOME.suppressedMachineStream);
+ expect(emissions[0]!.nextStep!.nextCommand).toBe(REGISTERED_COMMAND);
+ });
+});
+
+describe("wantsJsonFlag - a flag, not a positional value", () => {
+ test("the flag in its own token is still a JSON request", () => {
+ expect(wantsJsonFlag(["note", "hello", "--json"])).toBe(true);
+ expect(wantsJsonFlag(["--json"])).toBe(true);
+ expect(wantsJsonFlag(["list", "--json=pretty"])).toBe(true);
+ });
+
+ test("no flag at all is not a JSON request", () => {
+ expect(wantsJsonFlag([])).toBe(false);
+ expect(wantsJsonFlag(["note", "hello"])).toBe(false);
+ expect(wantsJsonFlag(["note", "--jsonx"])).toBe(false);
+ });
+
+ test("a note whose text merely mentions the flag is not a JSON request", () => {
+ expect(wantsJsonFlag(["note", "see --json for details"])).toBe(false);
+ });
+
+ test("after the argv terminator the flag is literal content", () => {
+ expect(wantsJsonFlag(["note", "--", "--json"])).toBe(false);
+ expect(wantsJsonFlag(["note", "--", "--json=pretty"])).toBe(false);
+ expect(wantsJsonFlag(["note", "--json", "--", "--json"])).toBe(true);
+ });
+
+ test("a value-position flag stays a JSON request, and that is deliberate", () => {
+ // `--principle --json` is the value of a string flag, but which flags
+ // take a value is per-verb schema the two `main.ts` call sites do not
+ // have. The scan errs toward the envelope (a buffered extra wrapper)
+ // rather than toward silencing a human-path advisory, and `--` is the
+ // documented way to make the token literal. Pinned so the limitation is
+ // visible rather than discovered.
+ expect(wantsJsonFlag(["feedback", "--principle", "--json"])).toBe(true);
+ expect(wantsJsonFlag(["feedback", "--principle", "--", "--json"])).toBe(false);
+ });
+
+ test("the scan agrees with the parser it guards", () => {
+ const shapes: ReadonlyArray<ReadonlyArray<string>> = [
+ [],
+ ["--json"],
+ ["hello", "--json"],
+ ["--", "--json"],
+ ["note", "--", "--json"],
+ ["see --json for details"],
+ ];
+ for (const argv of shapes) {
+ const parsed = parseFlags(argv, {});
+ expect(`${argv.join(" ")}: ${wantsJsonFlag(argv)}`).toBe(
+ `${argv.join(" ")}: ${parsed.flags["json"] === true}`,
+ );
+ }
+ });
+});
+
+describe("byte-identical when the rail is not called", () => {
+ let tmp: string;
+ let vault: string;
+ let configPath: string;
+
+ beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-advisory-rail-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+ });
+
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ });
+
+ test("a note mentioning the flag stays on the human path and prints its own line", async () => {
+ const res = await runCli(["brain", "note", "see --json for details"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toMatch(/^logged note at Brain\/log\/\d{4}-\d{2}-\d{2}\.md\n$/);
+ expect(res.stdout).not.toContain("next:");
+ });
+
+ test("the JSON envelope still wraps a command that does not own a JSON branch", async () => {
+ const plain = await runCli(["completions", "bash"]);
+ const wrapped = await runCli(["completions", "bash", "--json"]);
+ expect(plain.returncode).toBe(0);
+ expect(wrapped.returncode).toBe(0);
+ expect(JSON.parse(wrapped.stdout)).toEqual({
+ ok: true,
+ command: "completions",
+ code: 0,
+ stdout: plain.stdout,
+ stderr: "",
+ });
+ expect(plain.stdout).not.toContain("next:");
+ });
+
+ test("a command that owns its JSON branch is untouched", async () => {
+ const res = await runCli(["help", "--json"]);
+ expect(res.returncode).toBe(0);
+ expect(() => JSON.parse(res.stdout)).not.toThrow();
+ expect(res.stdout).not.toContain("next:");
+ });
+});
diff --git a/tests/cli/brain-doctor-next-step.test.ts b/tests/cli/brain-doctor-next-step.test.ts
new file mode 100644
index 00000000..2c59606f
--- /dev/null
+++ b/tests/cli/brain-doctor-next-step.test.ts
@@ -0,0 +1,228 @@
+/**
+ * `o2b brain doctor` names its exits (no-dead-ends, task 4).
+ *
+ * The doctor is the densest diagnosis surface in the product and, until
+ * this task, the only consumer of {@link DIAGNOSTIC_SIGNALS} it was NOT:
+ * it printed `[WARN] <code>: <message>` and stopped, leaving the caller
+ * to re-derive the repair. Every reported issue now goes through the
+ * advisory rail, so the human surface prints the structural command and
+ * the JSON surface carries it as a field.
+ *
+ * Three obligations are pinned here. A registered code names its command
+ * on both surfaces. An unregistered code names nothing on either - the
+ * doctor must be able to report an issue it has no exit for without
+ * inventing one. And a clean vault is byte-for-byte what it was before,
+ * because a surface that gained a line when it had nothing to say would
+ * be chrome, not a next step.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
+import { DOCTOR_EXIT_EXCLUSIONS } from "../../src/core/brain/doctor-exits.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+/** Two registered doctor codes that share one structural command. */
+const REPAIR_COMMAND = DIAGNOSTIC_SIGNALS.get("broken-wikilink")!.nextCommand;
+/** A registered doctor code with a command of its own. */
+const BACKLINKS_COMMAND = DIAGNOSTIC_SIGNALS.get("broken-backlinks")!.nextCommand;
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-next-step-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath: config });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/**
+ * Seed two registered warning classes that resolve to the SAME command
+ * (`broken-wikilink` from the dead evidence pointer, `dangling-workrun`
+ * from the unterminated journal) plus one that resolves to a different
+ * one (`broken-backlinks`, raised by the same dead pointer).
+ */
+function seedRegisteredIssues(): void {
+ const runs = join(vault, "Brain", "log", "dream-runs");
+ mkdirSync(runs, { recursive: true });
+ writeFileSync(
+ join(runs, "run-next-step.jsonl"),
+ JSON.stringify({ phase: "started", at: "2026-07-18T00:00:00.000Z", run_id: "run-next-step" }) +
+ "\n",
+ "utf8",
+ );
+ writePreference(vault, {
+ slug: "dead-pointer",
+ topic: "dead-pointer",
+ principle: "a rule whose evidence pointer went missing",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-does-not-exist]]"],
+ });
+}
+
+/**
+ * Seed `status-folder-mismatch`: a real doctor code with no registry
+ * entry, and the only issue in the vault. The status is rewritten after
+ * the write because the writer refuses to emit a folder-inconsistent
+ * one - which is the point of the lint.
+ */
+function seedUnregisteredIssue(): void {
+ writePreference(vault, {
+ slug: "mismatch",
+ topic: "mismatch",
+ principle: "a rule filed under the wrong folder",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ const path = join(vault, "Brain", "preferences", "pref-mismatch.md");
+ writeFileSync(
+ path,
+ readFileSync(path, "utf8").replace("_status: unconfirmed", "_status: retired"),
+ "utf8",
+ );
+}
+
+/** Every `next:` line in `stdout`, in order. */
+function nextLines(stdout: string): string[] {
+ return stdout.split("\n").filter((line) => line.startsWith("next: "));
+}
+
+describe("brain doctor - the human surface names the command", () => {
+ test("a registered code prints its structural next command", async () => {
+ seedRegisteredIssues();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("[WARN] broken-wikilink:");
+ expect(nextLines(r.stdout)).toContain(`next: ${REPAIR_COMMAND}`);
+ expect(nextLines(r.stdout)).toContain(`next: ${BACKLINKS_COMMAND}`);
+ });
+
+ test("two codes sharing one command print that command once", async () => {
+ seedRegisteredIssues();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ // `broken-wikilink` and `dangling-workrun` both exit through the
+ // repair verb. Two identical lines would be noise, not a next step.
+ expect(r.stdout).toContain("[WARN] broken-wikilink:");
+ expect(r.stdout).toContain("[WARN] dangling-workrun:");
+ const repeated = nextLines(r.stdout).filter((line) => line === `next: ${REPAIR_COMMAND}`);
+ expect(repeated).toHaveLength(1);
+ });
+
+ test("an unregistered code prints no next step at all", async () => {
+ seedUnregisteredIssue();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("[WARN] status-folder-mismatch:");
+ expect(nextLines(r.stdout)).toEqual([]);
+ });
+});
+
+describe("brain doctor --json - the field, never the line", () => {
+ test("a registered issue carries next_command and stdout still parses", async () => {
+ seedRegisteredIssues();
+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ const payload = JSON.parse(r.stdout) as {
+ warnings: ReadonlyArray<{ code: string; next_command?: string }>;
+ };
+ const wikilink = payload.warnings.find((w) => w.code === "broken-wikilink");
+ expect(wikilink?.next_command).toBe(REPAIR_COMMAND);
+ const backlinks = payload.warnings.find((w) => w.code === "broken-backlinks");
+ expect(backlinks?.next_command).toBe(BACKLINKS_COMMAND);
+ });
+
+ test("an unregistered issue carries no next_command key", async () => {
+ seedUnregisteredIssue();
+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ const payload = JSON.parse(r.stdout) as {
+ warnings: ReadonlyArray<Record<string, unknown>>;
+ };
+ const mismatch = payload.warnings.find((w) => w["code"] === "status-folder-mismatch");
+ expect(mismatch).toBeDefined();
+ expect(Object.hasOwn(mismatch!, "next_command")).toBe(false);
+ });
+});
+
+describe("brain doctor - silence is explained, not merely silent", () => {
+ test("a code with no exit says so, with the published reason", async () => {
+ seedUnregisteredIssue();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(
+ `no exit: status-folder-mismatch - ${DOCTOR_EXIT_EXCLUSIONS.get("status-folder-mismatch")!}`,
+ );
+ });
+
+ test("a registered code contributes no explanation - it has a command instead", async () => {
+ seedRegisteredIssues();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.stdout).not.toContain("no exit: broken-wikilink");
+ });
+
+ test("--json carries the reasons once per code, off the issue records", async () => {
+ seedUnregisteredIssue();
+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.stdout).not.toContain("no exit: ");
+ const payload = JSON.parse(r.stdout) as {
+ no_exit?: Record<string, string>;
+ warnings: ReadonlyArray<Record<string, unknown>>;
+ };
+ expect(payload.no_exit?.["status-folder-mismatch"]).toBe(
+ DOCTOR_EXIT_EXCLUSIONS.get("status-folder-mismatch")!,
+ );
+ // The reason rides once, beside the streams - never repeated per issue.
+ const mismatch = payload.warnings.find((w) => w["code"] === "status-folder-mismatch");
+ expect(Object.hasOwn(mismatch!, "no_exit")).toBe(false);
+ });
+});
+
+describe("brain doctor - byte-identical when there is nothing to point at", () => {
+ test("a clean vault prints exactly what it printed before", async () => {
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe("brain doctor: clean\n");
+ });
+
+ test("a clean vault's JSON payload is the pre-task shape", async () => {
+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe(JSON.stringify({ warnings: [], errors: [] }, null, 2) + "\n");
+ });
+});
diff --git a/tests/cli/brain-dream-operator-surface.test.ts b/tests/cli/brain-dream-operator-surface.test.ts
new file mode 100644
index 00000000..f47d9bf3
--- /dev/null
+++ b/tests/cli/brain-dream-operator-surface.test.ts
@@ -0,0 +1,470 @@
+/**
+ * The two shipped dream capabilities reach an operator (no-dead-ends,
+ * phase 3, item 1).
+ *
+ * `runDreamStep` and the per-run gate override both landed as TypeScript
+ * arguments with no flag, no MCP argument and no way to reach them from a
+ * shell. The kanban unit they implement asked for exactly the operator
+ * capability - run a targeted pass "without the stateful, error-prone
+ * dance of toggling phase gates and remembering to revert them" - so a
+ * TypeScript-only argument does not deliver it.
+ *
+ * What is asserted here:
+ * - both runnable steps run from `o2b brain dream --step <name>`;
+ * - every other token is REFUSED BY NAME, carrying the specific reason
+ * and the runnable set, on both the human and the `--json` stream;
+ * - `--gate <name>=<true|false>` steers one run and leaves
+ * `Brain/_brain.yaml` byte-identical;
+ * - the same two capabilities exist on MCP `brain_dream`;
+ * - with neither flag present the verb is byte-identical to today.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { DREAM_PHASE } from "../../src/core/brain/dream-phases.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-operator-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const brainConfigPath = (): string => join(vault, "Brain", "_brain.yaml");
+
+/** Three same-sign signals: enough that a full pass promotes them. */
+function seedPromotion(topic = "operator-surface"): void {
+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: "Prefer the operated approach",
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug: `op${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+/**
+ * Two user pages where one mentions the other's exact title, so the
+ * heal enrichment has something deterministic to rewrite.
+ */
+function makeLinkableNotes(): string {
+ const notes = join(vault, "Notes");
+ mkdirSync(notes, { recursive: true });
+ writeFileSync(join(notes, "target.md"), "---\ntitle: Widget Registry\n---\n\nBody.\n", "utf8");
+ const refPath = join(notes, "ref.md");
+ writeFileSync(
+ refPath,
+ "---\ntitle: Reference Page\n---\n\nSee the Widget Registry for details.\n",
+ "utf8",
+ );
+ return refPath;
+}
+
+async function makeServer(): Promise<MCPServer> {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "dream-operator-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ return server;
+}
+
+let callId = 100;
+async function callDream(
+ server: MCPServer,
+ args: Record<string, unknown>,
+): Promise<{ structured?: Record<string, unknown>; errorCode?: number; errorMessage?: string }> {
+ callId += 1;
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: callId,
+ method: "tools/call",
+ params: { name: "brain_dream", arguments: args },
+ })) as {
+ result?: { structuredContent?: Record<string, unknown> };
+ error?: { code: number; message: string };
+ };
+ if (r.error) return { errorCode: r.error.code, errorMessage: r.error.message };
+ return { structured: r.result?.structuredContent };
+}
+
+describe("o2b brain dream --step", () => {
+ test("runs the scan step and reports only what the scan observed", async () => {
+ seedPromotion();
+ const r = await runCli(["brain", "dream", "--step", "scan", "--vault", vault, "--json"]);
+
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.step).toBe("scan");
+ expect(payload.partial).toBe(true);
+ expect(payload.active_signals).toBe(3);
+ expect(payload.preferences).toBe(0);
+ // A partial result must not assert the fields a full pass owns.
+ expect(payload).not.toHaveProperty("run_id");
+ expect(payload).not.toHaveProperty("changed");
+ // A pure read promotes nothing.
+ const after = await runCli(["brain", "dream", "--step", "scan", "--vault", vault, "--json"]);
+ expect(JSON.parse(after.stdout).preferences).toBe(0);
+ });
+
+ test("runs the heal-enrich step even with the config gate off", async () => {
+ const refPath = makeLinkableNotes();
+ const before = readFileSync(brainConfigPath(), "utf8");
+
+ const r = await runCli(["brain", "dream", "--step", "heal-enrich", "--vault", vault, "--json"]);
+
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.step).toBe("heal-enrich");
+ expect(payload.partial).toBe(true);
+ expect(payload.enriched).toBe(1);
+ expect(readFileSync(refPath, "utf8")).toContain("[[Widget Registry]]");
+ // Asking for the step IS the opt-in; it never writes the config back.
+ expect(readFileSync(brainConfigPath(), "utf8")).toBe(before);
+ });
+
+ test("human output names the step and its counters", async () => {
+ seedPromotion();
+ const r = await runCli(["brain", "dream", "--step", "scan", "--vault", vault]);
+
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("step: scan\n");
+ expect(r.stdout).toContain("active_signals: 3\n");
+ });
+
+ test("refuses a reporting phase by name and prints the runnable set", async () => {
+ const r = await runCli(["brain", "dream", "--step", DREAM_PHASE.synthesize, "--vault", vault]);
+
+ expect(r.returncode).toBe(2);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toContain(`dream step '${DREAM_PHASE.synthesize}' is not independently`);
+ // The SPECIFIC reason, not a generic "unsupported".
+ expect(r.stderr).toContain("planRefresh and planAutoRetires mutate each other's accumulators");
+ expect(r.stderr).toContain("Independently runnable steps: scan, heal-enrich");
+ });
+
+ test("refuses a token that is not even a reporting phase", async () => {
+ const r = await runCli(["brain", "dream", "--step", "hibernate", "--vault", vault]);
+
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain(
+ "it is neither a runnable dream step nor one of the dream reporting phases",
+ );
+ expect(r.stderr).toContain("Independently runnable steps: scan, heal-enrich");
+ });
+
+ test("every non-runnable phase is refused, each with its own reason", async () => {
+ const reasons = new Set<string>();
+ for (const phase of Object.values(DREAM_PHASE)) {
+ // oxlint-disable-next-line no-await-in-loop -- runCli patches process.stdout in-process, so concurrent invocations would interleave each other's captured output
+ const r = await runCli(["brain", "dream", "--step", phase, "--vault", vault]);
+ expect(`${phase} exit: ${r.returncode}`).toBe(`${phase} exit: 2`);
+ reasons.add(r.stderr);
+ }
+ expect(reasons.size).toBe(Object.values(DREAM_PHASE).length);
+ });
+
+ test("the refusal is a clean JSON payload under --json", async () => {
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--step",
+ DREAM_PHASE.log,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+
+ expect(r.returncode).toBe(2);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.ok).toBe(false);
+ expect(payload.step).toBe(DREAM_PHASE.log);
+ expect(payload.runnable).toEqual(["scan", "heal-enrich"]);
+ expect(typeof payload.reason).toBe("string");
+ expect(payload.reason.length).toBeGreaterThan(0);
+ });
+
+ test("refuses --step combined with the flags a full pass owns", async () => {
+ for (const extra of [["--dry-run"], ["--strict"], ["--expect", "0"]]) {
+ // oxlint-disable-next-line no-await-in-loop -- runCli patches process.stdout in-process, so concurrent invocations would interleave each other's captured output
+ const r = await runCli(["brain", "dream", "--step", "scan", ...extra, "--vault", vault]);
+ expect(`${extra[0]} exit: ${r.returncode}`).toBe(`${extra[0]} exit: 2`);
+ expect(r.stderr).toContain(extra[0]!);
+ }
+ });
+
+ test("refuses --step on an action other than run", async () => {
+ const r = await runCli(["brain", "dream", "list", "--step", "scan", "--vault", vault]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("--step");
+ expect(r.stderr).toContain("list");
+ });
+});
+
+describe("o2b brain dream --gate", () => {
+ test("turns the heal gate on for one run and leaves the config byte-identical", async () => {
+ seedPromotion();
+ const refPath = makeLinkableNotes();
+ const before = readFileSync(brainConfigPath(), "utf8");
+
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--gate",
+ "heal_enrich=true",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+
+ expect(r.returncode).toBe(0);
+ expect(JSON.parse(r.stdout).changed).toBe(true);
+ expect(readFileSync(refPath, "utf8")).toContain("[[Widget Registry]]");
+ expect(readFileSync(brainConfigPath(), "utf8")).toBe(before);
+ });
+
+ test("turns the heal gate off for one run on a vault whose config enables it", async () => {
+ seedPromotion();
+ const refPath = makeLinkableNotes();
+ writeFileSync(
+ brainConfigPath(),
+ "schema_version: 1\ndream:\n heal_enrich_enabled: true\n",
+ "utf8",
+ );
+ const before = readFileSync(brainConfigPath(), "utf8");
+
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--gate",
+ "heal_enrich=false",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+
+ expect(r.returncode).toBe(0);
+ expect(readFileSync(refPath, "utf8")).not.toContain("[[Widget Registry]]");
+ expect(readFileSync(brainConfigPath(), "utf8")).toBe(before);
+ });
+
+ test("refuses an unknown gate name, listing the known ones", async () => {
+ const r = await runCli(["brain", "dream", "--gate", "retire_floor=true", "--vault", vault]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("retire_floor");
+ expect(r.stderr).toContain("heal_enrich");
+ });
+
+ test("refuses a value that is not a boolean token", async () => {
+ const r = await runCli(["brain", "dream", "--gate", "heal_enrich=maybe", "--vault", vault]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("maybe");
+ expect(r.stderr).toContain("true");
+ expect(r.stderr).toContain("false");
+ });
+
+ test("refuses an entry with no value at all", async () => {
+ const r = await runCli(["brain", "dream", "--gate", "heal_enrich", "--vault", vault]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("heal_enrich");
+ });
+
+ test("refuses two contradictory overrides of the same gate", async () => {
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--gate",
+ "heal_enrich=true",
+ "--gate",
+ "heal_enrich=false",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("heal_enrich");
+ });
+
+ test("refuses --gate together with --step", async () => {
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--step",
+ "heal-enrich",
+ "--gate",
+ "heal_enrich=true",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("--gate");
+ });
+});
+
+describe("byte-identical when absent", () => {
+ test("a run with neither flag prints exactly what it printed before", async () => {
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--dry-run",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe("run_id: dream-2026-05-30-100000\nchanged: false\n");
+ expect(r.stderr).toBe("");
+ });
+
+ test("the JSON run payload gains no step or gate key", async () => {
+ const r = await runCli([
+ "brain",
+ "dream",
+ "--dry-run",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ const payload = JSON.parse(r.stdout);
+ expect(payload).not.toHaveProperty("step");
+ expect(payload).not.toHaveProperty("gates");
+ expect(payload).toHaveProperty("run_id");
+ });
+});
+
+describe("the manifest advertises both flags", () => {
+ test("help --json models --step and --gate on brain dream", async () => {
+ const r = await runCli(["help", "--json"]);
+ const parsed = JSON.parse(r.stdout);
+ const brain = parsed.commands.find((c: { name: string }) => c.name === "brain");
+ const dream = brain.commands.find((c: { name: string }) => c.name === "dream");
+ expect(dream.flags).toContainEqual({ name: "step", type: "string" });
+ expect(dream.flags).toContainEqual({ name: "gate", type: "string-array" });
+ });
+
+ test("completions advertise the new flags", async () => {
+ const r = await runCli(["completions", "bash"]);
+ expect(r.stdout).toContain("--step");
+ expect(r.stdout).toContain("--gate");
+ });
+});
+
+describe("MCP brain_dream carries the same two capabilities", () => {
+ test("step=scan returns the partial scan result", async () => {
+ seedPromotion();
+ const server = await makeServer();
+ const r = await callDream(server, { step: "scan" });
+ expect(r.errorCode).toBeUndefined();
+ expect(r.structured!["step"]).toBe("scan");
+ expect(r.structured!["partial"]).toBe(true);
+ expect(r.structured!["active_signals"]).toBe(3);
+ });
+
+ test("step=heal-enrich runs the enrichment with the config gate off", async () => {
+ const refPath = makeLinkableNotes();
+ const server = await makeServer();
+ const r = await callDream(server, { step: "heal-enrich" });
+ expect(r.errorCode).toBeUndefined();
+ expect(r.structured!["enriched"]).toBe(1);
+ expect(readFileSync(refPath, "utf8")).toContain("[[Widget Registry]]");
+ });
+
+ test("a non-runnable step is INVALID_PARAMS carrying the specific reason", async () => {
+ const server = await makeServer();
+ const r = await callDream(server, { step: DREAM_PHASE.heal });
+ expect(r.errorCode).toBe(-32602);
+ expect(r.errorMessage).toContain("planAutoRetires deletes from refresh.updated");
+ expect(r.errorMessage).toContain("Independently runnable steps: scan, heal-enrich");
+ });
+
+ test("gates override the vault config for one run and write nothing back", async () => {
+ seedPromotion();
+ const refPath = makeLinkableNotes();
+ const before = readFileSync(brainConfigPath(), "utf8");
+ const server = await makeServer();
+
+ const r = await callDream(server, {
+ gates: { heal_enrich: true },
+ now: "2026-05-30T10:00:00Z",
+ });
+
+ expect(r.errorCode).toBeUndefined();
+ expect(r.structured!["changed"]).toBe(true);
+ expect(readFileSync(refPath, "utf8")).toContain("[[Widget Registry]]");
+ expect(readFileSync(brainConfigPath(), "utf8")).toBe(before);
+ });
+
+ test("an unknown gate is INVALID_PARAMS naming the known gates", async () => {
+ const server = await makeServer();
+ const r = await callDream(server, { gates: { retire_floor: true } });
+ expect(r.errorCode).toBe(-32602);
+ expect(r.errorMessage).toContain("retire_floor");
+ expect(r.errorMessage).toContain("heal_enrich");
+ });
+
+ test("a non-boolean gate value is INVALID_PARAMS", async () => {
+ const server = await makeServer();
+ const r = await callDream(server, { gates: { heal_enrich: "yes" } });
+ expect(r.errorCode).toBe(-32602);
+ });
+
+ test("the tool advertises both arguments", async () => {
+ const server = await makeServer();
+ const listed = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 900,
+ method: "tools/list",
+ })) as { result: { tools: Array<{ name: string; inputSchema: { properties: object } }> } };
+ const tool = listed.result.tools.find((t) => t.name === "brain_dream")!;
+ expect(Object.keys(tool.inputSchema.properties)).toContain("step");
+ expect(Object.keys(tool.inputSchema.properties)).toContain("gates");
+ });
+});
diff --git a/tests/cli/brain-hygiene.test.ts b/tests/cli/brain-hygiene.test.ts
new file mode 100644
index 00000000..9ba422dd
--- /dev/null
+++ b/tests/cli/brain-hygiene.test.ts
@@ -0,0 +1,238 @@
+/**
+ * `o2b brain hygiene` at the CLI level (no-dead-ends, task 23).
+ *
+ * The verb is write-capable and had no CLI-level test: the scan, the
+ * plan and the applier under it were covered, but nothing exercised the
+ * subcommand dispatch, the detector list parsing, the JSON surfaces, the
+ * `--ids` requirement, or the `--dry-run` claim through the CLI. This
+ * release touches the applier (task 8 moved its write guard and routed
+ * its exclusion decision through the capability table), so the tier is
+ * established here.
+ *
+ * As for lint: a dry run is measured against the whole tree digest, and
+ * an apply is measured against the exact set of paths that changed.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainDirs } from "../../src/core/brain/paths.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";
+import { runCli } from "../helpers/run-cli.ts";
+import { changedPaths, digestVaultFiles, digestVaultTree } from "../helpers/vault-digest.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+interface ScanJson {
+ readonly generated_at: string;
+ readonly detectors_run: ReadonlyArray<string>;
+ readonly findings: ReadonlyArray<{ id: string; detector: string; proposed_action: string }>;
+ readonly counts: Readonly<Record<string, number>>;
+ readonly errors: ReadonlyArray<unknown>;
+}
+
+interface ApplyJson {
+ readonly plan: {
+ readonly selected: ReadonlyArray<{ id: string }>;
+ readonly excluded_review: ReadonlyArray<string>;
+ readonly unknown_ids: ReadonlyArray<string>;
+ };
+ readonly result: {
+ readonly dry_run: boolean;
+ readonly planned: ReadonlyArray<{ action: string; finding_id: string }>;
+ readonly applied: ReadonlyArray<{ action: string; finding_id: string }>;
+ readonly errors: ReadonlyArray<unknown>;
+ };
+}
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-hygiene-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function env(): Record<string, string> {
+ return { OPEN_SECOND_BRAIN_CONFIG: configPath };
+}
+
+function writePref(slug: string, topic: string, principle: string): void {
+ writeFileSync(
+ join(brainDirs(vault).preferences, `pref-${slug}.md`),
+ [
+ "---",
+ "kind: brain-preference",
+ `id: pref-${slug}`,
+ "tags: [brain, brain/preference]",
+ `topic: ${topic}`,
+ "_status: confirmed",
+ `principle: ${principle}`,
+ "created_at: 2026-01-01T00:00:00Z",
+ "unconfirmed_until: 2026-01-15T00:00:00Z",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+}
+
+/** Two near-identical confirmed rules: the dedup detector proposes a merge. */
+function seedDuplicatePair(): void {
+ writePref("dup-a", "same-topic", "collect metrics before optimizing the code");
+ writePref("dup-b", "same-topic", "collect metrics before optimizing the code base");
+}
+
+async function scan(...extra: string[]): Promise<ScanJson> {
+ const out = await runCli(["brain", "hygiene", "scan", "--vault", vault, "--json", ...extra], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ return JSON.parse(out.stdout) as ScanJson;
+}
+
+describe("o2b brain hygiene scan", () => {
+ test("the JSON surface parses and names the dedup finding", async () => {
+ seedDuplicatePair();
+
+ const report = await scan("--detectors", "dedup");
+
+ expect(report.detectors_run).toEqual(["dedup"]);
+ expect(report.errors).toEqual([]);
+ expect(report.findings).toHaveLength(1);
+ expect(report.findings[0]!.proposed_action).toBe("merge");
+ expect(report.counts["dedup"]).toBe(1);
+ });
+
+ test("scan is read-only", async () => {
+ seedDuplicatePair();
+ const before = digestVaultTree(vault);
+ await scan("--detectors", "dedup");
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+
+ test("the human surface prints the finding and its proposed action", async () => {
+ seedDuplicatePair();
+ const out = await runCli(
+ ["brain", "hygiene", "scan", "--vault", vault, "--detectors", "dedup"],
+ { env: env() },
+ );
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toContain("dedup: 1 finding(s)");
+ expect(out.stdout).toContain("-> merge");
+ });
+
+ test("an unknown detector is a named refusal", async () => {
+ const out = await runCli(
+ ["brain", "hygiene", "scan", "--vault", vault, "--detectors", "not-a-detector"],
+ { env: env() },
+ );
+ expect(out.returncode).not.toBe(0);
+ expect(out.stderr).toContain("conflicts, dedup, freshness, usefulness");
+ });
+});
+
+describe("o2b brain hygiene apply", () => {
+ test("a dry run reports the routed action and leaves the tree digest unchanged", async () => {
+ seedDuplicatePair();
+ const id = (await scan("--detectors", "dedup")).findings[0]!.id;
+ const before = digestVaultTree(vault);
+
+ const out = await runCli(
+ [
+ "brain",
+ "hygiene",
+ "apply",
+ "--vault",
+ vault,
+ "--detectors",
+ "dedup",
+ "--ids",
+ id,
+ "--dry-run",
+ "--json",
+ ],
+ { env: env() },
+ );
+
+ expect(out.returncode).toBe(0);
+ const payload = JSON.parse(out.stdout) as ApplyJson;
+ expect(payload.result.dry_run).toBe(true);
+ expect(payload.result.applied).toEqual([]);
+ expect(payload.result.planned.map((a) => a.action)).toEqual(["merge"]);
+ expect(payload.plan.selected.map((f) => f.id)).toEqual([id]);
+
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+
+ test("an apply changes exactly the set the merge reports", async () => {
+ seedDuplicatePair();
+ const id = (await scan("--detectors", "dedup")).findings[0]!.id;
+ const before = digestVaultFiles(vault);
+
+ const out = await runCli(
+ [
+ "brain",
+ "hygiene",
+ "apply",
+ "--vault",
+ vault,
+ "--detectors",
+ "dedup",
+ "--ids",
+ id,
+ "--json",
+ ],
+ { env: env() },
+ );
+
+ expect(out.returncode).toBe(0);
+ const payload = JSON.parse(out.stdout) as ApplyJson;
+ expect(payload.result.dry_run).toBe(false);
+ expect(payload.result.errors).toEqual([]);
+ expect(payload.result.applied.map((a) => a.action)).toEqual(["merge"]);
+
+ // A merge keeps the first target, retires the second, and records the
+ // action in the hygiene audit log. Naming the set means a write
+ // anywhere else fails this test.
+ const changed = changedPaths(before, digestVaultFiles(vault));
+ expect(changed.filter((p) => p.startsWith("Brain/preferences/"))).toEqual([
+ "Brain/preferences/pref-dup-a.md",
+ "Brain/preferences/pref-dup-b.md",
+ ]);
+ expect(changed.some((p) => p.startsWith("Brain/retired/ret-"))).toBe(true);
+ expect(changed.some((p) => p.startsWith("Brain/log/hygiene/"))).toBe(true);
+ });
+
+ test("apply without --ids is refused and writes nothing", async () => {
+ seedDuplicatePair();
+ const before = digestVaultTree(vault);
+
+ const out = await runCli(
+ ["brain", "hygiene", "apply", "--vault", vault, "--detectors", "dedup"],
+ { env: env() },
+ );
+
+ expect(out.returncode).not.toBe(0);
+ expect(out.stderr).toContain("--ids");
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+
+ test("an unknown subcommand is a named refusal", async () => {
+ const out = await runCli(["brain", "hygiene", "sniff", "--vault", vault], { env: env() });
+ expect(out.returncode).not.toBe(0);
+ expect(out.stderr).toContain("scan|apply");
+ });
+});
diff --git a/tests/cli/brain-lint.test.ts b/tests/cli/brain-lint.test.ts
new file mode 100644
index 00000000..87e410dc
--- /dev/null
+++ b/tests/cli/brain-lint.test.ts
@@ -0,0 +1,170 @@
+/**
+ * `o2b brain lint` at the CLI level (no-dead-ends, task 23).
+ *
+ * The verb is write-capable and had no CLI-level test of any kind: the
+ * consolidation pass underneath it was covered, but nothing exercised the
+ * flag parsing, the non-interactive `--yes` gate, the JSON surface, or
+ * the claim that a dry run writes nothing. This release touches the pass
+ * (task 10 moved its write guard), so the tier is established here.
+ *
+ * The two load-bearing assertions:
+ *
+ * - a dry run leaves the vault tree digest UNCHANGED - measured over
+ * every file, not over the ones the report happened to name;
+ * - an apply changes EXACTLY the set the dry run reported - the set is
+ * compared, not merely its size or the fact that something moved.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, relative, sep } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainDirs } from "../../src/core/brain/paths.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";
+import { runCli } from "../helpers/run-cli.ts";
+import { changedPaths, digestVaultFiles, digestVaultTree } from "../helpers/vault-digest.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+/** A lint report as the `--json` surface renders it. */
+interface LintJson {
+ readonly scanned: number;
+ readonly applied: boolean;
+ readonly files_written: number;
+ readonly fixes: ReadonlyArray<{ path: string; from: string; to: string }>;
+ readonly demotions: ReadonlyArray<{ id: string; path: string }>;
+}
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-lint-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function pref(id: string, extra = ""): string {
+ return `---\nid: ${id}\ntopic: t\nprinciple: p\n${extra}---\n\nbody\n`;
+}
+
+/**
+ * A merged secondary plus two log days still naming it: the lint has two
+ * distinct files to rewrite, so "exactly the reported set" is a real
+ * claim rather than a one-element coincidence.
+ */
+function seedMergedLinks(): void {
+ const dirs = brainDirs(vault);
+ writeFileSync(join(dirs.preferences, "pref-canon.md"), pref("pref-canon"));
+ writeFileSync(
+ join(dirs.preferences, "pref-dup.md"),
+ pref("pref-dup", "merged_into: pref-canon\n"),
+ );
+ writeFileSync(join(dirs.log, "2026-05-25.md"), "saw [[pref-dup]] today\n");
+ writeFileSync(join(dirs.log, "2026-05-26.md"), "still [[pref-dup]] here\n");
+}
+
+function env(): Record<string, string> {
+ return { OPEN_SECOND_BRAIN_CONFIG: configPath };
+}
+
+function toRel(absolute: string): string {
+ return relative(vault, absolute).split(sep).join("/");
+}
+
+describe("o2b brain lint --consolidate", () => {
+ test("the JSON surface parses and reports the drift", async () => {
+ seedMergedLinks();
+
+ const out = await runCli(["brain", "lint", "--consolidate", "--vault", vault, "--json"], {
+ env: env(),
+ });
+
+ expect(out.returncode).toBe(0);
+ const report = JSON.parse(out.stdout) as LintJson;
+ expect(report.applied).toBe(false);
+ expect(report.files_written).toBe(0);
+ expect(report.scanned).toBeGreaterThan(0);
+ expect(report.fixes.map((f) => f.from)).toEqual(["pref-dup", "pref-dup"]);
+ expect(report.fixes.map((f) => f.to)).toEqual(["pref-canon", "pref-canon"]);
+ });
+
+ test("a dry run leaves the vault tree digest unchanged", async () => {
+ seedMergedLinks();
+ const before = digestVaultTree(vault);
+
+ const human = await runCli(["brain", "lint", "--consolidate", "--vault", vault], {
+ env: env(),
+ });
+ expect(human.returncode).toBe(0);
+ expect(human.stdout).toContain("dry-run");
+ expect(human.stdout).toContain("re-run with --apply --yes to write changes.");
+
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+
+ test("an apply changes exactly the set the dry run reported", async () => {
+ seedMergedLinks();
+
+ const preview = JSON.parse(
+ (await runCli(["brain", "lint", "--consolidate", "--vault", vault, "--json"], { env: env() }))
+ .stdout,
+ ) as LintJson;
+ const reported = [...new Set(preview.fixes.map((f) => toRel(f.path)))].toSorted();
+ expect(reported).toEqual(["Brain/log/2026-05-25.md", "Brain/log/2026-05-26.md"]);
+
+ const before = digestVaultFiles(vault);
+ const applied = await runCli(
+ ["brain", "lint", "--consolidate", "--apply", "--yes", "--vault", vault, "--json"],
+ { env: env() },
+ );
+ expect(applied.returncode).toBe(0);
+ const result = JSON.parse(applied.stdout) as LintJson;
+ expect(result.applied).toBe(true);
+ expect(result.files_written).toBe(reported.length);
+
+ expect(changedPaths(before, digestVaultFiles(vault))).toEqual(reported);
+ });
+
+ test("a clean vault reports nothing and writes nothing", async () => {
+ const before = digestVaultTree(vault);
+ const out = await runCli(["brain", "lint", "--consolidate", "--vault", vault, "--json"], {
+ env: env(),
+ });
+ const report = JSON.parse(out.stdout) as LintJson;
+ expect(report.fixes).toEqual([]);
+ expect(report.demotions).toEqual([]);
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+});
+
+describe("o2b brain lint - refusals", () => {
+ test("--apply without --yes is refused on the JSON path and writes nothing", async () => {
+ seedMergedLinks();
+ const before = digestVaultTree(vault);
+
+ const out = await runCli(
+ ["brain", "lint", "--consolidate", "--apply", "--vault", vault, "--json"],
+ { env: env() },
+ );
+
+ expect(out.returncode).not.toBe(0);
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+
+ test("no mode flag is a named refusal, not a silent success", async () => {
+ const out = await runCli(["brain", "lint", "--vault", vault], { env: env() });
+ expect(out.returncode).not.toBe(0);
+ expect(out.stderr).toContain("--consolidate");
+ });
+});
diff --git a/tests/cli/brain-pending.test.ts b/tests/cli/brain-pending.test.ts
index 30c65185..4a36adcf 100644
--- a/tests/cli/brain-pending.test.ts
+++ b/tests/cli/brain-pending.test.ts
@@ -77,6 +77,22 @@ describe("o2b brain pending", () => {
expect(existsSync(join(brainDirs(vault).retired, `${id}.md`))).toBe(true);
});
+ test("apply --dry-run reports the move and leaves the queue alone", async () => {
+ const id = stage("fact-url");
+ const out = await runCli(["brain", "pending", "apply", id, "--dry-run", "--json"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ const payload = JSON.parse(out.stdout) as { id: string; status: string; path: string };
+ expect(payload.id).toBe(id);
+ // A distinct status, so a JSON caller cannot read a preview as a move.
+ expect(payload.status).toBe("would-apply");
+ expect(payload.path.endsWith(`${id}.md`)).toBe(true);
+ // Nothing moved: the staged copy is still queued and the inbox is untouched.
+ expect(existsSync(join(brainDirs(vault).pending, `${id}.md`))).toBe(true);
+ expect(inboxNames()).not.toContain(`${id}.md`);
+ });
+
test("apply of a missing id exits 2 (typed error, not a no-op)", async () => {
const out = await runCli(["brain", "pending", "apply", "sig-2026-07-18-nope"], {
env: env(),
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index 8b61ac3f..b318dfa1 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -315,6 +315,18 @@ describe("onboarding", () => {
const parsed = JSON.parse(json.stdout);
expect(Array.isArray(parsed.steps)).toBe(true);
expect(parsed.steps.find((s: { id: string }) => s.id === "vault_configured").done).toBe(true);
+
+ // The notice records keep their three original keys and gain the
+ // structured command additively (no-dead-ends, task 3).
+ const missing = parsed.notices.find((n: { code: string }) => n.code === "search_index_missing");
+ expect(missing).toBeDefined();
+ expect(Object.keys(missing).toSorted()).toEqual([
+ "code",
+ "message",
+ "next_command",
+ "severity",
+ ]);
+ expect(missing.next_command).toBe("o2b search index");
});
});
diff --git a/tests/cli/forward-pointer-rail.test.ts b/tests/cli/forward-pointer-rail.test.ts
new file mode 100644
index 00000000..cedfdbfc
--- /dev/null
+++ b/tests/cli/forward-pointer-rail.test.ts
@@ -0,0 +1,381 @@
+/**
+ * The advisory rail is the only mechanism that emits a forward pointer
+ * (no-dead-ends, phase 3, item 2).
+ *
+ * `advisory-rail.ts` opens by stating that every forward-pointer line the
+ * CLI prints passes "through this module, and through nothing else".
+ * That was an aspiration, not a fact: hand-written pointers survived in
+ * five stdout call sites, one of them in the same file as a migrated one,
+ * so `clusters list` printed `- run: ...` while `clusters run` printed
+ * `next: ...`. The census in `terminal-state-census.test.ts` classifies
+ * which STATES have an exit; nothing stopped a second MECHANISM from
+ * reappearing beside the rail. This file is that ratchet.
+ *
+ * ## How a pointer is detected, structurally
+ *
+ * A forward pointer is a literal naming THIS TOOL'S OWN INVOCATION that
+ * reaches stdout on a success path. Both halves are structural facts
+ * about the source, not words in any language:
+ *
+ * - the invocation is the binary name `o2b` followed by verb tokens;
+ * - "reaches stdout" is the callee: `ok`, `info` and
+ * `process.stdout.write` are the CLI's stdout writers, while every
+ * refusal goes to stderr through `fail`, `failWith`, `usageError` or
+ * `process.stderr.write`. The refusal family is therefore outside the
+ * population BY CONSTRUCTION - it is never filtered out by matching
+ * on what the message says.
+ *
+ * Two SHAPES inside that population are not pointers, and each is
+ * subtracted by a rule rather than by an entry per instance, because both
+ * recur every time a verb is added:
+ *
+ * - a **usage grammar**: the text after the invocation carries this
+ * CLI's optional-group bracket or its alternation bar. A next command
+ * never can - it is one exact invocation, and a test below pins that
+ * against the whole registry.
+ * - a **self-label**: the literal opens with the invocation followed
+ * immediately by a colon, which is a command naming its own output
+ * line, not naming somewhere to go.
+ *
+ * ## The limit, stated rather than discovered
+ *
+ * The scan reads the arguments of a writer CALL. A literal that reaches
+ * stdout indirectly - returned by a renderer the caller writes, or pushed
+ * into an array joined later - is outside what a per-call-site scan can
+ * see. `o2b search status` was such a site and is migrated here; the
+ * `install` plan renderers legitimately name per-target commands the
+ * registry cannot hold and are out of reach of both this ratchet and the
+ * rail.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, relative } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
+import { resolveNextStep } from "../../src/core/brain/next-step.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+const CLI_ROOT = join(REPO_ROOT, "src", "cli");
+
+/**
+ * The CLI's stdout writers. `okJson` and `writeJson` are deliberately
+ * absent: they serialise a payload, and a next command belongs in that
+ * payload as a field, which is a different mechanism with its own test.
+ */
+const STDOUT_WRITER_RE = /(?:\bok|\binfo|process\.stdout\.write)\(/g;
+
+/** This tool's own invocation: the binary name plus its verb tokens. */
+const INVOCATION_RE = /\bo2b(?:\s+[a-z][a-z0-9-]*)+/g;
+
+/**
+ * This CLI's usage notation: an optional group or an alternation. A
+ * `nextCommand` is one exact invocation and carries neither - pinned
+ * against the whole registry by a test below.
+ */
+const USAGE_NOTATION_RE = /[[|]/;
+
+/** A source-level string delimiter. */
+const QUOTE_RE = /['"`]$/;
+
+/**
+ * Sites where a literal invocation reaches stdout and the rail genuinely
+ * cannot carry it. `count` pins how many such literals the site holds, so
+ * a NEW hand-written pointer in an already-sanctioned file fails here
+ * instead of hiding behind its neighbour's reason.
+ */
+interface SanctionedPointer {
+ readonly count: number;
+ readonly reason: string;
+}
+
+const SANCTIONED: Readonly<Record<string, SanctionedPointer>> = Object.freeze({
+ "src/cli/brain/verbs/protect.ts :: o2b brain protect": {
+ count: 1,
+ reason:
+ "provenance header of a generated artifact, not a pointer: the preview writes the deny-rule " +
+ "file to stdout for redirection and names, in a comment line, the command that produced it. " +
+ "The operator has already run it; there is nothing forward about it.",
+ },
+ "src/cli/main.ts :: o2b search check": {
+ count: 1,
+ reason:
+ "part of the semantic-search configuration template, whose two commands are the verification " +
+ "sequence AFTER the operator edits the keys printed immediately above them. Neither is " +
+ "runnable until that edit happens, and the rail resolves one structural command per code - it " +
+ "cannot express an ordered pair conditioned on a manual step.",
+ },
+ "src/cli/main.ts :: o2b search index": {
+ count: 1,
+ reason:
+ "the second half of that same configuration template (`o2b search index --embeddings`). It is " +
+ "listed for the identical reason and is counted separately so a new hand-written pointer " +
+ "naming this verb in this module cannot hide behind the template's entry.",
+ },
+ "src/cli/main.ts :: o2b install-cli": {
+ count: 1,
+ reason:
+ "`o2b uninstall --help` prose describing what `--remove-cli` removes, by naming the command " +
+ "that created those symlinks in the past. It is a mention of a command already run, not a " +
+ "command to run next, and routing it through the rail would advise the operator to reinstall " +
+ "the very symlinks the paragraph is about removing.",
+ },
+});
+
+/** A reason has to say something; a placeholder cannot reach this. */
+const MIN_REASON_LENGTH = 80;
+
+const readSource = (path: string): string => readFileSync(path, "utf8");
+
+function cliFiles(dir: string = CLI_ROOT): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...cliFiles(abs));
+ else if (entry.name.endsWith(".ts")) out.push(abs);
+ }
+ return out;
+}
+
+/**
+ * The argument text of a call whose opening paren sits at `start`.
+ * Quote-aware, so a paren inside a string literal cannot unbalance the
+ * scan and a multi-line argument (an array joined into one write) is
+ * read whole.
+ */
+function argumentText(text: string, start: number): string {
+ let depth = 1;
+ let quote: string | null = null;
+ let i = start;
+ while (i < text.length && depth > 0) {
+ const ch = text[i]!;
+ if (quote !== null) {
+ if (ch === "\\") i += 1;
+ else if (ch === quote) quote = null;
+ } else if (ch === '"' || ch === "'" || ch === "`") {
+ quote = ch;
+ } else if (ch === "(") {
+ depth += 1;
+ } else if (ch === ")") {
+ depth -= 1;
+ }
+ i += 1;
+ }
+ return text.slice(start, i - 1);
+}
+
+/**
+ * True when the invocation at `at` inside `args` is one of the two
+ * non-pointer shapes: a usage grammar, or the command labelling its own
+ * output line. Both are read from the source text around the match, not
+ * from what the sentence says.
+ */
+function isNotAPointer(args: string, at: number, invocation: string): boolean {
+ const before = args.slice(0, at);
+ const after = args.slice(at + invocation.length);
+ // Usage grammar: bounded to the invocation's own line, so a bracket
+ // somewhere else in a multi-line argument cannot excuse it.
+ const restOfLine = after.split("\n", 1)[0]!;
+ if (USAGE_NOTATION_RE.test(restOfLine)) return true;
+ // Self-label: the literal opens with the invocation, and a colon
+ // follows it immediately.
+ return QUOTE_RE.test(before) && after.startsWith(":");
+}
+
+/** Every invocation literal written to stdout from `text`. */
+function pointersIn(text: string): ReadonlyArray<string> {
+ const found: string[] = [];
+ for (const match of text.matchAll(STDOUT_WRITER_RE)) {
+ const args = argumentText(text, match.index! + match[0].length);
+ for (const invocation of args.matchAll(INVOCATION_RE)) {
+ if (isNotAPointer(args, invocation.index!, invocation[0])) continue;
+ found.push(invocation[0]);
+ }
+ }
+ return found;
+}
+
+/** `<relative path> :: <invocation>` -> how many times it was measured. */
+function census(): ReadonlyMap<string, number> {
+ const counts = new Map<string, number>();
+ for (const path of cliFiles()) {
+ const rel = relative(REPO_ROOT, path).split("\\").join("/");
+ for (const invocation of pointersIn(readSource(path))) {
+ const key = `${rel} :: ${invocation}`;
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+ return counts;
+}
+
+describe("the rail is the only forward-pointer mechanism", () => {
+ test("no unsanctioned invocation literal reaches stdout", () => {
+ const unsanctioned = [...census().keys()]
+ .filter((key) => SANCTIONED[key] === undefined)
+ .toSorted();
+ // Named, not counted: the failure message is the work to be done.
+ expect(unsanctioned.join("\n")).toBe("");
+ });
+
+ test("every sanctioned site still exists and holds exactly what it declares", () => {
+ const measured = census();
+ for (const [key, entry] of Object.entries(SANCTIONED)) {
+ expect(`${key} measured: ${measured.get(key) ?? 0}`).toBe(`${key} measured: ${entry.count}`);
+ }
+ });
+
+ test("every sanctioned reason is specific", () => {
+ for (const [key, entry] of Object.entries(SANCTIONED)) {
+ expect(`${key} reason is specific: ${entry.reason.trim().length >= MIN_REASON_LENGTH}`).toBe(
+ `${key} reason is specific: true`,
+ );
+ }
+ });
+
+ test("the detector is not vacuous - it still matches the shapes it removed", () => {
+ // The exact literals this change migrated. A regex that stopped
+ // matching would otherwise sweep the whole tree clean.
+ const removed = [
+ 'ok("no dream bundles - run: o2b brain dream stage");',
+ 'else ok("no cluster notes yet - run: o2b brain clusters run");',
+ 'ok("tune: no valid tuned parameters persisted - run: o2b brain tune run --dataset <path>");',
+ 'ok("resolve with: o2b brain tiers restore <path> --apply (or accept <path>)");',
+ 'process.stdout.write(" next: o2b search index # build the vault search index\\n");',
+ ];
+ for (const line of removed) {
+ expect(`${line} detected: ${pointersIn(line).length}`).toBe(`${line} detected: 1`);
+ }
+ // And a refusal naming a command is NOT a forward pointer.
+ expect(pointersIn('return fail("run o2b brain init first");')).toEqual([]);
+ expect(pointersIn('process.stderr.write("usage: o2b brain dream\\n");')).toEqual([]);
+ });
+
+ test("the two subtracted shapes are subtracted, and only those", () => {
+ // A usage grammar carries this CLI's optional-group bracket or its
+ // alternation bar.
+ expect(
+ pointersIn('process.stdout.write("usage: o2b secrets list|status [args...]\\n");'),
+ ).toEqual([]);
+ expect(
+ pointersIn('process.stdout.write("usage: o2b brain snapshot <verb> [args...]\\n");'),
+ ).toEqual([]);
+ // A self-label opens the line with the invocation and a colon.
+ expect(pointersIn("process.stdout.write(`o2b discipline: job created\\n`);")).toEqual([]);
+ // Neither rule excuses a bare pointer that merely starts the line...
+ expect(pointersIn('ok("o2b brain clusters run");')).toEqual(["o2b brain clusters run"]);
+ // ...nor one whose own arguments use the angle-bracket placeholder
+ // shape a real next command does use.
+ expect(pointersIn('ok("run: o2b brain tune run --dataset <path>");')).toEqual([
+ "o2b brain tune run",
+ ]);
+ });
+
+ test("no registered next command could be mistaken for a usage grammar", () => {
+ // The usage-notation rule is only sound while this holds.
+ const offenders = [...DIAGNOSTIC_SIGNALS.values()]
+ .filter((signal) => USAGE_NOTATION_RE.test(signal.nextCommand))
+ .map((signal) => `${signal.code}: ${signal.nextCommand}`);
+ expect(offenders.toSorted().join("\n")).toBe("");
+ });
+
+ test("the sanctioned table stays an exception", () => {
+ // Every measured site is sanctioned (test one), so the table's size
+ // IS the number of unmigrated sites. Four is the ceiling this change
+ // leaves behind; a fifth needs its own argument.
+ expect(Object.keys(SANCTIONED).length).toBeLessThanOrEqual(4);
+ });
+});
+
+describe("the migrated codes resolve to a structural command", () => {
+ test("each new registry code names its exit", () => {
+ const expected: ReadonlyArray<readonly [string, string]> = [
+ ["dream-bundles-absent", "o2b brain dream stage"],
+ ["cluster-notes-absent", "o2b brain clusters run"],
+ ["recall-tuning-absent", "o2b brain tune run --dataset <path>"],
+ ["tier-drift-restore", "o2b brain tiers restore <path> --apply"],
+ ["tier-drift-accept", "o2b brain tiers accept <path>"],
+ ];
+ for (const [code, command] of expected) {
+ expect(`${code} -> ${resolveNextStep(code)?.nextCommand ?? "(unregistered)"}`).toBe(
+ `${code} -> ${command}`,
+ );
+ }
+ });
+});
+
+describe("the migrated verbs emit through the rail", () => {
+ let tmp: string;
+ let vault: string;
+ let configPath: string;
+ const savedEnv: Record<string, string | undefined> = {};
+
+ beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-pointer-rail-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG", "VAULT_AGENT_NAME"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ });
+
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ test("brain dream list with no bundles names the stage command", async () => {
+ const r = await runCli(["brain", "dream", "list", "--vault", vault]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("next: o2b brain dream stage\n");
+ expect(r.stdout).not.toContain("- run:");
+ });
+
+ test("brain clusters list names the same exit whether the directory is missing or empty", async () => {
+ const missing = await runCli(["brain", "clusters", "list", "--vault", vault]);
+ expect(missing.returncode).toBe(0);
+ expect(missing.stdout).toContain("next: o2b brain clusters run\n");
+
+ // The empty-directory branch reached the SAME state and previously
+ // said nothing forward at all.
+ mkdirSync(join(vault, "Brain", "clusters"), { recursive: true });
+ const empty = await runCli(["brain", "clusters", "list", "--vault", vault]);
+ expect(empty.returncode).toBe(0);
+ expect(empty.stdout).toContain("next: o2b brain clusters run\n");
+ });
+
+ test("brain tune status with nothing persisted names the tuning run", async () => {
+ const r = await runCli(["brain", "tune", "status", "--vault", vault]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("next: o2b brain tune run --dataset <path>\n");
+ });
+
+ test("the rail line stays off the machine stream", async () => {
+ for (const argv of [
+ ["brain", "dream", "list", "--vault", vault, "--json"],
+ ["brain", "clusters", "list", "--vault", vault, "--json"],
+ ["brain", "tune", "status", "--vault", vault, "--json"],
+ ]) {
+ // oxlint-disable-next-line no-await-in-loop -- runCli patches process.stdout in-process, so concurrent invocations would interleave each other's captured output
+ const r = await runCli(argv);
+ expect(`${argv[1]} exit: ${r.returncode}`).toBe(`${argv[1]} exit: 0`);
+ expect(`${argv[1]} clean: ${!r.stdout.includes("next: ")}`).toBe(`${argv[1]} clean: true`);
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ }
+ });
+
+ test("search status with no index names the indexer through the rail", async () => {
+ const r = await runCli(["search", "status", "--vault", vault, "--db", join(tmp, "none.db")]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("next: o2b search index\n");
+ expect(r.stdout).not.toContain("Run: o2b search index");
+ });
+});
diff --git a/tests/cli/help-surface-parity.test.ts b/tests/cli/help-surface-parity.test.ts
new file mode 100644
index 00000000..85887574
--- /dev/null
+++ b/tests/cli/help-surface-parity.test.ts
@@ -0,0 +1,185 @@
+/**
+ * The two help surfaces describe one command set (no-dead-ends, phase 3,
+ * item 1).
+ *
+ * `o2b help --json` serialises the command manifest; `o2b help` used to
+ * print a hand-written constant. Two lists mean two truths, and the
+ * manifest repair that added sixty-four entries widened the gap until the
+ * human surface named twelve `brain` verbs out of a hundred and thirty.
+ * An operator reading the human surface therefore could not reach most of
+ * this tool - a discoverability dead end.
+ *
+ * The repair is derivation: one renderer over the manifest feeds both. A
+ * derived surface cannot disagree with its source by construction, so
+ * this file asserts the property that derivation is FOR - it parses the
+ * human text back into paths, summaries and flags and requires the result
+ * to equal the manifest exactly. A renderer that truncated, wrapped or
+ * dropped a level would pass a "both come from the manifest" claim and
+ * fail here.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ manifestForJson,
+ type CliCommandManifest,
+ type CliRootManifest,
+} from "../../src/cli/command-manifest.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+/** ` <path> <summary>` - two-space indent, two-or-more-space gutter. */
+const ENTRY_RE = /^ {2}(\S(?:.*?\S)?) {2,}(\S.*)$/;
+/** ` flags: --a --b` - the continuation line a flagged entry carries. */
+const FLAGS_RE = /^ {6}flags: (.+)$/;
+
+interface ParsedEntry {
+ readonly summary: string;
+ readonly flags: ReadonlyArray<string>;
+}
+
+/** Parse the human help back into `path -> { summary, flags }`. */
+function parseHumanHelp(text: string): ReadonlyMap<string, ParsedEntry> {
+ const out = new Map<string, ParsedEntry>();
+ let last: string | null = null;
+ for (const line of text.split("\n")) {
+ const flags = FLAGS_RE.exec(line);
+ if (flags !== null) {
+ expect(`flags line has an owner: ${last !== null}`).toBe("flags line has an owner: true");
+ const owner = out.get(last!)!;
+ out.set(last!, { summary: owner.summary, flags: flags[1]!.trim().split(/\s+/) });
+ continue;
+ }
+ const entry = ENTRY_RE.exec(line);
+ if (entry === null) continue;
+ last = entry[1]!;
+ out.set(last, { summary: entry[2]!.trimEnd(), flags: [] });
+ }
+ return out;
+}
+
+/** Walk the manifest into the same `path -> { summary, flags }` shape. */
+function walkManifest(root: CliRootManifest): ReadonlyMap<string, ParsedEntry> {
+ const out = new Map<string, ParsedEntry>();
+ const visit = (items: ReadonlyArray<CliCommandManifest>, prefix: string): void => {
+ for (const item of items) {
+ const path = `${prefix}${item.name}`;
+ out.set(path, {
+ summary: item.summary,
+ // The inherited `--json` flag is stated once in the header rather
+ // than repeated on all two hundred entries; parity is asserted over
+ // the flags a command DECLARES.
+ flags: (item.flags ?? []).filter((f) => f.inherited !== true).map((f) => `--${f.name}`),
+ });
+ if (item.commands) visit(item.commands, `${path} `);
+ }
+ };
+ visit(root.commands, "");
+ return out;
+}
+
+async function humanHelp(): Promise<string> {
+ const r = await runCli(["help"]);
+ expect(r.returncode).toBe(0);
+ return r.stdout;
+}
+
+describe("o2b help and o2b help --json describe one command set", () => {
+ test("every command the manifest models is named by the human help, and nothing else is", async () => {
+ const human = parseHumanHelp(await humanHelp());
+ const modelled = walkManifest(manifestForJson());
+ // Named, not counted: the failure message is the work to be done.
+ const missing = [...modelled.keys()].filter((p) => !human.has(p)).toSorted();
+ const invented = [...human.keys()].filter((p) => !modelled.has(p)).toSorted();
+ expect(missing.join("\n")).toBe("");
+ expect(invented.join("\n")).toBe("");
+ });
+
+ test("every summary is the manifest's, verbatim", async () => {
+ const human = parseHumanHelp(await humanHelp());
+ const modelled = walkManifest(manifestForJson());
+ const drifted: string[] = [];
+ for (const [path, entry] of modelled) {
+ const shown = human.get(path);
+ if (shown !== undefined && shown.summary !== entry.summary) {
+ drifted.push(`${path}\n manifest: ${entry.summary}\n help: ${shown.summary}`);
+ }
+ }
+ expect(drifted.join("\n")).toBe("");
+ });
+
+ test("every declared flag is the manifest's, verbatim", async () => {
+ const human = parseHumanHelp(await humanHelp());
+ const modelled = walkManifest(manifestForJson());
+ const drifted: string[] = [];
+ for (const [path, entry] of modelled) {
+ const shown = human.get(path);
+ if (shown === undefined) continue;
+ if (shown.flags.join(" ") !== entry.flags.join(" ")) {
+ drifted.push(
+ `${path}: manifest [${entry.flags.join(" ")}] help [${shown.flags.join(" ")}]`,
+ );
+ }
+ }
+ expect(drifted.join("\n")).toBe("");
+ });
+
+ test("the parse is not vacuous", async () => {
+ // A regex that stopped matching would report two empty sets as equal.
+ const human = parseHumanHelp(await humanHelp());
+ expect(human.size).toBeGreaterThan(180);
+ expect([...human.values()].filter((e) => e.flags.length > 0).length).toBeGreaterThan(10);
+ });
+
+ test("the JSON surface serialises the same manifest the human one renders", async () => {
+ const r = await runCli(["help", "--json"]);
+ expect(r.returncode).toBe(0);
+ expect(JSON.parse(r.stdout)).toEqual(JSON.parse(JSON.stringify(manifestForJson())));
+ });
+});
+
+describe("the flags the branch added verbs for are advertised", () => {
+ /** `path -> declared flag names`, from the JSON surface itself. */
+ async function jsonFlags(): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {
+ const r = await runCli(["help", "--json"]);
+ expect(r.returncode).toBe(0);
+ return walkManifestFlags(JSON.parse(r.stdout) as CliRootManifest);
+ }
+
+ function walkManifestFlags(root: CliRootManifest): ReadonlyMap<string, ReadonlyArray<string>> {
+ const out = new Map<string, ReadonlyArray<string>>();
+ for (const [path, entry] of walkManifest(root)) out.set(path, entry.flags);
+ return out;
+ }
+
+ test("brain lint advertises the consolidation flags its summary already mentions", async () => {
+ const flags = await jsonFlags();
+ expect((flags.get("brain lint") ?? []).toSorted()).toEqual(
+ ["--apply", "--consolidate", "--vault", "--yes"].toSorted(),
+ );
+ });
+
+ test("brain pending apply advertises the dry run this branch gave it", async () => {
+ const flags = await jsonFlags();
+ expect(flags.get("brain pending apply")).toContain("--dry-run");
+ });
+
+ test("brain pending reject advertises its reason, and list advertises neither", async () => {
+ const flags = await jsonFlags();
+ expect(flags.get("brain pending reject")).toContain("--reason");
+ expect(flags.get("brain pending list")).not.toContain("--dry-run");
+ expect(flags.get("brain pending list")).not.toContain("--reason");
+ });
+});
+
+describe("the terse usage names the complete help", () => {
+ test("an unknown command lists every top-level verb and where the rest are", async () => {
+ const r = await runCli(["no-such-verb"]);
+ expect(r.returncode).toBe(2);
+ for (const item of manifestForJson().commands) {
+ expect(`${item.name} listed: ${r.stderr.includes(item.name)}`).toBe(
+ `${item.name} listed: true`,
+ );
+ }
+ expect(r.stderr).toContain("o2b help");
+ });
+});
diff --git a/tests/cli/json-next-command.test.ts b/tests/cli/json-next-command.test.ts
new file mode 100644
index 00000000..3914f8be
--- /dev/null
+++ b/tests/cli/json-next-command.test.ts
@@ -0,0 +1,243 @@
+/**
+ * The machine-readable promise is actually delivered (no-dead-ends,
+ * phase 3, item 4).
+ *
+ * `emitNextStep` returns the resolved step even when it suppresses the
+ * line on a machine stream, and `advisory-rail.ts` says why in as many
+ * words: "Suppression is not a drop. A suppressed emission still returns
+ * the resolved `NextStep`, so a JSON verb carries it as a field in its
+ * own payload - which is where it belongs on that stream."
+ *
+ * No CLI caller used that return value. On every verb below the next step
+ * was computed and silently discarded under `--json`, so the agent-facing
+ * stream - the one this release exists for - was the only stream that got
+ * nothing. Each payload now carries the exit under the shared
+ * `NEXT_COMMAND_KEY`, and omits the key entirely where no step resolves.
+ *
+ * Both halves are asserted per verb. A field that is always present is a
+ * different bug from a field that is never present, and only the first
+ * one looks like success.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { NEXT_COMMAND_KEY, resolveNextStep } from "../../src/core/brain/next-step.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writeCaptureNote } from "../../src/core/brain/capture/capture-note.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-json-next-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const key of ["VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG", "VAULT_AGENT_NAME"]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+/** The command a code resolves to, read from the registry, never retyped. */
+function commandFor(code: string): string {
+ const step = resolveNextStep(code);
+ expect(`${code} is registered: ${step !== null}`).toBe(`${code} is registered: true`);
+ return step!.nextCommand;
+}
+
+/** Parse a `--json` payload and return it, failing loudly if it does not. */
+async function payload(argv: ReadonlyArray<string>): Promise<Record<string, unknown>> {
+ const r = await runCli([...argv], { env: env() });
+ expect(`${argv.join(" ")} exit: ${r.returncode}`).toBe(`${argv.join(" ")} exit: 0`);
+ // The advisory line must never reach a stream a caller parses.
+ expect(`${argv.join(" ")} has no chrome: ${!r.stdout.includes("next: ")}`).toBe(
+ `${argv.join(" ")} has no chrome: true`,
+ );
+ return JSON.parse(r.stdout) as Record<string, unknown>;
+}
+
+describe("each JSON payload carries the exit its human twin prints", () => {
+ test("brain init", async () => {
+ const empty = await payload([
+ "brain",
+ "init",
+ "--vault",
+ vault,
+ "--config",
+ configPath,
+ "--json",
+ ]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("brain-empty"));
+
+ writeSignal(vault, {
+ topic: "recorded",
+ signal: "positive",
+ agent: "claude",
+ principle: "Recorded.",
+ created_at: "2026-05-20T10:00:00Z",
+ date: "2026-05-20",
+ slug: "recorded-1",
+ scope: "writing",
+ });
+ const full = await payload([
+ "brain",
+ "init",
+ "--vault",
+ vault,
+ "--config",
+ configPath,
+ "--json",
+ ]);
+ expect(full).not.toHaveProperty(NEXT_COMMAND_KEY);
+ });
+
+ test("brain bridges list and discover", async () => {
+ const list = await payload(["brain", "bridges", "list", "--json"]);
+ expect(list[NEXT_COMMAND_KEY]).toBe(commandFor("bridge-proposals-absent"));
+
+ const discover = await payload(["brain", "bridges", "discover", "--json"]);
+ expect(discover[NEXT_COMMAND_KEY]).toBe(commandFor("search-index-missing"));
+ });
+
+ test("brain clusters list and run", async () => {
+ const missing = await payload(["brain", "clusters", "list", "--json"]);
+ expect(missing[NEXT_COMMAND_KEY]).toBe(commandFor("cluster-notes-absent"));
+
+ // Same state, other branch: the directory exists but is empty.
+ mkdirSync(join(vault, "Brain", "clusters"), { recursive: true });
+ const empty = await payload(["brain", "clusters", "list", "--json"]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("cluster-notes-absent"));
+
+ const run = await payload(["brain", "clusters", "run", "--json"]);
+ expect(run[NEXT_COMMAND_KEY]).toBe(commandFor("search-index-missing"));
+ });
+
+ test("brain git status and mine", async () => {
+ const status = await payload(["brain", "git", "status", "--json"]);
+ expect(status[NEXT_COMMAND_KEY]).toBe(commandFor("git-history-absent"));
+
+ const mine = await payload(["brain", "git", "mine", "--json"]);
+ expect(mine[NEXT_COMMAND_KEY]).toBe(commandFor("git-history-absent"));
+ });
+
+ test("brain intention list", async () => {
+ const empty = await payload(["brain", "intention", "list", "--json"]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("intentions-absent"));
+
+ const set = await runCli(
+ ["brain", "intention", "set", "--scope", "writing", "--text", "Ship it."],
+ { env: env() },
+ );
+ expect(set.returncode).toBe(0);
+ const listed = await payload(["brain", "intention", "list", "--json"]);
+ expect(listed).not.toHaveProperty(NEXT_COMMAND_KEY);
+ });
+
+ test("brain intent-review", async () => {
+ const empty = await payload(["brain", "intent-review", "--json"]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("signal-clusters-absent"));
+ });
+
+ test("brain inbox-drain", async () => {
+ const nothing = await payload(["brain", "inbox-drain", "--json"]);
+ expect(nothing).not.toHaveProperty(NEXT_COMMAND_KEY);
+
+ writeCaptureNote(vault, {
+ body: "an atomic idea to keep",
+ provenance: { source: "telegram", sender: "100", capturedAt: "2026-07-19T12:00:02Z" },
+ });
+ const staged = await payload(["brain", "inbox-drain", "--json"]);
+ expect(staged[NEXT_COMMAND_KEY]).toBe(commandFor("staged-captures-pending"));
+
+ // With --apply the captures are routed, so nothing is pending.
+ const applied = await payload(["brain", "inbox-drain", "--apply", "--json"]);
+ expect(applied).not.toHaveProperty(NEXT_COMMAND_KEY);
+ });
+
+ test("brain dream list", async () => {
+ const empty = await payload(["brain", "dream", "list", "--vault", vault, "--json"]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("dream-bundles-absent"));
+ });
+
+ test("brain tune status", async () => {
+ const empty = await payload(["brain", "tune", "status", "--vault", vault, "--json"]);
+ expect(empty[NEXT_COMMAND_KEY]).toBe(commandFor("recall-tuning-absent"));
+ });
+
+ test("search index and reindex", async () => {
+ writeFileSync(join(vault, "good.md"), "---\ntitle: Good\n---\n\nBody text.\n", "utf8");
+ const db = join(tmp, "index.db");
+
+ const indexed = await payload(["search", "index", "--vault", vault, "--db", db, "--json"]);
+ expect(indexed[NEXT_COMMAND_KEY]).toBe(commandFor("search-index-built"));
+
+ const reindexed = await payload(["search", "reindex", "--vault", vault, "--db", db, "--json"]);
+ expect(reindexed[NEXT_COMMAND_KEY]).toBe(commandFor("search-index-built"));
+
+ // A run that could not index every file claims nothing.
+ writeFileSync(join(vault, "broken.md"), "---\ntitle: Broken\n\nNo fence.\n", "utf8");
+ const broken = await payload(["search", "index", "--vault", vault, "--db", db, "--json"]);
+ expect(broken).not.toHaveProperty(NEXT_COMMAND_KEY);
+ });
+
+ test("search status", async () => {
+ const missing = await payload([
+ "search",
+ "status",
+ "--vault",
+ vault,
+ "--db",
+ join(tmp, "none.db"),
+ "--json",
+ ]);
+ expect(missing[NEXT_COMMAND_KEY]).toBe(commandFor("search-index-missing"));
+ });
+
+ test("status", async () => {
+ const absent = join(tmp, "__no-such-config__.yaml");
+ const missing = await runCli(["status", "--config", absent, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: absent },
+ });
+ expect(missing.returncode).toBe(0);
+ const parsed = JSON.parse(missing.stdout) as Record<string, unknown>;
+ expect(parsed[NEXT_COMMAND_KEY]).toBe(commandFor("cli-config-absent"));
+
+ const present = await runCli(["status", "--config", configPath, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(JSON.parse(present.stdout)).not.toHaveProperty(NEXT_COMMAND_KEY);
+ });
+});
+
+describe("human output is unchanged by the field", () => {
+ test("the same states still print exactly one rail line each", async () => {
+ const r = await runCli(["brain", "intention", "list"], { env: env() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe(`no active intentions\nnext: ${commandFor("intentions-absent")}\n`);
+ });
+
+ test("a state with no exit still prints none", async () => {
+ const r = await runCli(["brain", "git", "find", "nothing"], { env: env() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ });
+});
diff --git a/tests/cli/manifest-completeness.test.ts b/tests/cli/manifest-completeness.test.ts
new file mode 100644
index 00000000..4774a594
--- /dev/null
+++ b/tests/cli/manifest-completeness.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Command-manifest completeness ratchet (no-dead-ends, task 6).
+ *
+ * `command-manifest.ts` is not documentation. It is the source of the
+ * shell completion scripts and of `o2b help --json`, which is how an
+ * agent discovers what this CLI can do. A verb the manifest does not
+ * model is a verb that does not exist as far as either surface is
+ * concerned - a dead end reached by not knowing the road is there.
+ *
+ * The audit that produced this file found the manifest two top-level
+ * verbs, seven `search` subverbs and fifty-five `brain` cases short.
+ * Repairing it once fixes today; this ratchet is what stops it drifting
+ * again, and the direction of enumeration is the whole point: it reads
+ * the DISPATCHERS and asks the manifest to account for each case, never
+ * the reverse. A manifest cannot vouch for its own completeness.
+ *
+ * Scope is one level below each dispatcher - the switch in `main.ts`,
+ * the switch in `brain.ts`, and `KNOWN_VERBS` in `search.ts`. Deeper
+ * nesting (`brain schema report`, `brain git ingest`) is parsed by each
+ * verb from its own positionals, with no shared table to enumerate from,
+ * so it is out of this ratchet's reach and stays modelled by hand.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ CLI_COMMAND_MANIFEST,
+ nestedCommandNames,
+ type CliCommandManifest,
+} from "../../src/cli/command-manifest.ts";
+import { renderCompletions } from "../../src/cli/completions.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const CLI_ROOT = join(import.meta.dir, "..", "..", "src", "cli");
+
+/**
+ * Top-level cases with no manifest entry, and why. An entry may only sit
+ * here because listing the verb would be WRONG, never because writing
+ * its summary was inconvenient.
+ */
+const TOP_LEVEL_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});
+
+/** `brain` cases with no manifest entry, and why. */
+const BRAIN_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});
+
+/** `search` verbs with no manifest entry, and why. */
+const SEARCH_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});
+
+/** An exclusion reason has to say something; ten characters is the floor. */
+const MIN_REASON_LENGTH = 10;
+
+/** Read `file` under `src/cli/`. */
+function cliSource(file: string): string {
+ return readFileSync(join(CLI_ROOT, file), "utf8");
+}
+
+/**
+ * Every `case "<label>":` between `marker` and the switch's `default:`.
+ * Bounded on both ends so an unrelated switch elsewhere in the module
+ * cannot leak into the census.
+ */
+function switchCaseLabels(file: string, marker: string): string[] {
+ const text = cliSource(file);
+ const start = text.indexOf(marker);
+ expect(`${file} contains ${marker}: ${start >= 0}`).toBe(`${file} contains ${marker}: true`);
+ const end = text.indexOf("default:", start);
+ expect(`${file} switch is terminated: ${end > start}`).toBe(`${file} switch is terminated: true`);
+ return [...text.slice(start, end).matchAll(/case "([^"]+)":/g)].map((m) => m[1]!);
+}
+
+/** The `KNOWN_VERBS` set literal in `search.ts`. */
+function searchKnownVerbs(): string[] {
+ const text = cliSource("search.ts");
+ const start = text.indexOf("const KNOWN_VERBS = new Set([");
+ expect(`search.ts declares KNOWN_VERBS: ${start >= 0}`).toBe(
+ "search.ts declares KNOWN_VERBS: true",
+ );
+ const end = text.indexOf("]);", start);
+ return [...text.slice(start, end).matchAll(/"([^"]+)"/g)].map((m) => m[1]!);
+}
+
+/** Paths of every modelled command whose summary says nothing. */
+function emptySummaries(
+ items: ReadonlyArray<CliCommandManifest>,
+ prefix: string,
+): ReadonlyArray<string> {
+ const found: string[] = [];
+ for (const item of items) {
+ const path = `${prefix}${item.name}`;
+ if (item.summary.trim().length === 0) found.push(path);
+ if (item.commands) found.push(...emptySummaries(item.commands, `${path} `));
+ }
+ return found;
+}
+
+interface Level {
+ readonly label: string;
+ readonly dispatcherVerbs: ReadonlyArray<string>;
+ readonly manifestVerbs: ReadonlyArray<string>;
+ readonly unlisted: Readonly<Record<string, string>>;
+}
+
+function levels(): ReadonlyArray<Level> {
+ return [
+ {
+ label: "o2b",
+ dispatcherVerbs: switchCaseLabels("main.ts", "async function dispatchCommand"),
+ manifestVerbs: CLI_COMMAND_MANIFEST.commands.map((c) => c.name),
+ unlisted: TOP_LEVEL_UNLISTED,
+ },
+ {
+ label: "o2b brain",
+ dispatcherVerbs: switchCaseLabels("brain.ts", "export async function handleBrainSubcommand"),
+ manifestVerbs: nestedCommandNames("brain"),
+ unlisted: BRAIN_UNLISTED,
+ },
+ {
+ label: "o2b search",
+ dispatcherVerbs: searchKnownVerbs(),
+ manifestVerbs: nestedCommandNames("search"),
+ unlisted: SEARCH_UNLISTED,
+ },
+ ];
+}
+
+describe("command manifest completeness", () => {
+ test("every dispatcher case is modelled or excluded with a written reason", () => {
+ // Every level folds into ONE comparison so the failure message is
+ // the complete list of verbs to act on. Asserting per level would
+ // stop at the first and hide the rest.
+ const unclassified: string[] = [];
+ for (const level of levels()) {
+ const modelled = new Set(level.manifestVerbs);
+ for (const verb of level.dispatcherVerbs) {
+ if (modelled.has(verb) || level.unlisted[verb] !== undefined) continue;
+ unclassified.push(`${level.label} ${verb}`);
+ }
+ }
+ expect(unclassified.toSorted().join("\n")).toBe("");
+ });
+
+ test("no manifest entry outlives the dispatcher case it describes", () => {
+ const stale: string[] = [];
+ for (const level of levels()) {
+ const dispatched = new Set(level.dispatcherVerbs);
+ for (const verb of level.manifestVerbs) {
+ if (!dispatched.has(verb)) stale.push(`${level.label} ${verb}`);
+ }
+ }
+ expect(stale.toSorted().join("\n")).toBe("");
+ });
+
+ test("no exclusion outlives the verb it excuses, and every reason says something", () => {
+ for (const level of levels()) {
+ const dispatched = new Set(level.dispatcherVerbs);
+ for (const [verb, reason] of Object.entries(level.unlisted)) {
+ expect(`${level.label} ${verb} is dispatched: ${dispatched.has(verb)}`).toBe(
+ `${level.label} ${verb} is dispatched: true`,
+ );
+ // A placeholder ("todo", "n/a", "") cannot satisfy this.
+ expect(
+ `${level.label} ${verb} has a reason: ${reason.trim().length >= MIN_REASON_LENGTH}`,
+ ).toBe(`${level.label} ${verb} has a reason: true`);
+ }
+ }
+ });
+
+ test("the ratchet is not vacuous", () => {
+ // A parser that silently stopped matching would report a clean sweep
+ // over an empty set. Pin the measurement, not only its verdict.
+ const [top, brain, search] = levels();
+ expect(top!.dispatcherVerbs.length).toBeGreaterThan(15);
+ expect(brain!.dispatcherVerbs.length).toBeGreaterThan(130);
+ expect(search!.dispatcherVerbs.length).toBeGreaterThan(10);
+ });
+
+ test("the search dispatcher and its verb gate agree", () => {
+ // `KNOWN_VERBS` decides whether the first positional is a verb or a
+ // query string; the switch decides what runs. A verb in one and not
+ // the other is either unreachable or an unknown-verb error.
+ expect(
+ switchCaseLabels("search.ts", "export async function handleSearchSubcommand").toSorted(),
+ ).toEqual(searchKnownVerbs().toSorted());
+ });
+});
+
+describe("the repaired manifest reaches its two consumers", () => {
+ /** Verbs the audit found missing; a spot check of each level. */
+ const REPAIRED = Object.freeze({
+ top: ["secrets", "partner"],
+ brain: ["pending", "lint", "stale", "today", "obligation"],
+ search: ["expand", "focus", "feedback", "weights", "rerank-provider", "rerank-fit", "plan"],
+ });
+
+ test("shell completions offer the repaired verbs", () => {
+ const bash = renderCompletions("bash", CLI_COMMAND_MANIFEST);
+ for (const verb of REPAIRED.top) expect(bash).toContain(verb);
+ const zsh = renderCompletions("zsh", CLI_COMMAND_MANIFEST);
+ for (const verb of [...REPAIRED.brain, ...REPAIRED.search]) {
+ expect(`${verb}: ${zsh.includes(verb)}`).toBe(`${verb}: true`);
+ }
+ });
+
+ test("help --json carries every dispatcher verb", async () => {
+ const r = await runCli(["help", "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ commands: ReadonlyArray<{ name: string; commands?: ReadonlyArray<{ name: string }> }>;
+ };
+ const names = new Set(payload.commands.map((c) => c.name));
+ for (const verb of REPAIRED.top) {
+ expect(`${verb}: ${names.has(verb)}`).toBe(`${verb}: true`);
+ }
+ const nested = (parent: string): ReadonlySet<string> =>
+ new Set((payload.commands.find((c) => c.name === parent)?.commands ?? []).map((c) => c.name));
+ const brainNames = nested("brain");
+ for (const verb of REPAIRED.brain) {
+ expect(`brain ${verb}: ${brainNames.has(verb)}`).toBe(`brain ${verb}: true`);
+ }
+ const searchNames = nested("search");
+ for (const verb of REPAIRED.search) {
+ expect(`search ${verb}: ${searchNames.has(verb)}`).toBe(`search ${verb}: true`);
+ }
+ });
+
+ test("every modelled command carries a non-empty summary", () => {
+ // An entry added only to satisfy the ratchet, with an empty summary,
+ // would complete the manifest and tell a reader nothing.
+ expect(emptySummaries(CLI_COMMAND_MANIFEST.commands, "o2b ").join("\n")).toBe("");
+ });
+});
diff --git a/tests/cli/skill-proposals-recover.test.ts b/tests/cli/skill-proposals-recover.test.ts
new file mode 100644
index 00000000..522bfde7
--- /dev/null
+++ b/tests/cli/skill-proposals-recover.test.ts
@@ -0,0 +1,158 @@
+/**
+ * `o2b brain skill-proposals recover` - the surface that was missing
+ * (no-dead-ends, phase 3, item 1).
+ *
+ * `recoverSkillProposalAccepts` shipped with the accept transaction and
+ * was exported to nothing: no CLI verb, no MCP operation. An operator
+ * whose accept crashed had a recovery function they could not run. These
+ * tests pin the verb, and pin that both refusals it can meet name the
+ * exact file on stderr rather than leaving an errno to trace.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { skillAcceptJournalPath, skillProposalPendingPath } from "../../src/core/brain/paths.ts";
+import {
+ learnSkillProposals,
+ listPendingSkillProposals,
+ skillAcceptLockPath,
+} from "../../src/core/brain/skill-proposals.ts";
+import { writeSkillAcceptJournal } from "../../src/core/brain/skill-accept-journal.ts";
+import { _resetHeldLocksForTests } from "../../src/core/brain/sync-lockfile.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recover-cli-"));
+});
+
+afterEach(() => {
+ _resetHeldLocksForTests();
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const LEARNED_AT = new Date("2026-06-01T09:00:00.000Z");
+
+function seedAndLearn(): string {
+ for (let i = 0; i < 3; i++) {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: `2026-05-20T08:1${i}:00Z`,
+ sourceRefs: [{ id: `src-rotate-keys-${i}` }],
+ payload: { action: "rotate_keys", summary: `did rotate_keys run ${i}` },
+ });
+ }
+ learnSkillProposals(vault, { now: LEARNED_AT, minSupport: 3 });
+ const target = listPendingSkillProposals(vault).find((p) => p.patternKind === "repeated_action");
+ if (!target) throw new Error("test setup: no repeated_action draft was created");
+ return target.slug;
+}
+
+function corruptJournal(slug: string): string {
+ const path = skillAcceptJournalPath(vault, slug);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "{ this is not json", "utf8");
+ return path;
+}
+
+describe("o2b brain skill-proposals recover", () => {
+ test("with nothing outstanding it reports zero and exits clean", async () => {
+ const r = await runCli(["brain", "skill-proposals", "recover", "--vault", vault]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("0 sequence(s) resolved, 0 unreadable marker(s) discarded");
+ });
+
+ test("it resolves the sequence a crash abandoned", async () => {
+ const slug = seedAndLearn();
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "archive",
+ startedAt: LEARNED_AT.toISOString(),
+ acceptedExisted: false,
+ procedureExisted: false,
+ });
+
+ const r = await runCli(["brain", "skill-proposals", "recover", "--vault", vault]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("1 sequence(s) resolved");
+ expect(r.stdout).toContain(`rolled_back ${slug}`);
+ // Rolled back to the draft, which is still reviewable.
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ });
+
+ test("an unreadable marker refuses on stderr, naming that exact file", async () => {
+ const journal = corruptJournal("ghost");
+ const r = await runCli(["brain", "skill-proposals", "recover", "--vault", vault]);
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain(journal);
+ expect(r.stderr).toContain("o2b brain skill-proposals recover --discard-unreadable");
+ // A refusal never removes what it refuses to interpret.
+ expect(existsSync(journal)).toBe(true);
+ });
+
+ test("--discard-unreadable clears it and names what it removed", async () => {
+ const journal = corruptJournal("ghost");
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "recover",
+ "--vault",
+ vault,
+ "--discard-unreadable",
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(`discarded ${journal}`);
+ expect(existsSync(journal)).toBe(false);
+ });
+
+ test("accepting is blocked by the marker and unblocked once it is discarded", async () => {
+ const slug = seedAndLearn();
+ const journal = corruptJournal("ghost");
+
+ const blocked = await runCli(["brain", "skill-proposals", "accept", slug, "--vault", vault]);
+ expect(blocked.returncode).toBe(1);
+ expect(blocked.stderr).toContain(journal);
+ expect(blocked.stderr).toContain("o2b brain skill-proposals recover --discard-unreadable");
+
+ await runCli(["brain", "skill-proposals", "recover", "--vault", vault, "--discard-unreadable"]);
+ const accepted = await runCli(["brain", "skill-proposals", "accept", slug, "--vault", vault]);
+ expect(accepted.returncode).toBe(0);
+ expect(accepted.stdout).toContain(`accepted prop-${slug}`);
+ });
+
+ test("a lock a crash left behind refuses by file, and is never broken", async () => {
+ const lock = skillAcceptLockPath(vault);
+ mkdirSync(dirname(lock), { recursive: true });
+ writeFileSync(lock, "999999\n2026-06-01T09:59:00.000Z\n", "utf8");
+
+ const r = await runCli(["brain", "skill-proposals", "recover", "--vault", vault]);
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain(lock);
+ expect(r.stderr).toContain("o2b brain doctor");
+ expect(existsSync(lock)).toBe(true);
+ });
+
+ test("--json carries the same result as a machine payload", async () => {
+ const journal = corruptJournal("ghost");
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "recover",
+ "--vault",
+ vault,
+ "--discard-unreadable",
+ "--json",
+ ]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["discarded"]).toEqual([journal]);
+ expect(payload["recovered"]).toEqual([]);
+ expect(payload["total"]).toBe(0);
+ });
+});
diff --git a/tests/cli/terminal-state-census.test.ts b/tests/cli/terminal-state-census.test.ts
new file mode 100644
index 00000000..c08bf5c8
--- /dev/null
+++ b/tests/cli/terminal-state-census.test.ts
@@ -0,0 +1,345 @@
+/**
+ * Terminal-state census (no-dead-ends, task 7) - the enforcement
+ * artifact for this release.
+ *
+ * Every `o2b` invocation ends somewhere. This test enumerates those
+ * endings FROM THE DISPATCHERS - the switch in `main.ts`, the switch in
+ * `brain.ts`, the switch in `search.ts` - and requires each to fall into
+ * exactly one of three classes:
+ *
+ * names an exit the reachable code emits a next step through the
+ * advisory rail;
+ * names a refusal it can fail by name, with a specific message and
+ * a non-zero code;
+ * deliberately silent it says nothing forward AND an entry below says
+ * why that is right.
+ *
+ * The direction matters. A verb cannot vouch for itself, so the census
+ * reads each handler's transitive call graph WITHIN its own module and
+ * classifies from what is actually reachable. Adding a verb that can
+ * only exit zero in silence fails here, by name, until someone either
+ * gives it an exit or writes down why it has none.
+ *
+ * Modelled on `tests/core/brain/vault-guard-census.test.ts`: detect the
+ * property syntactically, keep one explicit inventory of exceptions, one
+ * entry one reason, and pin the measurement so a regex that stopped
+ * matching cannot report a clean sweep over an empty set.
+ *
+ * Two limits, stated rather than discovered. Sub-verbs (`brain git
+ * ingest`, `search focus clear`) are parsed by each handler from its own
+ * positionals and are covered through their parent's call graph, not
+ * individually. And a delegating case (`o2b brain`, `o2b search`) takes
+ * the classification of everything it can reach, which is the right
+ * answer to "can this invocation leave me with nothing".
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+const CLI_ROOT = join(REPO_ROOT, "src", "cli");
+
+/** The rail is the only sanctioned way to print a forward pointer. */
+const NAMES_EXIT_RE = /emitNextSteps?\(/;
+
+/**
+ * A named refusal: the shared failure helpers, a typed CLI error, any
+ * thrown error, or a direct write to stderr. All four end in a specific
+ * message and a non-zero code; none of them is a silent success.
+ */
+const NAMES_REFUSAL_RE =
+ /\bfail\(|\bfailWith\(|usageError\(|CliError|throw new |process\.stderr\.write\(/;
+
+/** The three classes a terminal state may hold, and only these three. */
+const STATE_CLASS = Object.freeze({
+ exit: "names-an-exit",
+ refusal: "names-a-refusal",
+ silent: "deliberately-silent",
+} as const);
+
+type StateClass = (typeof STATE_CLASS)[keyof typeof STATE_CLASS];
+
+interface HandClassification {
+ readonly cls: StateClass;
+ readonly reason: string;
+}
+
+/**
+ * States the syntactic detector cannot place, each classified by hand
+ * with the reason it belongs where it does. An entry may only be here
+ * because the detector genuinely cannot see the truth, never because
+ * covering the state was inconvenient - the two states this census
+ * found and COVERED (`o2b status`, `o2b brain inbox-drain`) are absent
+ * from this table for exactly that reason.
+ */
+const CLASSIFIED_BY_HAND: Readonly<Record<string, HandClassification>> = Object.freeze({
+ "o2b onboarding": {
+ cls: STATE_CLASS.exit,
+ reason:
+ "already names a command per unfinished step: `renderOnboardingChecklist` prints " +
+ "`run: <command>` beside every incomplete item. The rail carries a SINGLE exit per " +
+ "call; routing a whole checklist through it would drop the step-to-command pairing " +
+ "that is the entire value of the checklist.",
+ },
+ "o2b uninstall": {
+ cls: STATE_CLASS.exit,
+ reason:
+ "names its exits inside the rendered plan - the Hermes section lists, verbatim, the " +
+ "commands this tool refuses to run on the operator's behalf. They are commands for " +
+ "another tool and vary with the installation, so they are not a structural `o2b` " +
+ "string the diagnostics registry could hold.",
+ },
+ "o2b install-cli": {
+ cls: STATE_CLASS.refusal,
+ reason:
+ "refuses per symlink: `renderInstallResult` names each failed outcome and the verb " +
+ "returns a non-zero code when any error is present. The refusal does not travel " +
+ "through the shared `fail()` helper this census matches on, which is more specific, " +
+ "not less.",
+ },
+ "o2b brain semantics-backfill": {
+ cls: STATE_CLASS.silent,
+ reason:
+ "dry-run only by design - this verb has no apply path, so there is no command to " +
+ "name. An empty proposal list means the inverse-edge invariant it previews already " +
+ "holds, which is an answer, not a degraded state.",
+ },
+ "o2b brain mcp-landscape": {
+ cls: STATE_CLASS.silent,
+ reason:
+ "lists the MCP servers declared in runtime configuration files this tool never " +
+ "writes. An empty landscape changes by editing another runtime's config, so no " +
+ "`o2b` command is its exit and naming one would be an invention.",
+ },
+ "o2b brain stale": {
+ cls: STATE_CLASS.silent,
+ reason:
+ "is itself the exit other surfaces name: the `stale-notes` registry entry resolves " +
+ "to `o2b brain stale`. What to do with a stale entry - pin it, retire it, refresh " +
+ "its evidence - is a judgement over content, and naming any one of the three would " +
+ "be a guess dressed as an instruction.",
+ },
+});
+
+/** A reason has to say something; a placeholder cannot reach this. */
+const MIN_REASON_LENGTH = 60;
+
+const readSource = (path: string): string => readFileSync(path, "utf8");
+
+function cliFiles(dir: string = CLI_ROOT): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...cliFiles(abs));
+ else if (entry.name.endsWith(".ts")) out.push(abs);
+ }
+ return out;
+}
+
+/**
+ * Top-level function bodies in `text`, keyed by name. A body runs from
+ * its declaration to the first line beginning with `}` at column zero,
+ * which is where a top-level function closes in this codebase - a brace
+ * counter would be fooled by a lone brace inside a string literal.
+ */
+function topLevelBodies(text: string): ReadonlyMap<string, string> {
+ const bodies = new Map<string, string>();
+ for (const match of text.matchAll(/^(?:export )?(?:async )?function ([A-Za-z0-9_]+)\s*[(<]/gm)) {
+ const rest = text.slice(match.index!);
+ const close = rest.search(/\n\}/);
+ bodies.set(match[1]!, close === -1 ? rest : rest.slice(0, close + 2));
+ }
+ return bodies;
+}
+
+const MODULE_BODIES: ReadonlyArray<readonly [string, ReadonlyMap<string, string>]> = cliFiles().map(
+ (path) => [path, topLevelBodies(readSource(path))] as const,
+);
+
+/** The module that declares `fn`, or null when nothing does. */
+function moduleDeclaring(fn: string): readonly [string, ReadonlyMap<string, string>] | null {
+ return MODULE_BODIES.find(([, bodies]) => bodies.has(fn)) ?? null;
+}
+
+/**
+ * The source a call to `fn` can actually reach without leaving its own
+ * module: its body plus the bodies of every same-module function it
+ * calls, transitively. Handlers that fan out to private sub-verbs
+ * (`cmdBrainGit` -> `cmdStatus`) are classified by what those sub-verbs
+ * do, which is the only reading that matches what a caller experiences.
+ */
+function reachableSource(bodies: ReadonlyMap<string, string>, fn: string): string {
+ const seen = new Set<string>();
+ const pending = [fn];
+ let source = "";
+ while (pending.length > 0) {
+ const name = pending.pop()!;
+ if (seen.has(name)) continue;
+ seen.add(name);
+ const body = bodies.get(name);
+ if (body === undefined) continue;
+ source += body;
+ for (const call of body.matchAll(/\b([A-Za-z0-9_]+)\s*\(/g)) {
+ if (bodies.has(call[1]!) && !seen.has(call[1]!)) pending.push(call[1]!);
+ }
+ }
+ return source;
+}
+
+interface CensusRow {
+ /** `o2b brain doctor` - the invocation an operator types. */
+ readonly state: string;
+ readonly handler: string;
+ readonly module: string;
+ /** Null when neither detector matched; such a row owes a hand entry. */
+ readonly detected: StateClass | null;
+}
+
+/** `case "<verb>": return <handler>(` pairs between `marker` and `default:`. */
+function dispatcherCases(file: string, marker: string): ReadonlyArray<readonly [string, string]> {
+ const text = readSource(join(CLI_ROOT, file));
+ const start = text.indexOf(marker);
+ expect(`${file} declares ${marker}: ${start >= 0}`).toBe(`${file} declares ${marker}: true`);
+ const end = text.indexOf("default:", start);
+ expect(`${file} switch terminates: ${end > start}`).toBe(`${file} switch terminates: true`);
+ return [
+ ...text
+ .slice(start, end)
+ .matchAll(/case "([^"]+)":\s*\n\s*return (?:await )?([A-Za-z0-9_]+)\(/g),
+ ].map((m) => [m[1]!, m[2]!] as const);
+}
+
+const DISPATCHERS: ReadonlyArray<readonly [string, string, string]> = [
+ ["o2b", "main.ts", "async function dispatchCommand"],
+ ["o2b brain", "brain.ts", "export async function handleBrainSubcommand"],
+ ["o2b search", "search.ts", "export async function handleSearchSubcommand"],
+];
+
+function census(): ReadonlyArray<CensusRow> {
+ const rows: CensusRow[] = [];
+ for (const [level, file, marker] of DISPATCHERS) {
+ for (const [verb, handler] of dispatcherCases(file, marker)) {
+ const declaring = moduleDeclaring(handler);
+ // An unresolvable handler is a census failure, not a pass: it means
+ // the parse drifted away from the dispatcher it is meant to read.
+ expect(`${level} ${verb} handler ${handler} resolves: ${declaring !== null}`).toBe(
+ `${level} ${verb} handler ${handler} resolves: true`,
+ );
+ const [modulePath, bodies] = declaring!;
+ const source = reachableSource(bodies, handler);
+ rows.push({
+ state: `${level} ${verb}`,
+ handler,
+ module: relative(REPO_ROOT, modulePath).split("\\").join("/"),
+ detected: NAMES_EXIT_RE.test(source)
+ ? STATE_CLASS.exit
+ : NAMES_REFUSAL_RE.test(source)
+ ? STATE_CLASS.refusal
+ : null,
+ });
+ }
+ }
+ return rows;
+}
+
+describe("terminal-state census", () => {
+ test("every dispatcher case is classified", () => {
+ const unclassified = census()
+ .filter((row) => row.detected === null && CLASSIFIED_BY_HAND[row.state] === undefined)
+ .map((row) => `${row.state} (${row.handler} in ${row.module})`);
+ // Named, not counted: the failure message is the work to be done.
+ expect(unclassified.toSorted().join("\n")).toBe("");
+ });
+
+ test("every state holds exactly one class", () => {
+ const rows = census();
+ const byState = new Map(rows.map((row) => [row.state, row]));
+ for (const row of rows) {
+ const hand = CLASSIFIED_BY_HAND[row.state];
+ const classes = [row.detected, hand?.cls].filter((c) => c !== undefined && c !== null);
+ expect(`${row.state} class count: ${classes.length}`).toBe(`${row.state} class count: 1`);
+ }
+ // Nothing is counted twice; the dispatcher list is the key set.
+ expect(byState.size).toBe(rows.length);
+ });
+
+ test("no hand classification outlives the state it explains", () => {
+ const states = new Set(census().map((row) => row.state));
+ for (const state of Object.keys(CLASSIFIED_BY_HAND)) {
+ expect(`${state} is dispatched: ${states.has(state)}`).toBe(`${state} is dispatched: true`);
+ }
+ });
+
+ test("every hand-written reason is specific, and every class is a real class", () => {
+ const known = new Set<string>(Object.values(STATE_CLASS));
+ for (const [state, entry] of Object.entries(CLASSIFIED_BY_HAND)) {
+ expect(`${state} class is known: ${known.has(entry.cls)}`).toBe(
+ `${state} class is known: true`,
+ );
+ // A placeholder - "todo", "n/a", "see above", "" - cannot pass.
+ expect(
+ `${state} reason is specific: ${entry.reason.trim().length >= MIN_REASON_LENGTH}`,
+ ).toBe(`${state} reason is specific: true`);
+ // A reason that only restates the class name explains nothing.
+ expect(`${state} reason is not the class name: ${entry.reason.trim() !== entry.cls}`).toBe(
+ `${state} reason is not the class name: true`,
+ );
+ }
+ });
+
+ test("the census is not vacuous", () => {
+ const rows = census();
+ // A parser that stopped matching would sweep an empty set clean.
+ expect(rows.length).toBeGreaterThan(160);
+ expect(rows.filter((row) => row.detected === STATE_CLASS.exit).length).toBeGreaterThan(8);
+ expect(rows.filter((row) => row.detected === STATE_CLASS.refusal).length).toBeGreaterThan(120);
+ // And the exception table must stay an exception.
+ expect(Object.keys(CLASSIFIED_BY_HAND).length).toBeLessThan(rows.length / 10);
+ });
+
+ test("the deliberately-silent class is the smallest of the three", () => {
+ // If silence ever became the common answer, this release's thesis
+ // would have been abandoned rather than enforced.
+ const silent = Object.values(CLASSIFIED_BY_HAND).filter(
+ (entry) => entry.cls === STATE_CLASS.silent,
+ );
+ const rows = census();
+ expect(silent.length).toBeLessThan(
+ rows.filter((row) => row.detected === STATE_CLASS.exit).length,
+ );
+ });
+});
+
+describe("the two states this census found and covered", () => {
+ test("o2b status with no configuration file names the bootstrap command", async () => {
+ const missing = join(REPO_ROOT, "tests", "cli", "__no-such-config__.yaml");
+ const r = await runCli(["status", "--config", missing], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: missing },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("config_exists: false");
+ expect(r.stdout).toContain("next: o2b init --vault <path> --name <name>\n");
+ });
+
+ test("o2b status with a configuration file present says nothing extra", async () => {
+ const config = join(REPO_ROOT, "package.json");
+ const r = await runCli(["status", "--config", config], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ });
+
+ test("o2b status --json stays a clean payload", async () => {
+ const missing = join(REPO_ROOT, "tests", "cli", "__no-such-config__.yaml");
+ const r = await runCli(["status", "--config", missing, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: missing },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ });
+});
diff --git a/tests/cli/terminal-states.test.ts b/tests/cli/terminal-states.test.ts
new file mode 100644
index 00000000..b51b3ae1
--- /dev/null
+++ b/tests/cli/terminal-states.test.ts
@@ -0,0 +1,239 @@
+/**
+ * Terminal states that used to print nothing forward (no-dead-ends,
+ * task 5).
+ *
+ * A verb that exits zero in silence is a dead end for an agent whose
+ * whole world is the last command's stdout. This file pins the states
+ * this task covered, the two it deliberately did NOT, and the pinned
+ * self-heal it must not regress.
+ *
+ * Every covered state resolves its command through the diagnostics
+ * registry and prints it through the advisory rail, so the four
+ * hand-written `(run: ...)` parentheticals that used to live inside
+ * `ok()` strings are gone: one mechanism, one line format, one place
+ * that knows whether stdout is a machine payload.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const BRAIN_EMPTY_COMMAND = DIAGNOSTIC_SIGNALS.get("brain-empty")!.nextCommand;
+const CLUSTERS_ABSENT_COMMAND = DIAGNOSTIC_SIGNALS.get("signal-clusters-absent")!.nextCommand;
+const INTENTIONS_ABSENT_COMMAND = DIAGNOSTIC_SIGNALS.get("intentions-absent")!.nextCommand;
+const INDEX_BUILT_COMMAND = DIAGNOSTIC_SIGNALS.get("search-index-built")!.nextCommand;
+const GIT_HISTORY_COMMAND = DIAGNOSTIC_SIGNALS.get("git-history-absent")!.nextCommand;
+const BRIDGE_PROPOSALS_COMMAND = DIAGNOSTIC_SIGNALS.get("bridge-proposals-absent")!.nextCommand;
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-terminal-states-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: "${vault}"\nagent_name: test-agent\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Every `next:` line in `stdout`, in order. */
+function nextLines(stdout: string): string[] {
+ return stdout.split("\n").filter((line) => line.startsWith("next: "));
+}
+
+/**
+ * Run one verb under `--json` and assert the payload is uncontaminated.
+ * Sequential by construction: the in-process CLI harness swaps
+ * `process.stdout.write`, so two concurrent runs would interleave.
+ */
+async function expectCleanJson(argv: ReadonlyArray<string>): Promise<void> {
+ const label = argv.join(" ");
+ const r = await runCli(argv, { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ expect(`${label}: ${r.returncode}`).toBe(`${label}: 0`);
+ expect(`${label}: ${r.stdout.includes("next: ")}`).toBe(`${label}: false`);
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+}
+
+async function brainInit(): Promise<void> {
+ await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+}
+
+describe("brain init - the command that creates the empty Brain", () => {
+ test("names what fills the Brain it just created", async () => {
+ await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ const r = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("brain initialized:");
+ expect(nextLines(r.stdout)).toEqual([`next: ${BRAIN_EMPTY_COMMAND}`]);
+ });
+
+ test("--json stays a clean payload", async () => {
+ await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ const r = await runCli(["brain", "init", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ });
+});
+
+describe("search index - the index exists, now what", () => {
+ test("a successful index names the read verb", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nhello world\n");
+ const r = await runCli(["search", "index"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("done in ");
+ expect(nextLines(r.stdout)).toEqual([`next: ${INDEX_BUILT_COMMAND}`]);
+ });
+
+ test("reindex reaches the same terminal state and says the same thing", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nhello world\n");
+ const r = await runCli(["search", "reindex"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(nextLines(r.stdout)).toEqual([`next: ${INDEX_BUILT_COMMAND}`]);
+ });
+
+ test("--json stays a clean payload", async () => {
+ writeFileSync(join(vault, "a.md"), "# A\n\nhello world\n");
+ const r = await runCli(["search", "index", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("next: ");
+ expect(() => JSON.parse(r.stdout)).not.toThrow();
+ });
+});
+
+describe("empty-state brain verbs", () => {
+ test("intent-review with no clusters names the signal writer", async () => {
+ await brainInit();
+ const r = await runCli(["brain", "intent-review", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no active signal clusters");
+ expect(nextLines(r.stdout)).toEqual([`next: ${CLUSTERS_ABSENT_COMMAND}`]);
+ });
+
+ test("intention list with no chains names its own setter", async () => {
+ await brainInit();
+ const r = await runCli(["brain", "intention", "list", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no active intentions");
+ expect(nextLines(r.stdout)).toEqual([`next: ${INTENTIONS_ABSENT_COMMAND}`]);
+ });
+
+ test("both stay clean under --json", async () => {
+ await brainInit();
+ await expectCleanJson(["brain", "intent-review", "--vault", vault, "--json"]);
+ await expectCleanJson(["brain", "intention", "list", "--vault", vault, "--json"]);
+ });
+});
+
+describe("the hand-written pointers are gone, not duplicated", () => {
+ test("git status with no ingested history routes through the rail", async () => {
+ await brainInit();
+ const r = await runCli(["brain", "git", "status", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no git history ingested yet");
+ // The parenthetical `(run: ...)` was the second mechanism.
+ expect(r.stdout).not.toContain("(run:");
+ expect(nextLines(r.stdout)).toEqual([`next: ${GIT_HISTORY_COMMAND}`]);
+ });
+
+ test("git mine with no ingested history routes through the rail", async () => {
+ await brainInit();
+ const r = await runCli(["brain", "git", "mine", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("(run:");
+ expect(nextLines(r.stdout)).toEqual([`next: ${GIT_HISTORY_COMMAND}`]);
+ });
+
+ test("bridges list with no artifact routes through the rail", async () => {
+ await brainInit();
+ const r = await runCli(["brain", "bridges", "list", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no proposals artifact yet");
+ expect(r.stdout).not.toContain("- run:");
+ expect(nextLines(r.stdout)).toEqual([`next: ${BRIDGE_PROPOSALS_COMMAND}`]);
+ });
+
+ test("git and bridges stay clean under --json", async () => {
+ await brainInit();
+ await expectCleanJson(["brain", "git", "status", "--vault", vault, "--json"]);
+ await expectCleanJson(["brain", "bridges", "list", "--vault", vault, "--json"]);
+ });
+});
+
+describe("states this task deliberately leaves silent", () => {
+ test("an empty approval queue names nothing, because nothing names it", async () => {
+ // `Brain/pending/` fills only as a side effect of session capture
+ // and session import, and only while the opt-in `write_approval`
+ // toggle is on. An empty queue is the healthy steady state, and no
+ // single command is its exit - naming one would be the invention
+ // this release exists to remove. See the census for the record.
+ await brainInit();
+ const r = await runCli(["brain", "pending", "list", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe("no pending signals\n");
+ });
+
+ test("a query that matched nothing on a healthy index names nothing", async () => {
+ // An empty result set is a correct answer to the question asked,
+ // not a degraded state. The only forward move is a different query,
+ // which the system cannot derive from the one that missed.
+ writeFileSync(join(vault, "a.md"), "# A\n\nhello world\n");
+ await runCli(["search", "index"], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ const r = await runCli(["search", "zzz-no-such-term-zzz"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(nextLines(r.stdout)).toEqual([]);
+ });
+
+ test("the self-healing read path is untouched", async () => {
+ // Pinned independently by tests/cli/search.test.ts; asserted here
+ // too because a "run the indexer" hint would regress a deliberate
+ // feature, and this file is where that temptation lives.
+ const r = await runCli(["search", "nothing-here"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(nextLines(r.stdout)).toEqual([]);
+ });
+});
diff --git a/tests/core/brain.diagnostics.test.ts b/tests/core/brain.diagnostics.test.ts
index f0661a80..a8920a82 100644
--- a/tests/core/brain.diagnostics.test.ts
+++ b/tests/core/brain.diagnostics.test.ts
@@ -22,7 +22,7 @@ import {
resolveSignal,
} from "../../src/core/brain/diagnostics.ts";
import { brainConfigPath, brainDirs, dreamWorkrunPath } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { readLogDay, listLogDates } from "../../src/core/brain/log-jsonl.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
diff --git a/tests/core/brain.doctor-trust-atoms.test.ts b/tests/core/brain.doctor-trust-atoms.test.ts
index c6a6353b..1063cfac 100644
--- a/tests/core/brain.doctor-trust-atoms.test.ts
+++ b/tests/core/brain.doctor-trust-atoms.test.ts
@@ -12,7 +12,7 @@ import { join } from "node:path";
import { runDoctor } from "../../src/core/brain/doctor.ts";
import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.ts
index f1a90adc..b65fdf73 100644
--- a/tests/core/brain.doctor.test.ts
+++ b/tests/core/brain.doctor.test.ts
@@ -24,7 +24,7 @@ import {
retiredPath,
signalPath,
} from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { writeSignal } from "../../src/core/brain/signal.ts";
import { runDoctor } from "../../src/core/brain/doctor.ts";
diff --git a/tests/core/brain.dream.phases.test.ts b/tests/core/brain.dream.phases.test.ts
index 2b0dd87b..07ab0313 100644
--- a/tests/core/brain.dream.phases.test.ts
+++ b/tests/core/brain.dream.phases.test.ts
@@ -78,21 +78,25 @@ describe("dream multi-phase pipeline", () => {
expect(synth?.metrics["new_unconfirmed"]).toBe(1);
});
- test("a changed run emits ordered phase checkpoints in the workrun", () => {
+ test("a changed run emits its phase checkpoints where the work lands", () => {
seed("phase-topic-a", "2026-05-20");
seed("phase-topic-b", "2026-05-21");
seed("phase-topic-c", "2026-05-22");
dream(vault, { now: new Date("2026-05-23T12:00:00Z") });
const phases = workrunPhases();
- // The new phase checkpoints appear in order between started/finalized.
+ // Emission order is execution order, not DREAM_PHASE_ORDER
+ // (no-dead-ends, Unit E). `reconcile_complete` trails the mutation
+ // markers because reconcile's only durable output - its audit events -
+ // is written in the log phase; recording it earlier claimed a phase
+ // complete before a single preference had been written.
const ordered = phases.filter((p) =>
["close_complete", "reconcile_complete", "synthesize_complete", "heal_complete"].includes(p),
);
expect(ordered).toEqual([
"close_complete",
- "reconcile_complete",
"synthesize_complete",
"heal_complete",
+ "reconcile_complete",
]);
});
diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.ts
index b86a6486..924fba72 100644
--- a/tests/core/brain.init.test.ts
+++ b/tests/core/brain.init.test.ts
@@ -13,7 +13,7 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { brainDirs } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
// Shared temp scratch for both vault and machine-config directories.
// Tests that need to assert the "missing machine config" path can
@@ -42,19 +42,14 @@ describe("bootstrapBrain — empty vault", () => {
test("creates every Brain directory and the three managed files", () => {
const result = bootstrapBrain(vault, { configPath });
- // Directories: every entry in brainDirs() must exist as a real dir.
+ // Directories: EVERY entry in brainDirs() must exist as a real dir.
+ // Enumerated from the struct rather than from a hand-written list, so
+ // a directory added to `brainDirs` cannot be declared and then left
+ // uncreated — which is exactly how `pending` and `entities` went
+ // missing (downstream writers made them lazily instead).
const dirs = brainDirs(vault);
- for (const dir of [
- dirs.brain,
- dirs.inbox,
- dirs.processed,
- dirs.preferences,
- dirs.retired,
- dirs.log,
- dirs.bases,
- dirs.snapshots,
- ]) {
- expect(existsSync(dir)).toBe(true);
+ for (const [name, dir] of Object.entries(dirs)) {
+ expect(`${name}:${existsSync(dir)}`).toBe(`${name}:true`);
expect(statSync(dir).isDirectory()).toBe(true);
}
@@ -113,6 +108,22 @@ describe("bootstrapBrain — idempotent rerun", () => {
// Second pass must not throw even though every directory exists.
expect(() => bootstrapBrain(vault, { configPath })).not.toThrow();
});
+
+ test("a directory created by hand between runs survives the second pass", () => {
+ bootstrapBrain(vault, { configPath });
+ const dirs = brainDirs(vault);
+ // Drop a marker into each declared directory; a second bootstrap must
+ // leave every one of them in place (mkdir -p, never mkdir -p after rm).
+ for (const dir of Object.values(dirs)) {
+ writeFileSync(join(dir, "marker.txt"), "kept\n", "utf8");
+ }
+ const second = bootstrapBrain(vault, { configPath });
+ expect(second.created.length).toBe(0);
+ expect(second.overwritten.length).toBe(0);
+ for (const dir of Object.values(dirs)) {
+ expect(readFileSync(join(dir, "marker.txt"), "utf8")).toBe("kept\n");
+ }
+ });
});
describe("bootstrapBrain — force overwrite", () => {
diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.ts
index 02dc97ac..67a164fc 100644
--- a/tests/core/brain.inline-scan.test.ts
+++ b/tests/core/brain.inline-scan.test.ts
@@ -10,7 +10,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { scanInline } from "../../src/core/brain/inline-scan.ts";
diff --git a/tests/core/brain.operator-snapshot.test.ts b/tests/core/brain.operator-snapshot.test.ts
index a3d4721b..c4cdadb2 100644
--- a/tests/core/brain.operator-snapshot.test.ts
+++ b/tests/core/brain.operator-snapshot.test.ts
@@ -18,7 +18,7 @@ import {
} from "../../src/core/brain/operator-snapshot.ts";
import { resolveSignal } from "../../src/core/brain/diagnostics.ts";
import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
let tmp: string;
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index 9b61fa0c..c5f25482 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -8,13 +8,13 @@ import {
BRAIN_CONFIG_SUPPORTED_VERSIONS,
BrainConfigError,
DEFAULT_BRAIN_CONFIG,
- DEFAULT_BRAIN_CONFIG_YAML,
formatPrimaryAgentYamlValue,
loadBrainConfig,
loadBrainConfigDetailed,
validateBrainConfig,
validateBrainConfigDetailed,
} from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { resolveSchemaVocabulary } from "../../src/core/brain/schema-vocab.ts";
let tmp: string;
@@ -95,6 +95,35 @@ describe("validateBrainConfig — happy path", () => {
});
});
+describe("validateBrainConfig — retire block", () => {
+ // Regression: `confirmed_evidence_min_threshold` reached `mergeBlock`
+ // but was dropped when the typed config was assembled, so the
+ // destructive-from-confirmed gate the dream pass reads could never be
+ // switched on from `_brain.yaml` — and no warning said so.
+ test("carries confirmed_evidence_min_threshold through to the typed config", () => {
+ const config = validateBrainConfig(
+ parseBrainYaml("schema_version: 1\nretire:\n confirmed_evidence_min_threshold: 5\n"),
+ "<test>",
+ );
+ expect(config.retire.confirmed_evidence_min_threshold).toBe(5);
+ expect(config.retire.stale_evidence_days).toBe(90);
+ });
+
+ test("omits the key entirely when the operator did not set it", () => {
+ const config = validateBrainConfig(parseBrainYaml("schema_version: 1\n"), "<test>");
+ expect("confirmed_evidence_min_threshold" in config.retire).toBe(false);
+ });
+
+ test("rejects a non-positive threshold by name instead of ignoring it", () => {
+ expect(() =>
+ validateBrainConfig(
+ parseBrainYaml("schema_version: 1\nretire:\n confirmed_evidence_min_threshold: 0\n"),
+ "<test>",
+ ),
+ ).toThrow(/retire\.confirmed_evidence_min_threshold/);
+ });
+});
+
describe("validateBrainConfig — schema block", () => {
test("absent schema block keeps the default config unchanged", () => {
expect(DEFAULT_BRAIN_CONFIG).not.toHaveProperty("schema");
diff --git a/tests/core/brain.session-summary.test.ts b/tests/core/brain.session-summary.test.ts
index d7e2cf3f..fe2460f2 100644
--- a/tests/core/brain.session-summary.test.ts
+++ b/tests/core/brain.session-summary.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -9,6 +10,10 @@ import {
listSessionSummaries,
SessionSummaryError,
} from "../../src/core/brain/session-summary.ts";
+import {
+ resolveSessionScope,
+ SESSION_SCOPE_MAX_LENGTH,
+} from "../../src/core/brain/session-scope.ts";
import { listContinuityRecords } from "../../src/core/brain/continuity/store.ts";
let vault: string;
@@ -115,3 +120,151 @@ describe("byte-identical when unused", () => {
expect(listContinuityRecords(vault).length).toBe(0);
});
});
+
+describe("project scope (Task 18)", () => {
+ test("carries the project, normalized by the shared session-scope slug rule", () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-proj",
+ project: " Open Second/Brain -- v2! ",
+ decisions: ["scoped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ // Exactly what resolveSessionScope would produce for the same raw
+ // input on the session axis: lowercase, non-alphanumerics collapsed
+ // to single dashes, edge dashes trimmed.
+ const expected = resolveSessionScope(" Open Second/Brain -- v2! ");
+ expect(expected).toBe("open-second-brain-v2");
+ expect(digest.project).toBe(expected);
+ expect(getSessionSummary(vault, "sess-proj")!.project).toBe(expected);
+ });
+
+ test("caps the slug at the shared session-scope length", () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-long",
+ project: "p".repeat(SESSION_SCOPE_MAX_LENGTH + 40),
+ decisions: ["scoped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ expect(digest.project).toBe("p".repeat(SESSION_SCOPE_MAX_LENGTH));
+ });
+
+ test("a digest with no project is byte-identical to today, dedupe key included", () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-plain",
+ request: "Add a structured session summary",
+ decisions: ["Reuse the continuity store"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ expect(digest.project).toBeUndefined();
+ expect(Object.keys(digest).toSorted()).toEqual([
+ "createdAt",
+ "decisions",
+ "id",
+ "learnings",
+ "nextSteps",
+ "request",
+ "sessionId",
+ ]);
+
+ const record = listContinuityRecords(vault, { kind: "session_summary_digest" })[0]!;
+ // The pre-project key shape, pinned literally: a changed dedupe key
+ // would silently stop deduplicating every digest already on disk.
+ const contentHash = createHash("sha256")
+ .update(
+ JSON.stringify([
+ "Add a structured session summary",
+ ["Reuse the continuity store"],
+ [],
+ [],
+ ]),
+ )
+ .digest("hex")
+ .slice(0, 16);
+ expect(record.payload["dedupe_key"]).toBe(`session_summary_digest:sess-plain:${contentHash}`);
+ expect(record.payload["project"]).toBeUndefined();
+ expect(Object.keys(record.payload).toSorted()).toEqual([
+ "content_hash",
+ "decisions",
+ "dedupe_key",
+ "learnings",
+ "next_steps",
+ "request",
+ "session_id",
+ ]);
+ });
+
+ test("the same content under two projects are two digests, not one dedupe hit", () => {
+ const base = {
+ sessionId: "sess-two",
+ decisions: ["same decision"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ } as const;
+ const alpha = appendSessionSummary(vault, { ...base, project: "alpha" });
+ const beta = appendSessionSummary(vault, { ...base, project: "beta" });
+ const unscoped = appendSessionSummary(vault, base);
+ expect(new Set([alpha.id, beta.id, unscoped.id]).size).toBe(3);
+ // ...and a re-append under the same project still dedupes.
+ expect(appendSessionSummary(vault, { ...base, project: "alpha" }).id).toBe(alpha.id);
+ });
+
+ test("rejects a project with no alphanumeric by name rather than dropping it", () => {
+ expect(() =>
+ appendSessionSummary(vault, {
+ sessionId: "sess-bad",
+ project: "---",
+ decisions: ["scoped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ }),
+ ).toThrow(SessionSummaryError);
+ expect(() =>
+ appendSessionSummary(vault, {
+ sessionId: "sess-bad",
+ project: " ",
+ decisions: ["scoped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ }),
+ ).toThrow(/project/);
+ expect(listContinuityRecords(vault, { kind: "session_summary_digest" }).length).toBe(0);
+ });
+
+ test("listSessionSummaries filters by project", () => {
+ appendSessionSummary(vault, {
+ sessionId: "s-a",
+ project: "Alpha Project",
+ decisions: ["a"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ appendSessionSummary(vault, {
+ sessionId: "s-b",
+ project: "beta",
+ decisions: ["b"],
+ createdAt: "2026-06-14T11:00:00.000Z",
+ });
+ appendSessionSummary(vault, {
+ sessionId: "s-c",
+ decisions: ["c"],
+ createdAt: "2026-06-14T12:00:00.000Z",
+ });
+
+ expect(listSessionSummaries(vault).length).toBe(3);
+ // The filter normalizes by the same rule as the write.
+ const alpha = listSessionSummaries(vault, { project: "alpha-project" });
+ expect(alpha.length).toBe(1);
+ expect(alpha[0]!.sessionId).toBe("s-a");
+ expect(listSessionSummaries(vault, { project: "ALPHA PROJECT" })[0]!.sessionId).toBe("s-a");
+ expect(listSessionSummaries(vault, { project: "beta" }).length).toBe(1);
+ expect(listSessionSummaries(vault, { project: "nope" }).length).toBe(0);
+ });
+
+ test("a malformed project filter is rejected by name, not silently ignored", () => {
+ appendSessionSummary(vault, {
+ sessionId: "s-a",
+ project: "alpha",
+ decisions: ["a"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ // Silently ignoring it would return every digest - a wrong answer
+ // dressed as a successful filter.
+ expect(() => listSessionSummaries(vault, { project: "***" })).toThrow(SessionSummaryError);
+ });
+});
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index 83d64189..2825893e 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { brainDirs } from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { importSession, importSessionPath } from "../../src/core/brain/sessions/import.ts";
import { SessionImportError } from "../../src/core/brain/sessions/types.ts";
diff --git a/tests/core/brain/applier-capability.test.ts b/tests/core/brain/applier-capability.test.ts
new file mode 100644
index 00000000..f14fc83f
--- /dev/null
+++ b/tests/core/brain/applier-capability.test.ts
@@ -0,0 +1,256 @@
+/**
+ * no-dead-ends, task 8: the applier capability table.
+ *
+ * Three Finding-to-apply pipelines ship in this codebase and each one used
+ * to decide privately what it could repair. The table is the published
+ * answer - per finding code, mechanical (naming the fixer) or refused
+ * (naming the reason) - and this file is the mechanism that stops the
+ * table and the appliers from drifting apart.
+ *
+ * The table module imports nothing, deliberately (see its docblock), so
+ * every code in it is a literal. That is only safe because the checks
+ * below re-derive the same population from the appliers themselves and
+ * fail on any disagreement in either direction.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ APPLIER_CAPABILITY,
+ REPAIR_SURFACE,
+ REPAIR_VERDICT,
+ RefusedRepairError,
+ UnclassifiedRepairCodeError,
+ repairCapability,
+ requireMechanicalRepair,
+ requireRepairCapability,
+} from "../../../src/core/brain/applier-capability.ts";
+import {
+ REPAIR_CODE,
+ REPAIR_FIXER_CODES,
+ applyRepair,
+} from "../../../src/core/brain/diagnostics.ts";
+import { LINT_CONSOLIDATE_KIND } from "../../../src/core/brain/lint-consolidate.ts";
+import { applyHygienePlan } from "../../../src/core/brain/hygiene/apply.ts";
+import { buildHygienePlan } from "../../../src/core/brain/hygiene/plan.ts";
+import {
+ HYGIENE_PROPOSED_ACTIONS,
+ type HygieneFinding,
+ type HygieneProposedAction,
+ type HygieneScanReport,
+} from "../../../src/core/brain/hygiene/types.ts";
+import { applyRemediation, planRemediation } from "../../../src/core/brain/health/remediation.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import {
+ VaultIdentityMismatchError,
+ assertVaultIdentityForWrite,
+ resetVaultIdentityPins,
+ vaultIdentityPath,
+ writeVaultIdentity,
+} from "../../../src/core/brain/vault-identity.ts";
+
+/** Codes whose surface is one of the appliers, per the table. */
+function codesForSurface(surface: string): string[] {
+ return [...APPLIER_CAPABILITY.values()]
+ .filter((entry) => entry.surface === surface)
+ .map((entry) => entry.code)
+ .toSorted();
+}
+
+describe("applier capability table - shape", () => {
+ test("every entry is keyed by its own code", () => {
+ for (const [code, entry] of APPLIER_CAPABILITY) expect(entry.code).toBe(code);
+ expect(APPLIER_CAPABILITY.size).toBeGreaterThan(0);
+ });
+
+ test("every mechanical entry names a fixer and every refusal names a reason", () => {
+ for (const entry of APPLIER_CAPABILITY.values()) {
+ if (entry.verdict === REPAIR_VERDICT.mechanical) {
+ expect(entry.fixer.length).toBeGreaterThan(0);
+ } else {
+ expect(entry.verdict).toBe(REPAIR_VERDICT.refused);
+ // A refusal with an empty reason is the dead end this release
+ // exists to remove, so the emptiness check is the point.
+ expect(entry.reason.trim().length).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ test("a code no applier owns can only be a refusal", () => {
+ for (const entry of APPLIER_CAPABILITY.values()) {
+ if (entry.surface !== REPAIR_SURFACE.detectorOnly) continue;
+ expect(entry.verdict).toBe(REPAIR_VERDICT.refused);
+ }
+ // The four refusals reconnaissance verified as stated-and-deliberate.
+ expect(codesForSurface(REPAIR_SURFACE.detectorOnly)).toEqual([
+ "frontmatter-line-dropped",
+ "link_integrity",
+ "stale-lock",
+ "vault-marker-absent",
+ ]);
+ });
+
+ test("lookup refuses to invent an answer for an unregistered code", () => {
+ expect(repairCapability("no-such-code")).toBeNull();
+ expect(() => requireRepairCapability("no-such-code")).toThrow(UnclassifiedRepairCodeError);
+ expect(() => requireMechanicalRepair("stale-lock")).toThrow(RefusedRepairError);
+ });
+});
+
+describe("applier capability table - cannot disagree with the fixers", () => {
+ test("the diagnostics fixer registry and the table name the same codes", () => {
+ expect([...REPAIR_FIXER_CODES].toSorted()).toEqual(codesForSurface(REPAIR_SURFACE.diagnostics));
+ for (const code of REPAIR_FIXER_CODES) {
+ expect(requireMechanicalRepair(code).code).toBe(code);
+ }
+ expect(REPAIR_FIXER_CODES.has(REPAIR_CODE.walGap)).toBe(true);
+ expect(REPAIR_FIXER_CODES.has(REPAIR_CODE.orphanedReference)).toBe(true);
+ });
+
+ test("the remediation planner's classification matches the table verdict", () => {
+ const plan = planRemediation(
+ {
+ driftedSlugs: ["drifted"],
+ contradictions: [{ aId: "pref-a", bId: "pref-b" }],
+ staleClaims: [{ id: "pref-c" }],
+ conceptGaps: [{ term: "concept" }],
+ widePermissions: [{ path: "Brain/wide.md", isDir: false, mode: 0o644 }],
+ },
+ { stepCap: 10 },
+ );
+ const seen = new Set<string>();
+ for (const step of plan.steps) {
+ seen.add(step.code);
+ const entry = requireRepairCapability(step.code);
+ const expected =
+ entry.verdict === REPAIR_VERDICT.mechanical ? "auto-safe" : ("needs-review" as const);
+ expect(step.classification).toBe(expected);
+ }
+ // Both directions: nothing in the table claims a remediation code the
+ // planner cannot produce.
+ expect([...seen].toSorted()).toEqual(codesForSurface(REPAIR_SURFACE.healthRemediation));
+ });
+
+ test("the hygiene plan executes exactly the actions the table calls mechanical", () => {
+ const mechanical: string[] = [];
+ const refused: string[] = [];
+ for (const action of HYGIENE_PROPOSED_ACTIONS) {
+ const plan = buildHygienePlan(reportWithAction(action));
+ if (plan.selected.length === 1) mechanical.push(action);
+ else if (plan.excluded_review.length === 1) refused.push(action);
+ else throw new Error(`hygiene action '${action}' was neither selected nor excluded`);
+ }
+ expect(mechanical.toSorted()).toEqual(
+ codesForSurface(REPAIR_SURFACE.hygieneApply).filter(
+ (code) => APPLIER_CAPABILITY.get(code)!.verdict === REPAIR_VERDICT.mechanical,
+ ),
+ );
+ expect(refused).toEqual(["review"]);
+ });
+
+ test("the lint-consolidate fix kinds are the table's lint entries", () => {
+ const kinds: string[] = Object.values(LINT_CONSOLIDATE_KIND);
+ expect(kinds.toSorted()).toEqual(codesForSurface(REPAIR_SURFACE.lintConsolidate));
+ });
+});
+
+function reportWithAction(action: HygieneProposedAction): HygieneScanReport {
+ const finding: HygieneFinding = {
+ id: `probe:${action}`,
+ detector: "dedup",
+ severity: "action",
+ title: `probe for ${action}`,
+ targets: ["pref-a", "pref-b"],
+ proposed_action: action,
+ evidence: {},
+ };
+ return {
+ generated_at: "2026-07-25T00:00:00Z",
+ detectors_run: ["dedup"],
+ findings: [finding],
+ counts: { dedup: 1 },
+ errors: [],
+ };
+}
+
+// ----- Write-guard placement ------------------------------------------------
+
+let vault: string;
+let configDir: string;
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ vault = mkdtempSync(join(tmpdir(), "o2b-capability-vault-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-capability-cfg-"));
+ const configPath = join(configDir, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+/**
+ * Put the resolved root into the ONE state the guard refuses: a marker
+ * this process already pinned, replaced by a different one.
+ */
+function makeVaultIdentityMismatch(): void {
+ writeVaultIdentity(vault);
+ assertVaultIdentityForWrite(vault);
+ atomicWriteFileSync(
+ vaultIdentityPath(vault),
+ `${JSON.stringify(
+ { schema_version: 1, vault_id: "f".repeat(32), created_at: "2026-01-01T00:00:00.000Z" },
+ null,
+ 2,
+ )}\n`,
+ );
+}
+
+describe("write-guard placement is identical across the three appliers", () => {
+ const emptyHygienePlan = Object.freeze({
+ selected: Object.freeze([]),
+ excluded_review: Object.freeze([]),
+ unknown_ids: Object.freeze([]),
+ });
+ const now = new Date("2026-07-25T00:00:00Z");
+
+ test("a dry run previews against a root the guard would refuse to write", async () => {
+ makeVaultIdentityMismatch();
+
+ expect(applyRepair(vault, { dryRun: true }).dryRun).toBe(true);
+ expect(
+ (await applyHygienePlan(vault, emptyHygienePlan, { dryRun: true, agent: "t", now })).dry_run,
+ ).toBe(true);
+ expect(
+ applyRemediation(vault, planRemediation(NO_FINDINGS, { stepCap: 1 }), { dryRun: true })
+ .dryRun,
+ ).toBe(true);
+ });
+
+ test("a real apply refuses on the same root", async () => {
+ makeVaultIdentityMismatch();
+
+ expect(() => applyRepair(vault, { dryRun: false })).toThrow(VaultIdentityMismatchError);
+ await expect(
+ applyHygienePlan(vault, emptyHygienePlan, { dryRun: false, agent: "t", now }),
+ ).rejects.toThrow(VaultIdentityMismatchError);
+ expect(() =>
+ applyRemediation(vault, planRemediation(NO_FINDINGS, { stepCap: 1 }), { dryRun: false }),
+ ).toThrow(VaultIdentityMismatchError);
+ });
+});
+
+const NO_FINDINGS = Object.freeze({
+ driftedSlugs: Object.freeze([]),
+ contradictions: Object.freeze([]),
+ staleClaims: Object.freeze([]),
+ conceptGaps: Object.freeze([]),
+});
diff --git a/tests/core/brain/broken-link-findings.test.ts b/tests/core/brain/broken-link-findings.test.ts
new file mode 100644
index 00000000..16b0180a
--- /dev/null
+++ b/tests/core/brain/broken-link-findings.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Broken-link findings are machine-actionable (no-dead-ends, task 12).
+ *
+ * `broken-wikilink` carried the field name and the dead target only
+ * inside its sentence, and `broken-backlinks` carried no `path` at all -
+ * its referencing sources were joined into the message string. A consumer
+ * that wanted to act on either had to regex prose, which is how a
+ * detector and an applier end up disagreeing about what was detected.
+ *
+ * The data is now carried as fields. The message text is unchanged, byte
+ * for byte, because a human surface reads it and this task is not a
+ * rewording.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../../src/mcp/index.ts";
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import type { DoctorIssue } from "../../../src/core/brain/types.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-broken-link-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function seedPreference(
+ slug: string,
+ fields: Partial<Parameters<typeof writePreference>[1]>,
+): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `principle for ${slug}`,
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ ...fields,
+ });
+}
+
+function findAll(issues: ReadonlyArray<DoctorIssue>, code: string): ReadonlyArray<DoctorIssue> {
+ return issues.filter((issue) => issue.code === code);
+}
+
+describe("broken-wikilink carries its field and target", () => {
+ test("an evidence pointer with no file exposes both without prose parsing", () => {
+ seedPreference("dead-evidence", { evidenced_by: ["[[sig-does-not-exist]]"] });
+
+ const report = runDoctor(vault);
+ const hits = findAll(report.warnings, "broken-wikilink");
+ expect(hits.length).toBe(1);
+ const hit = hits[0]!;
+
+ expect(hit.field).toBe("evidenced_by");
+ expect(hit.target).toBe("sig-does-not-exist");
+ expect(hit.path).toBe(join(vault, "Brain", "preferences", "pref-dead-evidence.md"));
+ // The human sentence is untouched - this task adds fields, it does
+ // not reword anything.
+ expect(hit.message).toBe(
+ "field 'evidenced_by' references missing basename 'sig-does-not-exist'",
+ );
+ });
+
+ test("a structural lifecycle field is distinguishable from an evidence one", () => {
+ seedPreference("dead-supersedes", { supersedes: "[[pref-never-existed]]" });
+
+ const hits = findAll(runDoctor(vault).warnings, "broken-wikilink");
+ expect(hits.length).toBe(1);
+ // The whole point: an applier decides prune-vs-review from the field
+ // name, and the field name is now a value rather than a substring.
+ expect(hits[0]!.field).toBe("supersedes");
+ expect(hits[0]!.target).toBe("pref-never-existed");
+ });
+
+ test("an issue of another code carries none of the new keys", () => {
+ seedPreference("clean", {});
+ const report = runDoctor(vault);
+ for (const issue of [...report.errors, ...report.warnings]) {
+ if (issue.code === "broken-wikilink" || issue.code === "broken-backlinks") continue;
+ expect(Object.hasOwn(issue, "field")).toBe(false);
+ expect(Object.hasOwn(issue, "target")).toBe(false);
+ expect(Object.hasOwn(issue, "sources")).toBe(false);
+ }
+ });
+});
+
+/** Seed a preference whose BODY names `target`, producing a backlink. */
+function seedBodyReference(slug: string, target: string): void {
+ seedPreference(slug, {});
+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ appendFileSync(path, `\n## Notes\n\nsee [[${target}]]\n`, "utf8");
+}
+
+describe("broken-backlinks carries its target and its sources", () => {
+ test("the referencing sources are a list, not a joined sentence", () => {
+ seedBodyReference("src-a", "pref-vanished");
+ seedBodyReference("src-b", "pref-vanished");
+
+ const hits = findAll(runDoctor(vault).warnings, "broken-backlinks");
+ expect(hits.length).toBe(1);
+ const hit = hits[0]!;
+
+ expect(hit.target).toBe("pref-vanished");
+ expect(hit.sources).toEqual(["pref-src-a", "pref-src-b"]);
+ // Unchanged message, including the joined source list it always had.
+ expect(hit.message).toBe(
+ "[[pref-vanished]] is referenced by 2 source(s) but no file with that " +
+ "basename exists under Brain/: pref-src-a, pref-src-b",
+ );
+ });
+
+ test("a consumer can act on the finding without touching the message", () => {
+ seedBodyReference("src-a", "pref-vanished");
+
+ const hit = findAll(runDoctor(vault).warnings, "broken-backlinks")[0]!;
+ // A repair driver's whole input, derived from fields only.
+ const work = (hit.sources ?? []).map((source) => ({ source, target: hit.target }));
+ expect(work).toEqual([{ source: "pref-src-a", target: "pref-vanished" }]);
+ });
+});
+
+describe("the MCP doctor surface carries the same fields", () => {
+ /** `brain_doctor` over a live server, returning the parsed payload. */
+ async function callDoctor(): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "broken-link-findings-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "brain_doctor", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(r.result.content[0]!.text) as Record<string, unknown>;
+ }
+
+ test("both codes arrive with their fields, and next_command still resolves", async () => {
+ seedPreference("dead-evidence", { evidenced_by: ["[[sig-does-not-exist]]"] });
+ seedBodyReference("src-a", "pref-vanished");
+
+ const warnings = ((await callDoctor())["warnings"] ?? []) as ReadonlyArray<
+ Record<string, unknown>
+ >;
+
+ const wikilink = warnings.find((w) => w["code"] === "broken-wikilink")!;
+ expect(wikilink["field"]).toBe("evidenced_by");
+ expect(wikilink["target"]).toBe("sig-does-not-exist");
+ // Task 4's field is untouched by task 12's additions.
+ expect(wikilink["next_command"]).toBe(DIAGNOSTIC_SIGNALS.get("broken-wikilink")!.nextCommand);
+
+ // The dead `evidenced_by` pointer is a backlink source too, so this
+ // vault reports two `broken-backlinks` warnings. Selecting by the
+ // structured target - rather than by position or by a substring of
+ // the message - is itself the property under test.
+ const backlinks = warnings.find(
+ (w) => w["code"] === "broken-backlinks" && w["target"] === "pref-vanished",
+ )!;
+ expect(backlinks).toBeDefined();
+ expect(backlinks["sources"]).toEqual(["pref-src-a"]);
+ expect(backlinks["next_command"]).toBe(DIAGNOSTIC_SIGNALS.get("broken-backlinks")!.nextCommand);
+ });
+
+ test("an issue with none of the new data carries none of the new keys", async () => {
+ seedPreference("clean", {});
+ const payload = await callDoctor();
+ for (const key of ["errors", "warnings"]) {
+ for (const record of (payload[key] ?? []) as ReadonlyArray<Record<string, unknown>>) {
+ if (record["code"] === "broken-wikilink" || record["code"] === "broken-backlinks") continue;
+ expect(Object.hasOwn(record, "field")).toBe(false);
+ expect(Object.hasOwn(record, "target")).toBe(false);
+ expect(Object.hasOwn(record, "sources")).toBe(false);
+ }
+ }
+ });
+});
diff --git a/tests/core/brain/config-template-ratchet.test.ts b/tests/core/brain/config-template-ratchet.test.ts
new file mode 100644
index 00000000..795431c3
--- /dev/null
+++ b/tests/core/brain/config-template-ratchet.test.ts
@@ -0,0 +1,266 @@
+/**
+ * Ratchet: the `_brain.yaml` bootstrap template must represent every key
+ * the resolver understands.
+ *
+ * The template used to be a hand-written string constant that emitted 7
+ * of the 23 top-level keys the validator branches on. Nothing kept the
+ * two in sync, so sixteen keys resolved silently from defaults and never
+ * appeared in the file an operator reads. This suite closes that loop
+ * from BOTH ends:
+ *
+ * - the key index is enumerated from the validator itself
+ * (`brainConfigKnownKeys`), never from a hand-maintained list, so a
+ * key added to the resolver shows up here on the next run;
+ * - every enumerated key must either appear in the generated template
+ * or be listed in `BRAIN_CONFIG_TEMPLATE_OMISSIONS` with a written,
+ * non-empty reason.
+ *
+ * The remaining tests pin the two properties that make the change safe:
+ * the LIVE surface of the template is byte-identical to the one shipped
+ * before generation (only commentary was added), and a configuration
+ * carrying every documented default explicitly resolves to exactly what
+ * an empty configuration resolves to.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ BRAIN_CONFIG_TEMPLATE,
+ BRAIN_CONFIG_TEMPLATE_OMISSIONS,
+ DEFAULT_BRAIN_CONFIG_YAML,
+ renderBrainConfigTemplate,
+} from "../../../src/core/brain/config-template.ts";
+import {
+ brainConfigKnownKeys,
+ resolveGuardrails,
+ resolveHealth,
+ resolveIntegrity,
+ resolveLinkGraph,
+ resolveNotes,
+ resolveSessions,
+ resolveTemporal,
+ validateBrainConfigDetailed,
+ INJECT_BUDGET_CHARS_DEFAULT,
+ LESSONS_CORROBORATION_MIN_DEFAULT,
+ LESSONS_HALF_LIFE_DAYS_DEFAULT,
+ LESSONS_LIMIT_DEFAULT,
+ MOST_APPLIED_LIMIT_DEFAULT,
+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,
+} from "../../../src/core/brain/policy.ts";
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
+import { DEFAULT_VAULT_IGNORE_PATHS } from "../../../src/core/vault-scope/defaults.ts";
+import { resolveRollupThresholds } from "../../../src/core/brain/rollup-ladder.ts";
+import { resolveSchemaVocabulary } from "../../../src/core/brain/schema-vocab.ts";
+import {
+ DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ DEFAULT_ANTICIPATORY_TTL_SECONDS,
+} from "../../../src/core/brain/anticipatory-cache.ts";
+import type { BrainConfig } from "../../../src/core/brain/types.ts";
+
+/**
+ * The template exactly as it shipped in v1.38.0, before it was
+ * generated. Inlined (not imported) on purpose: it is the frozen
+ * baseline the LIVE surface must still equal, so importing the live
+ * constant would make the assertion vacuous.
+ */
+const LEGACY_TEMPLATE = `schema_version: 1
+
+# Optional. When set, dream runs from a different agent emit a stderr
+# warning and a non_primary_agent payload row. The vault should have a
+# single dream-running runtime even when it is shared across devices
+# via Syncthing.
+primary_agent: null
+
+dream:
+ candidate_threshold: 3
+ unconfirmed_window_days: 14
+ contradiction_window_days: 14
+
+retire:
+ stale_evidence_days: 90
+
+confidence:
+ # low_max_applied gates the "low-evidence-confirmed" doctor warning
+ # and the auto-promotion of unconfirmed preferences to confirmed.
+ low_max_applied: 2
+ # Band thresholds on the numeric confidence_value (Wilson lower
+ # bound times freshness decay). value >= high_min ⇒ high;
+ # value >= medium_min ⇒ medium; else low.
+ medium_min: 0.40
+ high_min: 0.75
+
+snapshots:
+ retention_count: 10
+
+# Vault-wide exclusion policy. Single source of truth for every
+# vault walker (search indexer, scan-inline, future scanners).
+# Entries without a slash match a directory name anywhere in the
+# tree; entries with a slash match a vault-relative POSIX path
+# exactly. Remove the block to fall back to the built-in defaults;
+# set ignore_paths to an empty list to disable exclusions entirely.
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+ - .open-second-brain
+ - .obsidian
+ - .trash
+ - .stversions
+ - Brain/.snapshots
+`;
+
+/** Drop comment-only and blank lines: what is left is the LIVE surface. */
+function liveSurface(yaml: string): string {
+ return yaml
+ .split("\n")
+ .filter((line) => line.trim() !== "" && !line.trimStart().startsWith("#"))
+ .join("\n");
+}
+
+function loadFrom(yaml: string): BrainConfig {
+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<ratchet>").config;
+}
+
+/**
+ * The fully-resolved configuration: every block passed through its
+ * resolver (or its consumer-side `?? DEFAULT`), so "block absent" and
+ * "block present at its default" collapse to the same value iff the
+ * template's documented defaults really are the resolver's defaults.
+ */
+function resolvedView(cfg: BrainConfig): Record<string, unknown> {
+ return {
+ schema_version: cfg.schema_version,
+ primary_agent: cfg.primary_agent,
+ dream: cfg.dream,
+ retire: cfg.retire,
+ confidence: cfg.confidence,
+ snapshots: cfg.snapshots,
+ vault_ignore_paths: cfg.vault?.ignore_paths ?? DEFAULT_VAULT_IGNORE_PATHS,
+ active_most_applied: cfg.active?.most_applied ?? {
+ window_days: MOST_APPLIED_WINDOW_DAYS_DEFAULT,
+ limit: MOST_APPLIED_LIMIT_DEFAULT,
+ },
+ active_inject_budget_chars: cfg.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT,
+ lessons: {
+ half_life_days: cfg.lessons?.half_life_days ?? LESSONS_HALF_LIFE_DAYS_DEFAULT,
+ corroboration_min: cfg.lessons?.corroboration_min ?? LESSONS_CORROBORATION_MIN_DEFAULT,
+ limit: cfg.lessons?.limit ?? LESSONS_LIMIT_DEFAULT,
+ },
+ guardrails: resolveGuardrails(cfg),
+ link_graph: resolveLinkGraph(cfg),
+ temporal: resolveTemporal(cfg),
+ health: resolveHealth(cfg),
+ integrity: resolveIntegrity(cfg),
+ notes: resolveNotes(cfg),
+ sessions: resolveSessions(cfg),
+ rollup: resolveRollupThresholds(cfg),
+ schema: resolveSchemaVocabulary(cfg.schema),
+ // `?? []` mirrors every consumer of these lists (`declarations[x] ?? []`
+ // in schema-report), so "block absent" and "declared empty" collapse to
+ // the same resolved vocabulary — which is exactly the claim under test.
+ schema_meta: {
+ aliases: cfg.schema?.aliases ?? [],
+ prefixes: cfg.schema?.prefixes ?? [],
+ link_types: cfg.schema?.link_types ?? [],
+ extractable: cfg.schema?.extractable ?? [],
+ expert_routing: cfg.schema?.expert_routing ?? [],
+ },
+ anticipatory: {
+ ttl_seconds: cfg.anticipatory?.ttl_seconds ?? DEFAULT_ANTICIPATORY_TTL_SECONDS,
+ max_tokens: cfg.anticipatory?.max_tokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ },
+ recall_degradation: cfg.recall?.degradation ?? "hard-cut",
+ hygiene_resolver_cmd: cfg.hygiene?.resolver_cmd,
+ feedback_default_scope: cfg.feedback?.default_scope,
+ discipline_report: cfg.discipline_report,
+ };
+}
+
+describe("config template ratchet — coverage", () => {
+ const known = brainConfigKnownKeys();
+ const templated = new Set(BRAIN_CONFIG_TEMPLATE.map((b) => b.key));
+ const omitted = new Map(BRAIN_CONFIG_TEMPLATE_OMISSIONS.map((o) => [o.key, o.reason]));
+
+ test("every top-level key the resolver understands is templated or justified", () => {
+ const unrepresented = [...known.topLevel]
+ .filter((key) => !templated.has(key) && !omitted.has(key))
+ .toSorted();
+ expect(unrepresented).toEqual([]);
+ });
+
+ test("every sub-key the resolver understands is templated or justified", () => {
+ const unrepresented: string[] = [];
+ for (const [block, subKeys] of known.subKeys) {
+ const entry = BRAIN_CONFIG_TEMPLATE.find((b) => b.key === block);
+ const present = new Set(entry?.keys.map((k) => k.key) ?? []);
+ for (const sub of subKeys) {
+ const dotted = `${block}.${sub}`;
+ if (present.has(sub)) continue;
+ if (omitted.has(dotted) || omitted.has(block)) continue;
+ unrepresented.push(dotted);
+ }
+ }
+ expect(unrepresented.toSorted()).toEqual([]);
+ });
+
+ test("the template names no key the resolver does not understand", () => {
+ const stray: string[] = [];
+ for (const block of BRAIN_CONFIG_TEMPLATE) {
+ if (!known.topLevel.has(block.key)) {
+ stray.push(block.key);
+ continue;
+ }
+ const subKeys = known.subKeys.get(block.key) ?? new Set<string>();
+ for (const k of block.keys) {
+ if (!subKeys.has(k.key)) stray.push(`${block.key}.${k.key}`);
+ }
+ }
+ expect(stray.toSorted()).toEqual([]);
+ });
+
+ test("every omission carries a written reason and is not also templated", () => {
+ for (const { key, reason } of BRAIN_CONFIG_TEMPLATE_OMISSIONS) {
+ expect(reason.trim().length).toBeGreaterThan(0);
+ expect(templated.has(key)).toBe(false);
+ }
+ });
+});
+
+describe("config template ratchet — generated text", () => {
+ test("round-trips through the hand-rolled parser without warnings", () => {
+ const { warnings } = validateBrainConfigDetailed(
+ parseBrainYaml(DEFAULT_BRAIN_CONFIG_YAML),
+ "<ratchet>",
+ );
+ expect(warnings).toEqual([]);
+ });
+
+ test("the live surface is byte-identical to the pre-generation template", () => {
+ expect(liveSurface(DEFAULT_BRAIN_CONFIG_YAML)).toBe(liveSurface(LEGACY_TEMPLATE));
+ });
+
+ test("newly exposed keys are emitted commented, never live", () => {
+ const lines = DEFAULT_BRAIN_CONFIG_YAML.split("\n");
+ for (const block of BRAIN_CONFIG_TEMPLATE) {
+ for (const k of block.keys) {
+ if (k.emit === "live") continue;
+ const live = lines.some((l) => new RegExp(`^\\s*${k.key}\\s*:`).test(l));
+ expect(`${block.key}.${k.key} live=${live}`).toBe(`${block.key}.${k.key} live=false`);
+ }
+ }
+ });
+});
+
+describe("config template ratchet — resolved-behaviour identity", () => {
+ test("a config with every documented default resolves like an empty one", () => {
+ const allDefaults = loadFrom(renderBrainConfigTemplate({ allDefaultsLive: true }));
+ const empty = loadFrom("schema_version: 1\n");
+ expect(resolvedView(allDefaults)).toEqual(resolvedView(empty));
+ });
+
+ test("an existing vault written by the pre-generation template resolves unchanged", () => {
+ const legacy = loadFrom(LEGACY_TEMPLATE);
+ const generated = loadFrom(DEFAULT_BRAIN_CONFIG_YAML);
+ expect(resolvedView(generated)).toEqual(resolvedView(legacy));
+ });
+});
diff --git a/tests/core/brain/dedup-telemetry.test.ts b/tests/core/brain/dedup-telemetry.test.ts
new file mode 100644
index 00000000..125b69ab
--- /dev/null
+++ b/tests/core/brain/dedup-telemetry.test.ts
@@ -0,0 +1,371 @@
+/**
+ * Task 17 - the exact-hash ingest dedup counts become observable.
+ *
+ * The counters already existed and reached a CLI/MCP response, then died
+ * one call deep. These tests pin the persisted `ingest_dedup` continuity
+ * record, the aggregator that reads a trend back out of it, and the two
+ * invariants that make the record trustworthy: an ingest that dedupes
+ * nothing writes NO record (a zero row would make a real zero
+ * indistinguishable from an absent measurement), and no surface here
+ * reports a semantic figure as a drop - the semantic detectors nominate
+ * and never drop.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
+import {
+ emitIngestDedupReport,
+ INGEST_DEDUP_RECORD_KIND,
+ IngestDedupTelemetryError,
+ listIngestDedupReports,
+ MAX_TRACKED_DEDUP_SOURCES,
+ summarizeIngestDedup,
+} from "../../../src/core/brain/dedup-telemetry.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { scanInline } from "../../../src/core/brain/inline-scan.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
+import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dedup-telemetry-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function storedRecords(): ReadonlyArray<{ payload: Record<string, unknown> }> {
+ return listContinuityRecords(vault, { kind: INGEST_DEDUP_RECORD_KIND }) as ReadonlyArray<{
+ payload: Record<string, unknown>;
+ }>;
+}
+
+describe("emitIngestDedupReport", () => {
+ test("persists one record carrying the surface and the per-source counts", () => {
+ const record = emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [
+ { ref: "Daily/2026-07-01.md", exactDeduped: 2 },
+ { ref: "Daily/2026-07-02.md", exactDeduped: 1 },
+ ],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+
+ expect(record).not.toBeNull();
+ expect(record!.kind).toBe(INGEST_DEDUP_RECORD_KIND);
+ expect(record!.payload["surface"]).toBe("scan_inline");
+ expect(record!.payload["exact_deduped"]).toBe(3);
+ expect(record!.payload["by_source"]).toEqual({
+ "Daily/2026-07-01.md": 2,
+ "Daily/2026-07-02.md": 1,
+ });
+ // The source refs are join keys, so the record answers "which source
+ // is being re-ingested" without re-reading the payload.
+ expect(record!.sourceRefs.map((ref) => ref.id).toSorted()).toEqual([
+ "Daily/2026-07-01.md",
+ "Daily/2026-07-02.md",
+ ]);
+ });
+
+ test("writes NO record when nothing was deduped (no zero row)", () => {
+ const record = emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/2026-07-01.md", exactDeduped: 0 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ expect(record).toBeNull();
+ expect(storedRecords()).toHaveLength(0);
+ });
+
+ test("writes NO record when the ingest saw no sources at all", () => {
+ expect(
+ emitIngestDedupReport(vault, {
+ surface: "session_lifecycle",
+ sources: [],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ }),
+ ).toBeNull();
+ expect(storedRecords()).toHaveLength(0);
+ });
+
+ test("rejects a malformed count by name rather than inventing one", () => {
+ expect(() =>
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/a.md", exactDeduped: -1 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ }),
+ ).toThrow(IngestDedupTelemetryError);
+ expect(() =>
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/a.md", exactDeduped: 1.5 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ }),
+ ).toThrow(IngestDedupTelemetryError);
+ expect(storedRecords()).toHaveLength(0);
+ });
+
+ test("rejects a blank source ref by name", () => {
+ expect(() =>
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: " ", exactDeduped: 3 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ }),
+ ).toThrow(IngestDedupTelemetryError);
+ });
+
+ test("rejects an unknown surface by name", () => {
+ expect(() =>
+ emitIngestDedupReport(vault, {
+ // Deliberately outside the surface union: a caller bug must be
+ // named, never silently recorded under a made-up label.
+ surface: "not_a_surface" as "scan_inline",
+ sources: [{ ref: "Daily/a.md", exactDeduped: 1 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ }),
+ ).toThrow(IngestDedupTelemetryError);
+ });
+
+ test("caps the per-source map and names how many refs it omitted", () => {
+ const sources = Array.from({ length: MAX_TRACKED_DEDUP_SOURCES + 3 }, (_unused, index) => ({
+ ref: `Daily/note-${String(index).padStart(3, "0")}.md`,
+ exactDeduped: index + 1,
+ }));
+ const record = emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources,
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ expect(record).not.toBeNull();
+ const bySource = record!.payload["by_source"] as Record<string, number>;
+ expect(Object.keys(bySource)).toHaveLength(MAX_TRACKED_DEDUP_SOURCES);
+ expect(record!.payload["by_source_omitted"]).toBe(3);
+ // The total stays exact even though the map is clipped.
+ const expectedTotal = sources.reduce((sum, source) => sum + source.exactDeduped, 0);
+ expect(record!.payload["exact_deduped"]).toBe(expectedTotal);
+ });
+});
+
+describe("summarizeIngestDedup", () => {
+ test("returns a trend across records plus the re-ingest ranking per source", () => {
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/loud.md", exactDeduped: 4 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [
+ { ref: "Daily/loud.md", exactDeduped: 5 },
+ { ref: "Daily/quiet.md", exactDeduped: 1 },
+ ],
+ createdAt: "2026-07-02T10:00:00.000Z",
+ });
+ emitIngestDedupReport(vault, {
+ surface: "session_lifecycle",
+ sources: [{ ref: "session-7", exactDeduped: 2 }],
+ createdAt: "2026-07-03T10:00:00.000Z",
+ });
+
+ const summary = summarizeIngestDedup(vault);
+ expect(summary.total_records).toBe(3);
+ expect(summary.total_exact_deduped).toBe(12);
+ expect(summary.by_surface).toEqual({ scan_inline: 10, session_lifecycle: 2 });
+ expect(summary.by_source[0]).toEqual({
+ ref: "Daily/loud.md",
+ surface: "scan_inline",
+ exact_deduped: 9,
+ records: 2,
+ });
+ expect(summary.trend).toEqual([
+ { at: "2026-07-01T10:00:00.000Z", surface: "scan_inline", exact_deduped: 4 },
+ { at: "2026-07-02T10:00:00.000Z", surface: "scan_inline", exact_deduped: 6 },
+ { at: "2026-07-03T10:00:00.000Z", surface: "session_lifecycle", exact_deduped: 2 },
+ ]);
+ });
+
+ test("filters by surface and by time window", () => {
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/a.md", exactDeduped: 1 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ emitIngestDedupReport(vault, {
+ surface: "session_import",
+ sources: [{ ref: "session-9", exactDeduped: 3 }],
+ createdAt: "2026-07-05T10:00:00.000Z",
+ });
+
+ expect(summarizeIngestDedup(vault, { surface: "session_import" }).total_exact_deduped).toBe(3);
+ expect(listIngestDedupReports(vault, { since: "2026-07-03T00:00:00.000Z" })).toHaveLength(1);
+ });
+
+ test("an empty vault summarises to zeros without inventing a record", () => {
+ const summary = summarizeIngestDedup(vault);
+ expect(summary.total_records).toBe(0);
+ expect(summary.total_exact_deduped).toBe(0);
+ expect(summary.by_source).toEqual([]);
+ expect(summary.trend).toEqual([]);
+ });
+
+ test("reports no semantic figure at all - the semantic layers nominate, never drop", () => {
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/a.md", exactDeduped: 1 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ const summary = summarizeIngestDedup(vault);
+ // Every count this surface publishes is explicitly an EXACT-hash
+ // count. Nothing here may be read as "semantically dropped".
+ for (const key of Object.keys(summary)) {
+ expect(key).not.toContain("semantic");
+ }
+ const payloadKeys = Object.keys(storedRecords()[0]!.payload);
+ for (const key of payloadKeys) {
+ expect(key).not.toContain("semantic");
+ }
+ expect(payloadKeys).toContain("exact_deduped");
+ });
+});
+
+describe("scanInline dedup telemetry", () => {
+ function writeMd(rel: string, content: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+ }
+
+ beforeEach(() => {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n`,
+ );
+ });
+
+ test("a re-scan that dedupes records the file that is being re-ingested", async () => {
+ writeMd("Daily/2026-07-01.md", "@osb feedback positive topic=telemetry principle=p\n");
+ const first = await scanInline(vault, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:00Z"),
+ });
+ expect(first.created).toBe(1);
+ expect(first.deduped).toBe(0);
+ // Nothing deduped -> no record.
+ expect(storedRecords()).toHaveLength(0);
+
+ // A second, identical marker in a DIFFERENT file re-ingests the same rule.
+ writeMd("Daily/2026-07-02.md", "@osb feedback positive topic=telemetry principle=p\n");
+ const second = await scanInline(vault, {
+ agent: "tester",
+ now: new Date("2026-07-02T10:00:00Z"),
+ });
+ expect(second.deduped).toBe(1);
+
+ const records = storedRecords();
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload["surface"]).toBe("scan_inline");
+ expect(records[0]!.payload["exact_deduped"]).toBe(1);
+ expect(Object.keys(records[0]!.payload["by_source"] as Record<string, number>)).toEqual([
+ "Daily/2026-07-02.md",
+ ]);
+ });
+
+ test("a dry run observes but never writes a record", async () => {
+ writeMd("Daily/2026-07-01.md", "@osb feedback positive topic=dry principle=p\n");
+ await scanInline(vault, { agent: "tester", now: new Date("2026-07-01T10:00:00Z") });
+ writeMd("Daily/2026-07-02.md", "@osb feedback positive topic=dry principle=p\n");
+ const dry = await scanInline(vault, {
+ agent: "tester",
+ dryRun: true,
+ now: new Date("2026-07-02T10:00:00Z"),
+ });
+ expect(dry.deduped).toBe(1);
+ expect(storedRecords()).toHaveLength(0);
+ });
+
+ test("the scan result shape is unchanged by the new record", async () => {
+ writeMd("Daily/2026-07-01.md", "@osb feedback positive topic=shape principle=p\n");
+ const result = await scanInline(vault, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:00Z"),
+ });
+ expect(Object.keys(result).toSorted()).toEqual([
+ "created",
+ "deduped",
+ "errors",
+ "filesWithMarkers",
+ "found",
+ "malformed",
+ "scanned",
+ ]);
+ });
+});
+
+describe("captureSessionLifecycleEvent dedup telemetry", () => {
+ const payload = {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "session-dedup",
+ prompt: '@osb feedback positive topic=lifecycle principle="observe dedup"',
+ };
+
+ test("a repeated prompt records the session that is being re-ingested", async () => {
+ const first = await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:00Z"),
+ });
+ expect(first.signals_deduped).toBe(0);
+ expect(storedRecords()).toHaveLength(0);
+
+ const second = await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:01Z"),
+ });
+ expect(second.signals_deduped).toBe(1);
+
+ const records = storedRecords();
+ expect(records).toHaveLength(1);
+ expect(records[0]!.payload["surface"]).toBe("session_lifecycle");
+ expect(records[0]!.payload["exact_deduped"]).toBe(1);
+ expect(records[0]!.payload["by_source"]).toEqual({ "session-dedup": 1 });
+ });
+
+ test("the lifecycle result keeps its existing counter fields unchanged", async () => {
+ await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:00Z"),
+ });
+ const second = await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:01Z"),
+ });
+ expect(second.signals_created).toBe(0);
+ expect(second.signals_deduped).toBe(1);
+ expect(second.facts_deduped).toBe(0);
+ expect(Object.keys(second)).not.toContain("dedup_record_id");
+ });
+
+ test("a dry run never writes a record", async () => {
+ await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date("2026-07-01T10:00:00Z"),
+ });
+ const dry = await captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ dryRun: true,
+ now: new Date("2026-07-01T10:00:01Z"),
+ });
+ expect(dry.signals_deduped).toBe(1);
+ expect(storedRecords()).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.ts
new file mode 100644
index 00000000..4957b859
--- /dev/null
+++ b/tests/core/brain/doctor-exit-census.test.ts
@@ -0,0 +1,231 @@
+/**
+ * Doctor exit census (no-dead-ends, phase 3, item 2).
+ *
+ * `o2b brain doctor` printed a `next:` line under some findings and
+ * nothing under others, and there was no way to tell the two apart. Both
+ * look identical from outside: silence is what an unregistered code
+ * produces AND what a code nobody has got round to registering produces.
+ * This census removes the second reading. Every code the doctor can emit
+ * is either registered in `DIAGNOSTIC_SIGNALS` with a structural command,
+ * or listed in `DOCTOR_EXIT_EXCLUSIONS` with a written reason there is
+ * none - never both, never neither.
+ *
+ * ## Enumerated from the detector, never from the tables
+ *
+ * `DoctorIssue.code` is a free string, so the population is read out of
+ * `doctor.ts` itself and the tables are asked to account for it. Two
+ * shapes carry a code in that module and the census reads both:
+ *
+ * - `code: "<literal>"` at a push site;
+ * - `const <NAME>_CODE = "<literal>"` hoisted to a module constant.
+ *
+ * A third shape would be invisible to both, so a separate test guards it:
+ * every `code:` value that is not a string literal must be either a
+ * `*_CODE` constant the scan already read, or an entry in
+ * {@link NON_LITERAL_CODE_SITES} saying what it can produce. A future
+ * computed code fails there rather than slipping past unclassified.
+ *
+ * ## The boundary, stated rather than discovered
+ *
+ * The population is what `doctor.ts` SPELLS. Three sites forward
+ * `notice.code` from the closed `DEGRADATION_CODE` vocabulary owned by
+ * other modules; those codes are classified in `applier-capability.ts`,
+ * which is the table that owns that vocabulary's repair question, and
+ * re-declaring them here would give one code two homes.
+ *
+ * Modelled on `tests/core/brain/vault-guard-census.test.ts` and the
+ * terminal-state census: detect the property syntactically, keep one
+ * explicit inventory, one entry one reason, and pin the measurement so a
+ * regex that stopped matching cannot report a clean sweep over an empty
+ * set.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import {
+ DOCTOR_EXIT_EXCLUSIONS,
+ doctorExitReason,
+ noExitReasons,
+} from "../../../src/core/brain/doctor-exits.ts";
+
+const DOCTOR_SOURCE = readFileSync(
+ join(import.meta.dir, "..", "..", "..", "src", "core", "brain", "doctor.ts"),
+ "utf8",
+);
+
+/** `code: "<literal>"` - the shape most of the doctor's codes take. */
+const LITERAL_CODE_RE = /\bcode: "([^"]+)"/g;
+
+/** `const <NAME>_CODE = "<literal>";` - a code hoisted to a constant. */
+const CONSTANT_CODE_RE = /^const [A-Z0-9_]*CODE[A-Z0-9_]* = "([^"]+)";$/gm;
+
+/** Any `code:` property, for the shape guard below. */
+const CODE_SITE_RE = /^\s*code: (.+?),?$/gm;
+
+/** A `*_CODE` identifier used directly as the property value. */
+const CODE_IDENTIFIER_RE = /^[A-Z0-9_]*CODE[A-Z0-9_]*$/;
+
+/**
+ * `code:` values that are neither a string literal nor a `*_CODE`
+ * identifier. Each entry must say WHERE the codes that value can hold are
+ * enumerated instead - a site may only sit here because its codes are
+ * already accounted for somewhere, never because writing them out was
+ * inconvenient.
+ */
+const NON_LITERAL_CODE_SITES: Readonly<Record<string, string>> = Object.freeze({
+ "notice.code":
+ "forwards a code from the closed DEGRADATION_CODE vocabulary owned by vault.ts, " +
+ "vault-identity.ts and the lineage verifier into the uncertain stream. Those codes are " +
+ "classified in applier-capability.ts, the table that owns that vocabulary; declaring them " +
+ "here too would give one code two homes that can disagree.",
+ "parseErrorCode(kindPrefix, msg)":
+ "returns one of the four parse-error constants declared beside it, every one of which the " +
+ "*_CODE scan above already reads. The function exists so the choice between them is made in " +
+ "one named place rather than by concatenating a prefix onto a suffix, which is what made " +
+ "those four codes unreadable from this module's source at all.",
+});
+
+/** A reason has to say something; a placeholder cannot reach this. */
+const MIN_REASON_LENGTH = 80;
+
+/** This tool's own invocation - a reason may never contain one. */
+const INVOCATION_RE = /\bo2b\s+[a-z]/;
+
+/** Lines that mention `code:` without being a push site. */
+function isCodeSite(line: string): boolean {
+ const trimmed = line.trim();
+ return !trimmed.startsWith("*") && !trimmed.startsWith("readonly ");
+}
+
+function literalCodes(): ReadonlySet<string> {
+ return new Set([...DOCTOR_SOURCE.matchAll(LITERAL_CODE_RE)].map((m) => m[1]!));
+}
+
+function constantCodes(): ReadonlySet<string> {
+ return new Set([...DOCTOR_SOURCE.matchAll(CONSTANT_CODE_RE)].map((m) => m[1]!));
+}
+
+/** Every code `doctor.ts` spells, from both shapes. */
+function doctorCodes(): ReadonlyArray<string> {
+ return [...new Set([...literalCodes(), ...constantCodes()])].toSorted();
+}
+
+/** The value text of every `code:` property in the module. */
+function codeSiteValues(): ReadonlyArray<string> {
+ return [...DOCTOR_SOURCE.matchAll(CODE_SITE_RE)]
+ .filter((m) => isCodeSite(m[0]!))
+ .map((m) => m[1]!.trim());
+}
+
+describe("every doctor code is classified", () => {
+ test("no code is left without either a command or a written reason", () => {
+ const unclassified = doctorCodes().filter(
+ (code) => !DIAGNOSTIC_SIGNALS.has(code) && !DOCTOR_EXIT_EXCLUSIONS.has(code),
+ );
+ // Named, not counted: the failure message is the work to be done.
+ expect(unclassified.join("\n")).toBe("");
+ });
+
+ test("no code claims both a command and a reason it has none", () => {
+ const both = doctorCodes().filter(
+ (code) => DIAGNOSTIC_SIGNALS.has(code) && DOCTOR_EXIT_EXCLUSIONS.has(code),
+ );
+ expect(both.join("\n")).toBe("");
+ });
+
+ test("no exclusion outlives the code it explains", () => {
+ const codes = new Set(doctorCodes());
+ const orphans = [...DOCTOR_EXIT_EXCLUSIONS.keys()].filter((code) => !codes.has(code));
+ expect(orphans.toSorted().join("\n")).toBe("");
+ });
+
+ test("every reason is specific", () => {
+ for (const [code, reason] of DOCTOR_EXIT_EXCLUSIONS) {
+ expect(`${code} reason is specific: ${reason.trim().length >= MIN_REASON_LENGTH}`).toBe(
+ `${code} reason is specific: true`,
+ );
+ }
+ });
+
+ test("no reason names a command - a code with one belongs in the registry", () => {
+ const offenders = [...DOCTOR_EXIT_EXCLUSIONS.entries()]
+ .filter(([, reason]) => INVOCATION_RE.test(reason))
+ .map(([code]) => code);
+ expect(offenders.toSorted().join("\n")).toBe("");
+ });
+
+ test("the census is not vacuous", () => {
+ const codes = doctorCodes();
+ // A regex that stopped matching would sweep an empty set clean.
+ expect(codes.length).toBeGreaterThan(35);
+ expect(constantCodes().size).toBeGreaterThan(3);
+ expect(codes.filter((c) => DIAGNOSTIC_SIGNALS.has(c)).length).toBeGreaterThan(14);
+ expect(codes.filter((c) => DOCTOR_EXIT_EXCLUSIONS.has(c)).length).toBeGreaterThan(20);
+ });
+});
+
+describe("every code site is readable from the source", () => {
+ test("no `code:` value escapes both scans without a declared expansion", () => {
+ const opaque = codeSiteValues().filter((value) => {
+ if (value.startsWith('"')) return false;
+ if (CODE_IDENTIFIER_RE.test(value)) return false;
+ return NON_LITERAL_CODE_SITES[value] === undefined;
+ });
+ expect([...new Set(opaque)].toSorted().join("\n")).toBe("");
+ });
+
+ test("every `*_CODE` identifier used as a value was read by the constant scan", () => {
+ const constants = constantCodes();
+ const unresolved = codeSiteValues()
+ .filter((value) => CODE_IDENTIFIER_RE.test(value))
+ .filter((value) => {
+ const declared = DOCTOR_SOURCE.match(new RegExp(`^const ${value} = "([^"]+)";$`, "m"))?.[1];
+ return declared === undefined || !constants.has(declared);
+ });
+ expect([...new Set(unresolved)].toSorted().join("\n")).toBe("");
+ });
+
+ test("every declared site is still there, and says where its codes live", () => {
+ const values = new Set(codeSiteValues());
+ for (const [site, reason] of Object.entries(NON_LITERAL_CODE_SITES)) {
+ expect(`${site} is present: ${values.has(site)}`).toBe(`${site} is present: true`);
+ expect(`${site} reason is specific: ${reason.trim().length >= MIN_REASON_LENGTH}`).toBe(
+ `${site} reason is specific: true`,
+ );
+ }
+ });
+
+ test("the shape guard is not vacuous - it still sees the sites it allows", () => {
+ const values = codeSiteValues();
+ expect(values.filter((v) => v.startsWith('"')).length).toBeGreaterThan(30);
+ expect(values.filter((v) => CODE_IDENTIFIER_RE.test(v)).length).toBeGreaterThan(2);
+ });
+});
+
+describe("the classification is readable at runtime, not only by this test", () => {
+ test("an excluded code resolves to its reason and a registered one to none", () => {
+ expect(doctorExitReason("iso-invalid")).toBe(DOCTOR_EXIT_EXCLUSIONS.get("iso-invalid")!);
+ expect(doctorExitReason("config-missing")).toBeNull();
+ expect(doctorExitReason("not-a-doctor-code")).toBeNull();
+ });
+
+ test("reasons are collected once per code, in the order the codes were reported", () => {
+ const reasons = noExitReasons([
+ "config-missing",
+ "iso-invalid",
+ "symlink-escape",
+ "iso-invalid",
+ "not-a-doctor-code",
+ ]);
+ // A registered code contributes nothing; an unknown one invents nothing.
+ expect([...reasons.keys()]).toEqual(["iso-invalid", "symlink-escape"]);
+ });
+
+ test("an empty report produces an empty map, so the surfaces stay byte-identical", () => {
+ expect(noExitReasons([]).size).toBe(0);
+ expect(noExitReasons(["config-missing", "broken-wikilink"]).size).toBe(0);
+ });
+});
diff --git a/tests/core/brain/doctor-trust.test.ts b/tests/core/brain/doctor-trust.test.ts
index ecf65a2a..034d5d23 100644
--- a/tests/core/brain/doctor-trust.test.ts
+++ b/tests/core/brain/doctor-trust.test.ts
@@ -13,7 +13,7 @@ import { join } from "node:path";
import { runDoctor } from "../../../src/core/brain/doctor.ts";
import type { DreamRunSummary } from "../../../src/core/brain/dream.ts";
import { brainConfigPath, brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
let vault: string;
diff --git a/tests/core/brain/dream-checkpoints.test.ts b/tests/core/brain/dream-checkpoints.test.ts
new file mode 100644
index 00000000..82c739a2
--- /dev/null
+++ b/tests/core/brain/dream-checkpoints.test.ts
@@ -0,0 +1,295 @@
+/**
+ * Dream tells the truth about its own progress (no-dead-ends, Unit E).
+ *
+ * Three properties are pinned here:
+ *
+ * 1. The workrun journal never claims a phase complete whose durable
+ * output has not landed. A run interrupted mid-write leaves a last
+ * marker naming work that genuinely finished.
+ * 2. The safeguard checkpoint the `DreamOptions` docstring promises
+ * before finalize actually exists, so the log writes / ledger write /
+ * snapshot pruning / digest regeneration tail is no longer unguarded.
+ * 3. A per-run gate override applies for exactly one run and never
+ * touches the stored configuration.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { createHash } from "node:crypto";
+import { tmpdir } from "node:os";
+import { join, relative } from "node:path";
+
+import { dream } from "../../../src/core/brain/dream.ts";
+import { brainDirs, dreamRunsDir } from "../../../src/core/brain/paths.ts";
+import { SafeguardTimeoutError, type Safeguard } from "../../../src/core/brain/safeguard.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+const NOW = new Date("2026-05-23T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-ckpt-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-ckpt-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ // A test that locked a directory to inject a write failure restores the
+ // mode itself; belt-and-braces so a failed assertion cannot leave an
+ // unremovable tree behind.
+ const prefs = brainDirs(vault).preferences;
+ if (existsSync(prefs)) chmodSync(prefs, 0o700);
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Three same-sign signals on one topic: enough to plan a promotion. */
+function seedPromotion(target: string = vault, topic = "ckpt-topic"): void {
+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {
+ writeSignal(target, {
+ topic,
+ signal: "positive",
+ agent: "claude",
+ principle: `Prefer the ${topic} approach`,
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug: `${topic}-${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+function workrunPhases(): string[] {
+ const dir = dreamRunsDir(vault);
+ if (!existsSync(dir)) return [];
+ const files = readdirSync(dir).filter((n) => n.endsWith(".jsonl"));
+ if (files.length === 0) return [];
+ return readFileSync(join(dir, files[0]!), "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0)
+ .map((l) => (JSON.parse(l) as { phase: string }).phase);
+}
+
+/**
+ * Counting safeguard. `tripAt` is the 1-based index of the checkpoint
+ * that throws; `null` never trips. Distinct from the shared
+ * `createSafeguard` helper because these tests care about WHICH
+ * checkpoint fires, not about a wall clock.
+ */
+function countingGuard(tripAt: number | null): { guard: Safeguard; calls: () => number } {
+ let calls = 0;
+ const guard: Safeguard = Object.freeze({
+ operation: "dream",
+ timeoutMs: null,
+ checkpoint: (): void => {
+ calls += 1;
+ if (tripAt !== null && calls === tripAt) throw new SafeguardTimeoutError("dream", 1);
+ },
+ });
+ return { guard, calls: () => calls };
+}
+
+/**
+ * Excluded from the byte-comparison digest: the snapshot archive and the
+ * workrun journal carry wall-clock stamps, and the two bootstrap identity
+ * artifacts embed the vault's own path / generated id. None of the four is
+ * dream output; everything else in the tree is compared byte for byte.
+ */
+const DIGEST_EXCLUSIONS: ReadonlyArray<string> = Object.freeze([
+ join("Brain", ".snapshots"),
+ join("Brain", "log", "dream-runs"),
+ join("Brain", "_BRAIN.md"),
+ join("Brain", "vault-id.json"),
+]);
+
+/** Recursive `<relative path>:<sha256>` digest of a tree, sorted. */
+function treeDigest(root: string): string {
+ const lines: string[] = [];
+ const walk = (dir: string): void => {
+ for (const name of readdirSync(dir).toSorted()) {
+ const full = join(dir, name);
+ const rel = relative(root, full);
+ if (DIGEST_EXCLUSIONS.some((v) => rel === v || rel.startsWith(`${v}/`))) continue;
+ if (statSync(full).isDirectory()) walk(full);
+ else lines.push(`${rel}:${createHash("sha256").update(readFileSync(full)).digest("hex")}`);
+ }
+ };
+ walk(root);
+ return lines.join("\n");
+}
+
+/** Drop the two absolute-path fields so two vaults compare structurally. */
+function withoutVaultPaths(summary: object): Record<string, unknown> {
+ const { snapshot_path: _snapshot, log_path: _log, ...rest } = summary as Record<string, unknown>;
+ return rest;
+}
+
+/** A linkable page plus a page mentioning it: the heal-enrichment fixture. */
+function makeNotes(target: string = vault): { refPath: string } {
+ const notes = join(target, "Notes");
+ mkdirSync(notes, { recursive: true });
+ writeFileSync(join(notes, "Acme.md"), "---\ntitle: Acme\n---\nThe Acme page.\n", "utf8");
+ const refPath = join(notes, "ref.md");
+ writeFileSync(refPath, "---\ntitle: Ref\n---\nwe rely on Acme daily\n", "utf8");
+ return { refPath };
+}
+
+// ----- 1. Truthful workrun checkpoints -------------------------------------
+
+describe("dream workrun checkpoints are truthful", () => {
+ test("a run interrupted mid-write claims only work that genuinely completed", () => {
+ seedPromotion();
+ const prefs = brainDirs(vault).preferences;
+ // Inject the failure between close and synthesize: the preferences
+ // directory is read-only, so the first preference write throws and the
+ // run dies with the mutation loops half-run.
+ chmodSync(prefs, 0o555);
+ try {
+ expect(() => dream(vault, { now: NOW })).toThrow();
+ } finally {
+ chmodSync(prefs, 0o700);
+ }
+
+ const phases = workrunPhases();
+ // Only the phases whose durable output was already on disk may appear.
+ expect(phases).toEqual(["started", "cluster_complete", "close_complete"]);
+ // Every marker for work that never ran must be absent - most sharply
+ // `reconcile_complete`, whose audit events are written in the log phase
+ // this run never reached.
+ for (const absent of [
+ "reconcile_complete",
+ "promote_complete",
+ "synthesize_complete",
+ "retire_complete",
+ "heal_complete",
+ "finalized",
+ ]) {
+ expect(phases).not.toContain(absent);
+ }
+ });
+
+ test("a complete run records every phase, reconcile after its audit events", () => {
+ seedPromotion();
+ dream(vault, { now: NOW });
+ expect(workrunPhases()).toEqual([
+ "started",
+ "cluster_complete",
+ "close_complete",
+ "promote_complete",
+ "synthesize_complete",
+ "retire_complete",
+ "heal_complete",
+ "reconcile_complete",
+ "finalized",
+ ]);
+ });
+});
+
+// ----- 2. The pre-finalize safeguard checkpoint -----------------------------
+
+describe("dream safeguard checkpoints", () => {
+ test("a changed run checkpoints five times, the last before finalize", () => {
+ seedPromotion();
+ const { guard, calls } = countingGuard(null);
+ dream(vault, { now: NOW, safeguard: guard });
+ expect(calls()).toBe(5);
+ });
+
+ test("the pre-finalize checkpoint fires and leaves the workrun dangling", () => {
+ seedPromotion();
+ const { guard } = countingGuard(5);
+ expect(() => dream(vault, { now: NOW, safeguard: guard })).toThrow(SafeguardTimeoutError);
+ const phases = workrunPhases();
+ // The tail is covered: every mutation landed, the journal recorded it,
+ // and the run stopped before claiming a clean finish.
+ expect(phases).toContain("heal_complete");
+ expect(phases).not.toContain("finalized");
+ expect(existsSync(join(brainDirs(vault).preferences, "pref-ckpt-topic.md"))).toBe(true);
+ });
+
+ test("a no-op run checkpoints once, at entry", () => {
+ const { guard, calls } = countingGuard(null);
+ const summary = dream(vault, { now: NOW, safeguard: guard });
+ expect(summary.changed).toBe(false);
+ expect(calls()).toBe(1);
+ });
+});
+
+// ----- 3. Per-run gate override --------------------------------------------
+
+describe("dream per-run gate override", () => {
+ test("heal_enrich overrides a disabled config gate for one run only", () => {
+ const { refPath } = makeNotes();
+ seedPromotion();
+ const cfgPath = join(vault, "Brain", "_brain.yaml");
+ const cfgBefore = readFileSync(cfgPath);
+
+ dream(vault, { now: NOW, gates: { heal_enrich: true } });
+
+ expect(readFileSync(refPath, "utf8")).toContain("[[Acme]]");
+ // The stored configuration is byte-identical: the override never
+ // persists, so nothing has to be remembered and reverted.
+ expect(readFileSync(cfgPath)).toEqual(cfgBefore);
+ });
+
+ test("heal_enrich: false overrides an enabled config gate", () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\ndream:\n heal_enrich_enabled: true\n",
+ "utf8",
+ );
+ const { refPath } = makeNotes();
+ seedPromotion();
+ const before = readFileSync(refPath, "utf8");
+
+ const summary = dream(vault, { now: NOW, gates: { heal_enrich: false } });
+
+ expect(summary.changed).toBe(true);
+ expect(readFileSync(refPath, "utf8")).toBe(before);
+ expect(summary.phases.find((p) => p.phase === "heal")?.metrics["enriched"]).toBe(0);
+ });
+
+ test("an omitted override leaves the run byte-identical to the config path", () => {
+ const { refPath } = makeNotes();
+ seedPromotion();
+ const summary = dream(vault, { now: NOW });
+ const digest = treeDigest(vault);
+ const untouched = readFileSync(refPath, "utf8");
+
+ // A second, identically seeded vault run with the override set to the
+ // value the config already resolves to: identical tree, identical
+ // summary bar the vault-dependent paths.
+ const twin = mkdtempSync(join(tmpdir(), "o2b-dream-ckpt-twin-"));
+ const twinConfig = join(configHome, "twin.yaml");
+ try {
+ atomicWriteFileSync(twinConfig, `vault: ${twin}\n`);
+ bootstrapBrain(twin, { configPath: twinConfig });
+ const { refPath: twinRef } = makeNotes(twin);
+ seedPromotion(twin);
+ const twinSummary = dream(twin, { now: NOW, gates: { heal_enrich: false } });
+
+ expect(treeDigest(twin)).toBe(digest);
+ expect(withoutVaultPaths(twinSummary)).toEqual(withoutVaultPaths(summary));
+ expect(readFileSync(twinRef, "utf8")).toBe(untouched);
+ } finally {
+ rmSync(twin, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/tests/core/brain/dream-phase-refusal.test.ts b/tests/core/brain/dream-phase-refusal.test.ts
new file mode 100644
index 00000000..027553d9
--- /dev/null
+++ b/tests/core/brain/dream-phase-refusal.test.ts
@@ -0,0 +1,223 @@
+/**
+ * A phase request that cannot be honoured is refused by name
+ * (no-dead-ends, Unit E).
+ *
+ * The five `DREAM_PHASE` labels are a reporting layer, not callable units,
+ * and two of the planning steps behind them mutate each other's
+ * accumulators specifically so a preference is never both refreshed and
+ * retired. Asking for one of those alone must raise a named error that says
+ * which steps ARE independently runnable and why the requested one is not -
+ * never a partial run, never a full-looking result whose fields are empty
+ * because the work did not happen.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { createHash } from "node:crypto";
+import { tmpdir } from "node:os";
+import { join, relative } from "node:path";
+
+import { DREAM_PHASE } from "../../../src/core/brain/dream-phases.ts";
+import {
+ DREAM_STEP,
+ DREAM_STEP_RUNNABLE,
+ DreamStepNotRunnableError,
+ runDreamStep,
+} from "../../../src/core/brain/dream-step.ts";
+import { brainDirs, dreamRunsDir } from "../../../src/core/brain/paths.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-step-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-step-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Three same-sign signals: enough that a full pass would promote them. */
+function seedPromotion(): void {
+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {
+ writeSignal(vault, {
+ topic: "step-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Prefer the stepped approach",
+ created_at: `${date}T10:00:00Z`,
+ date,
+ slug: `step-${i}`,
+ scope: "writing",
+ });
+ }
+}
+
+/** Recursive `<relative path>:<sha256>` digest of a tree, sorted. */
+function treeDigest(root: string): string {
+ const lines: string[] = [];
+ const walk = (dir: string): void => {
+ for (const name of readdirSync(dir).toSorted()) {
+ const full = join(dir, name);
+ if (statSync(full).isDirectory()) walk(full);
+ else
+ lines.push(
+ `${relative(root, full)}:${createHash("sha256").update(readFileSync(full)).digest("hex")}`,
+ );
+ }
+ };
+ walk(root);
+ return lines.join("\n");
+}
+
+function makeNotes(): { refPath: string } {
+ const notes = join(vault, "Notes");
+ mkdirSync(notes, { recursive: true });
+ writeFileSync(join(notes, "Acme.md"), "---\ntitle: Acme\n---\nThe Acme page.\n", "utf8");
+ const refPath = join(notes, "ref.md");
+ writeFileSync(refPath, "---\ntitle: Ref\n---\nwe rely on Acme daily\n", "utf8");
+ return { refPath };
+}
+
+// ----- The refusal ---------------------------------------------------------
+
+describe("runDreamStep refuses what it cannot honour", () => {
+ test("the coupled synthesize label is refused, by name, and writes nothing", () => {
+ seedPromotion();
+ const before = treeDigest(vault);
+
+ expect(() => runDreamStep(vault, DREAM_PHASE.synthesize)).toThrow(DreamStepNotRunnableError);
+
+ let caught: DreamStepNotRunnableError | undefined;
+ try {
+ runDreamStep(vault, DREAM_PHASE.synthesize);
+ } catch (err) {
+ caught = err as DreamStepNotRunnableError;
+ }
+ expect(caught?.requested).toBe(DREAM_PHASE.synthesize);
+ expect(caught?.runnable).toEqual([...DREAM_STEP_RUNNABLE]);
+ // Names the coupling itself, not a generic "unsupported phase".
+ expect(caught?.message).toContain("planRefresh");
+ expect(caught?.message).toContain("planAutoRetires");
+ expect(caught?.message).toContain("refresh.updated");
+ expect(caught?.message).toContain("plan.retires");
+ // And it names the way out.
+ for (const step of DREAM_STEP_RUNNABLE) expect(caught?.message).toContain(step);
+
+ expect(treeDigest(vault)).toBe(before);
+ expect(existsSync(dreamRunsDir(vault))).toBe(false);
+ expect(readdirSync(brainDirs(vault).preferences)).toEqual([]);
+ });
+
+ test("the heal label is refused for the same coupling and points at heal-enrich", () => {
+ seedPromotion();
+ const before = treeDigest(vault);
+
+ let caught: DreamStepNotRunnableError | undefined;
+ try {
+ runDreamStep(vault, DREAM_PHASE.heal);
+ } catch (err) {
+ caught = err as DreamStepNotRunnableError;
+ }
+ expect(caught).toBeInstanceOf(DreamStepNotRunnableError);
+ expect(caught?.message).toContain("planAutoRetires");
+ expect(caught?.message).toContain(DREAM_STEP.healEnrich);
+ expect(treeDigest(vault)).toBe(before);
+ });
+
+ test("every remaining phase label is refused with its own specific reason", () => {
+ const reasons = new Map<string, string>();
+ for (const phase of [DREAM_PHASE.close, DREAM_PHASE.reconcile, DREAM_PHASE.log]) {
+ let caught: DreamStepNotRunnableError | undefined;
+ try {
+ runDreamStep(vault, phase);
+ } catch (err) {
+ caught = err as DreamStepNotRunnableError;
+ }
+ expect(caught).toBeInstanceOf(DreamStepNotRunnableError);
+ expect(caught?.requested).toBe(phase);
+ reasons.set(phase, caught!.reason);
+ }
+ // No two labels share a reason: each refusal explains that label.
+ expect(new Set(reasons.values()).size).toBe(reasons.size);
+ expect(reasons.get(DREAM_PHASE.close)).toContain(DREAM_STEP.scan);
+ });
+
+ test("an unknown step name is refused rather than silently ignored", () => {
+ let caught: DreamStepNotRunnableError | undefined;
+ try {
+ runDreamStep(vault, "not-a-phase");
+ } catch (err) {
+ caught = err as DreamStepNotRunnableError;
+ }
+ expect(caught).toBeInstanceOf(DreamStepNotRunnableError);
+ expect(caught?.requested).toBe("not-a-phase");
+ expect(caught?.runnable).toEqual([...DREAM_STEP_RUNNABLE]);
+ });
+});
+
+// ----- The honoured steps --------------------------------------------------
+
+describe("runDreamStep performs exactly the step requested", () => {
+ test("scan reports the tree and mutates nothing", () => {
+ seedPromotion();
+ const before = treeDigest(vault);
+
+ const result = runDreamStep(vault, DREAM_STEP.scan);
+
+ expect(result).toEqual({
+ step: DREAM_STEP.scan,
+ partial: true,
+ active_signals: 3,
+ processed_signals: 0,
+ preferences: 0,
+ retired: 0,
+ corrupted: [],
+ });
+ // Nothing that a full pass would have done has happened: no
+ // preference, no signal move, no log, no workrun.
+ expect(treeDigest(vault)).toBe(before);
+ expect(existsSync(dreamRunsDir(vault))).toBe(false);
+ });
+
+ test("scan surfaces corrupted entries as paths rather than swallowing them", () => {
+ writeFileSync(join(brainDirs(vault).inbox, "sig-broken.md"), "not frontmatter\n", "utf8");
+
+ const result = runDreamStep(vault, DREAM_STEP.scan);
+
+ expect(result.step).toBe(DREAM_STEP.scan);
+ expect(result).toMatchObject({ corrupted: ["Brain/inbox/sig-broken.md"] });
+ });
+
+ test("heal-enrich enriches user pages and does nothing else", () => {
+ const { refPath } = makeNotes();
+ seedPromotion();
+
+ const result = runDreamStep(vault, DREAM_STEP.healEnrich);
+
+ expect(result).toMatchObject({ step: DREAM_STEP.healEnrich, partial: true, enriched: 1 });
+ expect(readFileSync(refPath, "utf8")).toContain("[[Acme]]");
+ // The promotion the full pass would have made did not happen.
+ expect(readdirSync(brainDirs(vault).preferences)).toEqual([]);
+ expect(readdirSync(brainDirs(vault).inbox).filter((n) => n.endsWith(".md"))).toHaveLength(3);
+ expect(existsSync(dreamRunsDir(vault))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/force-confirmed-cold-start.test.ts b/tests/core/brain/force-confirmed-cold-start.test.ts
new file mode 100644
index 00000000..aed3625a
--- /dev/null
+++ b/tests/core/brain/force-confirmed-cold-start.test.ts
@@ -0,0 +1,264 @@
+/**
+ * Issue #149 - the force-confirmed cold start (no-dead-ends, task 22).
+ *
+ * The report said a `force_confirmed` preference is stuck at 0.00
+ * confidence in a deadlock, and proposed two fixes. Reconnaissance found
+ * the report partially right with its load-bearing half wrong: there is
+ * no division by zero (`confidence.ts` guards `n > 0`), and the
+ * de-prioritization it describes does not exist on `active.md`, which
+ * filters on confirmed status with no cutoff and sorts by BAND, not
+ * value - both proposed values land in the same band, so neither would
+ * move the preference one position in the injected context.
+ *
+ * The real defect the report missed is one line away from the one it
+ * found: the value is written as `null`, not `0`, and `null` ranks WORSE
+ * than `0`. Two surfaces map an absent value to negative infinity and
+ * then sort and slice, so a brand-new confirmed rule sorts below every
+ * rule that has a number - including one whose measured confidence is
+ * zero. The dream pass already pre-seeds new preferences with an
+ * explicit `0` for exactly this reason; the two force-confirm writers
+ * did not.
+ *
+ * This file pins the fix and both refusals:
+ *
+ * - both writers emit an explicit `0`;
+ * - both ranking surfaces put it ABOVE a valueless entry;
+ * - the existing `low-evidence-confirmed` detector names recording
+ * real evidence as the exit;
+ * - and NO apply-evidence row is written, because forging one would
+ * assert a rule was exercised against work that never happened.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../../src/mcp/index.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { buildMorningBrief } from "../../../src/core/brain/morning-brief.ts";
+import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import { listLogDates, readLogDay } from "../../../src/core/brain/log-jsonl.ts";
+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";
+import { runCli } from "../../helpers/run-cli.ts";
+
+const LOW_EVIDENCE_CODE = "low-evidence-confirmed";
+
+let tmp: string;
+let vault: string;
+let config: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cold-start-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ writeFileSync(config, `vault: ${vault}\nagent_name: test-agent\n`);
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = config;
+ resetVaultIdentityPins();
+ bootstrapBrain(vault, { configPath: config });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+function preferenceFile(slug: string): string {
+ return readFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), "utf8");
+}
+
+/** Every log event kind recorded anywhere in `Brain/log/`. */
+function loggedEventKinds(): ReadonlySet<string> {
+ const kinds = new Set<string>();
+ for (const date of listLogDates(vault)) {
+ for (const entry of readLogDay(vault, date).entries) kinds.add(entry.eventType);
+ }
+ return kinds;
+}
+
+async function callMcpFeedback(args: Record<string, unknown>): Promise<void> {
+ const server = new MCPServer({ vault, configPath: config });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "cold-start-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "brain_feedback", arguments: args },
+ });
+}
+
+describe("the value is written, not left absent", () => {
+ test("the CLI writer emits an explicit zero", async () => {
+ const r = await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "cli-cold",
+ "--signal",
+ "positive",
+ "--principle",
+ "prefer the explicit zero",
+ "--force-confirmed",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(preferenceFile("cli-cold")).toContain("_confidence_value: 0\n");
+ const pref = parsePreference(join(vault, "Brain", "preferences", "pref-cli-cold.md"));
+ expect(pref.confidence_value).toBe(0);
+ });
+
+ test("the MCP writer emits an explicit zero", async () => {
+ await callMcpFeedback({
+ topic: "mcp-cold",
+ signal: "positive",
+ principle: "prefer the explicit zero",
+ force_confirmed: true,
+ });
+ expect(preferenceFile("mcp-cold")).toContain("_confidence_value: 0\n");
+ const pref = parsePreference(join(vault, "Brain", "preferences", "pref-mcp-cold.md"));
+ expect(pref.confidence_value).toBe(0);
+ });
+
+ test("no apply-evidence row is forged for the rule that was never applied", async () => {
+ // Option A in the report writes one. That row is the canonical
+ // durable signal that a preference was exercised against real work:
+ // forging it corrupts the most-applied ranking, the recent-
+ // applications section and the outcome-regression ratio, and
+ // consumes one of the two events the low-evidence warning needs.
+ await callMcpFeedback({
+ topic: "mcp-cold",
+ signal: "positive",
+ principle: "prefer the explicit zero",
+ force_confirmed: true,
+ });
+ expect(loggedEventKinds().has(BRAIN_LOG_EVENT_KIND.applyEvidence)).toBe(false);
+ const pref = parsePreference(join(vault, "Brain", "preferences", "pref-mcp-cold.md"));
+ expect(pref.applied_count).toBe(0);
+ expect(pref.evidenced_by.some((link) => link.includes("sig-"))).toBe(true);
+ });
+});
+
+describe("zero outranks absent on both surfaces that rank on the number", () => {
+ /**
+ * Two confirmed rules identical but for the value: one carrying the
+ * explicit `0` a force-confirm now writes, one carrying `null` as a
+ * force-confirm used to. `null` reads back as negative infinity in
+ * both rankers, so the ordering is the whole assertion.
+ */
+ function seedPair(): void {
+ writePreference(vault, {
+ slug: "zero-valued",
+ topic: "zero-valued",
+ principle: "the rule a force-confirm writes today",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-01T00:00:00Z",
+ confirmed_at: "2026-01-01T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ confidence_value: 0,
+ });
+ writePreference(vault, {
+ slug: "value-absent",
+ topic: "value-absent",
+ principle: "the rule a force-confirm used to write",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-01T00:00:00Z",
+ confirmed_at: "2026-01-01T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ });
+ expect(
+ parsePreference(join(vault, "Brain", "preferences", "pref-value-absent.md")).confidence_value,
+ ).toBeNull();
+ }
+
+ test("the pre-compress pack ranks the zero above the absent value", () => {
+ seedPair();
+ const pack = buildPreCompressPack(vault, { topK: 5 });
+ const ids = pack.items.map((item) => item.id);
+ expect(ids.indexOf("pref-zero-valued")).toBeLessThan(ids.indexOf("pref-value-absent"));
+ expect(ids.indexOf("pref-zero-valued")).toBe(0);
+ });
+
+ test("the morning brief ranks the zero above the absent value", () => {
+ seedPair();
+ const brief = buildMorningBrief(vault, {
+ now: new Date("2026-02-01T00:00:00Z"),
+ topK: 5,
+ });
+ const ids = brief.preferences.map((p) => p.id);
+ expect(ids.indexOf("pref-zero-valued")).toBeLessThan(ids.indexOf("pref-value-absent"));
+ expect(ids.indexOf("pref-zero-valued")).toBe(0);
+ });
+});
+
+describe("the detector names the exit", () => {
+ /** A confirmed rule past its trial window with no real use. */
+ function seedColdRule(): void {
+ writePreference(vault, {
+ slug: "never-used",
+ topic: "never-used",
+ principle: "a rule confirmed long ago and never applied",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-01T00:00:00Z",
+ confirmed_at: "2026-01-01T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ confidence_value: 0,
+ });
+ }
+
+ test("the code resolves to the command that records real evidence", () => {
+ const signal = DIAGNOSTIC_SIGNALS.get(LOW_EVIDENCE_CODE);
+ expect(signal).toBeDefined();
+ expect(signal!.nextCommand.startsWith("o2b brain apply-evidence")).toBe(true);
+ expect(signal!.autoRepairable).toBe(false);
+ });
+
+ test("the doctor's human output names the command", async () => {
+ seedColdRule();
+ const r = await runCli(["brain", "doctor", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.stdout).toContain(`[WARN] ${LOW_EVIDENCE_CODE}:`);
+ expect(r.stdout).toContain(`next: ${DIAGNOSTIC_SIGNALS.get(LOW_EVIDENCE_CODE)!.nextCommand}\n`);
+ });
+
+ test("the doctor's JSON output carries the command as a field", async () => {
+ seedColdRule();
+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ const payload = JSON.parse(r.stdout) as {
+ warnings: ReadonlyArray<{ code: string; next_command?: string }>;
+ };
+ const hit = payload.warnings.find((w) => w.code === LOW_EVIDENCE_CODE);
+ expect(hit?.next_command).toBe(DIAGNOSTIC_SIGNALS.get(LOW_EVIDENCE_CODE)!.nextCommand);
+ });
+});
diff --git a/tests/core/brain/lineage-continuation.test.ts b/tests/core/brain/lineage-continuation.test.ts
index c3393547..f377357c 100644
--- a/tests/core/brain/lineage-continuation.test.ts
+++ b/tests/core/brain/lineage-continuation.test.ts
@@ -183,7 +183,20 @@ describe("readGitWorkspaceIdentity — hardened, bounded probe", () => {
test("the probe is bounded: an exhausted budget yields no identity, never a hang", () => {
const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
- expect(readGitWorkspaceIdentity(repo, { timeoutMs: 1 })).toBeNull();
+ // An exhausted budget is stated, not approximated. This assertion
+ // previously passed `1`, which leaves the first invocation a whole
+ // millisecond of budget and so asserted only that this machine's git
+ // is slower than that - true on a loaded developer box, false on a
+ // fast runner, and a claim about hardware either way.
+ expect(readGitWorkspaceIdentity(repo, { timeoutMs: 0 })).toBeNull();
+ expect(readGitWorkspaceIdentity(repo, { timeoutMs: -1 })).toBeNull();
+ });
+
+ test("a budget that is not a number is a caller bug, and is named", () => {
+ const repo = initRepo(join(tmp, "nan-budget"), { remote: SECRET_REMOTE });
+ // Silently substituting the default would hand back a two-second
+ // probe to a caller who believes it asked for something else.
+ expect(() => readGitWorkspaceIdentity(repo, { timeoutMs: Number.NaN })).toThrow(/timeoutMs/);
});
});
diff --git a/tests/core/brain/lint-read-path.test.ts b/tests/core/brain/lint-read-path.test.ts
new file mode 100644
index 00000000..b7c6dfbd
--- /dev/null
+++ b/tests/core/brain/lint-read-path.test.ts
@@ -0,0 +1,127 @@
+/**
+ * A read-only verb must not fail with a write-path error
+ * (no-dead-ends, task 10).
+ *
+ * `lintConsolidate` asserted vault identity unconditionally, at its entry
+ * and ahead of its `apply` branch. The read-only `o2b brain actions`
+ * ranking verb calls it in report mode, so a root the write guard refuses
+ * took down a command that never intended to write a byte - which is the
+ * guard's own contract inverted, since it exists to gate writes.
+ *
+ * The assertion now follows the one rule the appliers share: at the entry
+ * point, before any other work, and only when the call will write.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { lintConsolidate } from "../../../src/core/brain/lint-consolidate.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import {
+ VaultIdentityMismatchError,
+ assertVaultIdentityForWrite,
+ resetVaultIdentityPins,
+ vaultIdentityPath,
+ writeVaultIdentity,
+} from "../../../src/core/brain/vault-identity.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { runCli } from "../../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-lint-read-path-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function frontmatter(id: string, extra = ""): string {
+ return `---\nid: ${id}\ntopic: t\nprinciple: p\n${extra}---\n\nbody\n`;
+}
+
+/** A page whose merged_into pointer gives the lint something to report. */
+function seedMergedPair(): string {
+ const prefs = brainDirs(vault).preferences;
+ writeFileSync(join(prefs, "pref-canon.md"), frontmatter("pref-canon"));
+ writeFileSync(join(prefs, "pref-dup.md"), frontmatter("pref-dup", "merged_into: pref-canon\n"));
+ const log = join(brainDirs(vault).log, "2026-05-25.md");
+ writeFileSync(log, "saw [[pref-dup]] today\n");
+ return log;
+}
+
+/**
+ * Put the resolved root into the ONE state the guard refuses: a marker
+ * this process already pinned, replaced by a different one.
+ */
+function makeVaultIdentityMismatch(): void {
+ writeVaultIdentity(vault);
+ assertVaultIdentityForWrite(vault);
+ atomicWriteFileSync(
+ vaultIdentityPath(vault),
+ `${JSON.stringify(
+ { schema_version: 1, vault_id: "e".repeat(32), created_at: "2026-01-01T00:00:00.000Z" },
+ null,
+ 2,
+ )}\n`,
+ );
+}
+
+describe("lintConsolidate in report mode is a pure read", () => {
+ test("a root the write guard refuses still returns its report", () => {
+ const log = seedMergedPair();
+ const before = readFileSync(log, "utf8");
+ makeVaultIdentityMismatch();
+
+ const report = lintConsolidate(vault, { apply: false });
+
+ expect(report.applied).toBe(false);
+ expect(report.fixes).toHaveLength(1);
+ expect(report.fixes[0]!.from).toBe("pref-dup");
+ expect(report.filesWritten).toBe(0);
+ expect(readFileSync(log, "utf8")).toBe(before);
+ });
+
+ test("apply mode against the same root still refuses", () => {
+ const log = seedMergedPair();
+ const before = readFileSync(log, "utf8");
+ makeVaultIdentityMismatch();
+
+ expect(() => lintConsolidate(vault, { apply: true })).toThrow(VaultIdentityMismatchError);
+ // The refusal lands before the first byte, which is the placement rule.
+ expect(readFileSync(log, "utf8")).toBe(before);
+ });
+
+ test("apply mode on a healthy root writes, so the guard did not become a no-op", () => {
+ const log = seedMergedPair();
+ const report = lintConsolidate(vault, { apply: true });
+ expect(report.filesWritten).toBeGreaterThan(0);
+ expect(readFileSync(log, "utf8")).toContain("[[pref-canon]]");
+ });
+});
+
+describe("o2b brain actions - the verb the defect took down", () => {
+ test("the read-only ranking verb succeeds on a root the write guard refuses", async () => {
+ seedMergedPair();
+ makeVaultIdentityMismatch();
+
+ const result = await runCli(["brain", "actions", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+
+ expect(result.returncode).toBe(0);
+ expect(() => JSON.parse(result.stdout) as unknown).not.toThrow();
+ });
+});
diff --git a/tests/core/brain/next-step.test.ts b/tests/core/brain/next-step.test.ts
new file mode 100644
index 00000000..93da22ed
--- /dev/null
+++ b/tests/core/brain/next-step.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Tests for src/core/brain/next-step.ts - strict next-step resolution over
+ * the existing {@link DIAGNOSTIC_SIGNALS} registry (no-dead-ends, task 1).
+ *
+ * Three obligations are pinned here. First, every registered code resolves
+ * and an unregistered one returns the explicit absent result rather than a
+ * fabricated command. Second, the registry contains commands and not prose -
+ * the guard test below is what stops an English sentence entering the
+ * next-step surface through the registry door. Third, the lenient
+ * {@link resolveSignal} keeps its two existing consumers working exactly as
+ * before, so the strict lookup is additive.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { DIAGNOSTIC_SIGNALS, resolveSignal } from "../../../src/core/brain/diagnostics.ts";
+import { resolveNextStep } from "../../../src/core/brain/next-step.ts";
+
+/** A code no registry entry uses, and none plausibly will. */
+const UNREGISTERED_CODE = "no-such-diagnostic-code";
+
+/**
+ * Structural shape of a next command, derived from the CLI grammar rather
+ * than from any word list: the binary name, one to three bare verb words,
+ * then only long flags (`--name`, `--name=value`) and `<placeholder>`
+ * arguments. A sentence fails this because its trailing words are neither
+ * flags nor placeholders, and because a verb path is at most three words.
+ */
+const STRUCTURAL_COMMAND_RE =
+ /^o2b(?: [a-z][a-z0-9-]*){1,3}(?: (?:--[a-z][a-z0-9-]*(?:=\S+)?|<[a-z][a-z0-9-]*>))*$/;
+
+/** Characters that end or join sentences; none belongs in a command line. */
+const SENTENCE_PUNCTUATION_RE = /[.!?;,:]/;
+
+describe("resolveNextStep", () => {
+ test("every registered code resolves to its registered command", () => {
+ expect(DIAGNOSTIC_SIGNALS.size).toBeGreaterThan(0);
+ for (const [code, signal] of DIAGNOSTIC_SIGNALS) {
+ const step = resolveNextStep(code);
+ expect(step).not.toBeNull();
+ expect(step).toEqual({
+ code: signal.code,
+ issueClass: signal.issueClass,
+ nextCommand: signal.nextCommand,
+ });
+ }
+ });
+
+ test("an unregistered code returns the absent result and does not throw", () => {
+ expect(() => resolveNextStep(UNREGISTERED_CODE)).not.toThrow();
+ expect(resolveNextStep(UNREGISTERED_CODE)).toBeNull();
+ });
+
+ test("the empty code is absent, never a fabricated generic", () => {
+ expect(resolveNextStep("")).toBeNull();
+ });
+});
+
+describe("registry prose guard", () => {
+ test("every registered nextCommand is a structural command line", () => {
+ for (const [code, signal] of DIAGNOSTIC_SIGNALS) {
+ const command = signal.nextCommand;
+ expect(`${code}: ${command}`).toBe(`${code}: ${command.trim()}`);
+ expect(`${code}: ${command}`).not.toContain("\n");
+ expect(`${code}: ${command}`).not.toContain(" ");
+ expect(`${code}: ${SENTENCE_PUNCTUATION_RE.test(command)}`).toBe(`${code}: false`);
+ expect(`${code}: ${STRUCTURAL_COMMAND_RE.test(command)}`).toBe(`${code}: true`);
+ }
+ });
+
+ test("the guard rejects prose that a naive check would accept", () => {
+ const prose = [
+ "Run o2b brain doctor to repair this.",
+ "o2b brain doctor to see the remaining issues",
+ "o2b brain doctor; then o2b brain health",
+ "o2b brain doctor, then retry",
+ "o2b brain doctor\no2b brain health",
+ "see the docs",
+ "",
+ ];
+ for (const line of prose) {
+ const structural = STRUCTURAL_COMMAND_RE.test(line) && !SENTENCE_PUNCTUATION_RE.test(line);
+ expect(`${line}: ${structural}`).toBe(`${line}: false`);
+ }
+ });
+});
+
+describe("resolveSignal (lenient, unchanged)", () => {
+ test("a registered code resolves to the frozen registry entry", () => {
+ const signal = resolveSignal("config-missing");
+ expect(signal).toBe(DIAGNOSTIC_SIGNALS.get("config-missing")!);
+ });
+
+ test("an unregistered code still yields the fabricated generic hint", () => {
+ expect(resolveSignal(UNREGISTERED_CODE)).toEqual({
+ code: UNREGISTERED_CODE,
+ issueClass: UNREGISTERED_CODE,
+ nextCommand: "o2b brain doctor",
+ autoRepairable: false,
+ });
+ });
+
+ test("the strict lookup and the lenient one disagree exactly on absence", () => {
+ expect(resolveNextStep(UNREGISTERED_CODE)).toBeNull();
+ expect(resolveSignal(UNREGISTERED_CODE).nextCommand).not.toBe("");
+ });
+});
diff --git a/tests/core/brain/note-title-resolver.test.ts b/tests/core/brain/note-title-resolver.test.ts
index 8bd96730..f7f0e56a 100644
--- a/tests/core/brain/note-title-resolver.test.ts
+++ b/tests/core/brain/note-title-resolver.test.ts
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import {
NoteTitleResolutionError,
diff --git a/tests/core/brain/note-walk.test.ts b/tests/core/brain/note-walk.test.ts
index 68a4f48c..f18902b0 100644
--- a/tests/core/brain/note-walk.test.ts
+++ b/tests/core/brain/note-walk.test.ts
@@ -13,7 +13,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import {
buildNoteWalkRules,
diff --git a/tests/core/brain/open-loops.test.ts b/tests/core/brain/open-loops.test.ts
index bf60c2f5..a245b631 100644
--- a/tests/core/brain/open-loops.test.ts
+++ b/tests/core/brain/open-loops.test.ts
@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { scanOpenLoops } from "../../../src/core/brain/open-loops.ts";
diff --git a/tests/core/brain/pending-dry-run.test.ts b/tests/core/brain/pending-dry-run.test.ts
new file mode 100644
index 00000000..668e7853
--- /dev/null
+++ b/tests/core/brain/pending-dry-run.test.ts
@@ -0,0 +1,129 @@
+/**
+ * The approval queue gets its preview (no-dead-ends, task 11).
+ *
+ * `applyPending` was the only applier in the codebase with no dry run:
+ * an operator reviewing the write-approval queue could see what was
+ * staged and could apply it, but had no way to be told what applying
+ * would do before it happened.
+ *
+ * "Writes nothing" is asserted by digesting the whole vault tree before
+ * and after, not by spot-checking the two files the move touches - the
+ * defect a preview must not have is a write somewhere the author did not
+ * think to look.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import {
+ PendingApplyConflictError,
+ PendingSignalNotFoundError,
+ applyPending,
+ listPending,
+ stagePendingSignal,
+} from "../../../src/core/brain/pending.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+import { digestVaultTree } from "../../helpers/vault-digest.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+const NOW = new Date("2026-07-18T12:00:00Z");
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-pending-dry-run-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function stageOne(topic: string): string {
+ return stagePendingSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "test-agent",
+ principle: `principle for ${topic}`,
+ created_at: NOW.toISOString(),
+ date: NOW.toISOString().slice(0, "YYYY-MM-DD".length),
+ slug: topic,
+ }).id;
+}
+
+describe("applyPending dry run", () => {
+ test("reports exactly what an apply would move", () => {
+ const id = stageOne("preview-me");
+
+ const preview = applyPending(vault, id, { dryRun: true });
+ expect(preview.dryRun).toBe(true);
+ expect(preview.id).toBe(id);
+ expect(preview.path).toBe(join(brainDirs(vault).inbox, `${id}.md`));
+
+ const real = applyPending(vault, id);
+ expect(real.dryRun).toBe(false);
+ // Identical report: the preview named the same id and the same
+ // destination the apply actually used.
+ expect({ id: real.id, path: real.path }).toEqual({ id: preview.id, path: preview.path });
+ });
+
+ test("leaves the vault tree byte-identical", () => {
+ const id = stageOne("untouched");
+ const before = digestVaultTree(vault);
+
+ applyPending(vault, id, { dryRun: true });
+
+ expect(digestVaultTree(vault)).toBe(before);
+ // And the queue still holds it, so the preview did not consume it.
+ expect(listPending(vault).map((entry) => entry.id)).toEqual([id]);
+ });
+
+ test("a missing id is refused by the preview exactly as by the apply", () => {
+ expect(() => applyPending(vault, "sig-2026-07-18-nope", { dryRun: true })).toThrow(
+ PendingSignalNotFoundError,
+ );
+ });
+
+ test("a destination that already exists is refused before either path writes", () => {
+ const id = stageOne("collide");
+ applyPending(vault, id);
+ // Re-stage the same id so a second apply would target an occupied inbox slot.
+ stageOne("collide");
+ const before = digestVaultTree(vault);
+
+ expect(() => applyPending(vault, id, { dryRun: true })).toThrow(PendingApplyConflictError);
+ expect(() => applyPending(vault, id)).toThrow(PendingApplyConflictError);
+ expect(digestVaultTree(vault)).toBe(before);
+ });
+});
+
+describe("applyPending apply behaviour is unchanged", () => {
+ test("the staged bytes land in the inbox verbatim and the staged copy goes", () => {
+ const id = stageOne("moved");
+ const staged = join(brainDirs(vault).pending, `${id}.md`);
+ const contents = readFileSync(staged, "utf8");
+
+ const result = applyPending(vault, id);
+
+ expect(existsSync(staged)).toBe(false);
+ expect(readFileSync(result.path, "utf8")).toBe(contents);
+ expect(listPending(vault)).toEqual([]);
+ });
+
+ test("omitting the option is the same call it always was", () => {
+ const id = stageOne("default-arg");
+ const result = applyPending(vault, id);
+ expect(result.path).toBe(join(brainDirs(vault).inbox, `${id}.md`));
+ });
+});
diff --git a/tests/core/brain/portability/profiles.test.ts b/tests/core/brain/portability/profiles.test.ts
index 056217eb..ee957e73 100644
--- a/tests/core/brain/portability/profiles.test.ts
+++ b/tests/core/brain/portability/profiles.test.ts
@@ -9,9 +9,11 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
+
+import lockfile from "proper-lockfile";
import {
createProfile,
@@ -39,10 +41,17 @@ afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
+/** A real directory under the temp home, since create validates the target. */
+function vaultDir(name: string): string {
+ const path = join(home, name);
+ mkdirSync(path, { recursive: true });
+ return path;
+}
+
describe("profile registry", () => {
test("create + list", () => {
- createProfile(configPath, "work", "/srv/vaults/work");
- createProfile(configPath, "personal", "/srv/vaults/personal");
+ createProfile(configPath, "work", vaultDir("work"));
+ createProfile(configPath, "personal", vaultDir("personal"));
const { profiles, active } = listProfiles(configPath);
expect(profiles.map((p) => p.name).toSorted()).toEqual(["personal", "work"]);
expect(active).toBeNull();
@@ -61,18 +70,104 @@ describe("profile registry", () => {
expect(() => switchProfile(configPath, "ghost")).toThrow();
});
- test("switching to a profile whose vault is not a directory fails at switch time", () => {
+ test("switching to a profile whose vault stopped being a directory still fails at switch time", () => {
// Unit J: activation used to succeed and fail in a LATER process,
- // where the first write would materialize the mis-resolved root.
- createProfile(configPath, "ghost-vault", join(home, "does-not-exist"));
+ // where the first write would materialize the mis-resolved root. The
+ // create-time check (Task 21) does not retire this one: a vault can be
+ // removed or replaced between create and switch.
+ const gone = vaultDir("removed-vault");
+ createProfile(configPath, "ghost-vault", gone);
+ rmSync(gone, { recursive: true, force: true });
expect(() => switchProfile(configPath, "ghost-vault")).toThrow(/not a directory/);
// The active pointer is unchanged, so nothing resolves to it.
expect(listProfiles(configPath).active).toBeNull();
+ const replaced = vaultDir("replaced-vault");
+ createProfile(configPath, "file-vault", replaced);
+ rmSync(replaced, { recursive: true, force: true });
+ atomicWriteFileSync(replaced, "not a vault\n");
+ expect(() => switchProfile(configPath, "file-vault")).toThrow(/not a directory/);
+ });
+
+ test("creating against a path that is not a directory is refused at create time", () => {
+ // The same error shape switching already uses, one step earlier.
+ expect(() => createProfile(configPath, "ghost", join(home, "does-not-exist"))).toThrow(
+ /profile 'ghost' points at a path that is not a directory/,
+ );
const filePath = join(home, "a-file");
atomicWriteFileSync(filePath, "not a vault\n");
- createProfile(configPath, "file-vault", filePath);
- expect(() => switchProfile(configPath, "file-vault")).toThrow(/not a directory/);
+ expect(() => createProfile(configPath, "file-vault", filePath)).toThrow(/not a directory/);
+ // Neither attempt reached the registry.
+ expect(listProfiles(configPath).profiles).toHaveLength(0);
+ });
+
+ test("creating over an existing name is refused and leaves the registry byte-identical", () => {
+ createProfile(configPath, "work", vaultDir("work"));
+ const registry = join(home, "profiles.json");
+ const before = readFileSync(registry, "utf8");
+
+ expect(() => createProfile(configPath, "work", vaultDir("other"))).toThrow(
+ /profile 'work' already exists/,
+ );
+ // A trimmed name is the same name, and must not slip past the check.
+ expect(() => createProfile(configPath, " work ", vaultDir("other"))).toThrow(
+ /profile 'work' already exists/,
+ );
+
+ expect(readFileSync(registry, "utf8")).toBe(before);
+ expect(listProfiles(configPath).profiles.map((p) => p.vault)).toEqual([join(home, "work")]);
+ });
+
+ test("the mutation is serialized: a held registry lock refuses the create", () => {
+ // Proves the lock is genuinely taken on the registry directory rather
+ // than the read-modify-write being merely narrow.
+ const release = lockfile.lockSync(dirname(configPath), { stale: 10_000, realpath: false });
+ try {
+ expect(() => createProfile(configPath, "work", vaultDir("work"))).toThrow(/ELOCKED|lock/i);
+ } finally {
+ release();
+ }
+ // Once released, the same create succeeds.
+ createProfile(configPath, "work", vaultDir("work"));
+ expect(listProfiles(configPath).profiles.map((p) => p.name)).toEqual(["work"]);
+ });
+
+ test("two concurrent creates both land", async () => {
+ // Two OS processes, both started before either is awaited - no sleep,
+ // no staggering. A lock-free read-modify-write loses one of them.
+ const script = join(home, "create-profile.ts");
+ const module = join(
+ import.meta.dir,
+ "..",
+ "..",
+ "..",
+ "..",
+ "src",
+ "core",
+ "brain",
+ "portability",
+ "profiles.ts",
+ );
+ writeFileSync(
+ script,
+ [
+ `import { createProfile } from ${JSON.stringify(module)};`,
+ `createProfile(process.argv[2]!, process.argv[3]!, process.argv[4]!);`,
+ ].join("\n") + "\n",
+ "utf8",
+ );
+
+ const spawn = (name: string) =>
+ Bun.spawn(["bun", "run", script, configPath, name, vaultDir(name)], {
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const alpha = spawn("alpha");
+ const beta = spawn("beta");
+ const [alphaCode, betaCode] = await Promise.all([alpha.exited, beta.exited]);
+
+ expect([alphaCode, betaCode]).toEqual([0, 0]);
+ expect(listProfiles(configPath).profiles.map((p) => p.name)).toEqual(["alpha", "beta"]);
});
test("resolveActiveProfileVault is null with no active profile", () => {
@@ -86,7 +181,7 @@ describe("profile registry", () => {
expect(listProfiles(configPath).profiles).toHaveLength(0);
expect(resolveActiveProfileVault(configPath)).toBeNull();
// ...but a mutating call fails fast instead of saving over it.
- expect(() => createProfile(configPath, "work", "/srv/vaults/work")).toThrow(/malformed/);
+ expect(() => createProfile(configPath, "work", vaultDir("work"))).toThrow(/malformed/);
expect(() => switchProfile(configPath, "work")).toThrow(/malformed/);
// The original bytes are left untouched.
expect(readFileSync(registry, "utf8")).toBe("{ this is not valid json");
diff --git a/tests/core/brain/repair-plan-source.test.ts b/tests/core/brain/repair-plan-source.test.ts
new file mode 100644
index 00000000..49adc9db
--- /dev/null
+++ b/tests/core/brain/repair-plan-source.test.ts
@@ -0,0 +1,196 @@
+/**
+ * The repair planner consumes the doctor's findings (no-dead-ends, task 9).
+ *
+ * `planRepair` used to call `runDoctor` and then ignore what it returned
+ * except as counts, while each fixer re-scanned the vault for its own
+ * class independently. The applier shared vocabulary with the detector
+ * but was not a consumer of it, so nothing forced the two to agree about
+ * what had been detected.
+ *
+ * The proof that a plan is DERIVED FROM findings rather than from a fresh
+ * scan is that the two can be made to disagree: hand the planner findings
+ * that do not match the disk and watch the plan follow the findings.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ MalformedDoctorFindingError,
+ REPAIR_CODE,
+ planRepair,
+} from "../../../src/core/brain/diagnostics.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
+import { brainConfigPath, brainDirs, dreamWorkrunPath } from "../../../src/core/brain/paths.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import type { DoctorIssue } from "../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-repair-source-"));
+ const dirs = brainDirs(tmp);
+ for (const d of [
+ dirs.brain,
+ dirs.inbox,
+ dirs.processed,
+ dirs.preferences,
+ dirs.retired,
+ dirs.log,
+ dirs.snapshots,
+ ]) {
+ mkdirSync(d, { recursive: true });
+ }
+ atomicWriteFileSync(brainConfigPath(tmp), DEFAULT_BRAIN_CONFIG_YAML);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Write a dangling workrun (last phase is neither finalized nor interrupted). */
+function writeDanglingWorkrun(runId: string): string {
+ const path = dreamWorkrunPath(tmp, runId);
+ mkdirSync(join(tmp, "Brain", "log", "dream-runs"), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify({ phase: "started", at: "2026-07-18T00:00:00.000Z", run_id: runId })}\n`,
+ "utf8",
+ );
+ return path;
+}
+
+function seedDeadEvidence(slug: string, target: string): void {
+ writePreference(tmp, {
+ slug,
+ topic: slug,
+ principle: `rule ${slug}`,
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [`[[${target}]]`],
+ });
+}
+
+function doctorIssues(): ReadonlyArray<DoctorIssue> {
+ const report = runDoctor(tmp);
+ return [...report.errors, ...report.warnings];
+}
+
+describe("planRepair derives its plan from the findings it is given", () => {
+ test("the supplied findings produce the same plan the doctor run does", () => {
+ writeDanglingWorkrun("run-same");
+ seedDeadEvidence("alpha", "sig-never-existed");
+
+ expect(planRepair(tmp, { issues: doctorIssues() })).toEqual(planRepair(tmp));
+ });
+
+ test("a finding withheld from the planner is absent from the plan, defect and all", () => {
+ const workrun = writeDanglingWorkrun("run-withheld");
+ seedDeadEvidence("alpha", "sig-never-existed");
+
+ const withoutWalGap = doctorIssues().filter((issue) => issue.code !== "dangling-workrun");
+ const plan = planRepair(tmp, { issues: withoutWalGap });
+
+ // The dangling workrun is still on disk. A planner that re-scanned
+ // would find it; one that consumes findings cannot.
+ expect(workrun).toBe(dreamWorkrunPath(tmp, "run-withheld"));
+ expect(plan.fixes.filter((f) => f.code === REPAIR_CODE.walGap)).toEqual([]);
+ expect(plan.fixes.filter((f) => f.code === REPAIR_CODE.orphanedReference)).toHaveLength(1);
+ });
+
+ test("a finding whose defect is already gone still shapes the plan", () => {
+ writeDanglingWorkrun("run-vanished");
+ const captured = doctorIssues();
+ unlinkSync(dreamWorkrunPath(tmp, "run-vanished"));
+
+ // A fresh scan now finds nothing; the captured finding still names it.
+ expect(planRepair(tmp).fixes).toEqual([]);
+ const fromCaptured = planRepair(tmp, { issues: captured }).fixes;
+ expect(fromCaptured).toHaveLength(1);
+ expect(fromCaptured[0]!.code).toBe(REPAIR_CODE.walGap);
+ expect(fromCaptured[0]!.target).toContain("run-vanished");
+ });
+
+ test("the unfixable aggregation reads the same supplied findings", () => {
+ const issues: ReadonlyArray<DoctorIssue> = [
+ { severity: "error", code: "duplicate-id", path: join(tmp, "a.md"), message: "seeded" },
+ { severity: "error", code: "duplicate-id", path: join(tmp, "b.md"), message: "seeded" },
+ ];
+ const plan = planRepair(tmp, { issues });
+ expect(plan.fixes).toEqual([]);
+ expect(plan.unfixable).toHaveLength(1);
+ expect(plan.unfixable[0]!.code).toBe("duplicate-id");
+ expect(plan.unfixable[0]!.count).toBe(2);
+ });
+});
+
+describe("a finding that cannot carry a fixer's input is named, not skipped", () => {
+ test("a dangling-workrun finding with no path raises", () => {
+ const issues: ReadonlyArray<DoctorIssue> = [
+ { severity: "warning", code: "dangling-workrun", message: "no path on this one" },
+ ];
+ expect(() => planRepair(tmp, { issues })).toThrow(MalformedDoctorFindingError);
+ });
+
+ test("a broken-wikilink finding with no target raises", () => {
+ const issues: ReadonlyArray<DoctorIssue> = [
+ {
+ severity: "warning",
+ code: "broken-wikilink",
+ path: join(tmp, "Brain", "preferences", "pref-alpha.md"),
+ field: "evidenced_by",
+ message: "no target on this one",
+ },
+ ];
+ expect(() => planRepair(tmp, { issues })).toThrow(MalformedDoctorFindingError);
+ });
+});
+
+describe("plans for the existing fixable classes are unchanged", () => {
+ test("a structural link is still needs-review and an evidence link still prunable", () => {
+ writePreference(tmp, {
+ slug: "gamma",
+ topic: "gamma",
+ principle: "rule gamma",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-gone]]"],
+ supersedes: "[[pref-gone]]",
+ });
+
+ const fixes = planRepair(tmp).fixes.filter((f) => f.code === REPAIR_CODE.orphanedReference);
+ const evidence = fixes.find((f) => f.target.includes("sig-gone"))!;
+ const structural = fixes.find((f) => f.target.includes("pref-gone"))!;
+
+ expect(evidence.applicable).toBe(true);
+ expect(evidence.target).toBe("Brain/preferences/pref-gamma.md::_evidenced_by::sig-gone");
+ expect(evidence.detail).toBe(
+ "prune orphaned evidence [[sig-gone]] from Brain/preferences/pref-gamma.md",
+ );
+
+ expect(structural.applicable).toBe(false);
+ expect(structural.target).toBe("Brain/preferences/pref-gamma.md::supersedes::pref-gone");
+ expect(structural.reason).toContain("provenance");
+ });
+
+ test("a link outside the Brain id space is still left alone", () => {
+ writePreference(tmp, {
+ slug: "delta",
+ topic: "delta",
+ principle: "rule delta",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[src/some/code.ts]]"],
+ });
+ expect(planRepair(tmp).fixes.filter((f) => f.code === REPAIR_CODE.orphanedReference)).toEqual(
+ [],
+ );
+ });
+});
diff --git a/tests/core/brain/runtime-notices.test.ts b/tests/core/brain/runtime-notices.test.ts
index fec756b5..bd7e3b50 100644
--- a/tests/core/brain/runtime-notices.test.ts
+++ b/tests/core/brain/runtime-notices.test.ts
@@ -3,6 +3,8 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:f
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import { NEXT_COMMAND_KEY, resolveNextStep } from "../../../src/core/brain/next-step.ts";
import {
collectRuntimeNotices,
renderRuntimeNotices,
@@ -146,6 +148,99 @@ test("an unreadable _brain.yaml is named rather than silently defaulted", () =>
expect(codes).toContain("brain_config_unreadable");
});
+// ----- The structured next command (no-dead-ends, task 3) -------------------
+
+/** Config that leaves semantic search enabled with no resolvable key. */
+const SEMANTIC_DEGRADED_CONFIG = [
+ `search_semantic_enabled: "true"`,
+ `embedding_provider: "openai-compat"`,
+ `embedding_base_url: "https://example.invalid/v1"`,
+ `embedding_model: "m"`,
+ "",
+].join("\n");
+
+/**
+ * The `semantic_degraded` block exactly as the SessionStart injection has
+ * always carried it, back when the command lived in the sentence. Pinned
+ * literally because this block lands in an agent's context: the command
+ * moving from prose to a field must not change one byte of what the agent
+ * reads.
+ */
+const HISTORICAL_SEMANTIC_BLOCK =
+ "Runtime notices:\n" +
+ "- [warning] Semantic search is enabled but no embedding key resolved, " +
+ "so search has fallen back to lexical. Run: o2b search check";
+
+test("a registered notice code carries its command as a structured field", () => {
+ writeConfig("");
+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });
+ const missing = notices.find((n) => n.code === "search_index_missing");
+ expect(missing).toBeDefined();
+ expect(missing![NEXT_COMMAND_KEY]).toBe(
+ DIAGNOSTIC_SIGNALS.get("search_index_missing")!.nextCommand,
+ );
+ expect(missing![NEXT_COMMAND_KEY]).toBe("o2b search index");
+});
+
+test("a notice code with no registered exit carries no command and invents none", () => {
+ writeConfig("");
+ seedIndex();
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 9\n", "utf8");
+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });
+ // Both conditions are ambiguous by construction (see the comments at
+ // each notice site), so neither may acquire a command to look uniform.
+ for (const code of ["vault_marker_absent", "brain_config_unreadable"]) {
+ const notice = notices.find((n) => n.code === code);
+ expect(`${code}: ${notice !== undefined}`).toBe(`${code}: true`);
+ expect(`${code}: ${NEXT_COMMAND_KEY in notice!}`).toBe(`${code}: false`);
+ expect(`${code}: ${resolveNextStep(code)}`).toBe(`${code}: null`);
+ }
+});
+
+test("no notice embeds its command in prose", () => {
+ writeConfig(SEMANTIC_DEGRADED_CONFIG);
+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });
+ // Both prose-carrying conditions hold at once: no index, and semantic
+ // enabled with no key.
+ expect(notices.map((n) => n.code).toSorted()).toEqual([
+ "search_index_missing",
+ "semantic_degraded",
+ ]);
+ for (const notice of notices) {
+ expect(`${notice.code}: ${notice.message.includes("Run:")}`).toBe(`${notice.code}: false`);
+ }
+});
+
+test("the rendered block still names the command, byte-identically", () => {
+ writeConfig(SEMANTIC_DEGRADED_CONFIG);
+ seedIndex();
+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });
+ expect(notices.map((n) => n.code)).toEqual(["semantic_degraded"]);
+ expect(renderRuntimeNotices(notices)).toBe(HISTORICAL_SEMANTIC_BLOCK);
+});
+
+test("a notice with no registered command renders with no command tail", () => {
+ expect(
+ renderRuntimeNotices([
+ { code: "reindex_in_progress", severity: "info", message: "Search index is rebuilding." },
+ ]),
+ ).toBe("Runtime notices:\n- [info] Search index is rebuilding.");
+});
+
+test("the index notice describes the self-healing read path, not a dead end", () => {
+ writeConfig("");
+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });
+ const missing = notices.find((n) => n.code === "search_index_missing")!;
+ // `openReadOrSelfHeal` builds the index and retries, so the old claim
+ // that recall returns nothing describes a world self-heal removed.
+ expect(missing.message).toBe(
+ "Search index is not built yet, so the first recall builds it before returning " +
+ "(that call pays the full index build).",
+ );
+ expect(renderRuntimeNotices(notices)).toContain("Run: o2b search index");
+});
+
test("a readable _brain.yaml yields no config notice", () => {
writeConfig("");
seedIndex();
diff --git a/tests/core/brain/sessions-import-offline.test.ts b/tests/core/brain/sessions-import-offline.test.ts
index 8cbff00f..59e15c87 100644
--- a/tests/core/brain/sessions-import-offline.test.ts
+++ b/tests/core/brain/sessions-import-offline.test.ts
@@ -15,7 +15,7 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { importSession } from "../../../src/core/brain/sessions/import.ts";
diff --git a/tests/core/brain/sessions/import-event-time.test.ts b/tests/core/brain/sessions/import-event-time.test.ts
index ff9a17ce..4086dfbd 100644
--- a/tests/core/brain/sessions/import-event-time.test.ts
+++ b/tests/core/brain/sessions/import-event-time.test.ts
@@ -22,7 +22,7 @@ import { join } from "node:path";
import { brainDirs } from "../../../../src/core/brain/paths.ts";
import { parseFrontmatter } from "../../../../src/core/vault.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { importSession } from "../../../../src/core/brain/sessions/import.ts";
import {
diff --git a/tests/core/brain/skill-accept-dead-ends.test.ts b/tests/core/brain/skill-accept-dead-ends.test.ts
new file mode 100644
index 00000000..e3a455a8
--- /dev/null
+++ b/tests/core/brain/skill-accept-dead-ends.test.ts
@@ -0,0 +1,193 @@
+/**
+ * The two operational dead ends the accept transaction created
+ * (no-dead-ends, phase 3, item 1).
+ *
+ * The write-ahead journal and the vault-wide accept lock each made the
+ * accept sequence crash-safe, and each introduced a state an operator
+ * could not leave:
+ *
+ * 1. a journal file the parser cannot read blocks EVERY future accept,
+ * because the sweep runs before anything else and reports an
+ * unreadable marker by throwing;
+ * 2. a lock a crash left behind refuses every future accept, and
+ * nothing breaks it - correctly, because a live writer cannot be
+ * told from a dead one.
+ *
+ * Neither refusal named a way out. These tests pin that both now do, and
+ * that the one which CAN be resolved mechanically actually is.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
+import {
+ skillAcceptJournalPath,
+ skillProposalAcceptedPath,
+} from "../../../src/core/brain/paths.ts";
+import {
+ acceptSkillProposal,
+ discardUnreadableSkillAcceptJournals,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ recoverSkillProposalAccepts,
+ skillAcceptLockPath,
+ SkillAcceptLockedError,
+} from "../../../src/core/brain/skill-proposals.ts";
+import {
+ readSkillAcceptJournals,
+ SkillAcceptJournalUnreadableError,
+ writeSkillAcceptJournal,
+} from "../../../src/core/brain/skill-accept-journal.ts";
+import { _resetHeldLocksForTests } from "../../../src/core/brain/sync-lockfile.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-skill-dead-end-"));
+});
+
+afterEach(() => {
+ _resetHeldLocksForTests();
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const ACCEPTED_AT = new Date("2026-06-01T10:00:00.000Z");
+const LEARNED_AT = new Date("2026-06-01T09:00:00.000Z");
+
+/** Seed three records of one repeated action; returns the drafted slug. */
+function seedAndLearn(action: string): string {
+ for (let i = 0; i < 3; i++) {
+ const mm = String(10 + i).padStart(2, "0");
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: `2026-05-20T08:${mm}:00Z`,
+ sourceRefs: [{ id: `src-${action.replaceAll("_", "-")}-${i}` }],
+ payload: { action, summary: `did ${action} run ${i}` },
+ });
+ }
+ learnSkillProposals(vault, { now: LEARNED_AT, minSupport: 3 });
+ const target = listPendingSkillProposals(vault).find((p) => p.patternKind === "repeated_action");
+ if (!target) throw new Error("test setup: no repeated_action draft was created");
+ return target.slug;
+}
+
+/** Put a file the journal parser cannot read at `slug`'s marker path. */
+function corruptJournal(slug: string): string {
+ const path = skillAcceptJournalPath(vault, slug);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "{ this is not json", "utf8");
+ return path;
+}
+
+/** Leave a lock on disk the way a hard crash does. */
+function stampAcceptLock(): string {
+ const path = skillAcceptLockPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "999999\n2026-06-01T09:59:00.000Z\n", "utf8");
+ return path;
+}
+
+describe("an unreadable accept journal names the command that clears it", () => {
+ test("the accept path refuses by name, naming the file and the exit", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const journal = corruptJournal("some-other-slug");
+
+ let thrown: unknown = null;
+ try {
+ acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(SkillAcceptJournalUnreadableError);
+ const err = thrown as SkillAcceptJournalUnreadableError;
+ expect(err.path).toBe(journal);
+ expect(err.message).toContain(journal);
+ expect(err.message).toContain("o2b brain skill-proposals recover --discard-unreadable");
+ });
+
+ test("the partitioned read reports the unreadable marker instead of throwing", () => {
+ const journal = corruptJournal("ghost");
+ const state = readSkillAcceptJournals(vault);
+ expect(state.entries).toEqual([]);
+ expect(state.unreadable.map((u) => u.path)).toEqual([journal]);
+ expect(state.unreadable[0]!.detail.length).toBeGreaterThan(0);
+ });
+
+ test("discarding the unreadable marker unblocks accepting", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const journal = corruptJournal("ghost");
+
+ const discarded = discardUnreadableSkillAcceptJournals(vault);
+ expect(discarded).toEqual([journal]);
+ expect(existsSync(journal)).toBe(false);
+
+ const accepted = acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ expect(accepted.status).toBe("accepted");
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(true);
+ });
+
+ test("discarding touches only the markers that cannot be read", () => {
+ const slug = seedAndLearn("rotate_keys");
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "archive",
+ startedAt: ACCEPTED_AT.toISOString(),
+ acceptedExisted: false,
+ procedureExisted: false,
+ });
+ const corrupt = corruptJournal("ghost");
+
+ expect(discardUnreadableSkillAcceptJournals(vault)).toEqual([corrupt]);
+ // The readable marker survived and is still resolvable.
+ const state = readSkillAcceptJournals(vault);
+ expect(state.unreadable).toEqual([]);
+ expect(state.entries.map((e) => e.slug)).toEqual([slug]);
+ expect(recoverSkillProposalAccepts(vault).map((r) => r.slug)).toEqual([slug]);
+ });
+
+ test("discarding nothing is not an error and reports nothing", () => {
+ expect(discardUnreadableSkillAcceptJournals(vault)).toEqual([]);
+ });
+});
+
+describe("a lock left by a crash refuses by name and is never broken", () => {
+ test("the accept path names the lock file and the command that inspects it", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const lock = stampAcceptLock();
+
+ let thrown: unknown = null;
+ try {
+ acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(SkillAcceptLockedError);
+ const err = thrown as SkillAcceptLockedError;
+ expect(err.path).toBe(lock);
+ expect(err.message).toContain(lock);
+ expect(err.message).toContain("o2b brain doctor");
+ // Refused, not broken: the file an operator must judge is still there.
+ expect(existsSync(lock)).toBe(true);
+ });
+
+ test("recovery refuses through the same named error", () => {
+ const lock = stampAcceptLock();
+ expect(() => recoverSkillProposalAccepts(vault)).toThrow(SkillAcceptLockedError);
+ expect(() => discardUnreadableSkillAcceptJournals(vault)).toThrow(SkillAcceptLockedError);
+ expect(existsSync(lock)).toBe(true);
+ });
+});
+
+describe("nothing changes when neither hazard is present", () => {
+ test("a clean accept is unaffected and leaves no journal behind", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const accepted = acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ expect(accepted.status).toBe("accepted");
+ expect(readSkillAcceptJournals(vault)).toEqual({ entries: [], unreadable: [] });
+ expect(existsSync(skillAcceptLockPath(vault))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/skill-contract.test.ts b/tests/core/brain/skill-contract.test.ts
new file mode 100644
index 00000000..f808c738
--- /dev/null
+++ b/tests/core/brain/skill-contract.test.ts
@@ -0,0 +1,326 @@
+/**
+ * Skill contract completeness (no-dead-ends, Unit I / Task 20).
+ *
+ * Three things this pins:
+ * 1. acceptance WRITES prerequisites / rollback / side effects /
+ * verification and the procedural-memory reader READS them back, so
+ * they are a contract rather than frontmatter decoration;
+ * 2. a proposal's self-reported evidence is resolved against the
+ * independently recorded procedural outcome ledger, keeping the three
+ * outcome states distinct (failures, successes, nothing recorded);
+ * 3. the accept sequence is a compensating transaction - a crash at each
+ * of its three gaps leaves neither a duplicate nor an orphan.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+import {
+ procedurePath,
+ proceduralMemoryIndexPath,
+ skillProposalAcceptedPath,
+ skillProposalPendingPath,
+} from "../../../src/core/brain/paths.ts";
+import {
+ acceptSkillProposal,
+ learnSkillProposals,
+ listPendingSkillProposals,
+ recoverSkillProposalAccepts,
+ resolveSkillProposalEvidence,
+} from "../../../src/core/brain/skill-proposals.ts";
+import {
+ listSkillAcceptJournals,
+ writeSkillAcceptJournal,
+} from "../../../src/core/brain/skill-accept-journal.ts";
+import {
+ listProceduralMemory,
+ proceduralEntryId,
+ recordProceduralOutcome,
+} from "../../../src/core/brain/procedural-memory.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-skill-contract-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const ACCEPTED_AT = new Date("2026-06-01T10:00:00.000Z");
+const LEARNED_AT = new Date("2026-06-01T09:00:00.000Z");
+
+/** Seed three records of one repeated action; returns the drafted slug. */
+function seedAndLearn(action: string): string {
+ for (let i = 0; i < 3; i++) {
+ const mm = String(10 + i).padStart(2, "0");
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: `2026-05-20T08:${mm}:00Z`,
+ sourceRefs: [{ id: `src-${action.replaceAll("_", "-")}-${i}` }],
+ payload: { action, summary: `did ${action} run ${i}` },
+ });
+ }
+ learnSkillProposals(vault, { now: LEARNED_AT, minSupport: 3 });
+ const target = listPendingSkillProposals(vault).find((p) => p.patternKind === "repeated_action");
+ if (!target) throw new Error("test setup: no repeated_action draft was created");
+ return target.slug;
+}
+
+function frontmatterOf(path: string): Record<string, unknown> {
+ const [fm] = parseFrontmatter(path);
+ return fm as Record<string, unknown>;
+}
+
+const CONTRACT = {
+ prerequisites: ["o2b brain doctor --json reports zero blocking issues"],
+ rollback: ["o2b brain restore --snapshot pre-rotate"],
+ sideEffects: ["rewrites Brain/procedural-memory/index.json"],
+ verification: ["o2b brain procedures list --json"],
+} as const;
+
+describe("the skill contract is written on acceptance", () => {
+ test("acceptance writes the four contract fields and the reader returns them", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const accepted = acceptSkillProposal(vault, slug, { now: ACCEPTED_AT, contract: CONTRACT });
+
+ const archiveFm = frontmatterOf(accepted.proposalPath);
+ expect(archiveFm["prerequisites"]).toEqual([...CONTRACT.prerequisites]);
+ expect(archiveFm["rollback"]).toEqual([...CONTRACT.rollback]);
+ expect(archiveFm["side_effects"]).toEqual([...CONTRACT.sideEffects]);
+ expect(archiveFm["verification"]).toEqual([...CONTRACT.verification]);
+
+ const procFm = frontmatterOf(procedurePath(vault, slug));
+ expect(procFm["prerequisites"]).toEqual([...CONTRACT.prerequisites]);
+ expect(procFm["rollback"]).toEqual([...CONTRACT.rollback]);
+ expect(procFm["side_effects"]).toEqual([...CONTRACT.sideEffects]);
+ expect(procFm["verification"]).toEqual([...CONTRACT.verification]);
+
+ // The contract is read BACK by the procedural-memory reader, so it
+ // reaches a consumer instead of decorating a file nobody parses.
+ const entry = listProceduralMemory(vault).find(
+ (e) => e.sourcePath === `Brain/procedures/proc-${slug}.md`,
+ );
+ expect(entry).toBeDefined();
+ expect(entry!.prerequisites).toEqual([...CONTRACT.prerequisites]);
+ expect(entry!.rollback).toEqual([...CONTRACT.rollback]);
+ expect(entry!.sideEffects).toEqual([...CONTRACT.sideEffects]);
+ expect(entry!.verification).toEqual([...CONTRACT.verification]);
+ });
+
+ test("an empty contract entry is refused by name instead of silently dropped", () => {
+ const slug = seedAndLearn("rotate_keys");
+ expect(() =>
+ acceptSkillProposal(vault, slug, {
+ now: ACCEPTED_AT,
+ contract: { prerequisites: [" "] },
+ }),
+ ).toThrow(/skill contract field 'prerequisites'/);
+ // Nothing was written: the draft is still pending and unreviewed.
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(false);
+ expect(existsSync(procedurePath(vault, slug))).toBe(false);
+ });
+});
+
+describe("byte-identical when the contract is absent", () => {
+ test("accepting with no contract produces exactly the pre-contract bytes", () => {
+ const slug = seedAndLearn("rotate_keys");
+ expect(slug).toBe("repeated_action-rotate-keys-0e4b812f");
+ acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+
+ // Golden bytes captured from the accept path BEFORE this unit landed.
+ expect(readFileSync(skillProposalAcceptedPath(vault, slug), "utf8")).toBe(
+ '---\nschema_version: 1\nkind: brain-skill-proposal\nid: prop-repeated_action-rotate-keys-0e4b812f\nslug: repeated_action-rotate-keys-0e4b812f\nstatus: accepted\npattern_kind: repeated_action\nname_key: "repeated_action:rotate_keys"\nversion: 1\nconfidence: 0.550\npayload_hash: 0e4b812f12089af795a186a2ac11330f26cdefb4f8e4d216d8ac6b3465bc64e0\ncreated_at: "2026-06-01T09:00:00.000Z"\nupdated_at: "2026-06-01T10:00:00.000Z"\nwatermark_from: ""\nwatermark_to: "2026-05-20T08:12:00Z"\nevidence_count: 3\nsource_refs: [ctn_20260520081000_d9c5e970465448f3, src-rotate-keys-0, ctn_20260520081100_5917efe2f4a20f97, src-rotate-keys-1, ctn_20260520081200_3d2812bae9bdffbe, src-rotate-keys-2]\nreviewed_at: "2026-06-01T10:00:00.000Z"\n---\n\n# Repeated action: rotate_keys\n\n## Pattern\n- kind: repeated_action\n- key: rotate_keys\n\n## Suggested skill body\nWhen pattern `rotate_keys` appears, follow the observed repeatable workflow.\nCapture inputs first, execute steps in stable order, and emit audit-friendly outputs.\n\n## Evidence\n- 2026-05-20T08:10:00Z :: session_turn :: ctn_20260520081000_d9c5e970465448f3 :: did rotate_keys run 0\n- 2026-05-20T08:11:00Z :: session_turn :: ctn_20260520081100_5917efe2f4a20f97 :: did rotate_keys run 1\n- 2026-05-20T08:12:00Z :: session_turn :: ctn_20260520081200_3d2812bae9bdffbe :: did rotate_keys run 2\n',
+ );
+ expect(readFileSync(procedurePath(vault, slug), "utf8")).toBe(
+ '---\nschema_version: 1\nkind: brain-procedure\nid: proc-repeated_action-rotate-keys-0e4b812f\nslug: repeated_action-rotate-keys-0e4b812f\nsource_proposal: prop-repeated_action-rotate-keys-0e4b812f\nversion: 1\ncreated_at: "2026-06-01T10:00:00.000Z"\nupdated_at: "2026-06-01T10:00:00.000Z"\nstatus: active\n---\n\n# Procedure\n\nAccepted from proposal: [[prop-repeated_action-rotate-keys-0e4b812f]]\n\nWhen pattern `rotate_keys` appears, follow the observed repeatable workflow.\nCapture inputs first, execute steps in stable order, and emit audit-friendly outputs.\n\n## Evidence\n- 2026-05-20T08:10:00Z :: session_turn :: ctn_20260520081000_d9c5e970465448f3 :: did rotate_keys run 0\n- 2026-05-20T08:11:00Z :: session_turn :: ctn_20260520081100_5917efe2f4a20f97 :: did rotate_keys run 1\n- 2026-05-20T08:12:00Z :: session_turn :: ctn_20260520081200_3d2812bae9bdffbe :: did rotate_keys run 2\n',
+ );
+ // The journal is a transient repair marker, not a residue.
+ expect(listSkillAcceptJournals(vault)).toHaveLength(0);
+ });
+});
+
+describe("claimed evidence resolved against the recorded outcome ledger", () => {
+ test("no recorded outcome, recorded successes and recorded failures stay three distinct states", () => {
+ const slug = seedAndLearn("rotate_keys");
+ acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ const entryId = proceduralEntryId(`Brain/procedures/proc-${slug}.md`);
+
+ // State 1 - nothing recorded. NOT "no failures": the rate is null.
+ const fresh = resolveSkillProposalEvidence(vault, slug);
+ expect(fresh.claimedEvidenceCount).toBe(3);
+ expect(fresh.proceduralEntryId).toBe(entryId);
+ expect(fresh.proceduralEntryPresent).toBe(true);
+ expect(fresh.recordedSuccesses).toBe(0);
+ expect(fresh.recordedFailures).toBe(0);
+ expect(fresh.recordedSuccessRate).toBeNull();
+ expect(fresh.outcomeState).toBe("unrecorded");
+
+ // State 2 - recorded failures.
+ expect(recordProceduralOutcome(vault, entryId, "failure")).not.toBeNull();
+ const failing = resolveSkillProposalEvidence(vault, slug);
+ expect(failing.recordedFailures).toBe(1);
+ expect(failing.recordedSuccessRate).toBe(0);
+ expect(failing.outcomeState).toBe("failing");
+
+ // State 3 - recorded successes alongside them is a fourth, honest state.
+ expect(recordProceduralOutcome(vault, entryId, "success")).not.toBeNull();
+ const mixed = resolveSkillProposalEvidence(vault, slug);
+ expect(mixed.recordedSuccesses).toBe(1);
+ expect(mixed.recordedFailures).toBe(1);
+ expect(mixed.outcomeState).toBe("mixed");
+
+ // Success-only is distinguishable from all of the above.
+ const other = seedAndLearnSecond();
+ acceptSkillProposal(vault, other, { now: ACCEPTED_AT });
+ const otherId = proceduralEntryId(`Brain/procedures/proc-${other}.md`);
+ expect(recordProceduralOutcome(vault, otherId, "success")).not.toBeNull();
+ const successful = resolveSkillProposalEvidence(vault, other);
+ expect(successful.recordedSuccessRate).toBe(1);
+ expect(successful.outcomeState).toBe("successful");
+ });
+
+ test("a pending proposal has no ledger entry, which is not the same as zero outcomes", () => {
+ const slug = seedAndLearn("rotate_keys");
+ const pending = resolveSkillProposalEvidence(vault, slug);
+ expect(pending.phase).toBe("pending");
+ expect(pending.proceduralEntryPresent).toBe(false);
+ expect(pending.recordedSuccesses).toBeNull();
+ expect(pending.recordedFailures).toBeNull();
+ expect(pending.recordedSuccessRate).toBeNull();
+ expect(pending.outcomeState).toBe("unrecorded");
+ });
+
+ test("an unknown slug raises a named error rather than an empty resolution", () => {
+ expect(() => resolveSkillProposalEvidence(vault, "no-such-slug")).toThrow(
+ /skill proposal not found in any phase: no-such-slug/,
+ );
+ });
+});
+
+/** Seed a second distinct pattern in the same vault; returns its slug. */
+function seedAndLearnSecond(): string {
+ const before = new Set(listPendingSkillProposals(vault).map((p) => p.slug));
+ for (let i = 0; i < 3; i++) {
+ const mm = String(20 + i).padStart(2, "0");
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: `2026-05-21T08:${mm}:00Z`,
+ sourceRefs: [{ id: `src-publish-${i}` }],
+ payload: { action: "publish_release", summary: `did publish_release run ${i}` },
+ });
+ }
+ learnSkillProposals(vault, { now: new Date("2026-06-02T09:00:00Z"), minSupport: 3 });
+ const target = listPendingSkillProposals(vault).find(
+ (p) => p.patternKind === "repeated_action" && !before.has(p.slug),
+ );
+ if (!target) throw new Error("test setup: no second repeated_action draft was created");
+ return target.slug;
+}
+
+describe("the accept sequence survives a crash at each of its three gaps", () => {
+ /**
+ * Reproduce the on-disk state a crash would leave at `phase` by running a
+ * real accept and then undoing the steps that would not yet have happened.
+ */
+ function crashAfter(slug: string, phase: "archive" | "materialize" | "commit"): void {
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ const pendingBytes = readFileSync(pendingPath, "utf8");
+ acceptSkillProposal(vault, slug, { now: ACCEPTED_AT });
+ if (phase === "archive") {
+ rmSync(procedurePath(vault, slug));
+ writeFileSync(pendingPath, pendingBytes, "utf8");
+ } else if (phase === "materialize") {
+ writeFileSync(pendingPath, pendingBytes, "utf8");
+ } else {
+ rmSync(join(vault, "Brain", "procedural-memory"), { recursive: true, force: true });
+ }
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase,
+ startedAt: ACCEPTED_AT.toISOString(),
+ acceptedExisted: false,
+ procedureExisted: false,
+ });
+ }
+
+ test("gap 1 - crash before the procedure was written leaves no orphaned archive", () => {
+ const slug = seedAndLearn("rotate_keys");
+ crashAfter(slug, "archive");
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((r) => r.action)).toEqual(["rolled_back"]);
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(false);
+ expect(existsSync(procedurePath(vault, slug))).toBe(false);
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ expect(listSkillAcceptJournals(vault)).toHaveLength(0);
+ });
+
+ test("gap 2 - crash before the pending copy was removed leaves no duplicate", () => {
+ const slug = seedAndLearn("rotate_keys");
+ crashAfter(slug, "materialize");
+ // The duplicate is real before recovery: pending AND accepted both exist.
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(true);
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((r) => r.action)).toEqual(["rolled_back"]);
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(false);
+ expect(existsSync(procedurePath(vault, slug))).toBe(false);
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ });
+
+ test("gap 3 - crash before the projections were rebuilt repairs them instead of leaving them stale", () => {
+ const slug = seedAndLearn("rotate_keys");
+ crashAfter(slug, "commit");
+ expect(existsSync(proceduralMemoryIndexPath(vault))).toBe(false);
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((r) => r.action)).toEqual(["completed"]);
+ // Rolled FORWARD: the pending copy is gone, so the accept had committed.
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(false);
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(true);
+ expect(existsSync(procedurePath(vault, slug))).toBe(true);
+ expect(
+ listProceduralMemory(vault).some((e) => e.sourcePath === `Brain/procedures/proc-${slug}.md`),
+ ).toBe(true);
+ expect(listSkillAcceptJournals(vault)).toHaveLength(0);
+ });
+
+ test("an exception materializing the procedure rolls the archive back and clears the journal", () => {
+ const slug = seedAndLearn("rotate_keys");
+ // A procedure already at the target path makes the exclusive write throw.
+ mkdirSync(dirname(procedurePath(vault, slug)), { recursive: true });
+ writeFileSync(procedurePath(vault, slug), "---\nkind: brain-procedure\n---\n\n# Squatter\n", {
+ encoding: "utf8",
+ });
+
+ expect(() => acceptSkillProposal(vault, slug, { now: ACCEPTED_AT })).toThrow(
+ /procedure already exists/,
+ );
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(false);
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ // The pre-existing file was NOT deleted by the rollback.
+ expect(readFileSync(procedurePath(vault, slug), "utf8")).toContain("# Squatter");
+ expect(listSkillAcceptJournals(vault)).toHaveLength(0);
+ });
+
+ test("a stale journal is swept by the next accept, not left for a human", () => {
+ const slug = seedAndLearn("rotate_keys");
+ crashAfter(slug, "materialize");
+ const second = seedAndLearnSecond();
+
+ acceptSkillProposal(vault, second, { now: ACCEPTED_AT });
+ // Accepting an unrelated draft resolved the abandoned sequence.
+ expect(existsSync(skillProposalAcceptedPath(vault, slug))).toBe(false);
+ expect(existsSync(skillProposalPendingPath(vault, slug))).toBe(true);
+ expect(existsSync(skillProposalAcceptedPath(vault, second))).toBe(true);
+ });
+});
diff --git a/tests/core/brain/temporal/citations.test.ts b/tests/core/brain/temporal/citations.test.ts
index f6e2c673..d4a1a0ae 100644
--- a/tests/core/brain/temporal/citations.test.ts
+++ b/tests/core/brain/temporal/citations.test.ts
@@ -19,7 +19,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
diff --git a/tests/core/brain/tension-detect.test.ts b/tests/core/brain/tension-detect.test.ts
index 763de2c7..c7e839e7 100644
--- a/tests/core/brain/tension-detect.test.ts
+++ b/tests/core/brain/tension-detect.test.ts
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import {
detectTensionsInVault,
diff --git a/tests/core/brain/today-dashboard.test.ts b/tests/core/brain/today-dashboard.test.ts
index 3c47eb48..dacf474f 100644
--- a/tests/core/brain/today-dashboard.test.ts
+++ b/tests/core/brain/today-dashboard.test.ts
@@ -16,7 +16,7 @@ import { join } from "node:path";
import { addObligation } from "../../../src/core/brain/obligations.ts";
import { brainDirs } from "../../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { buildTodayDashboard } from "../../../src/core/brain/today-dashboard.ts";
diff --git a/tests/core/config-path.test.ts b/tests/core/config-path.test.ts
new file mode 100644
index 00000000..e336f772
--- /dev/null
+++ b/tests/core/config-path.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Platform boundary for the plugin config path.
+ *
+ * `defaultConfigPath()` ends in `$HOME/.config/open-second-brain/…`.
+ * That layout is a POSIX convention; Windows does not use it, and this
+ * project has no Windows support - no adapter, no install document, no
+ * path handling beyond three incidental `win32` branches. Returning a
+ * `C:\Users\…\.config\…` path there is a plausible-looking answer to a
+ * question this build cannot answer, so the resolver refuses by name
+ * instead.
+ *
+ * The refusal is reachable ONLY on an unsupported platform AND only
+ * after both explicit overrides have been checked, so every supported
+ * platform is byte-identical.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import {
+ defaultConfigPath,
+ resolveDefaultConfigPath,
+ UnsupportedPlatformError,
+ type ConfigPathEnv,
+} from "../../src/core/config.ts";
+
+const HOME = "/home/tester";
+
+function envFor(platform: string, vars: Record<string, string> = {}): ConfigPathEnv {
+ return { platform, home: HOME, env: vars };
+}
+
+describe("resolveDefaultConfigPath — supported platforms", () => {
+ for (const platform of ["linux", "darwin", "freebsd", "openbsd", "sunos", "aix"]) {
+ test(`${platform} resolves to $HOME/.config/open-second-brain/config.yaml`, () => {
+ expect(resolveDefaultConfigPath(envFor(platform))).toBe(
+ join(HOME, ".config", "open-second-brain", "config.yaml"),
+ );
+ });
+ }
+
+ test("the explicit override wins over the home fallback", () => {
+ expect(
+ resolveDefaultConfigPath(envFor("linux", { OPEN_SECOND_BRAIN_CONFIG: "/etc/osb.yaml" })),
+ ).toBe("/etc/osb.yaml");
+ });
+
+ test("XDG_CONFIG_HOME wins over the home fallback", () => {
+ expect(resolveDefaultConfigPath(envFor("linux", { XDG_CONFIG_HOME: "/xdg" }))).toBe(
+ join("/xdg", "open-second-brain", "config.yaml"),
+ );
+ });
+
+ test("the zero-argument form reads the real process and still resolves here", () => {
+ // This test process runs on a supported platform; the refusal must be
+ // unreachable for it, and the answer unchanged from before the branch.
+ delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ delete process.env["XDG_CONFIG_HOME"];
+ expect(defaultConfigPath()).toBe(
+ join(homedir(), ".config", "open-second-brain", "config.yaml"),
+ );
+ });
+});
+
+describe("resolveDefaultConfigPath — unsupported platform", () => {
+ test("win32 raises a named error that names the platform", () => {
+ let thrown: unknown;
+ try {
+ resolveDefaultConfigPath(envFor("win32"));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(UnsupportedPlatformError);
+ const error = thrown as UnsupportedPlatformError;
+ expect(error.name).toBe("UnsupportedPlatformError");
+ expect(error.platform).toBe("win32");
+ expect(error.message).toContain("win32");
+ });
+
+ test("the refusal names both escape hatches", () => {
+ expect(() => resolveDefaultConfigPath(envFor("win32"))).toThrow(/OPEN_SECOND_BRAIN_CONFIG/);
+ expect(() => resolveDefaultConfigPath(envFor("win32"))).toThrow(/XDG_CONFIG_HOME/);
+ });
+
+ test("an explicit override is still honoured on win32", () => {
+ expect(
+ resolveDefaultConfigPath(
+ envFor("win32", { OPEN_SECOND_BRAIN_CONFIG: "C:\\osb\\config.yaml" }),
+ ),
+ ).toBe("C:\\osb\\config.yaml");
+ });
+
+ test("XDG_CONFIG_HOME is still honoured on win32", () => {
+ expect(resolveDefaultConfigPath(envFor("win32", { XDG_CONFIG_HOME: "C:\\cfg" }))).toBe(
+ join("C:\\cfg", "open-second-brain", "config.yaml"),
+ );
+ });
+});
diff --git a/tests/docs/install-verify-conformance.test.ts b/tests/docs/install-verify-conformance.test.ts
new file mode 100644
index 00000000..3052897a
--- /dev/null
+++ b/tests/docs/install-verify-conformance.test.ts
@@ -0,0 +1,269 @@
+/**
+ * Conformance: the expected-output block in every per-runtime install
+ * document must match what the adapter's `verify()` actually prints.
+ *
+ * The Verify section of each `install/<runtime>.md` used to say "run
+ * this" and never "this is what success looks like", so an agent
+ * following the document had nothing to pattern-match against. Each
+ * document now carries a block introduced by
+ *
+ * <!-- expected-output: o2b install --check --target <t> -->
+ *
+ * and this suite renders the real thing: it installs the target into an
+ * injected environment (temp home, temp vault - no adapter reads the
+ * real one), calls `verify()`, renders it through the same
+ * `renderVerifyTable` the CLI uses, and compares. Machine-specific
+ * absolute paths are replaced by the placeholders the documents use.
+ *
+ * When this fails, the message names the document to edit.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { Writable } from "node:stream";
+
+import { registerAllAdapters } from "../../src/core/install/adapters/all.ts";
+import {
+ resetCopilotRunner,
+ setCopilotRunner,
+ type CopilotRunner,
+} from "../../src/core/install/adapters/copilot-cli.ts";
+import { buildPayload } from "../../src/core/install/payload.ts";
+import { renderVerifyTable } from "../../src/cli/install/render.ts";
+import type {
+ ApplyOpts,
+ InstallAdapter,
+ InstallEnv,
+ McpPayload,
+} from "../../src/core/install/types.ts";
+
+const REPO_ROOT = resolve(import.meta.dir, "..", "..");
+const INSTALL_DOCS_DIR = join(REPO_ROOT, "install");
+
+/** Placeholders the documents use in place of machine-specific paths. */
+const HOME_PLACEHOLDER = "$HOME";
+const VAULT_PLACEHOLDER = "<vault>";
+const PLUGIN_PLACEHOLDER = "<plugin>";
+
+/** Marker that introduces a documented expected-output block. */
+const EXPECTED_OUTPUT_MARKER = "<!-- expected-output:";
+
+const AGENT_NAME = "claude-vps";
+const TIMEZONE = "UTC";
+
+/**
+ * Install documents with no registered adapter: their Verify step runs a
+ * third-party command (`claude mcp list`, `hermes memory status`, …),
+ * not `o2b install --check`, so there is nothing in this codebase to
+ * assert their output against. Listed rather than skipped so a NEW
+ * adapter-backed document cannot quietly avoid the binding.
+ */
+const PIPELINE_HOSTED_DOCS: Readonly<Record<string, string>> = Object.freeze({
+ "claudecode.md": "plugin-hosted; verified with `claude mcp list`, not an OSB adapter",
+ "codex.md": "plugin-hosted; verified with `codex mcp list`, not an OSB adapter",
+ "hermes.md": "provider-hosted; verified with `hermes memory status`, not an OSB adapter",
+ "openclaw.md": "plugin-hosted; verified with `openclaw plugins inspect`, not an OSB adapter",
+ "prerequisites.md": "shared setup, not a runtime document",
+});
+
+interface Harness {
+ readonly vault: string;
+ readonly home: string;
+ readonly opts: ApplyOpts;
+ readonly env: InstallEnv;
+ readonly payload: McpPayload;
+}
+
+let vault: string;
+let home: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-doc-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-doc-h-"));
+});
+
+afterEach(() => {
+ resetCopilotRunner();
+ for (const dir of [vault, home]) {
+ try {
+ rmSync(dir, { recursive: true, force: true });
+ } catch {
+ // temp cleanup is best-effort
+ }
+ }
+});
+
+function sink(): NodeJS.WriteStream {
+ return new Writable({
+ write(_chunk, _enc, cb) {
+ cb();
+ },
+ }) as unknown as NodeJS.WriteStream;
+}
+
+function harness(overrides: Partial<ApplyOpts> = {}): Harness {
+ return {
+ vault,
+ home,
+ env: {
+ vault,
+ home,
+ cwd: home,
+ env: { VAULT_AGENT_NAME: AGENT_NAME, VAULT_TIMEZONE: TIMEZONE },
+ now: new Date("2026-05-20T12:00:00.000Z"),
+ },
+ // Built from the SAME vault the adapter verifies against: several
+ // adapters recompute the expected payload from `env.vault`, so a
+ // payload for any other vault would (correctly) verify as drift.
+ payload: buildPayload({ vault, agent_name: AGENT_NAME, timezone: TIMEZONE }),
+ opts: { dryRun: false, force: false, stdout: sink(), stderr: sink(), ...overrides },
+ };
+}
+
+/**
+ * Per-target setup that puts the adapter into its INSTALLED state. Every
+ * entry performs a real apply against the injected environment; nothing
+ * here fabricates a manifest.
+ */
+const INSTALLERS: Readonly<Record<string, (adapter: InstallAdapter) => Harness>> = Object.freeze({
+ generic: (adapter) => {
+ const h = harness({ outPath: join(home, "osb-mcp.json") });
+ return applyInto(adapter, h);
+ },
+ pi: (adapter) => {
+ const h = harness({ piSkillSource: join(REPO_ROOT, "skills", "brain-memory") });
+ return applyInto(adapter, h);
+ },
+ "copilot-cli": (adapter) => {
+ // The copilot CLI is not present in a test environment; inject a
+ // runner that behaves like a working one so the document shows the
+ // subprocess path an operator with the CLI installed will see.
+ const registered: string[] = [];
+ const runner: CopilotRunner = {
+ available: () => true,
+ list: () => ({ ok: true, names: [...registered] }),
+ run: (args: ReadonlyArray<string>) => {
+ if (args[0] === "mcp" && args[1] === "add" && typeof args[2] === "string") {
+ registered.push(args[2]);
+ }
+ return { exitCode: 0, stdout: "", stderr: "" };
+ },
+ };
+ setCopilotRunner(runner);
+ return applyInto(adapter, harness());
+ },
+});
+
+function defaultInstaller(adapter: InstallAdapter): Harness {
+ return applyInto(adapter, harness());
+}
+
+/** Run the adapter's real plan+apply against the injected environment. */
+function applyInto(adapter: InstallAdapter, h: Harness): Harness {
+ adapter.apply(adapter.plan(h.payload, h.env), h.payload, h.env, h.opts);
+ return h;
+}
+
+/** Replace machine-specific absolute paths with the documented placeholders. */
+function placeholders(text: string, h: Harness): string {
+ return text
+ .split(h.vault)
+ .join(VAULT_PLACEHOLDER)
+ .split(h.home)
+ .join(HOME_PLACEHOLDER)
+ .split(REPO_ROOT)
+ .join(PLUGIN_PLACEHOLDER);
+}
+
+/**
+ * Trailing whitespace is not comparable across editors (the table pads
+ * its status column, and a detail-less row ends in spaces), so both
+ * sides are compared line-trimmed.
+ */
+function comparable(text: string): string {
+ return text
+ .split("\n")
+ .map((line) => line.trimEnd())
+ .join("\n")
+ .trim();
+}
+
+interface DocumentedBlock {
+ readonly command: string;
+ readonly body: string;
+ readonly line: number;
+}
+
+/** Extract the single expected-output block from an install document. */
+function readDocumentedBlock(docPath: string): DocumentedBlock | null {
+ const lines = readFileSync(docPath, "utf8").split("\n");
+ const markerIdx = lines.findIndex((line) => line.trimStart().startsWith(EXPECTED_OUTPUT_MARKER));
+ if (markerIdx < 0) return null;
+ const marker = lines[markerIdx]!.trim();
+ const command = marker.slice(EXPECTED_OUTPUT_MARKER.length, marker.lastIndexOf("-->")).trim();
+ let cursor = markerIdx + 1;
+ while (cursor < lines.length && lines[cursor]!.trim() === "") cursor++;
+ if (cursor >= lines.length || !lines[cursor]!.startsWith("```")) return null;
+ const bodyStart = cursor + 1;
+ const bodyEnd = lines.findIndex((line, idx) => idx >= bodyStart && line.startsWith("```"));
+ if (bodyEnd < 0) return null;
+ return {
+ command,
+ body: lines.slice(bodyStart, bodyEnd).join("\n"),
+ line: markerIdx + 1,
+ };
+}
+
+const adapters = registerAllAdapters().list();
+
+describe("install documents — expected output matches verify()", () => {
+ for (const adapter of adapters) {
+ const docRel = `install/${adapter.target}.md`;
+ const docPath = join(REPO_ROOT, docRel);
+
+ test(`${docRel} documents what a successful check prints`, () => {
+ const documented = readDocumentedBlock(docPath);
+ expect(`${docRel}: expected-output block present = ${documented !== null}`).toBe(
+ `${docRel}: expected-output block present = true`,
+ );
+ const install = INSTALLERS[adapter.target] ?? defaultInstaller;
+ const h = install(adapter);
+ const actual = placeholders(renderVerifyTable([adapter.verify(h.env)]), h);
+ // Naming the document inside the compared value puts it in the
+ // failure diff, not only in the test title.
+ expect(`${docRel}:${documented!.line}\n${comparable(actual)}`).toBe(
+ `${docRel}:${documented!.line}\n${comparable(documented!.body)}`,
+ );
+ });
+
+ test(`${docRel} documents the command the block came from`, () => {
+ const documented = readDocumentedBlock(docPath);
+ expect(documented?.command).toBe(`o2b install --check --target ${adapter.target}`);
+ });
+ }
+});
+
+describe("install documents — completeness", () => {
+ test("every runtime document is either adapter-bound or listed as pipeline-hosted", () => {
+ const targets = new Set(adapters.map((a) => `${a.target}.md`));
+ const unbound = readdirSyncSorted(INSTALL_DOCS_DIR).filter(
+ (name) => !targets.has(name) && !(name in PIPELINE_HOSTED_DOCS),
+ );
+ expect(unbound).toEqual([]);
+ });
+
+ test("every pipeline-hosted document carries a written reason and still exists", () => {
+ for (const [name, reason] of Object.entries(PIPELINE_HOSTED_DOCS)) {
+ expect(reason.trim().length).toBeGreaterThan(0);
+ expect(readdirSyncSorted(INSTALL_DOCS_DIR)).toContain(name);
+ }
+ });
+});
+
+function readdirSyncSorted(dir: string): string[] {
+ return readdirSync(dir)
+ .filter((name) => name.endsWith(".md"))
+ .toSorted();
+}
diff --git a/tests/helpers/vault-digest.ts b/tests/helpers/vault-digest.ts
new file mode 100644
index 00000000..c9a0d49f
--- /dev/null
+++ b/tests/helpers/vault-digest.ts
@@ -0,0 +1,66 @@
+/**
+ * Test helper: content digests over a vault tree.
+ *
+ * "The dry run wrote nothing" is only worth asserting if it covers the
+ * whole tree. Spot-checking the two files a preview was expected to touch
+ * cannot catch a write somewhere the test author did not think to look -
+ * an audit record, a lock left behind, a rebuilt projection - and those
+ * are exactly the writes a preview must not make.
+ *
+ * {@link digestVaultTree} answers "did anything at all change?" in one
+ * value; {@link digestVaultFiles} answers "which files changed?", which
+ * is what an apply-changed-exactly-the-reported-set assertion needs.
+ */
+
+import { createHash } from "node:crypto";
+import { readFileSync, readdirSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+
+/** Per-file content digests, keyed by POSIX-style vault-relative path. */
+export function digestVaultFiles(root: string): Map<string, string> {
+ const out = new Map<string, string>();
+ const walk = (dir: string): void => {
+ const entries = readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
+ a.name.localeCompare(b.name),
+ );
+ for (const entry of entries) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else if (entry.isFile()) {
+ const rel = relative(root, abs).split(sep).join("/");
+ out.set(rel, createHash("sha256").update(readFileSync(abs)).digest("hex"));
+ }
+ }
+ };
+ walk(root);
+ return out;
+}
+
+/**
+ * One digest over every file under `root`, path names included, so a
+ * created or deleted file changes the value as surely as an edited one.
+ */
+export function digestVaultTree(root: string): string {
+ const hash = createHash("sha256");
+ for (const [path, digest] of [...digestVaultFiles(root)].toSorted((a, b) =>
+ a[0].localeCompare(b[0]),
+ )) {
+ hash.update(`${path}\0${digest}\n`);
+ }
+ return hash.digest("hex");
+}
+
+/**
+ * Vault-relative paths whose content differs between two snapshots,
+ * including files that appeared or vanished. Sorted, so a test can
+ * compare the set against a reported one directly.
+ */
+export function changedPaths(
+ before: ReadonlyMap<string, string>,
+ after: ReadonlyMap<string, string>,
+): string[] {
+ const changed = new Set<string>();
+ for (const [path, digest] of before) if (after.get(path) !== digest) changed.add(path);
+ for (const [path, digest] of after) if (before.get(path) !== digest) changed.add(path);
+ return [...changed].toSorted();
+}
diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.ts
index 370b80c7..433a3bf3 100644
--- a/tests/hooks/active-inject.test.ts
+++ b/tests/hooks/active-inject.test.ts
@@ -264,6 +264,10 @@ describe("active-inject hook", () => {
const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;
expect(injected).toContain("Runtime notices:");
expect(injected).toContain("Search index is not built");
+ // The command the notice used to spell out in prose still reaches the
+ // agent's context, now rendered from the structured field
+ // (no-dead-ends, task 3).
+ expect(injected).toContain("Run: o2b search index");
// The active body still follows the notice block.
expect(injected).toContain("pref-foo");
expect(injected.indexOf("Runtime notices:")).toBeLessThan(injected.indexOf("pref-foo"));
diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.ts
index f065b08a..7c9d4ba9 100644
--- a/tests/mcp/consolidated-tools.test.ts
+++ b/tests/mcp/consolidated-tools.test.ts
@@ -12,6 +12,7 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { emitIngestDedupReport } from "../../src/core/brain/dedup-telemetry.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
@@ -155,6 +156,37 @@ describe("brain_analytics", () => {
expect(typeof result).toBe("object");
});
+ test("view=dedup summarises the persisted exact-hash ingest dedup records", async () => {
+ emitIngestDedupReport(vault, {
+ surface: "scan_inline",
+ sources: [{ ref: "Daily/2026-07-01.md", exactDeduped: 3 }],
+ createdAt: "2026-07-01T10:00:00.000Z",
+ });
+ const result = (await run("brain_analytics", { view: "dedup" })) as Record<string, unknown>;
+ expect(result["total_records"]).toBe(1);
+ expect(result["total_exact_deduped"]).toBe(3);
+ expect(result["by_surface"]).toEqual({ scan_inline: 3 });
+ expect(result["trend"]).toEqual([
+ { at: "2026-07-01T10:00:00.000Z", surface: "scan_inline", exact_deduped: 3 },
+ ]);
+ // The semantic detectors nominate and never drop, so no key on this
+ // surface may be read as a semantic drop count.
+ for (const key of Object.keys(result)) expect(key).not.toContain("semantic");
+ });
+
+ test("view=dedup on a vault that deduped nothing reports zeros, not a fabricated row", async () => {
+ const result = (await run("brain_analytics", { view: "dedup" })) as Record<string, unknown>;
+ expect(result["total_records"]).toBe(0);
+ expect(result["total_exact_deduped"]).toBe(0);
+ expect(result["trend"]).toEqual([]);
+ });
+
+ test("view=dedup rejects an unknown surface filter by name", async () => {
+ await expect(
+ run("brain_analytics", { view: "dedup", surface: "not_a_surface" }),
+ ).rejects.toThrow(/surface/);
+ });
+
test("invalid view raises a clear error", async () => {
await expect(run("brain_analytics", { view: "recurrence" })).rejects.toThrow(/view/);
});
diff --git a/tests/mcp/doctor-next-step.test.ts b/tests/mcp/doctor-next-step.test.ts
new file mode 100644
index 00000000..00b3e681
--- /dev/null
+++ b/tests/mcp/doctor-next-step.test.ts
@@ -0,0 +1,162 @@
+/**
+ * `brain_doctor` names its exits over MCP (no-dead-ends, task 4).
+ *
+ * The CLI twin of this surface gained the structural next command; an
+ * agent driving the doctor over MCP would otherwise still get a code and
+ * a sentence and have to re-derive the repair. The tool resolves each
+ * reported issue against the same registry the CLI uses, and carries the
+ * command as a field on the issue record - there is no stream here to
+ * contaminate, so the field is the only form the pointer takes.
+ *
+ * The absent case matters as much as the present one: a code with no
+ * registered signal must arrive with no `next_command` key, never with a
+ * generic one.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
+import { DOCTOR_EXIT_EXCLUSIONS } from "../../src/core/brain/doctor-exits.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";
+
+const REPAIR_COMMAND = DIAGNOSTIC_SIGNALS.get("broken-wikilink")!.nextCommand;
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-doctor-next-step-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ resetVaultIdentityPins();
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+async function callDoctor(): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault, configPath });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "doctor-next-step-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "brain_doctor", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(r.result.content[0]!.text) as Record<string, unknown>;
+}
+
+type IssueRecord = Record<string, unknown> & { code: string };
+
+function issues(payload: Record<string, unknown>, key: string): ReadonlyArray<IssueRecord> {
+ return (payload[key] ?? []) as ReadonlyArray<IssueRecord>;
+}
+
+describe("brain_doctor - the next command reaches an MCP caller", () => {
+ test("a registered warning carries next_command", async () => {
+ mkdirSync(join(vault, "Brain", "log", "dream-runs"), { recursive: true });
+ writePreference(vault, {
+ slug: "dead-pointer",
+ topic: "dead-pointer",
+ principle: "a rule whose evidence pointer went missing",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-does-not-exist]]"],
+ });
+ const payload = await callDoctor();
+ const hit = issues(payload, "warnings").find((w) => w.code === "broken-wikilink");
+ expect(hit).toBeDefined();
+ expect(hit!["next_command"]).toBe(REPAIR_COMMAND);
+ });
+
+ test("an unregistered warning carries no next_command key", async () => {
+ writePreference(vault, {
+ slug: "mismatch",
+ topic: "mismatch",
+ principle: "a rule filed under the wrong folder",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ const path = join(vault, "Brain", "preferences", "pref-mismatch.md");
+ writeFileSync(
+ path,
+ readFileSync(path, "utf8").replace("_status: unconfirmed", "_status: retired"),
+ "utf8",
+ );
+ const payload = await callDoctor();
+ const hit = issues(payload, "warnings").find((w) => w.code === "status-folder-mismatch");
+ expect(hit).toBeDefined();
+ expect(Object.hasOwn(hit!, "next_command")).toBe(false);
+ });
+
+ test("an unregistered warning arrives with the published reason it has none", async () => {
+ writePreference(vault, {
+ slug: "mismatch",
+ topic: "mismatch",
+ principle: "a rule filed under the wrong folder",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-28T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ const path = join(vault, "Brain", "preferences", "pref-mismatch.md");
+ writeFileSync(
+ path,
+ readFileSync(path, "utf8").replace("_status: unconfirmed", "_status: retired"),
+ "utf8",
+ );
+ const payload = await callDoctor();
+ // Beside the streams, once per code - the same shape and the same key
+ // the CLI's `--json` renderer uses.
+ expect((payload["no_exit"] as Record<string, string>)["status-folder-mismatch"]).toBe(
+ DOCTOR_EXIT_EXCLUSIONS.get("status-folder-mismatch")!,
+ );
+ });
+
+ test("a clean vault reports no issues and invents no commands", async () => {
+ const payload = await callDoctor();
+ expect(issues(payload, "errors")).toEqual([]);
+ expect(issues(payload, "warnings")).toEqual([]);
+ for (const record of issues(payload, "uncertain")) {
+ // The hand-built fixture root is marked, so `uncertain` is empty
+ // here; the assertion holds the invariant if that ever changes.
+ expect(Object.hasOwn(record, "next_command")).toBe(
+ DIAGNOSTIC_SIGNALS.has(record.code as string),
+ );
+ }
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index c921ba6f..7f2451a3 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -519,6 +519,31 @@ describe("tool calls", () => {
expect(Array.isArray(s.notices)).toBe(true);
});
+ test("vault_health notices carry the next command as a field, additively", async () => {
+ // The sandbox vault has a Brain tree with no identity marker and no
+ // search index, so one notice with a registered exit and one without
+ // are both present (no-dead-ends, task 3).
+ const vault = createSandboxVault(tmp);
+ const server = new MCPServer({ vault });
+ await initialize(server);
+ const r = (await callTool(server, "vault_health", {})) as any;
+ const notices = r.result.structuredContent.notices as Array<Record<string, unknown>>;
+
+ const missing = notices.find((n) => n["code"] === "search_index_missing");
+ expect(missing).toBeDefined();
+ // The three fields this surface has always carried are untouched...
+ expect(missing!["severity"]).toBe("info");
+ expect(String(missing!["message"])).not.toContain("Run:");
+ // ...and the command is a field rather than a sentence to regex.
+ expect(missing!["next_command"]).toBe("o2b search index");
+
+ // A code with no registered exit contributes no key at all: absent,
+ // never present-and-null.
+ const marker = notices.find((n) => n["code"] === "vault_marker_absent");
+ expect(marker).toBeDefined();
+ expect(Object.keys(marker!).toSorted()).toEqual(["code", "message", "severity"]);
+ });
+
test("unknown tool returns method-not-found", async () => {
const server = new MCPServer({ vault: tmp });
await initialize(server);
diff --git a/tests/mcp/procedural-learning-tools.test.ts b/tests/mcp/procedural-learning-tools.test.ts
index 94b540ec..1d506b7a 100644
--- a/tests/mcp/procedural-learning-tools.test.ts
+++ b/tests/mcp/procedural-learning-tools.test.ts
@@ -189,6 +189,51 @@ describe("procedural learning MCP tools", () => {
});
expect(recShow.supportCount).toBe(1);
});
+
+ test("accept carries the execution contract and evidence resolves it against the ledger", async () => {
+ const server = new MCPServer({ vault });
+ await initialize(server);
+
+ await callTool(server, "brain_skill_proposals", { operation: "learn", min_support: 3 });
+ const listed = await callTool(server, "brain_skill_proposals", { operation: "list" });
+ const slug = (listed.proposals as Array<Record<string, unknown>>)[0]!["slug"] as string;
+
+ await callTool(server, "brain_skill_proposals", {
+ operation: "accept",
+ slug,
+ prerequisites: ["o2b brain doctor --json is clean"],
+ rollback: ["o2b brain pending apply --revert"],
+ side_effects: ["writes Brain/procedures"],
+ verification: ["o2b brain procedures list --json"],
+ });
+
+ const mem = await callTool(server, "brain_procedural_memory", { operation: "list" });
+ const procedure = (mem.entries as Array<Record<string, unknown>>).find(
+ (entry) => entry["sourcePath"] === `Brain/procedures/proc-${slug}.md`,
+ );
+ expect(procedure).toBeDefined();
+ expect(procedure!["prerequisites"]).toEqual(["o2b brain doctor --json is clean"]);
+ expect(procedure!["rollback"]).toEqual(["o2b brain pending apply --revert"]);
+ expect(procedure!["sideEffects"]).toEqual(["writes Brain/procedures"]);
+ expect(procedure!["verification"]).toEqual(["o2b brain procedures list --json"]);
+
+ // Nothing recorded yet: null rate, not a zero that reads as total failure.
+ const before = await callTool(server, "brain_skill_proposals", { operation: "evidence", slug });
+ expect(before.claimedEvidenceCount as number).toBeGreaterThanOrEqual(3);
+ expect(before.proceduralEntryId).toBe(procedure!["id"]);
+ expect(before.recordedSuccessRate).toBeNull();
+ expect(before.outcomeState).toBe("unrecorded");
+
+ await callTool(server, "brain_procedural_memory", {
+ operation: "mark_outcome",
+ id: procedure!["id"],
+ outcome: "failure",
+ });
+ const after = await callTool(server, "brain_skill_proposals", { operation: "evidence", slug });
+ expect(after.recordedFailures).toBe(1);
+ expect(after.recordedSuccessRate).toBe(0);
+ expect(after.outcomeState).toBe("failing");
+ });
});
function seedContinuity(vaultPath: string): void {
diff --git a/tests/mcp/session-summary-tool.test.ts b/tests/mcp/session-summary-tool.test.ts
index b2d2c088..28d49d21 100644
--- a/tests/mcp/session-summary-tool.test.ts
+++ b/tests/mcp/session-summary-tool.test.ts
@@ -108,3 +108,65 @@ describe("brain_session_summary tool", () => {
expect((scoped["digests"] as Array<Record<string, unknown>>)[0]!["session_id"]).toBe("a");
});
});
+
+describe("brain_session_summary project scope (Task 18)", () => {
+ test("write carries the normalized project and list filters by it", async () => {
+ const written = payload(
+ await call({
+ operation: "write",
+ session_id: "p1",
+ project_scope: "Open Second/Brain -- v2!",
+ decisions: ["scoped"],
+ }),
+ );
+ expect(written["written"]).toBe(true);
+ expect((written["digest"] as Record<string, unknown>)["project"]).toBe("open-second-brain-v2");
+
+ await call({ operation: "write", session_id: "p2", decisions: ["unscoped"] });
+
+ const all = payload(await call({ operation: "list" }));
+ expect(all["count"]).toBe(2);
+ const scoped = payload(
+ await call({ operation: "list", project_scope: "OPEN SECOND BRAIN V2" }),
+ );
+ expect(scoped["count"]).toBe(1);
+ expect((scoped["digests"] as Array<Record<string, unknown>>)[0]!["session_id"]).toBe("p1");
+ });
+
+ test("a digest written with no project omits the field entirely", async () => {
+ const written = payload(
+ await call({ operation: "write", session_id: "plain", decisions: ["d"] }),
+ );
+ const digest = written["digest"] as Record<string, unknown>;
+ expect("project" in digest).toBe(false);
+ });
+
+ test("a malformed project is an invalid-params error naming the argument", async () => {
+ const response = await call({
+ operation: "write",
+ session_id: "bad",
+ project_scope: "***",
+ decisions: ["d"],
+ });
+ expect(response.error).toBeDefined();
+ const error = response.error as { code: number; message: string };
+ expect(error.code).toBe(-32602);
+ expect(error.message).toMatch(/project/);
+ });
+
+ test("a non-string project is an invalid-params error", async () => {
+ const response = await call({
+ operation: "write",
+ session_id: "bad2",
+ project_scope: 42,
+ decisions: ["d"],
+ });
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+
+ test("the tool advertises project_scope, matching the brain_search filter name", () => {
+ const tool = buildToolTable("full").find((entry) => entry.name === "brain_session_summary");
+ const properties = (tool!.inputSchema as { properties: Record<string, unknown> }).properties;
+ expect(properties["project_scope"]).toBeDefined();
+ });
+});