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

v0.10.3: Brain visibility and control โ€” snapshot diff, numeric confidence, primary agent, titled wikilinks

Sol Aitkend75b338a7560
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index d59ddcec..b79bc035 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.2",
+ "version": "0.10.3",
"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 1cf05f66..95b6d136 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.2",
+ "version": "0.10.3",
"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 7d82271b..eb60a9ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,152 @@ 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).
+## [0.10.3] - 2026-05-17
+
+Brings four Tier-A items from
+`Projects/OpenSecondBrain/Features/_summary`: ยง5 snapshot diff and
+rollback dry-run (without the deferred sha256-manifest drift abort),
+ยง10 numeric confidence with derived band, ยง21 cross-project pointer
+plus a `primary_agent` declaration, and ยง27 titled wikilinks for
+preferences and retired rules across every Brain writer.
+
+No vault migration is required. Existing preferences and retired
+files parse unchanged; the writer emits the new `_confidence_value`
+field on the first dream refresh that touches each file, and the
+`Brain/_brain.yaml.primary_agent` key defaults to `null` so vaults
+without an explicit declaration keep their current behaviour.
+
+### Added
+
+- **`o2b brain snapshot diff <run_id_a> [<run_id_b>]`** โ€” read-only
+ artifact diff between two snapshots or between a snapshot and the
+ live `Brain/` tree. Output groups changes by artifact kind
+ (preference / retired / signal / log / config / other); `--json`
+ emits the structured `BrainTreeDiff` payload for scripting.
+- **`o2b brain rollback <run_id> --dry-run`** โ€” previews the
+ would-be restore plan as a live โ†’ snapshot diff via the same
+ renderer. Mutually exclusive with `--yes` so preview and execute
+ never collide. Leaves the live tree untouched.
+- **`extractSnapshotToTemp(vault, runId)`** โ€” shared snapshot
+ extraction primitive used by `restoreSnapshot`,
+ `rollback --dry-run`, and `snapshot diff`. The tar / zstd / gzip
+ decompression logic lives in one place.
+- **`src/core/brain/snapshot-diff.ts`** โ€” pure `diffBrainTrees`
+ walker plus `BrainTreeEntry` / `BrainFieldChange` / `BrainTreeChange`
+ / `BrainTreeDiff` types. No I/O beyond `readFileSync` /
+ `readdirSync`; classifier maps every Brain file into one of six
+ artifact kinds.
+- **`src/core/brain/snapshot-diff-render.ts`** โ€” pure renderers
+ (`renderDiffMarkdown`, `renderDiffJson`) split out so the differ
+ stays format-neutral.
+- **`_confidence_value` field** on every preference and retired
+ file. Wilson 95% lower bound on `applied / (applied + violated)`
+ modulated by linear freshness decay over
+ `retire.stale_evidence_days`. Stored alongside the existing
+ `_confidence` band, which becomes a derived view (band is the
+ max of the legacy step-function and a numeric-threshold view,
+ so it can only lift, never demote).
+- **`_brain.yaml.confidence.medium_min` (default 0.40) and
+ `high_min` (default 0.75)** โ€” derived-band thresholds on the
+ numeric value. Validated to lie in `[0, 1]` with `medium_min <
+ high_min`.
+- **`Brain/_brain.yaml.primary_agent`** declarative field. When set,
+ dream runs invoked from a different agent emit a stderr warning,
+ a `warnings` array entry on the MCP `brain_dream` response, and a
+ `non_primary_agent: <caller>` row in the dream summary log.
+- **`o2b brain set-primary <name>` / `o2b brain set-primary --clear`** โ€”
+ idempotent edit of the primary declaration without rewriting the
+ rest of `_brain.yaml`.
+- **`o2b brain init --primary-agent <name>`** โ€” sets the value
+ during the fresh bootstrap; on re-runs the flag is a no-op (use
+ `set-primary` instead).
+- **`src/core/brain/set-primary.ts`** โ€” `setPrimaryAgent(vault,
+ name | null): SetPrimaryAgentResult`. Validates the rewritten
+ YAML before persisting; surfaces a typed `BrainConfigError` when
+ the on-disk file is malformed.
+- **`renderPrefLink({ id, principle })`** in `src/core/brain/wikilink.ts`
+ with `MAX_PREF_LINK_TITLE_LEN = 80`. Sanitises wikilink-breaking
+ characters and truncates titles at a word boundary with an
+ ellipsis. Empty titles fall back to bare `[[id]]`.
+- **`docs/cross-project-pointer.md`** โ€” agent-facing setup guide
+ for projects whose coding work happens outside the vault root.
+ Covers the canonical `CLAUDE.md` / `AGENTS.md` snippet, the
+ `primary_agent` workflow, and the Syncthing multi-device case.
+- **CLI tests:** `tests/cli/brain.snapshot-diff.test.ts`,
+ `tests/cli/brain.test.ts` (new `set-primary` and
+ `--primary-agent` sections).
+- **Core tests:** `tests/core/brain.snapshot-diff.test.ts`
+ (differ + renderer), `tests/core/brain.confidence-value.test.ts`
+ (Wilson + freshness + hard floors + max-lift band derivation),
+ `tests/core/brain.set-primary.test.ts`,
+ `tests/core/brain.dream.non-primary.test.ts`.
+
+### Changed
+
+- **`computeConfidence`** returns `{ value, band }`. The band is the
+ max of the legacy step-function (preserved verbatim) and a
+ numeric-threshold view. Dream's refresh phase writes both
+ `_confidence` and `_confidence_value` on every touched
+ preference; legacy files migrate lazily on the next refresh.
+- **`dream` summary log** carries a `confidence_shifts: [...]`
+ payload whenever a band drop is detected during refresh โ€” the
+ digest's `## Confidence shifts` section picks them up through
+ the existing tolerant parser. `non_primary_agent: <name>` payload
+ row appears whenever the primary check triggers.
+- **`brain_query` MCP response** carries `confidence_value` next to
+ `confidence` on every preference and retired result row.
+- **`brain_dream` MCP response** carries a `warnings: [{code,
+ message}]` array. CLI `o2b brain dream` writes the same warnings
+ to `stderr`.
+- **`brain_dream` MCP schema** accepts an optional `agent` argument
+ for the primary-agent check.
+- **`active.md`** appends `(0.NN)` after the band on confirmed
+ bullets and `conf: 0.NN` to the Quarantine block when the file
+ carries a numeric value.
+- **Every Brain writer** that emits a preference or retired wikilink
+ now uses `renderPrefLink`. Affected surfaces: dream log payloads
+ (promote, retire, retain-pinned, noted-redundant,
+ signal-suppressed, summary), apply-evidence log entry, pin / unpin
+ log entries, digest sections (new-unconfirmed, confirmed,
+ retired, top-applied, top-referenced, confidence-shifts,
+ contradictions), reject log entry, force-confirmed log entry,
+ retired body's `superseded_by` reference. Signals and external
+ artifacts stay bare-id because they have no useful title source.
+- **`BrainConfig`** widens with `primary_agent: string | null`.
+ `BrainConfidenceConfig` gains `medium_min` and `high_min`.
+ `BrainPreference` and `BrainRetired` gain
+ `confidence_value: number | null` (`null` only on pre-v0.10.3
+ files that have not been refreshed yet).
+- **`Brain/log/<today>.md`** dream events optionally carry a
+ `confidence_shifts` array and a `non_primary_agent` scalar โ€” both
+ forward-compat and surfaced through the digest renderer.
+- **`DigestJson*` shapes** gain `principle: string` on every entry
+ rendered with a wikilink, so the markdown renderer can build
+ titled links without re-parsing the artifact files.
+- **`scanBrain` retired record** carries `principle` so the dream
+ log payloads can render titled wikilinks for the retired side
+ without re-reading the file.
+- **README** lists the new CLI verbs (`set-primary`, `snapshot diff`)
+ and the `--dry-run` flag on `rollback`; documents the
+ Cross-project setup subsection.
+- **install.md branch A (Hermes)** recommends
+ `--primary-agent <agent-name>` during the `o2b brain init` step,
+ with guidance on the `set-primary` follow-up.
+- **`docs/how-it-works.md`** documents the numeric `confidence_value`,
+ the read-only snapshot inspectors, and the primary-agent
+ observability contract.
+
+### Notes
+
+- Snapshot diff and `rollback --dry-run` are CLI-only. The MCP
+ surface deliberately stays read-and-shape-only (`brain_query` +
+ the new `warnings` array); operator-only mutations stay outside
+ the agent loop, matching how `rollback`, `reject`, and
+ `migrate-frontmatter` are handled today.
+- The deferred ยง5 sub-features (sha256-manifest drift abort and
+ post-dream integrity drill hook) remain out of scope โ€” see
+ `Projects/OpenSecondBrain/Features/_summary` for the rationale.
+
## [0.10.2] - 2026-05-16
Adds three Tier-A capture and hygiene items from
@@ -1375,6 +1521,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.10.3]: https://github.com/itechmeat/open-second-brain/compare/v0.10.2...v0.10.3
[0.10.2]: https://github.com/itechmeat/open-second-brain/compare/v0.10.1...v0.10.2
[0.10.1]: https://github.com/itechmeat/open-second-brain/compare/v0.10.0...v0.10.1
[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0
diff --git a/README.md b/README.md
index 3eb1982f..6f168938 100644
--- a/README.md
+++ b/README.md
@@ -125,7 +125,9 @@ o2b brain digest Render a Markdown or JSON summary of recent Brain
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain reject (CLI-only) Move a preference to retired/ with reason: user-rejected
o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)
-o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot
+o2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain/_brain.yaml (--clear)
+o2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/
+o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot (--dry-run previews)
o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, โ€ฆ)
o2b brain backlinks List inbound references to a Brain artifact id
o2b brain scan-inline Capture `@osb` markers from vault markdown files (Daily/, project notes, โ€ฆ)
@@ -226,13 +228,28 @@ o2b brain dream --vault /path/to/vault
o2b brain digest --vault /path/to/vault --silent-if-empty
```
-Fourteen CLI verbs in total: `init`, `feedback`, `dream`,
+The Brain verbs in full: `init`, `feedback`, `dream`,
`apply-evidence`, `digest`, `query`, `reject`, `pin`, `unpin`,
-`rollback`, `doctor`, `backlinks`, `scan-inline`, `import-session`,
-`migrate-frontmatter`. Seven are mirrored as MCP tools (`brain_*`);
-the rest are intentionally CLI-only because they change the
-protected set, overwrite vault state, or are operator-only
-maintenance commands.
+`set-primary`, `snapshot diff`, `rollback`, `doctor`, `backlinks`,
+`scan-inline`, `import-session`, `migrate-frontmatter`. Seven are
+mirrored as MCP tools (`brain_*`); the rest are intentionally
+CLI-only because they change the protected set, overwrite vault
+state, or are operator-only maintenance commands.
+
+### Cross-project setup
+
+When your coding work happens in a project directory that is not the
+vault itself, add a pointer snippet to your project's `CLAUDE.md` or
+`AGENTS.md` so the agent knows where to read preferences from. The
+canonical snippet, the rules for multi-device Syncthing setups, and
+the `o2b brain set-primary` invocation are in
+[`docs/cross-project-pointer.md`](docs/cross-project-pointer.md).
+
+A vault shared across hosts should declare a single
+`primary_agent` in `Brain/_brain.yaml` โ€” the runtime that owns the
+dream cron. Dream runs from a different agent emit a non-fatal
+warning (stderr for CLI, `warnings` array for MCP) and tag the dream
+summary log with `non_primary_agent: <caller>`.
### Capture surfaces
diff --git a/docs/cross-project-pointer.md b/docs/cross-project-pointer.md
new file mode 100644
index 00000000..e22f8f8a
--- /dev/null
+++ b/docs/cross-project-pointer.md
@@ -0,0 +1,114 @@
+# Cross-project setup
+
+When the coding work happens in a project directory that is not the
+Open Second Brain vault, the agent needs a pointer to find the vault
+on session start. This page describes the canonical snippet to drop
+into a project, the conventions around the vault's primary
+dream-running agent, and what changes when several devices share the
+same vault.
+
+## 1. Add the pointer snippet to your project
+
+Append the block below to one of the agent-prompt files your runtime
+reads on startup. Common targets:
+
+- `CLAUDE.md` โ€” Claude Code.
+- `AGENTS.md` โ€” Codex, Cursor, Aider, and other tools that follow the
+ `agents.md` convention.
+
+Pick one location per project. The managed-block fences let a future
+`o2b brain bootstrap` command rewrite the snippet idempotently; manual
+edits inside the fences are preserved on subsequent runs.
+
+Replace `<absolute-vault-path>` with the absolute path of your
+Obsidian-compatible vault before pasting.
+
+```text
+# >>> open-second-brain managed >>>
+## Open Second Brain
+
+This project shares an Obsidian-compatible vault with an active
+observing-memory layer. At session start, read the current
+preferences:
+
+ <absolute-vault-path>/Brain/active.md
+
+Record taste signals via `brain_feedback` (MCP) or
+`o2b brain feedback` (CLI). After producing a durable artifact, call
+`brain_apply_evidence` with `result: applied | violated | outdated`
+for any preference whose `scope` matches.
+
+Do not run `o2b brain dream` from this runtime. The vault has a
+primary dream-running agent declared in `<vault>/Brain/_brain.yaml`
+(key `primary_agent`).
+# <<< open-second-brain managed <<<
+```
+
+The snippet is intentionally short. The agent does not need
+configuration here โ€” every operational detail lives in the vault
+itself (preferences, the active digest, the `_brain.yaml` config).
+
+## 2. Primary agent and the dream cron
+
+A shared vault has exactly one runtime responsible for running the
+deterministic `dream` consolidation pass. Declare that runtime in
+`Brain/_brain.yaml`:
+
+```bash
+o2b brain set-primary <agent-name> --vault <vault-path>
+```
+
+`<agent-name>` is the value of `agent_name` in
+`~/.config/open-second-brain/config.yaml` on the host that runs the
+dream cron. To verify, run:
+
+```bash
+grep agent_name ~/.config/open-second-brain/config.yaml
+```
+
+When dream runs from a different agent, the response carries a
+structured warning:
+
+- The CLI prints
+ `warning: non-primary-dream-run: dream run from agent '<caller>', ...`
+ to `stderr`. Exit code stays `0`.
+- The MCP `brain_dream` tool returns a `warnings` array containing
+ `{ code: "non-primary-dream-run", message: "..." }` alongside the
+ usual summary.
+- The dream summary log event (`Brain/log/<date>.md`) gains a
+ `non_primary_agent: <caller>` payload row so the breach is greppable
+ in the audit trail.
+
+The pass still completes โ€” the declaration is observability, not
+access control. Pinning, rejecting, and toggling pins remain
+unrestricted: any agent on any device can mutate the protected set.
+
+To clear the primary declaration (the vault becomes single-host
+again, or you want to disable the check during local
+experimentation):
+
+```bash
+o2b brain set-primary --clear --vault <vault-path>
+```
+
+A vault initialised with `o2b brain init --primary-agent <name>`
+writes the value into the fresh `_brain.yaml` on the first run; on
+re-runs against an existing file `--primary-agent` is ignored โ€” use
+`set-primary` instead.
+
+## 3. Multi-device through Syncthing
+
+The vault is designed to be Syncthing-shared. Signals can be captured
+on any peer:
+
+- `brain_feedback` from a coding session on the laptop.
+- `o2b brain feedback` from a terminal.
+- `@osb` markers added by hand in Daily notes from the phone (captured
+ later by `o2b brain scan-inline` on any peer).
+
+All of these land in `Brain/inbox/`. The primary host's dream cron
+picks them up on the next pass, regardless of which peer wrote them.
+Use the `primary_agent` declaration to keep dream serialised to one
+host so signal processing does not race; the rest of the Brain
+layer is conflict-free because writes are append-only or
+locally-scoped (signals, daily logs, snapshots).
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index e6092411..6cd4f3a2 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -282,8 +282,25 @@ Defaults from `_brain.yaml`:
- `high_freshness_factor: 0.8` โ€” "fresh" means
`now - last_evidence_at < stale_evidence_days * 0.8`.
- `stale_evidence_days: 90` โ€” the boundary for fresh / stale.
-
-All four are tunable per vault in `Brain/_brain.yaml`.
+- `medium_min: 0.40`, `high_min: 0.75` โ€” derived-band thresholds on
+ the numeric `confidence_value` (see below).
+
+All six are tunable per vault in `Brain/_brain.yaml`.
+
+### Numeric `confidence_value`
+
+Each preference also carries a continuous
+`_confidence_value: 0.0โ€“1.0` field, computed alongside the band on
+every dream refresh. The value is the **Wilson 95% lower bound** on
+`applied / (applied + violated)` modulated by **freshness decay**
+that runs linearly from `1.0` at age 0 to `0.0` at
+`stale_evidence_days`. The band is the **maximum** of the legacy
+step-function and a numeric-threshold view (`medium_min`,
+`high_min`) โ€” so legacy boundaries stay intact and numeric tuning
+can only lift bands, never demote them. The digest's
+`## Confidence shifts` section uses the value to spot drops between
+runs; the MCP `brain_query` response and `Brain/active.md` both
+expose the number alongside the band for inspection.
## Active preferences injection
@@ -387,6 +404,46 @@ A snapshot captures every file under `Brain/` **except** `.snapshots/`
itself โ€” otherwise rollback would erase any snapshots taken after
this one. Retention defaults to ten newest archives.
+### Read-only inspectors over the snapshot family
+
+Two CLI surfaces share the same diff renderer over the snapshot
+extraction primitive (`extractSnapshotToTemp`), so previewing and
+auditing stay byte-equal:
+
+- **`o2b brain rollback <run_id> --dry-run`** โ€” extract the archive
+ into a sibling tmp dir, compute the live โ†’ snapshot diff, print it,
+ drop the tmp dir. Mutually exclusive with `--yes` since
+ preview-vs-execute is contradictory. No live writes; no log entry.
+- **`o2b brain snapshot diff <run_id_a> [<run_id_b>]`** โ€” same
+ renderer, but compares snapshot โ†” snapshot when both ids are
+ supplied (and snapshot โ†” live when only one is). `--json` yields
+ the structured `BrainTreeDiff` payload for scripting.
+
+The diff classifies every file under each root into six artifact
+kinds (preference, retired, signal, log, config, other). Preference
+and retired files receive a typed field-level diff for the derived
+counters (`_status`, `_applied_count`, `_violated_count`,
+`_confidence`, `_confidence_value`, `pinned`, and a few identity
+adjuncts); other kinds compare by byte equality and surface as
+`(body changed)`.
+
+## Primary agent declaration
+
+`Brain/_brain.yaml` carries an optional `primary_agent: <name> | null`
+key. When set, dream runs invoked from a different agent emit:
+
+- a stderr warning of the form `warning: non-primary-dream-run: โ€ฆ`,
+- a `warnings` array entry on the MCP `brain_dream` response,
+- a `non_primary_agent: <caller>` payload row in the dream summary
+ log event.
+
+The dream pass still completes โ€” the declaration is observability,
+not access control. Set / clear via `o2b brain set-primary <name>`
+or `o2b brain set-primary --clear`. A vault initialised with
+`o2b brain init --primary-agent <name>` writes the value into the
+fresh `_brain.yaml`. The full multi-device walkthrough is in
+[`docs/cross-project-pointer.md`](./cross-project-pointer.md).
+
## Hygiene: sanitisation and lints
Two cheap, deterministic layers keep the data clean.
diff --git a/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-design.md b/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-design.md
new file mode 100644
index 00000000..af0db5a9
--- /dev/null
+++ b/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-design.md
@@ -0,0 +1,553 @@
+# Tier-A bundle: snapshot diff, numeric confidence, cross-project pointer, titled wikilinks
+
+> Status: design draft for review.
+> Bundle covers items ยง5, ยง10, ยง21, ยง27 of
+> `Projects/OpenSecondBrain/Features/_summary` (vault knowledge base).
+> Target: one release (`v0.10.3-draft`), one CHANGELOG version, ordered
+> rollout per the dependency notes at the end of this document.
+
+## 1. Summary
+
+This bundle ships four mostly-orthogonal Brain layer increments:
+
+| ยง | Title | Scope this iteration |
+|---|---|---|
+| 5 | Snapshot diff + rollback dry-run | `o2b brain snapshot diff` (read-only inspector) and `o2b brain rollback --dry-run` (preview restore). No sha256 manifest, no drift abort, no archive-format change. |
+| 10 | Numeric confidence | `_confidence_value: 0.0โ€“1.0` as new primary field; existing `_confidence: low\|medium\|high` becomes derived (and is still emitted on disk for reader backwards compatibility). Wilson lower bound formula, freshness decay, new band thresholds in `_brain.yaml`. Lazy migration through the next dream refresh. |
+| 21 | Cross-project pointer + primary agent | `Brain/_brain.yaml.primary_agent` declarative field; `o2b brain set-primary` CLI; soft warning in dream when non-primary; `docs/cross-project-pointer.md` with the canonical CLAUDE.md / AGENTS.md snippet; install.md branch A recommendation. No managed-block CLI bootstrap (deferred until ยง4 installer ships together). |
+| 27 | Titled wikilinks for preferences | New `renderPrefLink({id, principle})` helper in `wikilink.ts`. All Brain writers that reference a preference or retired artifact emit `[[pref-slug\|short-title]]`. Parsers already strip `\|alias`; reading path unchanged. |
+
+Out of scope (called out explicitly so writing-plans does not re-open them):
+
+- sha256 manifest, `--force-rollback`, drift abort (ยง5 partial โ€” see _summary).
+- Post-dream integrity drill hook (ยง5 partial โ€” backed by rclone-crypt
+ off-host backups, not worth the moving part).
+- Hard refusal of non-primary dream runs (ยง21 โ€” soft warning only).
+- MCP `brain_set_primary` tool (ยง21 โ€” CLI-only, joins
+ `rollback` / `reject` / `migrate-frontmatter` in the operator-only band).
+- `o2b brain bootstrap` (ยง21 โ€” defers to ยง4 installer epic).
+- `aliases` first-class rename safety (ยง27 โ€” no real renames yet).
+- Loosening the `BrainPreference.confidence` agent API (ยง10 โ€” band stays
+ on the public MCP shape).
+
+## 2. Goals & non-goals
+
+### Goals
+
+1. Give the operator a read-only inspector for the snapshot family (diff
+ between two runs, or between a run and live) without touching the live
+ tree.
+2. Promote confidence from a step-function (low/medium/high) to a continuous
+ signal that the digest, doctor, and future tuners can reason about,
+ without breaking the published agent shape.
+3. Declare which runtime owns `dream` for a given vault, in a place that
+ syncs across devices (Syncthing).
+4. Make Brain wikilinks self-describing in Obsidian without changing how
+ parsers resolve them.
+
+### Non-goals
+
+1. Re-deriving snapshots themselves. Existing tar+zstd format, retention,
+ and `restoreSnapshot` semantics are untouched.
+2. Changing how `dream` clusters signals or decides retire reasons. Only
+ the **value** of confidence and the **payload** of log events shift.
+3. Adding hard enforcement around primary agent. The whole point is
+ visibility, not access control โ€” pinning, rejecting, and pin-toggling
+ from a non-primary host remain valid.
+
+## 3. ยง5 โ€” Snapshot diff + rollback dry-run
+
+### 3.1 CLI surface
+
+```text
+o2b brain rollback <run_id> --dry-run [--vault <path>] [--json]
+ # Mutually exclusive with --yes. Extracts the archive into a sibling
+ # tmp directory, computes the would-be restore plan, prints it, and
+ # removes tmp. Does NOT modify Brain/. Exit code 0.
+
+o2b brain snapshot diff <run_id_a> [<run_id_b>] [--vault <path>] [--json]
+ # With one positional: diff snapshot โ†” live Brain/.
+ # With two positionals: diff <a> โ†” <b>.
+ # Order semantics: <a> is "before", <b> (or live) is "after".
+ # Output groups changes by artifact kind (preference, retired,
+ # signal, log, config, other) and by mode (added, removed, modified).
+ # Exit code 0 even when the diff is empty.
+```
+
+`snapshot` becomes a new sub-namespace under `brain`. Today it carries
+only `diff`; future `snapshot list / show / verify` slots in here. The
+flat alternative (`o2b brain snapshot-diff`) is consciously rejected.
+
+### 3.2 Module layout
+
+| file | role |
+|---|---|
+| `src/core/brain/snapshot.ts` (existing) | + `extractSnapshotToTemp(vault, runId): { tmpRoot, brainRoot, cleanup }`. Pure extraction step pulled out of `restoreSnapshot` (lines 452โ€“520 today). `restoreSnapshot` rewires to call it. No behaviour change to existing callers โ€” verified by snapshotting the rollback test fixtures. |
+| `src/core/brain/snapshot-diff.ts` (new) | `diffBrainTrees(rootA: string, rootB: string): BrainTreeDiff`. Walks the two roots, classifies each top-level entry under `Brain/` (except `.snapshots/`), reads frontmatter for `preferences/*.md` and `retired/*.md` and computes a typed field diff for the canonical set (`_status`, `_applied_count`, `_violated_count`, `_confidence`, `_confidence_value`, `pinned`). Signals, logs, config, and other files compare by byte equality (no semantic diff). No I/O beyond `readFileSync` + `readdirSync`. |
+| `src/core/brain/snapshot-diff-render.ts` (new) | Two pure renderers: `renderDiffMarkdown(diff): string`, `renderDiffJson(diff): unknown`. Markdown rendering uses `renderPrefLink` from ยง27 once that lands. |
+| `src/cli/brain.ts` | + `cmdBrainSnapshotDiff`, `--dry-run` in `cmdBrainRollback`. Helptext, usage matrix. |
+
+### 3.3 Types
+
+```ts
+export interface BrainTreeDiff {
+ readonly added: ReadonlyArray<BrainTreeEntry>;
+ readonly removed: ReadonlyArray<BrainTreeEntry>;
+ readonly modified: ReadonlyArray<BrainTreeChange>;
+}
+
+export interface BrainTreeEntry {
+ readonly kind: "preference" | "retired" | "signal" | "log" | "config" | "other";
+ readonly path: string; // vault-relative
+ readonly id?: string; // pref-/ret-/sig- when applicable
+}
+
+export interface BrainTreeChange {
+ readonly entry: BrainTreeEntry;
+ readonly fields: ReadonlyArray<BrainFieldChange>; // empty when only body changed
+ readonly bodyChanged: boolean;
+}
+
+export interface BrainFieldChange {
+ readonly field: string; // e.g. "_status", "_applied_count"
+ readonly before: string | number | boolean | null;
+ readonly after: string | number | boolean | null;
+}
+```
+
+### 3.4 Output format
+
+Markdown shape (stable, doctor-style; safe to grep):
+
+```markdown
+# Brain snapshot diff
+
+- A: 2026-05-17T03-00-00Z (run-2026-05-17-03)
+- B: live (or 2026-05-18T03-00-00Z)
+
+## Preferences
+- + pref-no-internal-abbrev (added)
+- - pref-stale-rule (removed)
+- ~ pref-no-trailing-comma:
+ - _status: confirmed โ†’ quarantine
+ - _applied_count: 4 โ†’ 7
+ - _violated_count: 0 โ†’ 3
+
+## Retired
+- + ret-stale-rule (removed; reason: stale-no-evidence)
+
+## Signals
+- + sig-2026-05-18-foo (added)
+
+## Logs
+- ~ Brain/log/2026-05-18.md (body changed)
+
+## Config / Other
+- (no changes)
+```
+
+JSON shape is the literal `BrainTreeDiff` serialisation.
+
+### 3.5 Logging
+
+`rollback --dry-run` and `snapshot diff` are read-only and **do not**
+append to `Brain/log/`. This matches `digest` and `query`.
+
+### 3.6 Tests
+
+- `tests/core/brain.snapshot-diff.test.ts` โ€” fixture-driven: two pre-built
+ Brain trees on disk, expected `BrainTreeDiff`. Covers add/remove/modify
+ for each artifact kind, ordering stability, byte-equal short-circuit.
+- `tests/cli/brain.snapshot-diff.test.ts` โ€” CLI invocation, markdown vs
+ `--json`, mutual-exclusion `--dry-run` ร— `--yes`, missing run_id exit 2.
+- Existing `tests/core/brain.snapshot.test.ts` โ€” assert
+ `extractSnapshotToTemp` extraction matches the previous inline path
+ byte-for-byte (regression net).
+
+## 4. ยง10 โ€” Numeric confidence
+
+### 4.1 Frontmatter shape
+
+Preferences and retired files gain one new field:
+
+```yaml
+_confidence_value: 0.7413 # NEW โ€” primary, written by dream
+_confidence: medium # DERIVED โ€” kept for backwards-compat readers
+```
+
+Both are stored. Writer emits both. Parser tolerates either being absent
+on legacy files (lazy migration via the next refresh).
+
+### 4.2 Formula
+
+```text
+n = applied + violated
+
+if n == 0:
+ value = 0.0
+else:
+ p_hat = applied / n
+ z = 1.96 # 95 % one-sided lower confidence bound
+ denom = 1 + zยฒ / n
+ centre = (p_hat + zยฒ/(2n)) / denom
+ margin = z * sqrt(p_hat*(1 - p_hat)/n + zยฒ/(4nยฒ)) / denom
+ wilson_low = max(0, centre - margin)
+
+ if last_evidence_at is null:
+ freshness = 0.0
+ else:
+ age_days = (now - last_evidence_at) / 1 day
+ freshness = clamp(1 - age_days / cfg.retire.stale_evidence_days, 0, 1)
+
+ value = round(wilson_low * freshness, 4) # 4 decimals โ€” stable in YAML
+```
+
+### 4.3 Band derivation
+
+```text
+band(value) =
+ cfg.confidence.high_min โ‰ค value โ†’ high
+ cfg.confidence.medium_min โ‰ค value < high_min โ†’ medium
+ value < medium_min โ†’ low
+```
+
+Then the existing count-based hard floors override the numeric band:
+
+```text
+if applied โ‰ค cfg.confidence.low_max_applied โ†’ low
+if applied > 0 โˆง violated โ‰ฅ applied โ†’ low
+if applied < cfg.confidence.high_min_applied
+ โˆจ violated > 0
+ โˆจ ยฌfresh โ†’ at most medium
+```
+
+The numeric value is **always** the Wilson * freshness product (it does
+not get clamped by the hard floors); only the **derived band** is
+adjusted by them. This preserves the contract that agents (reading
+band) keep their existing semantics, while the value remains a clean
+continuous signal for the digest and future tuning work.
+
+### 4.4 `_brain.yaml` configuration
+
+```yaml
+confidence:
+ # Existing โ€” keep, they drive hard-floor band rules and the legacy
+ # freshness window used inside computeConfidence.
+ low_max_applied: 2
+ high_min_applied: 10
+ high_freshness_factor: 0.8
+ # NEW โ€” derived band thresholds on the numeric value.
+ medium_min: 0.40
+ high_min: 0.75
+```
+
+Constraints validated by `policy.ts`:
+
+```text
+0 โ‰ค medium_min < high_min โ‰ค 1
+```
+
+Defaults (`DEFAULT_BRAIN_CONFIG`, `DEFAULT_BRAIN_CONFIG_YAML`) populate
+the two new keys. Unknown keys remain forward-compat (warning, not
+error).
+
+### 4.5 Migration
+
+- Parser accepts both shapes: legacy (no `_confidence_value`), new
+ (both present). On `_confidence_value` absent โ†’ `confidence_value:
+ null` on the parsed object. Public type widens
+ (`confidence_value: number | null`).
+- Writer always emits both fields, computed via the formula. Dream's
+ refresh pass touches every pref every run; `wouldRewritePreference`
+ already short-circuits on byte equality, so legacy files get the new
+ field on the next refresh.
+- No explicit `migrate-frontmatter` extension. The mechanism that lands
+ `_confidence_value` is the same one that lands the band shift today.
+
+### 4.6 Digest: confidence drops
+
+Within a single dream run, the refresh phase already builds a
+`RefreshResult` containing the old + new pref records. Capture the
+band transition and surface in the digest:
+
+```markdown
+## Confidence drops
+
+- pref-no-internal-abbrev: high โ†’ medium (applied=11, violated=2)
+- pref-old-rule: medium โ†’ low (applied=3, violated=4)
+```
+
+Rendered only when the list is non-empty.
+
+### 4.7 Code touchpoints
+
+| file | change |
+|---|---|
+| `src/core/brain/types.ts` | `BrainPreference.confidence_value: number \| null`; `BrainRetired.confidence_value: number \| null`; `BrainConfidenceConfig.medium_min: number`, `high_min: number`. |
+| `src/core/brain/policy.ts` | `DEFAULT_BRAIN_CONFIG.confidence` adds new keys; `DEFAULT_BRAIN_CONFIG_YAML` adds two lines; validator checks the `[0, 1]` bounds and ordering. |
+| `src/core/brain/preference.ts` | `WritePreferenceInput.confidence_value?: number`; writer emits `_confidence_value`; parser reads both. `moveToRetired` propagates the field into retired frontmatter. |
+| `src/core/brain/dream.ts` | `computeConfidence` returns `{ value: number, band: BrainConfidence }`; refresh writes both; drop-tracking added to `RefreshResult`. |
+| `src/core/brain/digest.ts` | New `## Confidence drops` section; reads the band transitions list passed from `dream`. |
+| `src/mcp/brain-tools.ts` | `brain_query` JSON output includes `confidence_value` alongside `confidence`. |
+| `src/core/brain/active.ts` | Active list and Quarantine list โ€” append a numeric tail to each pref bullet, format `(conf: 0.74)`. In scope for this PR. |
+| Tests | `tests/core/brain.dream.test.ts` (Wilson outputs, freshness decay edge cases, hard-floor interaction), `tests/core/brain.digest.test.ts` (drops section), parser tolerance test, policy validation test. |
+
+### 4.8 MCP shape
+
+`brain_query` adds `confidence_value: number | null` next to the
+existing `confidence: 'low' | 'medium' | 'high'`. Older agents that
+read only `confidence` are unaffected. The change is additive on the
+JSON contract.
+
+## 5. ยง21 โ€” Cross-project pointer + primary agent
+
+### 5.1 `_brain.yaml` field
+
+```yaml
+primary_agent: hermes-vps-agent # OR ~ / null when unset
+```
+
+Validation: either `null` or a non-empty string matching the same
+charset as `agent_name` elsewhere in the codebase (reuse the existing
+validator).
+
+### 5.2 CLI surface
+
+```text
+o2b brain init [--primary-agent <name>] [...existing flags]
+ # Writes primary_agent into the fresh _brain.yaml. On already-
+ # initialised vault โ†’ no-op (matches existing brain init contract).
+
+o2b brain set-primary <name> [--vault <path>] [--json]
+ # Idempotent edit of Brain/_brain.yaml: replaces the primary_agent
+ # line. Re-run with same value โ†’ exits 0 with "primary already
+ # set to <name>". Re-run with new value โ†’ overwrites, prints
+ # "primary changed: <prev> โ†’ <next>".
+
+o2b brain set-primary --clear [--vault <path>] [--json]
+ # Sets primary_agent: null. For vaults that want to back out.
+```
+
+No MCP equivalent.
+
+### 5.3 Dream soft warning
+
+After `loadBrainConfig` and before any writes in `dream.ts`:
+
+```ts
+if (cfg.primary_agent != null && cfg.primary_agent !== agentName) {
+ warnings.push({
+ code: "non-primary-dream-run",
+ message:
+ `dream run from agent '${agentName}', but primary is ` +
+ `'${cfg.primary_agent}'. Convention violation โ€” the run will ` +
+ `proceed.`,
+ });
+}
+```
+
+CLI prints warnings to `stderr`. MCP includes them in the
+`warnings: string[]` array of the `brain_dream` response (already
+exists for snapshot-tooling warnings โ€” same channel).
+
+Log event for the dream run gains an optional `non_primary_agent: <name>`
+payload key whenever the warning fires. Read path of existing
+`BrainDreamLogEvent` accepts this key in the payload union without a
+schema bump (payload is already `Record<string, string | string[]>`).
+
+### 5.4 Documentation
+
+- `docs/cross-project-pointer.md` (new). Three sections:
+ 1. **Where to put the snippet** โ€” CLAUDE.md, AGENTS.md, Cursor rules,
+ Aider conventions. One canonical snippet (managed-block-style fences
+ so a future `o2b brain bootstrap` can patch them):
+
+ ```text
+ # >>> open-second-brain managed >>>
+ ## Open Second Brain
+
+ This project shares an Obsidian-compatible vault with an active
+ observing-memory layer. At session start, read the current
+ preferences:
+
+ <absolute-vault-path>/Brain/active.md
+
+ Record taste signals via `brain_feedback` (MCP) or
+ `o2b brain feedback` (CLI). After producing a durable artifact,
+ call `brain_apply_evidence` with `result: applied | violated |
+ outdated` for any preference whose `scope` matches.
+
+ Do not run `o2b brain dream` from this runtime. The vault has a
+ primary dream-running agent; see `<vault>/Brain/_brain.yaml`
+ (key `primary_agent`).
+ # <<< open-second-brain managed <<<
+ ```
+ 2. **Primary agent and dream-cron** โ€” what `primary_agent` is, the
+ `o2b brain set-primary` invocation, what the non-primary warning
+ looks like, what is *not* restricted (signal capture, pin/unpin,
+ reject โ€” all stay multi-host).
+ 3. **Multi-device through Syncthing** โ€” note that the vault is
+ designed to be Syncthing-shared, signals come from any host,
+ dream consolidates them on the primary host's cron.
+- README โ€” add **Cross-project setup** subsection that points to the
+ new doc. No content duplication.
+- `install.md` Branch A (Hermes) โ€” add a recommendation in the `o2b init`
+ step: `--primary-agent <agent-name>` when this Hermes install is
+ intended to own dream.
+
+### 5.5 Code touchpoints
+
+| file | change |
+|---|---|
+| `src/core/brain/types.ts` | `BrainConfig.primary_agent: string \| null`. |
+| `src/core/brain/policy.ts` | Parser accepts quoted/unquoted strings + `null`; validator enforces non-empty string or `null`; `DEFAULT_BRAIN_CONFIG.primary_agent = null`; default YAML adds the line as `primary_agent: null`. |
+| `src/core/brain/init.ts` | Accepts `primaryAgent: string \| null`; writes into the scaffolded YAML. |
+| `src/core/brain/set-primary.ts` (new) | `setPrimaryAgent(vault, name \| null): { previous, next, changed }`. Reads YAML, replaces the line via the same atomic writer as `migrate-frontmatter`. |
+| `src/core/brain/dream.ts` | Emits the non-primary warning and the log-event payload key. |
+| `src/cli/brain.ts` | `cmdBrainSetPrimary`; `cmdBrainInit` honours `--primary-agent`; helptext, usage. |
+| `src/cli/main.ts` | Pass-through if `o2b init` (vault-level) is responsible for bootstrapping Brain. |
+| Tests | `tests/core/brain.set-primary.test.ts`, `tests/core/brain.dream.non-primary.test.ts`, parser/validator unit tests, CLI integration. |
+
+## 6. ยง27 โ€” Titled wikilinks for preferences
+
+### 6.1 Helper
+
+In `src/core/brain/wikilink.ts`:
+
+```ts
+export const MAX_PREF_LINK_TITLE_LEN = 80;
+
+export function renderPrefLink(input: {
+ id: string;
+ principle?: string;
+}): string;
+```
+
+Algorithm:
+
+1. NFC-normalise principle; replace `\r\n?` with `\n`; collapse all
+ whitespace runs to a single space; trim.
+2. Replace each of `[`, `]`, `|` with a single space; re-collapse +
+ trim.
+3. If empty โ†’ return `[[${id}]]`.
+4. If length > `MAX_PREF_LINK_TITLE_LEN`: truncate to the limit; back
+ off to the previous word boundary if the cut lands inside a word;
+ append `โ€ฆ` (U+2026, single character).
+5. Return `[[${id}|${title}]]`.
+
+### 6.2 Call-site rewrite
+
+Every Brain writer that emits a preference or retired wikilink calls
+`renderPrefLink`. Bare `[[pref-id]]` strings are not allowed in new
+code (lint rule deferred โ€” manual review during this PR).
+
+| site | current | becomes |
+|---|---|---|
+| `active.ts` โ€” Active / Quarantine sections | `[[pref-id]]` | `[[pref-id\|principle]]` |
+| `digest.ts` โ€” newly-confirmed, retired, hot, drops, quarantine | `[[pref-id]]` / `[[ret-id]]` | titled |
+| `dream.ts` โ€” log payload `preference: ...`, `retired: ...`, `superseded_by: ...` | bare | titled |
+| `apply-evidence.ts` โ€” `preference: [[pref-id]]` log entry | bare | titled |
+| `preference.ts moveToRetired` โ€” `superseded_by` frontmatter, `## Origin` references to a pref | bare | titled |
+| `backlinks.ts` โ€” inbound reference output (CLI + render layer) | bare | titled |
+| `cli/brain.ts cmdBrainBacklinks`, `cmdBrainQuery` human output | bare | titled |
+
+Not touched (signals + external artifacts have no useful title source):
+
+- `evidenced_by` (lists signals).
+- `apply-evidence.artifact` (external vault files).
+- `BrainSignal.source` (external links).
+
+### 6.3 Parsers + readers
+
+No changes. `normaliseWikilinkTarget` and `parseWikilink` already strip
+`|alias` (`wikilink.ts:60-67`). Brain doctor's wikilink resolution and
+`brain_query`'s pref-id matching keep working byte-for-byte.
+
+### 6.4 MCP shape
+
+JSON output remains structured (`{ id, principle, ... }`). MCP clients
+that render their own markdown can call the equivalent of
+`renderPrefLink` themselves; the server stays format-neutral.
+
+### 6.5 Tests
+
+- `tests/core/brain.wikilink.test.ts` โ€” unit table for `renderPrefLink`:
+ empty principle, characters needing sanitisation, exactly-at-limit,
+ past-limit-with-word-boundary, past-limit-no-space (hard cut), unicode
+ in title.
+- Update existing snapshot assertions in `tests/core/brain.active.test.ts`,
+ `tests/core/brain.digest.test.ts`, `tests/core/brain.dream.test.ts`,
+ `tests/core/brain.apply-evidence.test.ts`, `tests/core/brain.backlinks.test.ts`
+ to expect the titled form.
+
+## 7. CHANGELOG outline (one PR, one version)
+
+Target version: next minor or patch after `v0.10.2` โ€” picked by the
+release step, **not** baked into this design. CHANGELOG section
+structure:
+
+```markdown
+## [<next version>] - <date stamped at release time>
+
+Brings Tier-A items ยง5, ยง10, ยง21, ยง27 of
+`Projects/OpenSecondBrain/Features/_summary` โ€ฆ
+
+### Added
+- `o2b brain snapshot diff`, `o2b brain rollback --dry-run`
+- `_confidence_value` on every preference / retired file โ€ฆ
+- `Brain/_brain.yaml.primary_agent`, `o2b brain set-primary`,
+ non-primary dream-run warning
+- `renderPrefLink` and titled wikilink emission across every Brain
+ writer
+- `docs/cross-project-pointer.md`
+
+### Changed
+- `_brain.yaml.confidence` adds `medium_min`, `high_min` keys
+- `dream` refresh writes `_confidence_value`; legacy files migrate
+ lazily on the next refresh
+- README โ€” Cross-project setup subsection
+- install.md branch A โ€” `--primary-agent` recommendation
+
+### Notes
+- No vault migration required โ€ฆ
+```
+
+Per the project's "one PR = one CHANGELOG version" rule
+(`Brain/preferences/`), every entry in this bundle goes under the
+**same** version header โ€” no mid-PR version bumps.
+
+## 8. Implementation order
+
+ยงยง27, 21, 10, 5 are mostly independent. The ordering below is a
+suggestion to the writing-plans phase, not a constraint:
+
+1. **ยง27 first.** It adds one new helper plus a sweep of call-site
+ edits. Once landed, the rest of the bundle uses `renderPrefLink`
+ from the moment they are written, so no second sweep is needed.
+2. **ยง21 next.** Self-contained; touches `_brain.yaml` schema, init,
+ set-primary CLI, dream warning channel, and the new doc.
+3. **ยง10 next.** Schema (`_brain.yaml.confidence`, frontmatter
+ `_confidence_value`), dream's `computeConfidence`, digest drops
+ section. Depends on ยง27 only insofar as the digest section emits
+ pref wikilinks via `renderPrefLink`.
+4. **ยง5 last.** Pure read-only inspector + dry-run preview. Uses
+ `renderPrefLink` for its markdown renderer. Depends on ยง27 for the
+ renderer and on ยง10 if we want to surface
+ `_confidence_value` changes in modified-field listings (we do โ€” the
+ diff is more useful with it).
+
+## 9. Open invariants worth re-checking during implementation
+
+These exist today and must survive the bundle:
+
+- Brain writers go through `writeFrontmatterAtomic`; nothing in this
+ bundle introduces a non-atomic write.
+- `wouldRewritePreference` short-circuit on byte equality is intact.
+ Adding `_confidence_value` will trigger a one-time rewrite per pref;
+ subsequent refresh runs settle back to no-op when values are stable.
+- `Brain/.snapshots/` is preserved across rollback โ€” `extractSnapshotToTemp`
+ refactor must not regress this.
+- MCP-facing brain_query JSON shape stays additive (no removals, no
+ renames).
+- Public `BrainConfig`, `BrainPreference`, `BrainRetired` types widen
+ only with optional / nullable fields. No required-field additions.
diff --git a/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-impl.md b/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-impl.md
new file mode 100644
index 00000000..7f68c04d
--- /dev/null
+++ b/docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-impl.md
@@ -0,0 +1,2547 @@
+# Tier-A bundle Implementation Plan
+
+> **For agentic workers:** Use `superpowers:executing-plans` (or
+> `superpowers:subagent-driven-development` for fresh-context-per-task
+> dispatch) to walk this plan task-by-task. Steps use checkbox
+> (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship Tier-A items ยง5 (snapshot diff + rollback dry-run),
+ยง10 (numeric confidence + derived band), ยง21 (cross-project pointer
++ primary agent), ยง27 (titled wikilinks for prefs) of
+`Projects/OpenSecondBrain/Features/_summary` in one PR.
+
+**Architecture:** Four mostly-independent slices land in dependency
+order. ยง27 is the only one that touches every other slice: it adds
+the `renderPrefLink` helper that ยง21, ยง10, ยง5 all consume in their
+rendered output. The remaining three slices are orthogonal in code
+terms โ€” each owns a separate sub-tree under `src/core/brain/` and
+`src/cli/`.
+
+- **ยง27** lives in `wikilink.ts` (new helper) and sweeps every Brain
+ writer that emits a preference / retired wikilink.
+- **ยง21** adds one field to `Brain/_brain.yaml`, one CLI verb
+ (`set-primary`), a non-fatal dream-warning channel, and one new
+ documentation file.
+- **ยง10** widens `BrainPreference` / `BrainRetired` with one numeric
+ field, extends `_brain.yaml.confidence` with two new thresholds,
+ reworks `computeConfidence` in `dream.ts`, and threads the new
+ signal through digest + active + MCP.
+- **ยง5** refactors the snapshot extraction step out of
+ `restoreSnapshot`, adds a pure `diffBrainTrees` walker plus its
+ markdown / JSON renderer, and exposes two new CLI surfaces
+ (`o2b brain rollback --dry-run`, `o2b brain snapshot diff`).
+
+**Tech Stack:** TypeScript on Bun. No new external dependencies.
+Re-uses `proper-lockfile`, `fs-atomic.ts`, `snapshot.ts`,
+`writeFrontmatterAtomic`, `appendLogEvent` from existing code.
+
+**Source of truth for behaviour:**
+[`docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-design.md`](./2026-05-17-tier-a-snapshot-confidence-pointer-design.md).
+Every task below implements a slice of that spec โ€” on conflict the
+spec wins and the plan is amended.
+
+---
+
+## Plan-wide conventions
+
+These apply to every task; do not re-state per step.
+
+- **Imports.** Production code uses `node:`-prefixed builtins
+ (`node:fs`, `node:crypto`, `node:path`). Tests use
+ `import { test, expect, describe, beforeEach, afterEach } from "bun:test"`.
+ Always `.ts` extensions in imports.
+- **Result shape.** Public-API return values are `Object.freeze`-d at
+ the producing call site (project convention, mirrors
+ `src/core/brain/query.ts`).
+- **Errors.** Reuse existing typed error classes
+ (`BrainSnapshotError`, `BrainConfigError`, `CliError`). New typed
+ errors only when a new failure shape needs distinct catch-handling
+ (none expected for this bundle).
+- **No git from this plan.** Each task ends with **Pause for review
+ (no commit).** The user (Sergey) does all git work themselves โ€”
+ this project's `Brain/preferences/` has an active rule against
+ active git from the agent.
+- **No bait fallbacks.** New CLI flags exit 2 with an explicit message
+ rather than silently fall through. Wilson formula at `n == 0` returns
+ `value = 0.0` (honest, not derived).
+- **Atomic writes** via `src/core/fs-atomic.ts:atomicWriteFileSync`.
+ In-place YAML edits hold the same lock pattern as `migrate-frontmatter`
+ (`proper-lockfile.lock(path, { retries: 3, factor: 2 })`).
+- **Brain log events.** Use the existing `appendLogEvent` writer; only
+ add new `BrainLogEventKind` constants when the event has a
+ payload-key set that warrants type narrowing (none in this bundle โ€”
+ ยง21's warning rides on the existing `dream` event payload).
+- **Verification.** Every task ends with `bun test tests/path/to/file.test.ts`
+ and an expected pass count. End of every Phase: full
+ `bun test` + `bun run typecheck` green. CHANGELOG is touched
+ exactly once, in Phase 5.
+- **Style preferences.** Active Brain rules at the time of writing:
+ no exclamation marks in technical prose
+ ([[pref-no-exclamation-marks-in-docs]]), no use of `simply`
+ ([[pref-no-simply-word]]). Both extend to test descriptions and
+ CHANGELOG copy.
+
+## File map
+
+Create:
+
+```
+src/core/brain/snapshot-diff.ts โ€” pure diffBrainTrees(rootA, rootB)
+src/core/brain/snapshot-diff-render.ts โ€” renderDiffMarkdown, renderDiffJson
+src/core/brain/set-primary.ts โ€” setPrimaryAgent(vault, name|null)
+docs/cross-project-pointer.md โ€” agent-facing pointer doc + snippet + primary-agent guidance
+tests/core/brain.wikilink.test.ts โ€” renderPrefLink unit (extends existing wikilink coverage)
+tests/core/brain.snapshot-diff.test.ts โ€” diffBrainTrees fixture-driven
+tests/core/brain.snapshot-diff-render.test.ts โ€” render snapshot tests
+tests/core/brain.set-primary.test.ts โ€” setPrimaryAgent unit
+tests/core/brain.dream.non-primary.test.ts โ€” dream-warning channel
+tests/core/brain.confidence-value.test.ts โ€” Wilson + freshness + hard-floor interaction
+tests/cli/brain.snapshot-diff.test.ts โ€” CLI snapshot diff + rollback --dry-run
+tests/cli/brain.set-primary.test.ts โ€” CLI set-primary
+tests/e2e/brain-tier-a-bundle.test.ts โ€” end-to-end chain through every new surface
+```
+
+Modify:
+
+```
+src/core/brain/wikilink.ts โ€” renderPrefLink + MAX_PREF_LINK_TITLE_LEN
+src/core/brain/active.ts โ€” call sites: pref/retired link emission
+src/core/brain/digest.ts โ€” call sites + new "## Confidence drops" section
+src/core/brain/dream.ts โ€” log payload link emission; computeConfidence โ†’ {value, band}; refresh tracks previous band; non-primary warning channel
+src/core/brain/apply-evidence.ts โ€” log entry uses renderPrefLink
+src/core/brain/preference.ts โ€” moveToRetired retired-body links; writer emits _confidence_value; parser tolerates both shapes
+src/core/brain/backlinks.ts โ€” output uses renderPrefLink (if it renders)
+src/core/brain/snapshot.ts โ€” extract extractSnapshotToTemp helper; restoreSnapshot rewires to call it
+src/core/brain/types.ts โ€” BrainConfig.primary_agent; BrainConfidenceConfig adds medium_min, high_min; BrainPreference/BrainRetired add confidence_value
+src/core/brain/policy.ts โ€” parser+validator+DEFAULT_BRAIN_CONFIG_YAML for primary_agent + new confidence thresholds
+src/core/brain/init.ts โ€” accept primaryAgent in scaffold
+src/cli/brain.ts โ€” flag wiring (`--primary-agent` on init), new verbs (`set-primary`, `snapshot diff`), `--dry-run` on rollback, VERB_HELP entries, dispatch
+src/cli/main.ts โ€” pass-through for `--primary-agent` on `o2b init` if it bootstraps Brain
+src/mcp/brain-tools.ts โ€” brain_query JSON includes confidence_value; brain_dream surfaces warnings array
+README.md โ€” Cross-project setup subsection, CLI table extension
+docs/how-it-works.md โ€” snapshot diff family, numeric confidence, primary_agent paragraph
+install.md โ€” Branch A (Hermes): --primary-agent recommendation
+CHANGELOG.md โ€” single new version section (added/changed/notes)
+package.json โ€” version bump via `bun run sync-version`
+pyproject.toml โ€” version bump via sync
+```
+
+---
+
+## Phase 1 โ€” ยง27 Titled wikilinks (foundation)
+
+ยง27 must land first because every other phase emits new log payloads
+or markdown using `renderPrefLink`. Implementing it later forces a
+second sweep.
+
+### Task 1: `renderPrefLink` helper
+
+**Files:**
+- Modify: `src/core/brain/wikilink.ts`
+- Test: `tests/core/brain.wikilink.test.ts`
+
+- [ ] **Step 1: Failing test for the unit table**
+
+Add to `tests/core/brain.wikilink.test.ts`:
+
+```ts
+import { test, expect } from "bun:test";
+import {
+ MAX_PREF_LINK_TITLE_LEN,
+ renderPrefLink,
+} from "../../src/core/brain/wikilink.ts";
+
+test("renderPrefLink renders bare id when principle missing", () => {
+ expect(renderPrefLink({ id: "pref-foo" })).toBe("[[pref-foo]]");
+});
+
+test("renderPrefLink renders titled link for non-empty principle", () => {
+ expect(
+ renderPrefLink({ id: "pref-foo", principle: "Prefer the calm option" }),
+ ).toBe("[[pref-foo|Prefer the calm option]]");
+});
+
+test("renderPrefLink strips wikilink-breaking characters", () => {
+ expect(
+ renderPrefLink({ id: "pref-foo", principle: "Use [brackets] | here" }),
+ ).toBe("[[pref-foo|Use brackets here]]");
+});
+
+test("renderPrefLink collapses internal whitespace and trims", () => {
+ expect(
+ renderPrefLink({ id: "pref-foo", principle: " a\n\tb c " }),
+ ).toBe("[[pref-foo|a b c]]");
+});
+
+test("renderPrefLink falls back to bare id when sanitised title is empty", () => {
+ expect(renderPrefLink({ id: "pref-foo", principle: "[]|" })).toBe(
+ "[[pref-foo]]",
+ );
+});
+
+test("renderPrefLink truncates at word boundary with ellipsis", () => {
+ const long =
+ "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen";
+ const link = renderPrefLink({ id: "pref-foo", principle: long });
+ expect(link.startsWith("[[pref-foo|")).toBe(true);
+ expect(link.endsWith("โ€ฆ]]")).toBe(true);
+ const titleLen = link.slice("[[pref-foo|".length, -"]]".length).length;
+ // ellipsis counts as one char; truncation cap is MAX_PREF_LINK_TITLE_LEN
+ expect(titleLen).toBeLessThanOrEqual(MAX_PREF_LINK_TITLE_LEN + 1);
+});
+
+test("renderPrefLink hard-cuts when no word boundary fits", () => {
+ const oneLongWord = "x".repeat(MAX_PREF_LINK_TITLE_LEN + 20);
+ const link = renderPrefLink({ id: "pref-foo", principle: oneLongWord });
+ expect(link).toBe(`[[pref-foo|${"x".repeat(MAX_PREF_LINK_TITLE_LEN)}โ€ฆ]]`);
+});
+
+test("renderPrefLink works for retired ids", () => {
+ expect(
+ renderPrefLink({ id: "ret-bar", principle: "Old rule" }),
+ ).toBe("[[ret-bar|Old rule]]");
+});
+```
+
+- [ ] **Step 2: Run to verify failure**
+
+Run: `bun test tests/core/brain.wikilink.test.ts`
+Expected: FAIL with `Cannot find name 'renderPrefLink'`.
+
+- [ ] **Step 3: Implement in `wikilink.ts`**
+
+Append after `parseArtifactRef`:
+
+```ts
+/** Title length cap before truncation. Chosen for one-line Obsidian display. */
+export const MAX_PREF_LINK_TITLE_LEN = 80;
+
+/**
+ * Render a wikilink to a Brain preference or retired artifact with a
+ * human-readable title sourced from the `principle` field.
+ *
+ * The title is NFC-normalised, whitespace-collapsed, sanitised of
+ * wikilink-breaking characters (`[`, `]`, `|`), and truncated to
+ * MAX_PREF_LINK_TITLE_LEN at a word boundary (with an ellipsis suffix).
+ * Empty input after sanitisation falls back to the bare `[[id]]` form
+ * so the link stays resolvable.
+ *
+ * Used by every Brain writer that emits a pref/retired reference;
+ * signal and external-artifact wikilinks stay bare-id since they have
+ * no useful title source.
+ */
+export function renderPrefLink(input: {
+ readonly id: string;
+ readonly principle?: string;
+}): string {
+ const raw = input.principle ?? "";
+ let title = raw.normalize("NFC")
+ .replace(/\r\n?/g, "\n")
+ .replace(/[\[\]\|]/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (title.length === 0) return `[[${input.id}]]`;
+ if (title.length <= MAX_PREF_LINK_TITLE_LEN) return `[[${input.id}|${title}]]`;
+ // Truncate, then back off to the previous word boundary if any exists
+ // within the cap window.
+ let cut = title.slice(0, MAX_PREF_LINK_TITLE_LEN);
+ const lastSpace = cut.lastIndexOf(" ");
+ if (lastSpace > 0) cut = cut.slice(0, lastSpace);
+ return `[[${input.id}|${cut}โ€ฆ]]`;
+}
+```
+
+- [ ] **Step 4: Run to verify pass**
+
+Run: `bun test tests/core/brain.wikilink.test.ts`
+Expected: all 8 tests pass.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 2: Sweep `active.ts` call sites
+
+**Files:**
+- Modify: `src/core/brain/active.ts`
+- Test: `tests/core/brain.active.test.ts`
+
+- [ ] **Step 1: Update tests first**
+
+Find every existing assertion in `tests/core/brain.active.test.ts` that
+matches `[[pref-...]]` or `[[ret-...]]` on a preference/retired line
+inside the rendered `active.md`. Rewrite the expected substring to the
+titled form `[[pref-slug|principle]]`. Keep the bare form for any
+signal or external wikilink the test happens to cover.
+
+- [ ] **Step 2: Run to verify expected failures**
+
+Run: `bun test tests/core/brain.active.test.ts`
+Expected: FAIL โ€” assertions miss the new shape.
+
+- [ ] **Step 3: Implement**
+
+Locate the loop that builds the Active and Quarantine bullets. Replace
+the existing `${id}` interpolation in the wikilink position:
+
+```ts
+import { renderPrefLink } from "./wikilink.ts";
+
+// before: `- [[${pref.id}]] ...`
+// after: `- ${renderPrefLink({ id: pref.id, principle: pref.principle })} ...`
+```
+
+Apply the same change to the Recently-retired section if it renders
+retired-pref links (`{ id: retired.id, principle: retired.principle }`).
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.active.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 3: Sweep `digest.ts` call sites
+
+**Files:**
+- Modify: `src/core/brain/digest.ts`
+- Test: `tests/core/brain.digest.test.ts`
+
+- [ ] **Step 1: Update digest tests for the titled form**
+
+Same pattern as Task 2. Sections to touch: newly-confirmed prefs,
+newly-retired prefs, hot prefs, quarantined prefs, suppressed-signal
+listing (retired-pref wikilink). Verify with `grep -n '\[\[pref-' tests/core/brain.digest.test.ts`
+and `grep -n '\[\[ret-' tests/core/brain.digest.test.ts` first.
+
+- [ ] **Step 2: Verify failures**
+
+Run: `bun test tests/core/brain.digest.test.ts`
+Expected: FAIL on touched sections.
+
+- [ ] **Step 3: Implement**
+
+In each section's renderer, swap `[[${pref.id}]]` for
+`renderPrefLink({ id: pref.id, principle: pref.principle })`. Same for
+retired references (use the retired's snapshot `principle`).
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.digest.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 4: Sweep `dream.ts` log payloads
+
+**Files:**
+- Modify: `src/core/brain/dream.ts`
+- Test: `tests/core/brain.dream.test.ts`
+
+- [ ] **Step 1: Update dream tests**
+
+Sections affected (assert on `Brain/log/<date>.md` body): promote /
+retire / signal-suppressed events; refresh-with-superseded; pinned
+retain. Each event currently writes `preference: [[pref-id]]` or
+`retired: [[ret-id]]` in the bullet payload. Update assertions to
+expect the titled form sourced from the in-memory pref/retired record
+passed into the log writer.
+
+- [ ] **Step 2: Verify failures**
+
+Run: `bun test tests/core/brain.dream.test.ts`
+Expected: FAIL on touched assertions.
+
+- [ ] **Step 3: Implement**
+
+`dream.ts` already builds `BrainLogEntry` objects via the `body`
+record. Replace the inline `[[${id}]]` strings with the helper:
+
+```ts
+preference: renderPrefLink({ id: pref.id, principle: pref.principle }),
+```
+
+For retired references in the same payload, use the in-flight retired
+record's principle. For `superseded_by` in retire events, source from
+the newer preference being recorded.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.dream.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 5: Sweep `apply-evidence.ts` log payload
+
+**Files:**
+- Modify: `src/core/brain/apply-evidence.ts`
+- Test: `tests/core/brain.apply-evidence.test.ts`
+
+- [ ] **Step 1: Update tests**
+
+`apply-evidence` writes one bullet per call: `preference: [[pref-id]]`.
+Update the assertion to expect `[[pref-id|principle]]`.
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.apply-evidence.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+`appendApplyEvidence` already reads the target preference via
+`parsePreference` to validate it exists. Reuse the parsed object to
+render the link:
+
+```ts
+preference: renderPrefLink({ id: target.id, principle: target.principle }),
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.apply-evidence.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 6: Sweep `preference.ts moveToRetired` body and superseded_by
+
+**Files:**
+- Modify: `src/core/brain/preference.ts`
+- Test: `tests/core/brain.preference.test.ts` and any retired-body assertion in `tests/core/brain.body-hygiene.test.ts`
+
+- [ ] **Step 1: Update tests**
+
+Touch every assertion that expects bare `[[pref-...]]` or `[[ret-...]]`
+inside the rendered retired body or the `superseded_by` frontmatter
+line. The frontmatter writer for retired records the value via
+`writeFrontmatterAtomic`; YAML rendering of `[[id|title]]` works
+unquoted only if the title is wikilink-safe (no `:` immediately after
+`[[`). The sanitiser already removes `[`, `]`, `|`; titles never
+contain `:` adjacent to the opening bracket. Safe to emit unquoted.
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.preference.test.ts tests/core/brain.body-hygiene.test.ts`
+Expected: FAIL on touched assertions.
+
+- [ ] **Step 3: Implement**
+
+In `moveToRetired`:
+- Where `superseded_by` is set in the inherited frontmatter, replace
+ bare `[[${supersededByPref.id}]]` with the titled form (when a
+ superseding pref is provided).
+- In `renderRetiredBody`, the Origin / Recent applications /
+ Recent violations sections currently reference signals (bare-id is
+ correct) and the artifact (external, bare-id is correct). The
+ `## Retired` section may carry a `superseded_by` pointer โ€” render
+ it via `renderPrefLink` for consistency with the frontmatter.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.preference.test.ts tests/core/brain.body-hygiene.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 7: Sweep `backlinks.ts` + CLI human output
+
+**Files:**
+- Modify: `src/core/brain/backlinks.ts`, `src/cli/brain.ts`
+- Test: `tests/core/brain.backlinks.test.ts`, `tests/cli/brain.test.ts` (existing)
+
+- [ ] **Step 1: Update tests**
+
+In `backlinks.test.ts`, every assertion of the form `[[pref-...]]` or
+`[[ret-...]]` that came from the backlinks output (not from frontmatter
+parse round-trip) gains the titled form. In `tests/cli/brain.test.ts`,
+the `cmdBrainBacklinks` and `cmdBrainQuery` human-output assertions get
+the same treatment.
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.backlinks.test.ts tests/cli/brain.test.ts`
+Expected: FAIL on touched cases.
+
+- [ ] **Step 3: Implement**
+
+In `buildBacklinkIndex` (or its renderer wrapper): for every result row
+that points at a pref/retired, switch to `renderPrefLink`.
+
+In `src/cli/brain.ts`:
+- `cmdBrainBacklinks` โ€” when human (not `--json`) output prints a
+ preference target line, emit titled link.
+- `cmdBrainQuery` โ€” same treatment when the query result row carries a
+ pref/retired record.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.backlinks.test.ts tests/cli/brain.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 8: Phase 1 close
+
+- [ ] **Step 1: Full Brain suite**
+
+Run: `bun test tests/core/brain.*.test.ts`
+Expected: all green.
+
+- [ ] **Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: zero errors.
+
+**Pause for review (no commit).**
+
+---
+
+## Phase 2 โ€” ยง21 Cross-project pointer + primary agent
+
+### Task 9: Extend `BrainConfig` type
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+- Test: covered by Task 10 policy tests
+
+- [ ] **Step 1: Add field**
+
+In the `BrainConfig` interface (currently in `types.ts`):
+
+```ts
+export interface BrainConfig {
+ readonly schema_version: number;
+ readonly primary_agent: string | null; // NEW
+ readonly dream: BrainDreamConfig;
+ readonly retire: BrainRetireConfig;
+ readonly confidence: BrainConfidenceConfig;
+ readonly snapshots: BrainSnapshotsConfig;
+}
+```
+
+- [ ] **Step 2: Verify type errors surface**
+
+Run: `bun run typecheck`
+Expected: errors only in `policy.ts` (the validator still doesn't
+populate the field). Resolved in Task 10.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 10: `policy.ts` parser + validator + default YAML
+
+**Files:**
+- Modify: `src/core/brain/policy.ts`
+- Test: `tests/core/brain.policy.test.ts` (existing file in
+ `tests/core/` if present; otherwise create alongside)
+
+- [ ] **Step 1: Failing tests**
+
+```ts
+test("loadBrainConfig defaults primary_agent to null", () => {
+ const cfg = validateBrainConfig({ schema_version: 1 });
+ expect(cfg.primary_agent).toBeNull();
+});
+
+test("loadBrainConfig parses quoted primary_agent string", () => {
+ const cfg = validateBrainConfig({ schema_version: 1, primary_agent: "hermes-vps" });
+ expect(cfg.primary_agent).toBe("hermes-vps");
+});
+
+test("loadBrainConfig rejects empty string primary_agent", () => {
+ expect(() =>
+ validateBrainConfig({ schema_version: 1, primary_agent: "" }),
+ ).toThrow(/primary_agent/);
+});
+
+test("loadBrainConfig rejects non-string non-null primary_agent", () => {
+ expect(() =>
+ validateBrainConfig({ schema_version: 1, primary_agent: 42 }),
+ ).toThrow(/primary_agent/);
+});
+```
+
+- [ ] **Step 2: Run to fail**
+
+Run: `bun test tests/core/brain.policy.test.ts`
+Expected: FAIL โ€” primary_agent unknown to validator.
+
+- [ ] **Step 3: Implement**
+
+Update `DEFAULT_BRAIN_CONFIG`:
+
+```ts
+export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
+ schema_version: 1,
+ primary_agent: null,
+ dream: Object.freeze({ /* ... */ }),
+ // ...
+}) as BrainConfig;
+```
+
+Update `DEFAULT_BRAIN_CONFIG_YAML`:
+
+```yaml
+schema_version: 1
+
+# Optional. When set, dream runs from a different agent emit a
+# warning. 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
+ # ...
+```
+
+In `validateBrainConfigDetailed`, after parsing `schema_version` and
+before the dream block:
+
+```ts
+let primaryAgent: string | null = null;
+if ("primary_agent" in obj) {
+ const v = obj["primary_agent"];
+ if (v === null) {
+ primaryAgent = null;
+ } else if (typeof v === "string" && v.trim().length > 0) {
+ primaryAgent = v.trim();
+ } else {
+ throw new BrainConfigError(
+ `must be either null or a non-empty string; got ${describe(v)}`,
+ "primary_agent",
+ source,
+ );
+ }
+}
+```
+
+Then add `primaryAgent` to the assembled `config` object and to the
+known-keys set used by the unknown-key warning loop.
+
+Update `parseBrainYaml`'s scalar handler if needed so that
+`primary_agent: hermes-vps-agent` (unquoted) parses as the literal
+string `hermes-vps-agent` (current behaviour โ€” verify with one
+explicit test). Hyphens are already supported.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.policy.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 11: `init.ts` accepts `primaryAgent`
+
+**Files:**
+- Modify: `src/core/brain/init.ts`
+- Test: `tests/core/brain.init.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("bootstrapBrain writes primary_agent into _brain.yaml when provided", () => {
+ const result = bootstrapBrain(tmpVault, { primaryAgent: "hermes-vps" });
+ const yaml = readFileSync(brainConfigPath(tmpVault), "utf8");
+ expect(yaml).toMatch(/^primary_agent: hermes-vps$/m);
+});
+
+test("bootstrapBrain leaves primary_agent: null on fresh init by default", () => {
+ bootstrapBrain(tmpVault, {});
+ const yaml = readFileSync(brainConfigPath(tmpVault), "utf8");
+ expect(yaml).toMatch(/^primary_agent: null$/m);
+});
+
+test("bootstrapBrain re-run preserves primary_agent already set", () => {
+ bootstrapBrain(tmpVault, { primaryAgent: "hermes-vps" });
+ bootstrapBrain(tmpVault, {});
+ const yaml = readFileSync(brainConfigPath(tmpVault), "utf8");
+ expect(yaml).toMatch(/^primary_agent: hermes-vps$/m);
+});
+```
+
+- [ ] **Step 2: Verify failure**
+
+Run: `bun test tests/core/brain.init.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Widen `bootstrapBrain`'s options:
+
+```ts
+export interface BootstrapBrainOptions {
+ readonly primaryAgent?: string;
+ // ...existing options
+}
+```
+
+On a fresh init, render the template with the supplied value (default
+`null`). On re-run when `_brain.yaml` already exists, read it, replace
+the `primary_agent:` line only when a new value is explicitly passed,
+otherwise leave intact. The line-replace uses the same idempotent
+single-line edit pattern as `setPrimaryAgent` (Task 12).
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.init.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 12: `setPrimaryAgent` module
+
+**Files:**
+- Create: `src/core/brain/set-primary.ts`
+- Test: `tests/core/brain.set-primary.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+import { test, expect, beforeEach } from "bun:test";
+import { setPrimaryAgent } from "../../src/core/brain/set-primary.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = createTempVault();
+ bootstrapBrain(vault, {});
+});
+
+test("setPrimaryAgent writes a non-null value", () => {
+ const r = setPrimaryAgent(vault, "hermes-vps");
+ expect(r.previous).toBeNull();
+ expect(r.next).toBe("hermes-vps");
+ expect(r.changed).toBe(true);
+});
+
+test("setPrimaryAgent is idempotent on repeat", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = setPrimaryAgent(vault, "hermes-vps");
+ expect(r.previous).toBe("hermes-vps");
+ expect(r.next).toBe("hermes-vps");
+ expect(r.changed).toBe(false);
+});
+
+test("setPrimaryAgent --clear writes null", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = setPrimaryAgent(vault, null);
+ expect(r.next).toBeNull();
+});
+
+test("setPrimaryAgent throws on missing _brain.yaml", () => {
+ rmSync(brainConfigPath(vault));
+ expect(() => setPrimaryAgent(vault, "x")).toThrow(/config file/);
+});
+```
+
+- [ ] **Step 2: Verify failure**
+
+Run: `bun test tests/core/brain.set-primary.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+```ts
+import { existsSync, readFileSync } from "node:fs";
+import { brainConfigPath } from "./paths.ts";
+import { BrainConfigError, parseBrainYaml, validateBrainConfig } from "./policy.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+
+export interface SetPrimaryResult {
+ readonly previous: string | null;
+ readonly next: string | null;
+ readonly changed: boolean;
+}
+
+const LINE_RE = /^primary_agent:.*$/m;
+
+export function setPrimaryAgent(
+ vault: string,
+ name: string | null,
+): SetPrimaryResult {
+ const path = brainConfigPath(vault);
+ if (!existsSync(path)) {
+ throw new BrainConfigError(
+ "config file does not exist; run `o2b brain init` first",
+ null,
+ path,
+ );
+ }
+ const text = readFileSync(path, "utf8");
+ const parsed = parseBrainYaml(text);
+ validateBrainConfig({ ...parsed, primary_agent: name ?? null }, path); // strict re-validate
+ const cfg = validateBrainConfig(parsed, path);
+ const previous = cfg.primary_agent;
+ const nextValue = name ?? null;
+ if (previous === nextValue) {
+ return Object.freeze({ previous, next: nextValue, changed: false });
+ }
+ const line = nextValue === null
+ ? "primary_agent: null"
+ : `primary_agent: ${nextValue}`;
+ let updated: string;
+ if (LINE_RE.test(text)) {
+ updated = text.replace(LINE_RE, line);
+ } else {
+ // Insert after schema_version line, or prepend if absent.
+ const sv = /^schema_version:.*$/m;
+ updated = sv.test(text)
+ ? text.replace(sv, (m) => `${m}\n\n${line}`)
+ : `${line}\n\n${text}`;
+ }
+ atomicWriteFileSync(path, updated);
+ return Object.freeze({ previous, next: nextValue, changed: true });
+}
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.set-primary.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 13: CLI `cmdBrainSetPrimary` + `--primary-agent` on init
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Test: `tests/cli/brain.set-primary.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("o2b brain set-primary writes the agent name", async () => {
+ const exit = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault]);
+ expect(exit).toBe(0);
+ expect(readBrainYaml(vault)).toMatch(/^primary_agent: hermes-vps$/m);
+});
+
+test("o2b brain set-primary --clear writes null", async () => {
+ await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault]);
+ const exit = await runCli(["brain", "set-primary", "--clear", "--vault", vault]);
+ expect(exit).toBe(0);
+ expect(readBrainYaml(vault)).toMatch(/^primary_agent: null$/m);
+});
+
+test("o2b brain set-primary requires <name> or --clear", async () => {
+ const exit = await runCli(["brain", "set-primary", "--vault", vault]);
+ expect(exit).toBe(1);
+});
+
+test("o2b brain init --primary-agent threads value", async () => {
+ const exit = await runCli(["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"]);
+ expect(exit).toBe(0);
+ expect(readBrainYaml(vault)).toMatch(/^primary_agent: hermes-vps$/m);
+});
+```
+
+- [ ] **Step 2: Verify failure**
+
+Run: `bun test tests/cli/brain.set-primary.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In `src/cli/brain.ts`, add a new dispatcher case:
+
+```ts
+case "set-primary":
+ return cmdBrainSetPrimary(rest);
+```
+
+```ts
+async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ clear: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const cfg = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, cfg);
+ let name: string | null;
+ if (flags["clear"]) {
+ if (positional.length > 0) {
+ return fail("brain set-primary --clear takes no positional arg");
+ }
+ name = null;
+ } else {
+ if (positional.length < 1) {
+ return fail("brain set-primary requires <name> or --clear");
+ }
+ name = positional[0]!.trim();
+ if (name.length === 0) {
+ return fail("brain set-primary <name> must be non-empty");
+ }
+ }
+ let r;
+ try {
+ r = setPrimaryAgent(vault, name);
+ } catch (exc) {
+ return fail(`set-primary failed: ${(exc as Error).message ?? exc}`);
+ }
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(r) + "\n");
+ return 0;
+ }
+ if (!r.changed) {
+ ok(`primary_agent already set to ${r.next ?? "null"}`);
+ } else {
+ ok(`primary_agent: ${r.previous ?? "null"} โ†’ ${r.next ?? "null"}`);
+ }
+ return 0;
+}
+```
+
+Extend `cmdBrainInit` to accept `--primary-agent <name>` and thread it
+into `bootstrapBrain({ primaryAgent: flags["primary-agent"] as string | undefined })`.
+
+Add VERB_HELP entry:
+
+```ts
+"set-primary":
+ "usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
+ " o2b brain set-primary --clear [--vault <path>] [--json]\n" +
+ "Set or clear the vault's primary dream-running agent.\n",
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/cli/brain.set-primary.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 14: Non-primary dream warning
+
+**Files:**
+- Modify: `src/core/brain/dream.ts`
+- Test: `tests/core/brain.dream.non-primary.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("dream emits a non-primary warning when agent differs", async () => {
+ bootstrapBrain(vault, {});
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = await dream(vault, { agentName: "claude-vps-agent", now });
+ expect(r.warnings.map(w => w.code)).toContain("non-primary-dream-run");
+ expect(r.warnings.find(w => w.code === "non-primary-dream-run")!.message).toMatch(/claude-vps-agent.*hermes-vps/);
+});
+
+test("dream does not warn when primary_agent matches", async () => {
+ bootstrapBrain(vault, {});
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = await dream(vault, { agentName: "hermes-vps", now });
+ expect(r.warnings.map(w => w.code)).not.toContain("non-primary-dream-run");
+});
+
+test("dream does not warn when primary_agent is null (default)", async () => {
+ bootstrapBrain(vault, {});
+ const r = await dream(vault, { agentName: "anyone", now });
+ expect(r.warnings.map(w => w.code)).not.toContain("non-primary-dream-run");
+});
+
+test("dream log event carries non_primary_agent payload when warning fires", async () => {
+ bootstrapBrain(vault, {});
+ setPrimaryAgent(vault, "hermes-vps");
+ await dream(vault, { agentName: "claude-vps-agent", now });
+ const logText = readTodayLog(vault);
+ expect(logText).toMatch(/^- non_primary_agent: claude-vps-agent$/m);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.dream.non-primary.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+`DreamResult` already exposes a `warnings: ReadonlyArray<โ€ฆ>` slot
+(used by snapshot-tooling missing-binary warnings). Add a new code
+constant if needed; otherwise use a free-form `{ code, message }`
+pair consistent with existing warning shape.
+
+After `loadBrainConfig` and before any state mutation:
+
+```ts
+if (cfg.primary_agent !== null && cfg.primary_agent !== agentName) {
+ warnings.push({
+ code: "non-primary-dream-run",
+ message:
+ `dream run from agent '${agentName}', but primary is ` +
+ `'${cfg.primary_agent}'. Convention violation, run proceeds.`,
+ });
+}
+```
+
+When composing the `dream` summary log body, conditionally add the
+`non_primary_agent` key:
+
+```ts
+const body: Record<string, string> = {
+ run_id: runId,
+ /* existing keys */,
+};
+if (cfg.primary_agent !== null && cfg.primary_agent !== agentName) {
+ body["non_primary_agent"] = agentName;
+}
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.dream.non-primary.test.ts tests/core/brain.dream.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 15: CLI surfaces the warning
+
+**Files:**
+- Modify: `src/cli/brain.ts` (cmdBrainDream)
+- Test: `tests/cli/brain.test.ts` (existing dream coverage)
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("o2b brain dream prints non-primary warning to stderr", async () => {
+ bootstrapBrain(vault, {});
+ setPrimaryAgent(vault, "hermes-vps");
+ const { exit, stderr } = await runCli(
+ ["brain", "dream", "--vault", vault, "--agent", "claude-vps-agent"],
+ { captureStderr: true },
+ );
+ expect(exit).toBe(0);
+ expect(stderr).toMatch(/non-primary-dream-run/);
+});
+```
+
+- [ ] **Step 2: Verify failure**
+
+Run: `bun test tests/cli/brain.test.ts -t "non-primary"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+After `dream(...)` returns, iterate `result.warnings` and write each
+to stderr in the existing warning format used by `cmdBrainRollback`'s
+log-failure warning. Do not change the exit code.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/cli/brain.test.ts -t "non-primary"`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 16: MCP `brain_dream` exposes warnings
+
+**Files:**
+- Modify: `src/mcp/brain-tools.ts`
+- Test: `tests/mcp/brain-tools.test.ts` (existing)
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("brain_dream JSON response includes warnings array", async () => {
+ bootstrapBrain(vault, {});
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = await callMcpTool("brain_dream", { vault, agent: "claude-vps-agent" });
+ expect(r.warnings).toContainEqual(
+ expect.objectContaining({ code: "non-primary-dream-run" }),
+ );
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/mcp/brain-tools.test.ts -t "warnings"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In the `brain_dream` tool handler, return
+`{ warnings: result.warnings, ...existing }` instead of dropping the
+warnings on the floor.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/mcp/brain-tools.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 17: `docs/cross-project-pointer.md`
+
+**Files:**
+- Create: `docs/cross-project-pointer.md`
+
+- [ ] **Step 1: Write the doc**
+
+Three sections:
+
+```markdown
+# Cross-project setup
+
+This page tells coding-runtimes (Claude Code, Codex, Cursor, Aider, โ€ฆ)
+how to find an Open Second Brain vault when they are launched from a
+project directory that is not the vault itself.
+
+## 1. Add the pointer snippet to your project
+
+Append the block below to one of the agent-prompt files your runtime
+reads on startup. Common targets:
+
+- `CLAUDE.md` โ€” Claude Code.
+- `AGENTS.md` โ€” Codex, Cursor, Aider, and other tools that follow the
+ agents.md convention.
+
+Pick **one** location per project. The managed-block fences let a
+future `o2b brain bootstrap` command rewrite the snippet idempotently;
+manual edits inside the fences are preserved on subsequent runs.
+
+> NOTE: replace `<absolute-vault-path>` with the absolute path of
+> your Obsidian-compatible vault.
+
+```text
+# >>> open-second-brain managed >>>
+## Open Second Brain
+
+This project shares an Obsidian-compatible vault with an active
+observing-memory layer. At session start, read the current
+preferences:
+
+ <absolute-vault-path>/Brain/active.md
+
+Record taste signals via `brain_feedback` (MCP) or
+`o2b brain feedback` (CLI). After producing a durable artifact, call
+`brain_apply_evidence` with `result: applied | violated | outdated`
+for any preference whose `scope` matches.
+
+Do not run `o2b brain dream` from this runtime. The vault has a
+primary dream-running agent; see `<vault>/Brain/_brain.yaml`
+(key `primary_agent`).
+# <<< open-second-brain managed <<<
+```
+
+## 2. Primary agent and dream cron
+
+A shared vault has one runtime responsible for running the
+deterministic `dream` consolidation pass. Declare that runtime in
+`Brain/_brain.yaml`:
+
+ o2b brain set-primary <agent-name> --vault <vault-path>
+
+The agent name is the value of `agent_name` in
+`~/.config/open-second-brain/config.yaml` on the host that runs the
+dream cron. When dream runs from a different agent, you get a stderr
+warning and a `non_primary_agent` payload row in the dream log
+entry; the run still proceeds (no hard block โ€” the data is safe).
+
+Pin / unpin / reject / pin-toggle are unrestricted: any agent on any
+device can mutate the protected set.
+
+To clear the primary declaration (vault is single-host again):
+
+ o2b brain set-primary --clear --vault <vault-path>
+
+## 3. Multi-device through Syncthing
+
+The vault is designed to be Syncthing-shared. Signals can be captured
+on any device โ€” `brain_feedback` from a coding session on the laptop,
+`@osb` markers added by hand on the phone โ€” and they all land in
+`Brain/inbox/` on every peer. The primary host's dream cron picks
+them up next pass, regardless of which peer wrote them.
+```
+
+- [ ] **Step 2: Verify the doc renders cleanly**
+
+Run: `grep -n '<vault-path>' docs/cross-project-pointer.md | head`
+Expected: every placeholder is intentional and bracketed.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 18: README cross-project section + CLI table
+
+**Files:**
+- Modify: `README.md`
+
+- [ ] **Step 1: Add the CLI line**
+
+In the Brain CLI table (current block lists 14 verbs), add a row for
+`set-primary` between `unpin` and `rollback`:
+
+```text
+o2b brain set-primary Declare or clear primary_agent in _brain.yaml
+```
+
+- [ ] **Step 2: Add cross-project subsection**
+
+After the "Brain (observing memory)" section, insert:
+
+```markdown
+### Cross-project setup
+
+When your coding work happens in a project directory that is not the
+vault itself, add a pointer snippet to your project's `CLAUDE.md` /
+`AGENTS.md` so the agent knows where to read preferences from. The
+canonical snippet, the rules for multi-device Syncthing setups, and
+the `o2b brain set-primary` invocation are in
+[`docs/cross-project-pointer.md`](docs/cross-project-pointer.md).
+```
+
+- [ ] **Step 3: Verify**
+
+Run: `grep -n 'set-primary' README.md`
+Expected: one CLI-table line, one section link.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 19: install.md branch A recommends `--primary-agent`
+
+**Files:**
+- Modify: `install.md`
+
+- [ ] **Step 1: Add the recommendation**
+
+In Branch A โ€” Hermes, step 4 (`o2b init` invocation), append a note:
+
+```markdown
+**Set this Hermes install as the vault's primary dream-running agent.**
+If this is the runtime that will run `hermes cron` for `o2b brain
+dream`, pass `--primary-agent <agent-name>` (use the same value as
+`--agent-name`). Doing so writes `primary_agent` into
+`Brain/_brain.yaml` and any subsequent dream run from a different
+runtime emits a warning. You can change or clear the primary later
+with `o2b brain set-primary <name>` / `o2b brain set-primary --clear`.
+```
+
+- [ ] **Step 2: Verify**
+
+Run: `grep -n '--primary-agent' install.md`
+Expected: one or two occurrences in Branch A.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 20: Phase 2 close
+
+- [ ] **Step 1: Full Brain suite + CLI**
+
+Run: `bun test tests/core/brain.*.test.ts tests/cli/brain.*.test.ts tests/mcp/brain-tools.test.ts`
+Expected: all green.
+
+- [ ] **Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: zero errors.
+
+**Pause for review (no commit).**
+
+---
+
+## Phase 3 โ€” ยง10 Numeric confidence
+
+### Task 21: Extend `BrainConfidenceConfig` + frontmatter types
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+
+- [ ] **Step 1: Add fields**
+
+```ts
+export interface BrainConfidenceConfig {
+ readonly low_max_applied: number;
+ readonly high_min_applied: number;
+ readonly high_freshness_factor: number;
+ readonly medium_min: number; // NEW
+ readonly high_min: number; // NEW
+}
+
+export interface BrainPreference {
+ // existing fields...
+ readonly confidence: BrainConfidence;
+ readonly confidence_value: number | null; // NEW
+ // existing fields...
+}
+
+export interface BrainRetired {
+ // existing fields...
+ readonly confidence: BrainConfidence;
+ readonly confidence_value: number | null; // NEW
+ // existing fields...
+}
+```
+
+- [ ] **Step 2: Verify type errors surface**
+
+Run: `bun run typecheck`
+Expected: errors at policy / preference / digest / dream / mcp sites
+that build these objects. Resolved in following tasks.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 22: `policy.ts` accepts new thresholds
+
+**Files:**
+- Modify: `src/core/brain/policy.ts`
+- Test: `tests/core/brain.policy.test.ts`
+
+- [ ] **Step 1: Failing tests**
+
+```ts
+test("validateBrainConfig defaults medium_min and high_min", () => {
+ const cfg = validateBrainConfig({ schema_version: 1 });
+ expect(cfg.confidence.medium_min).toBeCloseTo(0.40);
+ expect(cfg.confidence.high_min).toBeCloseTo(0.75);
+});
+
+test("validateBrainConfig rejects medium_min outside [0, 1]", () => {
+ expect(() =>
+ validateBrainConfig({
+ schema_version: 1,
+ confidence: { medium_min: -0.1 },
+ }),
+ ).toThrow(/medium_min/);
+});
+
+test("validateBrainConfig rejects medium_min >= high_min", () => {
+ expect(() =>
+ validateBrainConfig({
+ schema_version: 1,
+ confidence: { medium_min: 0.8, high_min: 0.6 },
+ }),
+ ).toThrow(/medium_min.*high_min/);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.policy.test.ts -t "medium_min"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Extend `DEFAULT_BRAIN_CONFIG.confidence`:
+
+```ts
+confidence: Object.freeze({
+ low_max_applied: 2,
+ high_min_applied: 10,
+ high_freshness_factor: 0.8,
+ medium_min: 0.40,
+ high_min: 0.75,
+}),
+```
+
+Extend `DEFAULT_BRAIN_CONFIG_YAML`:
+
+```yaml
+confidence:
+ low_max_applied: 2
+ high_min_applied: 10
+ high_freshness_factor: 0.8
+ medium_min: 0.40
+ high_min: 0.75
+```
+
+In `validateBrainConfigDetailed`, after existing confidence-block
+checks:
+
+```ts
+function requireUnitInterval(field: string, v: unknown, source: string | null): void {
+ if (
+ typeof v !== "number" ||
+ !Number.isFinite(v) ||
+ v < 0 || v > 1
+ ) {
+ throw new BrainConfigError(
+ `must be a number in [0, 1]; got ${describe(v)}`,
+ field, source,
+ );
+ }
+}
+
+requireUnitInterval("confidence.medium_min", confidence.medium_min, source);
+requireUnitInterval("confidence.high_min", confidence.high_min, source);
+if ((confidence.medium_min as number) >= (confidence.high_min as number)) {
+ throw new BrainConfigError(
+ `medium_min must be strictly less than high_min; got ` +
+ `medium_min=${confidence.medium_min}, high_min=${confidence.high_min}`,
+ "confidence.medium_min",
+ source,
+ );
+}
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.policy.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 23: `preference.ts` writer + parser
+
+**Files:**
+- Modify: `src/core/brain/preference.ts`
+- Test: `tests/core/brain.preference.test.ts`
+
+- [ ] **Step 1: Failing tests**
+
+```ts
+test("writePreference emits _confidence_value", () => {
+ writePreference(vault, { /* minimal valid input */, confidence_value: 0.5413 });
+ const raw = readFileSync(path, "utf8");
+ expect(raw).toMatch(/^_confidence_value: 0\.5413$/m);
+});
+
+test("parsePreference reads _confidence_value as a number", () => {
+ const p = writePref({ _confidence_value: 0.74 });
+ expect(parsePreference(p).confidence_value).toBeCloseTo(0.74);
+});
+
+test("parsePreference falls back to null when _confidence_value absent (legacy file)", () => {
+ const p = writeLegacyPref(); // no _confidence_value line
+ expect(parsePreference(p).confidence_value).toBeNull();
+});
+
+test("moveToRetired propagates confidence_value into retired frontmatter", () => {
+ const ret = moveToRetired(vault, "pref-foo", { now, retired_by: "[[dream-x]]", confidence_value: 0.61 });
+ const raw = readFileSync(ret.path, "utf8");
+ expect(raw).toMatch(/^_confidence_value: 0\.61$/m);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.preference.test.ts -t "_confidence_value"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Extend `WritePreferenceInput`:
+
+```ts
+readonly confidence_value?: number;
+```
+
+In `preferenceFrontmatter` add:
+
+```ts
+const confidenceValue = input.confidence_value;
+// inside metadata:
+_confidence_value: confidenceValue === undefined ? "null" : Number(confidenceValue.toFixed(4)),
+```
+
+Round to 4 decimals at write time so YAML stays stable across no-op
+refreshes.
+
+In `parsePreference`, read `_confidence_value` through the existing
+derived-field path; coerce the parsed value to `number | null`. Same
+in `parseRetired`. Propagate through `moveToRetired` (it currently
+inherits the originating pref's `_confidence_value` already once the
+field flows through the inherited frontmatter โ€” verify and add to
+the test list above if not).
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.preference.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 24: `dream.ts` `computeConfidence` returns `{ value, band }`
+
+**Files:**
+- Modify: `src/core/brain/dream.ts`
+- Test: `tests/core/brain.confidence-value.test.ts`
+
+- [ ] **Step 1: Failing test for the formula**
+
+```ts
+import { test, expect } from "bun:test";
+import {
+ computeConfidence,
+ type ConfidenceComputeResult,
+} from "../../src/core/brain/dream.ts";
+
+const cfg = /* DEFAULT_BRAIN_CONFIG */;
+const now = new Date("2026-05-17T00:00:00Z");
+
+test("computeConfidence value=0 when no evidence", () => {
+ const r = computeConfidence(0, 0, null, cfg, now);
+ expect(r.value).toBe(0);
+ expect(r.band).toBe("low");
+});
+
+test("computeConfidence Wilson lower bound for 8 applied 0 violated, fresh", () => {
+ const last = "2026-05-15T00:00:00Z"; // 2 days old
+ const r = computeConfidence(8, 0, last, cfg, now);
+ // Wilson 95% lower bound for 8/8 โ‰ˆ 0.6764; freshness โ‰ˆ 1 - 2/90 = 0.9778
+ // value โ‰ˆ 0.6764 * 0.9778 โ‰ˆ 0.6614
+ expect(r.value).toBeGreaterThan(0.60);
+ expect(r.value).toBeLessThan(0.70);
+});
+
+test("computeConfidence violated >= applied โ†’ band low (hard floor)", () => {
+ const r = computeConfidence(5, 5, "2026-05-15T00:00:00Z", cfg, now);
+ expect(r.band).toBe("low");
+});
+
+test("computeConfidence applied <= low_max_applied โ†’ band low (hard floor)", () => {
+ const r = computeConfidence(2, 0, "2026-05-15T00:00:00Z", cfg, now);
+ expect(r.band).toBe("low");
+});
+
+test("computeConfidence high band requires high_min_applied + no violated + fresh + numeric high", () => {
+ const last = "2026-05-15T00:00:00Z";
+ // n=20, applied=20, violated=0; Wilson lower bound 0.832 * freshness โ‰ˆ 0.813
+ const r = computeConfidence(20, 0, last, cfg, now);
+ expect(r.band).toBe("high");
+ expect(r.value).toBeGreaterThan(0.78);
+});
+
+test("computeConfidence stale evidence โ†’ freshness 0 โ†’ value 0", () => {
+ const last = "2025-01-01T00:00:00Z"; // > stale_evidence_days old
+ const r = computeConfidence(20, 0, last, cfg, now);
+ expect(r.value).toBe(0);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.confidence-value.test.ts`
+Expected: FAIL on the value-based assertions (existing
+`computeConfidence` only returns a band).
+
+- [ ] **Step 3: Implement**
+
+Replace the body of `computeConfidence` in `dream.ts`:
+
+```ts
+export interface ConfidenceComputeResult {
+ readonly value: number;
+ readonly band: BrainConfidence;
+}
+
+export function computeConfidence(
+ applied: number,
+ violated: number,
+ lastEvidenceAt: string | null,
+ cfg: BrainConfig,
+ now: Date,
+): ConfidenceComputeResult {
+ const n = applied + violated;
+ let wilsonLow = 0;
+ if (n > 0) {
+ const z = 1.96;
+ const z2 = z * z;
+ const pHat = applied / n;
+ const denom = 1 + z2 / n;
+ const centre = (pHat + z2 / (2 * n)) / denom;
+ const margin = z * Math.sqrt(pHat * (1 - pHat) / n + z2 / (4 * n * n)) / denom;
+ wilsonLow = Math.max(0, centre - margin);
+ }
+ let freshness = 0;
+ if (lastEvidenceAt) {
+ const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
+ if (Number.isFinite(ageMs)) {
+ const limitMs = cfg.retire.stale_evidence_days * 24 * 3600 * 1000;
+ freshness = Math.max(0, Math.min(1, 1 - ageMs / limitMs));
+ }
+ }
+ const value = Math.round(wilsonLow * freshness * 10_000) / 10_000;
+
+ // Derive band: hard floors first, then numeric thresholds.
+ let band: BrainConfidence = BRAIN_CONFIDENCE.medium;
+ if (applied <= cfg.confidence.low_max_applied) band = BRAIN_CONFIDENCE.low;
+ else if (applied > 0 && violated >= applied) band = BRAIN_CONFIDENCE.low;
+ else {
+ const fresh = freshness >= (1 - cfg.confidence.high_freshness_factor);
+ const allowHigh =
+ applied >= cfg.confidence.high_min_applied
+ && violated === 0
+ && fresh;
+ if (value >= cfg.confidence.high_min && allowHigh) {
+ band = BRAIN_CONFIDENCE.high;
+ } else if (value >= cfg.confidence.medium_min) {
+ band = BRAIN_CONFIDENCE.medium;
+ } else {
+ band = BRAIN_CONFIDENCE.low;
+ }
+ }
+ return Object.freeze({ value, band });
+}
+```
+
+Update the refresh loop call site to consume `{ value, band }`:
+
+```ts
+const conf = computeConfidence(applied, violated, lastEvidence, cfg, now);
+const prospective: WritePreferenceInput = {
+ // ...
+ confidence: conf.band,
+ confidence_value: conf.value,
+};
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.confidence-value.test.ts tests/core/brain.dream.test.ts`
+Expected: green. Existing dream tests may need band-expectation
+updates if their fixture's evidence count crosses one of the new
+numeric thresholds โ€” adjust as the suite tells you.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 25: Refresh-time band-drop tracking
+
+**Files:**
+- Modify: `src/core/brain/dream.ts`
+- Test: `tests/core/brain.dream.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("dream RefreshResult records previous_band โ†’ next_band on band change", async () => {
+ // Build fixture where a confirmed pref currently has confidence high
+ // and the refresh recomputes to medium.
+ const r = await dream(vault, { /* fixture */ now });
+ expect(r.refresh.bandDrops).toContainEqual(
+ expect.objectContaining({ slug: "pref-foo", previous: "high", next: "medium" }),
+ );
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.dream.test.ts -t "bandDrops"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Add to `RefreshResult`:
+
+```ts
+readonly bandDrops: ReadonlyArray<{
+ readonly slug: string;
+ readonly principle: string;
+ readonly previous: BrainConfidence;
+ readonly next: BrainConfidence;
+ readonly applied: number;
+ readonly violated: number;
+}>;
+```
+
+In the refresh loop, after computing `prospective`:
+
+```ts
+const oldBand = rec.pref.confidence;
+const newBand = prospective.confidence;
+const rank = { low: 0, medium: 1, high: 2 } as const;
+if (rank[newBand] < rank[oldBand]) {
+ drops.push({
+ slug, principle: rec.pref.principle,
+ previous: oldBand, next: newBand,
+ applied, violated,
+ });
+}
+```
+
+Pass `bandDrops` up to `DreamResult` so digest can read it.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.dream.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 26: Digest `## Confidence drops` section
+
+**Files:**
+- Modify: `src/core/brain/digest.ts`
+- Test: `tests/core/brain.digest.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("digest emits Confidence drops section when refresh.bandDrops non-empty", async () => {
+ const md = renderDigest(/* fixture with one drop */);
+ expect(md).toMatch(/^## Confidence drops$/m);
+ expect(md).toMatch(/\[\[pref-foo\|.*\]\]: high โ†’ medium \(applied=11, violated=2\)/);
+});
+
+test("digest omits the section when bandDrops is empty", async () => {
+ const md = renderDigest(/* fixture with no drops */);
+ expect(md).not.toMatch(/^## Confidence drops$/m);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.digest.test.ts -t "Confidence drops"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In `renderDigest`, after the existing sections (newly-confirmed,
+retired, quarantined, hot, โ€ฆ):
+
+```ts
+if (drops.length > 0) {
+ out.push("## Confidence drops", "");
+ for (const d of drops) {
+ out.push(
+ `- ${renderPrefLink({ id: \`pref-\${d.slug}\`, principle: d.principle })}: ` +
+ `${d.previous} โ†’ ${d.next} ` +
+ `(applied=${d.applied}, violated=${d.violated})`,
+ );
+ }
+ out.push("");
+}
+```
+
+The digest already accepts a `RefreshResult` (or its summary) in its
+input pipeline; thread `bandDrops` through that channel.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.digest.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 27: `active.ts` numeric tail
+
+**Files:**
+- Modify: `src/core/brain/active.ts`
+- Test: `tests/core/brain.active.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("active.md renders numeric confidence tail when available", async () => {
+ const md = renderActive([
+ { id: "pref-foo", principle: "Use spaces", status: "confirmed",
+ confidence: "medium", confidence_value: 0.62, pinned: false, scope: "code" },
+ ]);
+ expect(md).toMatch(/\[\[pref-foo\|Use spaces\]\].*\(conf: 0\.62\)/);
+});
+
+test("active.md omits tail when confidence_value is null (legacy)", async () => {
+ const md = renderActive([
+ { id: "pref-bar", principle: "Old rule", status: "confirmed",
+ confidence: "medium", confidence_value: null, pinned: false, scope: "code" },
+ ]);
+ expect(md).not.toMatch(/\(conf:/);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.active.test.ts -t "numeric"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In `renderActive`, where each Active / Quarantine bullet is composed:
+
+```ts
+const tail = pref.confidence_value !== null
+ ? ` (conf: ${pref.confidence_value.toFixed(2)})`
+ : "";
+out.push(
+ `- ${renderPrefLink({ id: pref.id, principle: pref.principle })} ` +
+ `${meta}${tail}`,
+);
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.active.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 28: MCP `brain_query` JSON includes `confidence_value`
+
+**Files:**
+- Modify: `src/mcp/brain-tools.ts`
+- Test: `tests/mcp/brain-tools.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("brain_query result row carries confidence_value", async () => {
+ // Fixture: one pref with _confidence_value 0.74
+ const r = await callMcpTool("brain_query", { preference: "pref-foo" });
+ expect(r.row.confidence).toBe("medium");
+ expect(r.row.confidence_value).toBeCloseTo(0.74);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/mcp/brain-tools.test.ts -t "confidence_value"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Locate the `brain_query` result serialiser. Add
+`confidence_value: row.confidence_value` to the emitted object โ€”
+typically a one-line addition in the `toJSON` / `toResultRow` mapper.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/mcp/brain-tools.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 29: Phase 3 close
+
+- [ ] **Step 1: Full Brain + CLI + MCP suite**
+
+Run: `bun test tests/core/brain.*.test.ts tests/cli/brain.*.test.ts tests/mcp/brain-tools.test.ts`
+Expected: green.
+
+- [ ] **Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: zero errors.
+
+**Pause for review (no commit).**
+
+---
+
+## Phase 4 โ€” ยง5 Snapshot diff + rollback dry-run
+
+### Task 30: Extract `extractSnapshotToTemp`
+
+**Files:**
+- Modify: `src/core/brain/snapshot.ts`
+- Test: `tests/core/brain.snapshot.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+import { extractSnapshotToTemp } from "../../src/core/brain/snapshot.ts";
+
+test("extractSnapshotToTemp materialises a Brain/ tree in a sibling tmp dir", () => {
+ createSnapshot(vault, "run-x");
+ const r = extractSnapshotToTemp(vault, "run-x");
+ try {
+ expect(existsSync(r.brainRoot)).toBe(true);
+ expect(r.brainRoot).toMatch(/Brain$/);
+ expect(existsSync(join(r.brainRoot, "preferences"))).toBe(true);
+ } finally {
+ r.cleanup();
+ }
+ expect(existsSync(r.tmpRoot)).toBe(false);
+});
+
+test("extractSnapshotToTemp throws on missing archive", () => {
+ expect(() => extractSnapshotToTemp(vault, "missing-run")).toThrow(/archive does not exist/);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.snapshot.test.ts -t "extractSnapshotToTemp"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Pull the extract step out of `restoreSnapshot` (lines ~452โ€“520 today).
+Signature:
+
+```ts
+export interface ExtractSnapshotResult {
+ readonly tmpRoot: string;
+ readonly brainRoot: string;
+ readonly cleanup: () => void;
+}
+
+export function extractSnapshotToTemp(
+ vault: string,
+ runId: string,
+): ExtractSnapshotResult;
+```
+
+Body: existing archive-existence probe, tooling detection, magic-byte
+based decompressor pick, `tar -x` into `mkdtempSync(...)`,
+`existsSync(extractedBrain)` sanity-check. `cleanup` is the same
+`rmSync(tmp, { recursive: true, force: true })` that `restoreSnapshot`
+currently runs in its `finally` block.
+
+Rewire `restoreSnapshot` to:
+
+```ts
+const ext = extractSnapshotToTemp(vault, runId);
+try {
+ // existing live-tree wipe + cpSync loop, sourced from ext.brainRoot
+} finally {
+ ext.cleanup();
+}
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.snapshot.test.ts`
+Expected: all existing tests stay green; new ones pass.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 31: `BrainTreeDiff` types + `diffBrainTrees`
+
+**Files:**
+- Create: `src/core/brain/snapshot-diff.ts`
+- Test: `tests/core/brain.snapshot-diff.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+import { diffBrainTrees } from "../../src/core/brain/snapshot-diff.ts";
+
+test("diffBrainTrees reports added preference", () => {
+ // a/ Brain/preferences/pref-a.md (parsed)
+ // b/ Brain/preferences/pref-a.md (same) + Brain/preferences/pref-b.md
+ const d = diffBrainTrees(rootA, rootB);
+ expect(d.added).toContainEqual(
+ expect.objectContaining({ kind: "preference", id: "pref-b" }),
+ );
+ expect(d.removed).toEqual([]);
+ expect(d.modified).toEqual([]);
+});
+
+test("diffBrainTrees reports removed retired", () => { /* mirror */ });
+
+test("diffBrainTrees reports modified preference with field deltas", () => {
+ // pref-a status confirmed โ†’ quarantine, applied 4 โ†’ 7
+ const d = diffBrainTrees(rootA, rootB);
+ const chg = d.modified.find(c => c.entry.id === "pref-a")!;
+ expect(chg.fields).toContainEqual({ field: "_status", before: "confirmed", after: "quarantine" });
+ expect(chg.fields).toContainEqual({ field: "_applied_count", before: 4, after: 7 });
+ expect(chg.bodyChanged).toBe(false);
+});
+
+test("diffBrainTrees marks body-only change with empty fields and bodyChanged true", () => {
+ // pref-a frontmatter identical, body differs
+ const d = diffBrainTrees(rootA, rootB);
+ const chg = d.modified.find(c => c.entry.id === "pref-a")!;
+ expect(chg.fields).toEqual([]);
+ expect(chg.bodyChanged).toBe(true);
+});
+
+test("diffBrainTrees treats signals as immutable (added/removed only)", () => {
+ // sig-a present in A absent in B
+ const d = diffBrainTrees(rootA, rootB);
+ expect(d.removed).toContainEqual(expect.objectContaining({ kind: "signal", id: "sig-a" }));
+ expect(d.modified.find(c => c.entry.kind === "signal")).toBeUndefined();
+});
+
+test("diffBrainTrees compares logs byte-equal (bodyChanged only)", () => {
+ // Brain/log/2026-05-17.md differs in B
+ const d = diffBrainTrees(rootA, rootB);
+ expect(d.modified).toContainEqual(
+ expect.objectContaining({ entry: expect.objectContaining({ kind: "log" }), bodyChanged: true }),
+ );
+});
+
+test("diffBrainTrees ignores .snapshots/", () => {
+ // .snapshots dir differs
+ const d = diffBrainTrees(rootA, rootB);
+ expect(d.added.find(e => e.path.startsWith(".snapshots"))).toBeUndefined();
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.snapshot-diff.test.ts`
+Expected: FAIL (module missing).
+
+- [ ] **Step 3: Implement**
+
+```ts
+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+import { parsePreference, parseRetired } from "./preference.ts";
+
+const TRACKED_FIELDS = [
+ "_status",
+ "_applied_count",
+ "_violated_count",
+ "_confidence",
+ "_confidence_value",
+ "pinned",
+] as const;
+
+export interface BrainTreeEntry {
+ readonly kind: "preference" | "retired" | "signal" | "log" | "config" | "other";
+ readonly path: string;
+ readonly id?: string;
+}
+// (other types from spec ยง3.3)
+
+export function diffBrainTrees(
+ rootA: string,
+ rootB: string,
+): BrainTreeDiff {
+ // 1. Walk both roots, classify entries (excluding .snapshots/).
+ // 2. Map by relative path.
+ // 3. paths in A only โ†’ removed; in B only โ†’ added; in both โ†’
+ // compare; if preferences/retired โ†’ frontmatter field diff;
+ // other kinds โ†’ byte equality, marked bodyChanged.
+ // 4. Sort outputs deterministically (by kind, then id, then path).
+}
+```
+
+Provide a `classify(relativePath)` helper that maps
+`preferences/pref-*.md` โ†’ preference, `retired/ret-*.md` โ†’ retired,
+`inbox/sig-*.md` and `inbox/processed/sig-*.md` โ†’ signal,
+`log/*.md` โ†’ log, `_brain.yaml` / `_BRAIN.md` / `active.md` โ†’ config,
+everything else under `Brain/` โ†’ other.
+
+Frontmatter diff: parse both files; emit one `BrainFieldChange` per
+tracked field whose value differs.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.snapshot-diff.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 32: Diff renderers
+
+**Files:**
+- Create: `src/core/brain/snapshot-diff-render.ts`
+- Test: `tests/core/brain.snapshot-diff-render.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("renderDiffMarkdown groups by kind and uses titled wikilinks", () => {
+ const md = renderDiffMarkdown(/* sample diff */, { aLabel: "run-x", bLabel: "live" });
+ expect(md).toMatch(/^# Brain snapshot diff$/m);
+ expect(md).toMatch(/^- A: run-x$/m);
+ expect(md).toMatch(/^- B: live$/m);
+ expect(md).toMatch(/^## Preferences$/m);
+ expect(md).toMatch(/^- \+ \[\[pref-foo\|Use spaces\]\] \(added\)$/m);
+ expect(md).toMatch(/^- ~ \[\[pref-bar\|.*\]\]:$/m);
+ expect(md).toMatch(/^ - _status: confirmed โ†’ quarantine$/m);
+});
+
+test("renderDiffJson returns the BrainTreeDiff verbatim", () => {
+ const d = /* sample */;
+ expect(renderDiffJson(d)).toEqual(d);
+});
+
+test("renderDiffMarkdown shows '(no changes)' under each section if empty", () => {
+ const md = renderDiffMarkdown(emptyDiff, {});
+ expect(md).toMatch(/^## Preferences\s+\(no changes\)$/m);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/core/brain.snapshot-diff-render.test.ts`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+Pure rendering of `BrainTreeDiff` into Markdown. Use `renderPrefLink`
+when the entry is a preference or retired (look up `principle` from
+the diff's stored frontmatter snapshot โ€” Task 31 stores enough on the
+entry for the renderer to source the title).
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/core/brain.snapshot-diff-render.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 33: `cmdBrainRollback --dry-run`
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Test: `tests/cli/brain.snapshot-diff.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("rollback --dry-run prints would-be restore plan and does not modify Brain/", async () => {
+ createSnapshot(vault, "run-x");
+ writeFileSync(join(vault, "Brain/preferences/pref-new.md"), "...");
+ const { exit, stdout } = await runCli(["brain", "rollback", "run-x", "--dry-run", "--vault", vault]);
+ expect(exit).toBe(0);
+ expect(stdout).toMatch(/^# Brain snapshot diff$/m);
+ expect(stdout).toMatch(/^- A: run-x$/m);
+ expect(stdout).toMatch(/^- B: live$/m);
+ expect(existsSync(join(vault, "Brain/preferences/pref-new.md"))).toBe(true);
+});
+
+test("rollback --dry-run + --yes is an error", async () => {
+ const { exit, stderr } = await runCli(["brain", "rollback", "run-x", "--dry-run", "--yes", "--vault", vault]);
+ expect(exit).toBe(1);
+ expect(stderr).toMatch(/mutually exclusive/);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/cli/brain.snapshot-diff.test.ts -t "rollback --dry-run"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In `cmdBrainRollback`, extend the flag schema:
+
+```ts
+"dry-run": { type: "boolean" },
+```
+
+After resolving `runId` and verifying the snapshot exists:
+
+```ts
+if (flags["dry-run"]) {
+ if (flags["yes"]) return fail("rollback: --dry-run and --yes are mutually exclusive");
+ const ext = extractSnapshotToTemp(vault, runId);
+ try {
+ const diff = diffBrainTrees(ext.brainRoot, join(vault, "Brain"));
+ const out = flags["json"]
+ ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
+ : renderDiffMarkdown(diff, { aLabel: runId, bLabel: "live" }) + "\n";
+ process.stdout.write(out);
+ return 0;
+ } finally {
+ ext.cleanup();
+ }
+}
+```
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/cli/brain.snapshot-diff.test.ts -t "rollback --dry-run"`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 34: `cmdBrainSnapshotDiff`
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Test: `tests/cli/brain.snapshot-diff.test.ts`
+
+- [ ] **Step 1: Failing test**
+
+```ts
+test("snapshot diff <run_id> against live", async () => {
+ createSnapshot(vault, "run-x");
+ writeFileSync(join(vault, "Brain/preferences/pref-new.md"), "...");
+ const { exit, stdout } = await runCli(["brain", "snapshot", "diff", "run-x", "--vault", vault]);
+ expect(exit).toBe(0);
+ expect(stdout).toMatch(/^- A: run-x$/m);
+ expect(stdout).toMatch(/^- B: live$/m);
+ expect(stdout).toMatch(/\+ \[\[pref-new/);
+});
+
+test("snapshot diff <run_a> <run_b>", async () => {
+ createSnapshot(vault, "run-x");
+ writeFileSync(join(vault, "Brain/preferences/pref-new.md"), "...");
+ createSnapshot(vault, "run-y");
+ const { exit, stdout } = await runCli(["brain", "snapshot", "diff", "run-x", "run-y", "--vault", vault]);
+ expect(exit).toBe(0);
+ expect(stdout).toMatch(/- A: run-x.*- B: run-y/s);
+});
+
+test("snapshot diff --json yields parseable JSON", async () => {
+ createSnapshot(vault, "run-x");
+ const { exit, stdout } = await runCli(["brain", "snapshot", "diff", "run-x", "--vault", vault, "--json"]);
+ expect(exit).toBe(0);
+ const parsed = JSON.parse(stdout);
+ expect(parsed).toHaveProperty("added");
+ expect(parsed).toHaveProperty("removed");
+ expect(parsed).toHaveProperty("modified");
+});
+
+test("snapshot diff with unknown run_id exits 2", async () => {
+ const { exit } = await runCli(["brain", "snapshot", "diff", "missing", "--vault", vault]);
+ expect(exit).toBe(2);
+});
+```
+
+- [ ] **Step 2: Failing run**
+
+Run: `bun test tests/cli/brain.snapshot-diff.test.ts -t "snapshot diff"`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+In `handleBrainSubcommand`, add a `snapshot` sub-namespace dispatcher:
+
+```ts
+case "snapshot":
+ return handleBrainSnapshotSubcommand(rest);
+```
+
+```ts
+function handleBrainSnapshotSubcommand(argv: string[]): Promise<number> {
+ const [sub, ...rest] = argv;
+ switch (sub) {
+ case "diff": return cmdBrainSnapshotDiff(rest);
+ default:
+ process.stderr.write(
+ "usage: o2b brain snapshot diff <run_id_a> [<run_id_b>] " +
+ "[--vault <path>] [--json]\n",
+ );
+ return Promise.resolve(1);
+ }
+}
+```
+
+`cmdBrainSnapshotDiff`:
+
+```ts
+async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const cfg = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, cfg);
+ if (positional.length < 1 || positional.length > 2) {
+ return fail("snapshot diff requires <run_id_a> [<run_id_b>]");
+ }
+ const [a, b] = positional;
+ const snaps = listSnapshots(vault);
+ if (!snaps.some(s => s.run_id === a)) return notFound(`snapshot not found: ${a}`);
+ if (b && !snaps.some(s => s.run_id === b)) return notFound(`snapshot not found: ${b}`);
+
+ const extA = extractSnapshotToTemp(vault, a);
+ let extB: ExtractSnapshotResult | null = null;
+ try {
+ const bRoot = b
+ ? (extB = extractSnapshotToTemp(vault, b)).brainRoot
+ : join(vault, "Brain");
+ const diff = diffBrainTrees(extA.brainRoot, bRoot);
+ const out = flags["json"]
+ ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
+ : renderDiffMarkdown(diff, { aLabel: a!, bLabel: b ?? "live" }) + "\n";
+ process.stdout.write(out);
+ return 0;
+ } finally {
+ extA.cleanup();
+ extB?.cleanup();
+ }
+}
+```
+
+Add VERB_HELP entry for `snapshot` and update the top-level
+help-string in `cmdBrainHelp` to mention `o2b brain snapshot diff`.
+
+- [ ] **Step 4: Verify**
+
+Run: `bun test tests/cli/brain.snapshot-diff.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 35: Phase 4 close
+
+- [ ] **Step 1: Full suite**
+
+Run: `bun test`
+Expected: all green.
+
+- [ ] **Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: zero errors.
+
+**Pause for review (no commit).**
+
+---
+
+## Phase 5 โ€” Release wrap
+
+### Task 36: E2E test through the bundle
+
+**Files:**
+- Create: `tests/e2e/brain-tier-a-bundle.test.ts`
+
+- [ ] **Step 1: Build the scenario**
+
+```ts
+test("Tier-A bundle: init โ†’ set-primary โ†’ dream โ†’ snapshot diff โ†’ rollback dry-run", async () => {
+ // 1. o2b brain init --vault <tmp> --primary-agent hermes
+ // 2. o2b brain feedback (positive, topic X) ร— 3 from agent=other
+ // 3. o2b brain dream (agent=other) โ†’ warns non-primary
+ // 4. o2b brain feedback (positive, topic X) ร— 2 more
+ // 5. o2b brain dream (agent=hermes) โ†’ no warning
+ // 6. listSnapshots โ†’ at least 2 entries
+ // 7. o2b brain snapshot diff <run_a> <run_b> โ†’ JSON contains a pref-X with status quarantine|confirmed change
+ // 8. o2b brain rollback <run_a> --dry-run โ†’ markdown shows the delta vs live
+ // 9. Live Brain/ unchanged after dry-run
+});
+```
+
+- [ ] **Step 2: Run, expecting full pass**
+
+Run: `bun test tests/e2e/brain-tier-a-bundle.test.ts`
+Expected: green.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 37: README CLI table updates
+
+**Files:**
+- Modify: `README.md`
+
+- [ ] **Step 1: Extend the CLI table**
+
+Two new rows under "Brain":
+
+```text
+o2b brain set-primary Declare or clear primary_agent in _brain.yaml
+o2b brain snapshot diff Diff between two snapshots (or snapshot vs live)
+```
+
+Add `--dry-run` mention under the existing `rollback` row.
+
+- [ ] **Step 2: Add Cross-project setup subsection**
+
+Already covered in Task 18 โ€” verify the section is present.
+
+- [ ] **Step 3: Verify**
+
+Run: `grep -nE 'set-primary|snapshot diff|dry-run' README.md | head`
+Expected: every row matches one CLI line.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 38: `docs/how-it-works.md` extension
+
+**Files:**
+- Modify: `docs/how-it-works.md`
+
+- [ ] **Step 1: Three paragraph additions**
+
+Add under the relevant existing sections (do not create new top-level
+sections โ€” work within the file's current outline):
+
+- **Snapshot diff** โ€” short paragraph in the "Snapshot model" section
+ describing `o2b brain snapshot diff <a> [<b>]` and
+ `rollback --dry-run` as the two read-only inspectors over the
+ snapshot family.
+- **Numeric confidence** โ€” short paragraph in the "Confidence" section
+ documenting `_confidence_value`, the Wilson + freshness formula at a
+ high level, and the new band thresholds in `_brain.yaml.confidence`.
+- **Primary agent** โ€” short paragraph in the "Configuration" /
+ `_brain.yaml` section listing `primary_agent: <name> | null` and the
+ non-primary warning behaviour.
+
+- [ ] **Step 2: Verify**
+
+Run: `grep -nE 'snapshot diff|confidence_value|primary_agent' docs/how-it-works.md | head`
+Expected: at least one hit each.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 39: CHANGELOG entry
+
+**Files:**
+- Modify: `CHANGELOG.md`
+
+- [ ] **Step 1: Compose the section**
+
+One new release block (no `[Unreleased]` placeholder โ€” project rule).
+Date stamped at release time, version chosen by the release step
+(this plan does not encode a specific number to avoid drift):
+
+```markdown
+## [<next version>] - <release date>
+
+Brings four Tier-A items from `Projects/OpenSecondBrain/Features/_summary`:
+ยง5 snapshot diff and dry-run rollback, ยง10 numeric confidence with
+derived band, ยง21 cross-project pointer plus primary-agent
+declaration, ยง27 titled wikilinks for preferences.
+
+### Added
+- `o2b brain snapshot diff <run_a> [<run_b>]` โ€” read-only artifact
+ diff between two snapshots, or between a snapshot and live Brain/.
+ Groups output by artifact kind; `--json` for structured callers.
+- `o2b brain rollback --dry-run <run_id>` โ€” preview the restore plan
+ via the same diff renderer, with the live tree untouched.
+- `_confidence_value` numeric field on every preference and retired
+ file, computed from a Wilson 95% lower bound on
+ applied vs (applied + violated), modulated by linear freshness
+ decay over `retire.stale_evidence_days`. The existing
+ `_confidence` band stays on disk as a derived view.
+- `_brain.yaml.confidence.medium_min`, `_brain.yaml.confidence.high_min`
+ โ€” derived-band thresholds on the numeric value.
+- `_brain.yaml.primary_agent` โ€” declarative owner of the
+ dream-cron for a vault.
+- `o2b brain set-primary <name> | --clear` โ€” idempotent edit of
+ `primary_agent`.
+- `o2b brain init --primary-agent <name>` โ€” set the primary at
+ bootstrap time.
+- `renderPrefLink({ id, principle })` โ€” internal helper plus a
+ sweep of every Brain writer that emits a pref / retired wikilink.
+ Output shifts from `[[pref-id]]` to
+ `[[pref-id|short principle]]` in `active.md`, digests, log
+ payloads, retired bodies, and CLI human output.
+- `docs/cross-project-pointer.md` โ€” agent-facing setup guide for
+ projects whose work happens outside the vault root.
+
+### Changed
+- `dream` refresh writes `_confidence_value` alongside the band on
+ every touched preference. Legacy files migrate lazily on the next
+ refresh pass.
+- `dream` emits a non-fatal `non-primary-dream-run` warning (stderr
+ + MCP `warnings` array) when run from an agent other than
+ `primary_agent`. The dream pass still completes; the warning is
+ visibility, not enforcement.
+- `digest` adds a `## Confidence drops` section listing preferences
+ whose band fell during the current dream pass.
+- `active.md` bullets now append `(conf: 0.NN)` when a numeric value
+ is on disk.
+- `brain_query` MCP response carries `confidence_value` alongside
+ the band on every result row.
+- README adds a Cross-project setup subsection.
+- install.md Branch A recommends `--primary-agent` during the
+ Hermes-side `o2b init`.
+
+### Notes
+- No vault migration required. The first post-upgrade dream pass
+ writes `_confidence_value` into every touched preference, and the
+ bundled `o2b brain doctor` is unchanged.
+- The four new CLI surfaces (`snapshot diff`, `rollback --dry-run`,
+ `set-primary`, `init --primary-agent`) are CLI-only on the
+ operator side; the MCP surface gains only an additive field on
+ `brain_query` and an additive `warnings` channel on `brain_dream`.
+```
+
+- [ ] **Step 2: Verify the entry conforms to project rules**
+
+Run: `grep -in 'unreleased' CHANGELOG.md | head`
+Expected: zero occurrences (project rule "No `[Unreleased]` section").
+
+Run: `grep -E '!{1}' CHANGELOG.md | head` to spot-check that the new
+section follows the `pref-no-exclamation-marks-in-docs` rule. Expected:
+no `!` in the new prose.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 40: Version bump via `sync-version`
+
+**Files:**
+- Modify: `package.json`, `pyproject.toml`
+
+- [ ] **Step 1: Pick the next version**
+
+Open `package.json`, read the current version (the previous release
+on this lineage). Bump the patch (or minor โ€” defer to release-call
+judgement) to the next number consistent with semver and the
+"one PR = one CHANGELOG version" rule.
+
+- [ ] **Step 2: Run the sync script**
+
+Run: `bun run sync-version <new version>`
+Expected: both files updated; the script is the canonical writer.
+
+- [ ] **Step 3: Verify**
+
+Run: `grep version package.json pyproject.toml | head`
+Expected: both report the same new value.
+
+**Pause for review (no commit).**
+
+---
+
+### Task 41: Release-pass close
+
+- [ ] **Step 1: Full suite + typecheck**
+
+Run: `bun test && bun run typecheck`
+Expected: green.
+
+- [ ] **Step 2: Read CHANGELOG once more**
+
+Skim the new section. Confirm: no `[Unreleased]`, no `simply`, no `!`
+in prose, all four feature numbers referenced. Section header dates
+**not** baked in from the planning phase (project rule).
+
+**Pause for review (no commit).** Bundle ready for the user to
+review, run any cloud reviews (CodeRabbit only if Sergey asks โ€”
+project rule against unsolicited runs), and stage / commit / push.
diff --git a/install.md b/install.md
index b2948784..e9ed9b5d 100644
--- a/install.md
+++ b/install.md
@@ -182,7 +182,8 @@ o2b init --vault /path/to/vault --name "My Second Brain" \
# Recommended on v0.9.0+: bootstrap the Brain observing-memory layer
# next to AI Wiki/. Idempotent; safe to skip on first install if the
# user explicitly opts out of Brain.
-o2b brain init --vault /path/to/vault
+o2b brain init --vault /path/to/vault \
+ --primary-agent "<chosen-agent-name>"
```
`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md`
@@ -192,6 +193,19 @@ IANA name via stdlib `zoneinfo` and persists it to the same config; from
that moment on, every `event_log_append` call stamps Daily entries in
that timezone regardless of the host's clock.
+**Declare this Hermes install as the vault's primary dream-running
+agent.** When the vault is shared with other devices through
+Syncthing, exactly one runtime should run `hermes cron` for
+`o2b brain dream`; the typical choice is the Hermes install on the
+always-on host. Passing `--primary-agent <chosen-agent-name>` writes
+the value into `Brain/_brain.yaml`. Subsequent dream invocations from
+a different agent emit a stderr warning and tag the log entry with
+`non_primary_agent: <caller>`. You can change or clear the primary
+later with `o2b brain set-primary <name>` or
+`o2b brain set-primary --clear`. The flag is ignored on re-runs
+against an already-initialised `_brain.yaml`; use `set-primary`
+there.
+
**Wire the `brain-memory` skill into the default Hermes profile.** The
plugin ships `skills/brain-memory/SKILL.md`, which tells the agent when
to call `brain_feedback` / `brain_apply_evidence` in conversation โ€”
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 0dbabd30..81348a4f 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": "0.10.2",
+ "version": "0.10.3",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 4ebf4d51..1381f779 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.2",
+ "version": "0.10.3",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index 0337c407..8076ba81 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.2"
+version: "0.10.3"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 6233090e..dac071bd 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.2",
+ "version": "0.10.3",
"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 8971d2dd..fe7c0981 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.2"
+version: "0.10.3"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index c2b6c79e..d97865a4 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 = "0.10.2"
+version = "0.10.3"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 50ceb1ee..f03dafcf 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -31,7 +31,7 @@ import {
resolveVault,
} from "../core/config.ts";
import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
-import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
+import { normaliseWikilinkTarget, renderPrefLink } from "../core/brain/wikilink.ts";
import { bootstrapBrain } from "../core/brain/init.ts";
import {
appendApplyEvidence,
@@ -50,7 +50,7 @@ import {
} from "../core/brain/sessions/import.ts";
import { SessionImportError } from "../core/brain/sessions/types.ts";
import { moveToRetired, parsePreference, writePreference } from "../core/brain/preference.ts";
-import { preferencePath } from "../core/brain/paths.ts";
+import { brainDirs, preferencePath } from "../core/brain/paths.ts";
import { isoDate, isoSecond } from "../core/brain/time.ts";
import {
queryByLogSince,
@@ -61,8 +61,19 @@ import {
import { renderDigest, type RenderDigestOptions } from "../core/brain/digest.ts";
import { runDoctor } from "../core/brain/doctor.ts";
import { setPinned } from "../core/brain/pin.ts";
+import { setPrimaryAgent } from "../core/brain/set-primary.ts";
import { writeSignal } from "../core/brain/signal.ts";
-import { listSnapshots, restoreSnapshot } from "../core/brain/snapshot.ts";
+import {
+ extractSnapshotToTemp,
+ listSnapshots,
+ restoreSnapshot,
+ type ExtractSnapshotResult,
+} from "../core/brain/snapshot.ts";
+import { diffBrainTrees } from "../core/brain/snapshot-diff.ts";
+import {
+ renderDiffJson,
+ renderDiffMarkdown,
+} from "../core/brain/snapshot-diff-render.ts";
import { appendLogEvent, type BrainLogEntry } from "../core/brain/log.ts";
import {
BRAIN_LOG_EVENT_KIND,
@@ -144,6 +155,7 @@ async function cmdBrainInit(argv: string[]): Promise<number> {
vault: { type: "string" },
config: { type: "string" },
force: { type: "boolean" },
+ "primary-agent": { type: "string" },
json: { type: "boolean" },
});
const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
@@ -152,11 +164,24 @@ async function cmdBrainInit(argv: string[]): Promise<number> {
// can run `o2b brain init` without restating `--vault`.
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const primaryAgentFlag = flags["primary-agent"];
+ let primaryAgent: string | undefined;
+ if (typeof primaryAgentFlag === "string") {
+ const trimmed = primaryAgentFlag.trim();
+ if (trimmed.length === 0) {
+ return fail(
+ "brain init: --primary-agent must be a non-empty string when provided",
+ );
+ }
+ primaryAgent = trimmed;
+ }
+
let result;
try {
result = bootstrapBrain(vault, {
force: Boolean(flags["force"]),
configPath: config,
+ ...(primaryAgent !== undefined ? { primaryAgent } : {}),
});
} catch (exc) {
return fail(`failed to initialize Brain: ${(exc as Error).message ?? exc}`);
@@ -310,7 +335,10 @@ async function cmdBrainFeedback(argv: string[]): Promise<number> {
timestamp: isoSecond(new Date(now.getTime() + 1000)),
eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
body: {
- preference: `[[${prefResult.id}]]`,
+ preference: renderPrefLink({
+ id: prefResult.id,
+ principle: String(flags["principle"]),
+ }),
agent,
},
});
@@ -347,10 +375,28 @@ async function cmdBrainDream(argv: string[]): Promise<number> {
vault: { type: "string" },
"dry-run": { type: "boolean" },
now: { type: "string" },
+ agent: { type: "string" },
json: { type: "boolean" },
});
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ // Match `cmdBrainInit`'s --primary-agent contract: when the flag is
+ // supplied, reject blank input rather than silently fall through to
+ // the resolved default. A whitespace-only --agent would otherwise
+ // bypass the non-primary check entirely.
+ const agentFlag = flags["agent"];
+ let agent: string;
+ if (typeof agentFlag === "string") {
+ const trimmed = agentFlag.trim();
+ if (trimmed.length === 0) {
+ return fail(
+ "brain dream: --agent must be a non-empty string when provided",
+ );
+ }
+ agent = trimmed;
+ } else {
+ agent = resolveAgentName(config);
+ }
let now: Date | undefined;
const nowStr = flags["now"] as string | undefined;
@@ -370,11 +416,20 @@ async function cmdBrainDream(argv: string[]): Promise<number> {
summary = dream(vault, {
...(now !== undefined ? { now } : {}),
dryRun: Boolean(flags["dry-run"]),
+ ...(agent ? { agentName: agent } : {}),
});
} catch (exc) {
return fail(`dream failed: ${(exc as Error).message ?? exc}`);
}
+ // Surface non-fatal warnings (ยง21 non-primary check, future advisory
+ // codes) on stderr regardless of output mode. The run already
+ // completed successfully; stdout stays reserved for the structured
+ // summary / human-readable status lines.
+ for (const w of summary.warnings ?? []) {
+ process.stderr.write(`warning: ${w.code}: ${w.message}\n`);
+ }
+
if (flags["json"]) {
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
return 0;
@@ -660,7 +715,10 @@ async function cmdBrainReject(argv: string[]): Promise<number> {
// Log a `reject` event so the audit trail stays complete.
try {
const body: Record<string, string> = {
- preference: `[[ret-${slug}]]`,
+ preference: renderPrefLink({
+ id: `ret-${slug}`,
+ principle: pref.principle,
+ }),
agent,
};
if (flags["reason"]) body["reason"] = String(flags["reason"]);
@@ -686,6 +744,136 @@ async function cmdBrainReject(argv: string[]): Promise<number> {
return 0;
}
+async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ if (positional.length < 1 || positional.length > 2) {
+ return fail(
+ "brain snapshot diff requires <run_id_a> [<run_id_b>] (with one arg, the live tree is compared as B)",
+ );
+ }
+ const [a, b] = positional;
+ const snaps = listSnapshots(vault);
+ if (!snaps.some((s) => s.run_id === a)) {
+ process.stderr.write(
+ `snapshot not found: ${a}; run \`o2b brain rollback --list\` to enumerate.\n`,
+ );
+ return 2;
+ }
+ if (b !== undefined && !snaps.some((s) => s.run_id === b)) {
+ process.stderr.write(
+ `snapshot not found: ${b}; run \`o2b brain rollback --list\` to enumerate.\n`,
+ );
+ return 2;
+ }
+
+ let extA: ExtractSnapshotResult | null = null;
+ let extB: ExtractSnapshotResult | null = null;
+ try {
+ extA = extractSnapshotToTemp(vault, a!);
+ const bRoot = b !== undefined
+ ? (extB = extractSnapshotToTemp(vault, b)).brainRoot
+ : brainDirs(vault).brain;
+ const diff = diffBrainTrees(extA.brainRoot, bRoot);
+ const out = flags["json"]
+ ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
+ : renderDiffMarkdown(diff, { aLabel: a!, bLabel: b ?? "live" });
+ process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
+ return 0;
+ } catch (exc) {
+ return fail(`snapshot diff failed: ${(exc as Error).message ?? exc}`);
+ } finally {
+ extA?.cleanup();
+ extB?.cleanup();
+ }
+}
+
+async function handleBrainSnapshotSubcommand(
+ argv: ReadonlyArray<string>,
+): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(
+ "usage: o2b brain snapshot <verb> [args...]\n" +
+ "Verbs:\n" +
+ " diff <run_id_a> [<run_id_b>] Read-only diff between two snapshots,\n" +
+ " or between a snapshot and live Brain/.\n",
+ );
+ return argv.length === 0 ? 2 : 0;
+ }
+ const sub = argv[0]!;
+ const rest = argv.slice(1);
+ switch (sub) {
+ case "diff":
+ return await cmdBrainSnapshotDiff([...rest]);
+ default:
+ process.stderr.write(
+ `unknown brain snapshot verb: ${sub}; supported: diff\n`,
+ );
+ return 2;
+ }
+}
+
+async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ clear: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let name: string | null;
+ if (flags["clear"]) {
+ if (positional.length > 0) {
+ return fail("brain set-primary --clear takes no positional argument");
+ }
+ name = null;
+ } else {
+ if (positional.length < 1) {
+ return fail(
+ "brain set-primary requires <name> or --clear; see `o2b brain help set-primary`",
+ );
+ }
+ if (positional.length > 1) {
+ return fail("brain set-primary accepts a single <name> argument");
+ }
+ const supplied = positional[0]!.trim();
+ if (supplied.length === 0) {
+ return fail("brain set-primary <name> must be non-empty");
+ }
+ name = supplied;
+ }
+
+ let result;
+ try {
+ result = setPrimaryAgent(vault, name);
+ } catch (exc) {
+ return fail(`set-primary failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ okJson({
+ previous: result.previous,
+ next: result.next,
+ changed: result.changed,
+ });
+ return 0;
+ }
+
+ const fmt = (v: string | null): string => v ?? "null";
+ if (!result.changed) {
+ ok(`primary_agent already set to ${fmt(result.next)}`);
+ } else {
+ ok(`primary_agent: ${fmt(result.previous)} โ†’ ${fmt(result.next)}`);
+ }
+ return 0;
+}
+
async function cmdBrainPin(argv: string[]): Promise<number> {
return await pinOrUnpin(argv, true);
}
@@ -738,6 +926,7 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
vault: { type: "string" },
list: { type: "boolean" },
yes: { type: "boolean" },
+ "dry-run": { type: "boolean" },
json: { type: "boolean" },
});
const config = defaultConfigPath();
@@ -779,6 +968,33 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
return 2;
}
+ // --dry-run prints the would-be restore plan without modifying
+ // Brain/. Mutually exclusive with --yes โ€” combining "preview" and
+ // "execute non-interactively" is contradictory and would silently
+ // hide one of the two intents.
+ if (flags["dry-run"]) {
+ if (flags["yes"]) {
+ return fail("rollback: --dry-run and --yes are mutually exclusive");
+ }
+ let ext;
+ try {
+ ext = extractSnapshotToTemp(vault, runId);
+ } catch (exc) {
+ return fail(`rollback dry-run failed: ${(exc as Error).message ?? exc}`);
+ }
+ try {
+ const liveBrain = brainDirs(vault).brain;
+ const diff = diffBrainTrees(liveBrain, ext.brainRoot);
+ const out = flags["json"]
+ ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
+ : renderDiffMarkdown(diff, { aLabel: "live", bLabel: runId });
+ process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
+ return 0;
+ } finally {
+ ext.cleanup();
+ }
+ }
+
// Interactive confirm. We compute a minimal diff summary by counting
// entries in the current state (the snapshot's content would require
// extracting first; the headline is intentionally lightweight โ€” "you
@@ -1280,7 +1496,10 @@ Brain verbs (observing memory):
reject Move a preference to retired (user-rejected); --yes if pinned
pin Mark a preference exempt from automatic retire (idempotent)
unpin Clear the pinned flag (idempotent)
- rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes)
+ set-primary Declare or clear primary_agent in _brain.yaml (--clear)
+ snapshot diff Read-only diff between two snapshots, or snapshot vs live
+ rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
+ --dry-run previews via the same diff renderer)
doctor Validate Brain invariants (--strict promotes warnings to exit 2)
backlinks List inbound references to a Brain artifact id
migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'
@@ -1295,8 +1514,10 @@ Common flags:
const VERB_HELP: Record<string, string> = {
init:
- "usage: o2b brain init [--vault <path>] [--force] [--json]\n" +
- "Bootstrap <vault>/Brain/. Requires `o2b init` to have run first.\n",
+ "usage: o2b brain init [--vault <path>] [--force] [--primary-agent <name>] [--json]\n" +
+ "Bootstrap <vault>/Brain/. Requires `o2b init` to have run first.\n" +
+ "--primary-agent <name> writes the value into _brain.yaml on first init;\n" +
+ "on re-run against an existing _brain.yaml use `o2b brain set-primary` instead.\n",
feedback:
"usage: o2b brain feedback --topic <slug> --signal positive|negative --principle <text>\n" +
" [--scope <slug>] [--source <wikilink>...] [--agent <name>] [--raw <text>|--raw-file <path>]\n" +
@@ -1326,8 +1547,16 @@ const VERB_HELP: Record<string, string> = {
"Clear pinned: true. Idempotent.\n",
rollback:
"usage: o2b brain rollback <run_id> [--vault <path>] [--yes] [--json]\n" +
+ " o2b brain rollback <run_id> --dry-run [--vault <path>] [--json]\n" +
" o2b brain rollback --list [--vault <path>] [--json]\n" +
- "Restore Brain/ from a snapshot. Interactive prompt unless --yes.\n",
+ "Restore Brain/ from a snapshot. Interactive prompt unless --yes.\n" +
+ "--dry-run prints the would-be restore plan as live โ†’ snapshot\n" +
+ "diff and exits 0 without writing.\n",
+ snapshot:
+ "usage: o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" +
+ " [--vault <path>] [--json]\n" +
+ "Read-only diff between two snapshots, or between a snapshot and\n" +
+ "the live Brain/ tree (when <run_id_b> is omitted).\n",
doctor:
"usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +
"Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n",
@@ -1340,6 +1569,13 @@ const VERB_HELP: Record<string, string> = {
"to the '_'-prefixed shape across Brain/preferences/ and Brain/retired/.\n" +
"Default is --dry-run; --apply takes a pre-run snapshot (rollback via run_id).\n" +
"--apply requires --yes in non-interactive mode (--json or non-TTY stdin).\n",
+ "set-primary":
+ "usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
+ " o2b brain set-primary --clear [--vault <path>] [--json]\n" +
+ "Declare which agent owns the dream consolidation pass for this vault.\n" +
+ "Stored in Brain/_brain.yaml as `primary_agent:`. Dream runs from a\n" +
+ "different agent emit a warning but still proceed (observability, not\n" +
+ "access control). Use --clear to remove the declaration.\n",
"scan-inline":
"usage: o2b brain scan-inline [--vault <path>] [--path <subdir>...] [--exclude <subdir>...]\n" +
" [--dry-run] [--strict] [--json] [--agent <name>]\n" +
@@ -1409,6 +1645,10 @@ export async function handleBrainSubcommand(
return await cmdBrainPin(rest);
case "unpin":
return await cmdBrainUnpin(rest);
+ case "set-primary":
+ return await cmdBrainSetPrimary(rest);
+ case "snapshot":
+ return await handleBrainSnapshotSubcommand(rest);
case "rollback":
return await cmdBrainRollback(rest);
case "doctor":
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index 2d078c27..80731031 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -238,7 +238,7 @@ function renderBody(input: RenderInput): string {
function renderConfirmedLine(p: BrainPreference): string {
const tags: string[] = [];
if (p.scope) tags.push(`scope: ${p.scope}`);
- tags.push(`confidence: ${p.confidence}`);
+ tags.push(`confidence: ${p.confidence}${formatConfidenceValueTail(p)}`);
if (p.pinned) tags.push("pinned");
return `- \`${p.id}\` (${tags.join(", ")}) โ€” ${p.principle}`;
}
@@ -247,10 +247,24 @@ function renderQuarantineLine(p: BrainPreference): string {
const tags: string[] = [];
if (p.scope) tags.push(`scope: ${p.scope}`);
tags.push(`applied: ${p.applied_count} / violated: ${p.violated_count}`);
+ if (p.confidence_value !== null) {
+ tags.push(`conf: ${p.confidence_value.toFixed(2)}`);
+ }
if (p.pinned) tags.push("pinned");
return `- \`${p.id}\` (${tags.join(", ")}) โ€” ${p.principle}`;
}
+/**
+ * Numeric `confidence_value` tail rendered next to the band in the
+ * `confidence:` metadata. Empty when the field is `null` (legacy
+ * preference written before v0.10.3 โ€” the next dream refresh lifts
+ * it to a real number).
+ */
+function formatConfidenceValueTail(p: BrainPreference): string {
+ if (p.confidence_value === null) return "";
+ return ` (${p.confidence_value.toFixed(2)})`;
+}
+
function renderRetiredLine(r: BrainRetired): string {
const date = r.retired_at.slice(0, 10);
return `- \`${r.id}\` โ€” ${r.retired_reason} on ${date}`;
diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.ts
index d3877c79..b15f7150 100644
--- a/src/core/brain/apply-evidence.ts
+++ b/src/core/brain/apply-evidence.ts
@@ -36,6 +36,7 @@ import { appendLogEvent, type AppendLogEventResult, type BrainLogEntry } from ".
import { parsePreference } from "./preference.ts";
import { preferencePath, validateSlug } from "./paths.ts";
import { isoSecond } from "./time.ts";
+import { renderPrefLink } from "./wikilink.ts";
import {
BRAIN_APPLY_RESULT,
BRAIN_LOG_EVENT_KIND,
@@ -158,12 +159,13 @@ export function appendApplyEvidence(
}
// Parse so a corrupted target produces a meaningful error rather
// than silently appending an evidence row that points at garbage.
- // Pollutes the typecheck only โ€” we don't use the return value.
- parsePreference(prefFilePath);
+ // The parsed pref also supplies the principle used to title the
+ // wikilink we emit below.
+ const target = parsePreference(prefFilePath);
const now = opts.now ?? new Date();
const timestamp = isoSecond(now);
- const wikilink = `[[pref-${slug}]]`;
+ const wikilink = renderPrefLink({ id: target.id, principle: target.principle });
// Render the canonical payload. Ordering is deliberate: the wikilink
// to the preference comes first so a human scrolling the log finds
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index 0939ed2d..33762a53 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -40,7 +40,7 @@ import { join } from "node:path";
import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";
import { brainDirs, vaultRelative } from "./paths.ts";
-import { normaliseWikilinkTarget } from "./wikilink.ts";
+import { normaliseWikilinkTarget, renderPrefLink } from "./wikilink.ts";
import { parsePreference, parseRetired } from "./preference.ts";
import { parseLogDay, type BrainLogEntry } from "./log.ts";
import {
@@ -86,6 +86,7 @@ export interface RenderDigestResult {
export interface DigestJsonNewUnconfirmed {
readonly id: string;
readonly topic: string;
+ readonly principle: string;
readonly scope: string | null;
readonly signal_count: number;
readonly unconfirmed_until: string;
@@ -95,6 +96,7 @@ export interface DigestJsonNewUnconfirmed {
export interface DigestJsonConfirmed {
readonly id: string;
readonly topic: string;
+ readonly principle: string;
readonly scope: string | null;
readonly confirmed_at: string;
readonly first_applied_artifact: string | null;
@@ -103,6 +105,7 @@ export interface DigestJsonConfirmed {
export interface DigestJsonRetired {
readonly id: string;
readonly topic: string;
+ readonly principle: string;
readonly scope: string | null;
readonly retired_at: string;
readonly reason: string;
@@ -111,6 +114,12 @@ export interface DigestJsonRetired {
export interface DigestJsonConfidenceShift {
readonly id: string;
+ /**
+ * Human-readable title sourced from the referenced pref or retired's
+ * `principle` field. Empty string when the id does not resolve to a
+ * known artifact (the markdown renderer falls back to bare `[[id]]`).
+ */
+ readonly principle: string;
readonly from: BrainConfidence | string;
readonly to: BrainConfidence | string;
readonly applied_count: number | null;
@@ -119,6 +128,8 @@ export interface DigestJsonConfidenceShift {
export interface DigestJsonContradiction {
readonly id: string;
+ /** See {@link DigestJsonConfidenceShift.principle}. */
+ readonly principle: string;
readonly topic: string | null;
readonly description: string;
}
@@ -132,6 +143,7 @@ export interface DigestJsonContradiction {
export interface DigestJsonTopApplied {
readonly id: string;
readonly topic: string;
+ readonly principle: string;
readonly scope: string | null;
readonly applied_count: number;
readonly violated_count: number;
@@ -147,6 +159,7 @@ export interface DigestJsonTopApplied {
export interface DigestJsonTopReferenced {
readonly id: string;
readonly topic: string;
+ readonly principle: string;
readonly scope: string | null;
readonly backlink_count: number;
}
@@ -273,6 +286,7 @@ function collectDigestData(
new_unconfirmed.push({
id: pref.id,
topic: pref.topic,
+ principle: pref.principle,
scope: pref.scope ?? null,
signal_count: pref.evidenced_by.length,
unconfirmed_until: pref.unconfirmed_until,
@@ -283,6 +297,7 @@ function collectDigestData(
confirmed.push({
id: pref.id,
topic: pref.topic,
+ principle: pref.principle,
scope: pref.scope ?? null,
confirmed_at: pref.confirmed_at!,
first_applied_artifact: findFirstAppliedArtifact(vault, pref.id),
@@ -292,13 +307,15 @@ function collectDigestData(
// 2. Iterate retired/ for entries retired in window.
const retiredEntries: DigestJsonRetired[] = [];
- for (const { ret, path } of readAllRetired(vault)) {
+ const retiredAll = readAllRetired(vault);
+ for (const { ret, path } of retiredAll) {
void path;
if (inWindow(ret.retired_at)) {
const daysStale = daysStaleFor(ret);
retiredEntries.push({
id: ret.id,
topic: ret.topic,
+ principle: ret.principle,
scope: ret.scope ?? null,
retired_at: ret.retired_at,
reason: ret.retired_reason,
@@ -308,10 +325,16 @@ function collectDigestData(
}
// 3 & 4. Confidence shifts and contradictions โ€” degraded gracefully
- // when payload data is missing.
+ // when payload data is missing. The extractors look principles up
+ // against the combined pref + retired index so the markdown renderer
+ // can emit titled wikilinks; ids that resolve to neither map fall
+ // back to an empty principle (and a bare `[[id]]` link).
+ const idToPrinciple = new Map<string, string>();
+ for (const { pref } of preferences) idToPrinciple.set(pref.id, pref.principle);
+ for (const { ret } of retiredAll) idToPrinciple.set(ret.id, ret.principle);
const logEntries = readLogsInWindow(vault, since, until);
- const confidenceShifts = extractConfidenceShifts(logEntries);
- const contradictions = extractContradictions(logEntries);
+ const confidenceShifts = extractConfidenceShifts(logEntries, idToPrinciple);
+ const contradictions = extractContradictions(logEntries, idToPrinciple);
// Stable ordering โ€” id ascending so two runs on the same fixture
// produce byte-identical output.
@@ -352,6 +375,7 @@ function pickTopApplied(
return active.slice(0, HOT_SECTION_LIMIT).map(({ pref }) => ({
id: pref.id,
topic: pref.topic,
+ principle: pref.principle,
scope: pref.scope ?? null,
applied_count: pref.applied_count,
violated_count: pref.violated_count,
@@ -379,6 +403,7 @@ function pickTopReferenced(
return scored.slice(0, HOT_SECTION_LIMIT).map(({ pref, count }) => ({
id: pref.id,
topic: pref.topic,
+ principle: pref.principle,
scope: pref.scope ?? null,
backlink_count: count,
}));
@@ -546,6 +571,7 @@ function daysStaleFor(ret: BrainRetired): number | null {
function extractConfidenceShifts(
entries: ReadonlyArray<BrainLogEntry>,
+ idToPrinciple: ReadonlyMap<string, string>,
): ReadonlyArray<DigestJsonConfidenceShift> {
const out: DigestJsonConfidenceShift[] = [];
for (const e of entries) {
@@ -555,7 +581,7 @@ function extractConfidenceShifts(
const shifts = e.body["confidence_shifts"];
if (Array.isArray(shifts)) {
for (const raw of shifts) {
- const parsed = parseShiftLine(raw);
+ const parsed = parseShiftLine(raw, idToPrinciple);
if (parsed) out.push(parsed);
}
}
@@ -563,7 +589,10 @@ function extractConfidenceShifts(
return out;
}
-function parseShiftLine(raw: string): DigestJsonConfidenceShift | null {
+function parseShiftLine(
+ raw: string,
+ idToPrinciple: ReadonlyMap<string, string>,
+): DigestJsonConfidenceShift | null {
// Tolerant parser: accept `[[pref-x]] medium -> high (applied: N, violated: M)`
// and variations (en-dash / em-dash for arrow, missing parens).
const m = /^\s*(?:\[\[([^\]]+)\]\]|(\S+))\s+(\w+)\s*(?:->|โ†’)\s*(\w+)(?:\s*\(([^)]*)\))?/.exec(
@@ -582,11 +611,19 @@ function parseShiftLine(raw: string): DigestJsonConfidenceShift | null {
const violMatch = /violated\s*[:=]?\s*(\d+)/i.exec(m[5]);
if (violMatch) violated = parseInt(violMatch[1]!, 10);
}
- return { id: idRaw, from, to, applied_count: applied, violated_count: violated };
+ return {
+ id: idRaw,
+ principle: idToPrinciple.get(idRaw) ?? "",
+ from,
+ to,
+ applied_count: applied,
+ violated_count: violated,
+ };
}
function extractContradictions(
entries: ReadonlyArray<BrainLogEntry>,
+ idToPrinciple: ReadonlyMap<string, string>,
): ReadonlyArray<DigestJsonContradiction> {
const out: DigestJsonContradiction[] = [];
for (const e of entries) {
@@ -594,7 +631,7 @@ function extractContradictions(
const list = e.body["contradictions"];
if (Array.isArray(list)) {
for (const raw of list) {
- const parsed = parseContradictionLine(raw);
+ const parsed = parseContradictionLine(raw, idToPrinciple);
if (parsed) out.push(parsed);
}
}
@@ -602,7 +639,10 @@ function extractContradictions(
return out;
}
-function parseContradictionLine(raw: string): DigestJsonContradiction | null {
+function parseContradictionLine(
+ raw: string,
+ idToPrinciple: ReadonlyMap<string, string>,
+): DigestJsonContradiction | null {
// Best-effort: extract a wikilink as id and treat the rest as topic
// or description. A missing wikilink means we cannot anchor the
// contradiction to a preference; skip rather than fabricate.
@@ -614,7 +654,12 @@ function parseContradictionLine(raw: string): DigestJsonContradiction | null {
let topic: string | null = null;
const tm = /topic\s*[:=]\s*([A-Za-z0-9_-]+)/.exec(description);
if (tm) topic = tm[1]!;
- return { id, topic, description };
+ return {
+ id,
+ principle: idToPrinciple.get(id) ?? "",
+ topic,
+ description,
+ };
}
// ----- Markdown rendering --------------------------------------------------
@@ -649,7 +694,7 @@ function renderMarkdown(
const scope = item.scope ?? "โ€”";
const trialDay = item.unconfirmed_until.slice(0, 10);
lines.push(
- `- [[${item.id}]] โ€” ${scope}, ${item.signal_count} signals, trial ends ${trialDay}`,
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${scope}, ${item.signal_count} signals, trial ends ${trialDay}`,
);
}
lines.push("");
@@ -659,7 +704,9 @@ function renderMarkdown(
for (const item of data.confirmed) {
const scope = item.scope ?? "โ€”";
const artifact = item.first_applied_artifact ?? "_(none)_";
- lines.push(`- [[${item.id}]] โ€” ${scope}, first applied in ${artifact}`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${scope}, first applied in ${artifact}`,
+ );
}
lines.push("");
}
@@ -671,7 +718,9 @@ function renderMarkdown(
item.reason === BRAIN_RETIRED_REASON.staleNoEvidence && item.days_stale !== null
? `${item.reason} (${item.days_stale} days)`
: item.reason;
- lines.push(`- [[${item.id}]] โ€” ${scope}, ${detail}`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${scope}, ${detail}`,
+ );
}
lines.push("");
}
@@ -681,7 +730,9 @@ function renderMarkdown(
const scope = item.scope ?? "โ€”";
const stats = `applied: ${item.applied_count}, violated: ${item.violated_count}`;
const tags = item.status === "quarantine" ? " [quarantine]" : "";
- lines.push(`- [[${item.id}]] โ€” ${scope}, ${stats}${tags}`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${scope}, ${stats}${tags}`,
+ );
}
lines.push("");
}
@@ -689,7 +740,9 @@ function renderMarkdown(
lines.push(`## Top referenced (${data.top_referenced.length})`, "");
for (const item of data.top_referenced) {
const scope = item.scope ?? "โ€”";
- lines.push(`- [[${item.id}]] โ€” ${scope}, ${item.backlink_count} inbound`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${scope}, ${item.backlink_count} inbound`,
+ );
}
lines.push("");
}
@@ -700,7 +753,9 @@ function renderMarkdown(
item.applied_count !== null && item.violated_count !== null
? ` (applied: ${item.applied_count}, violated: ${item.violated_count})`
: "";
- lines.push(`- [[${item.id}]] ${item.from} โ†’ ${item.to}${stats}`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} ${item.from} โ†’ ${item.to}${stats}`,
+ );
}
lines.push("");
}
@@ -708,7 +763,9 @@ function renderMarkdown(
lines.push("## Contradictions", "");
for (const item of data.contradictions) {
const topic = item.topic ? ` (topic: ${item.topic})` : "";
- lines.push(`- [[${item.id}]] โ€” ${item.description}${topic}`);
+ lines.push(
+ `- ${renderPrefLink({ id: item.id, principle: item.principle })} โ€” ${item.description}${topic}`,
+ );
}
lines.push("");
}
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 15b2aef8..09685b33 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -66,7 +66,7 @@ import {
vaultRelative,
} from "./paths.ts";
import { isoDate, isoSecond } from "./time.ts";
-import { parseWikilink } from "./wikilink.ts";
+import { parseWikilink, renderPrefLink } from "./wikilink.ts";
import {
BRAIN_APPLY_RESULT,
BRAIN_CONFIDENCE,
@@ -84,6 +84,16 @@ import {
// ----- Public types --------------------------------------------------------
+/**
+ * Structured non-fatal warning emitted alongside a dream summary. The
+ * dream pass still completes when warnings are present; callers
+ * (CLI / MCP) decide whether to surface them.
+ */
+export interface DreamWarning {
+ readonly code: string;
+ readonly message: string;
+}
+
export interface DreamRunSummary {
/** `dream-YYYY-MM-DD-HHMMSS`. */
readonly run_id: string;
@@ -107,6 +117,13 @@ export interface DreamRunSummary {
* land in the `signal-suppressed` log event).
*/
readonly suppressed: ReadonlyArray<string>;
+ /**
+ * Non-fatal warnings raised during the run. Currently emitted only
+ * for `non-primary-dream-run` (the runtime running dream differs
+ * from `Brain/_brain.yaml.primary_agent`); the list is the
+ * extension point for future advisory checks.
+ */
+ readonly warnings: ReadonlyArray<DreamWarning>;
/** Snapshot file (absent on a no-op run). */
readonly snapshot_path?: string;
/** Log file the run summary landed in (absent on a no-op run). */
@@ -120,6 +137,15 @@ export interface DreamOptions {
readonly now?: Date;
/** When true, compute the plan but make no writes. */
readonly dryRun?: boolean;
+ /**
+ * Identity of the agent invoking dream. Compared against
+ * `Brain/_brain.yaml.primary_agent`; mismatch emits a
+ * `non-primary-dream-run` warning and tags the dream summary log
+ * event with `non_primary_agent: <name>`. When unset, the warning
+ * never fires (back-compat with callers that have not been
+ * threaded yet); the CLI always provides the value.
+ */
+ readonly agentName?: string;
}
// ----- Internal scan types ------------------------------------------------
@@ -140,6 +166,7 @@ interface RetiredRecord {
readonly path: string;
readonly topic: string;
readonly id: string;
+ readonly principle: string;
readonly scope?: string;
/**
* The free-form user reason passed to `o2b brain reject --reason`.
@@ -169,6 +196,26 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
const runId = formatRunId(now);
const wikilinkToRun = `[[Brain/log/${isoDate(now)}]]`;
+ // Collect non-fatal warnings raised during the run. The
+ // non-primary-dream-run check is the first one: when the caller
+ // declares an agent name and it differs from the vault's declared
+ // primary, surface a structured warning. We do NOT abort โ€” the
+ // declaration is observability, not access control.
+ const warnings: DreamWarning[] = [];
+ const callerAgent = opts.agentName?.trim() ?? "";
+ const isNonPrimary =
+ cfg.primary_agent !== null
+ && callerAgent.length > 0
+ && callerAgent !== cfg.primary_agent;
+ if (isNonPrimary) {
+ warnings.push({
+ code: "non-primary-dream-run",
+ message:
+ `dream run from agent '${callerAgent}', but primary is `
+ + `'${cfg.primary_agent}'. Convention violation, run proceeds.`,
+ });
+ }
+
// 0. Scan the whole Brain/ tree. Corrupted files (frontmatter
// parse-errors) are surfaced separately so the planning phase
// can emit `skip-corrupted-frontmatter` log entries without
@@ -225,6 +272,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
contradictions: [...plan.contradictionTopics],
moved_to_processed: [],
suppressed: [],
+ warnings: Object.freeze([...warnings]),
...(dryRun ? { dry_run: true } : {}),
} satisfies DreamRunSummary);
}
@@ -269,6 +317,11 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
),
status: BRAIN_PREFERENCE_STATUS.unconfirmed,
evidenced_by: np.evidencedBy,
+ // No evidence yet โ†’ Wilson lower bound on (0, 0) is 0. Pre-
+ // seed the field so refresh on the next pass does not have
+ // to treat `null` as "needs update" (which would lift
+ // `changed: false` no-ops into spurious rewrites).
+ confidence_value: 0,
recentApplied: [],
recentViolated: [],
...(np.scope ? { scope: np.scope } : {}),
@@ -301,6 +354,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
violated_count: update.violated_count,
last_evidence_at: update.last_evidence_at,
confidence: update.confidence,
+ confidence_value: update.confidence_value,
pinned: update.pinned,
recentApplied: ev.applied,
recentViolated: ev.violated,
@@ -412,13 +466,31 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
});
}
- // Summary event last.
- const newUnconfirmedIds = plan.newUnconfirmed.map((p) => `[[pref-${p.slug}]]`);
- const confirmedIds = Array.from(refresh.confirmed.values()).map(
- (slug) => `[[pref-${slug}]]`,
+ // Summary event last. Link rendering threads the in-memory
+ // principle alongside the id so the digest / Obsidian view can
+ // hover-preview the rule without an extra file open.
+ const slugToPrefPrinciple = new Map<string, string>();
+ for (const rec of scan.preferences) {
+ const recSlug = rec.pref.id.startsWith("pref-")
+ ? rec.pref.id.slice("pref-".length)
+ : rec.pref.id;
+ slugToPrefPrinciple.set(recSlug, rec.pref.principle);
+ }
+ const newUnconfirmedIds = plan.newUnconfirmed.map((p) =>
+ renderPrefLink({ id: `pref-${p.slug}`, principle: p.principle }),
+ );
+ const confirmedIds = Array.from(refresh.confirmed.values()).map((slug) =>
+ renderPrefLink({
+ id: `pref-${slug}`,
+ principle:
+ refresh.updated.get(slug)?.principle
+ ?? slugToPrefPrinciple.get(slug)
+ ?? "",
+ }),
);
const retiredEntries = plan.retires.map(
- (r) => `[[ret-${r.slug}]] (${r.reason})`,
+ (r) =>
+ `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,
);
const summaryBody: Record<string, string | ReadonlyArray<string>> = {
run_id: runId,
@@ -435,6 +507,25 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
(s) => `${s.signal} โ† ${s.retired}`,
);
}
+ if (refresh.bandDrops.length > 0) {
+ // Format matches the digest's tolerant `parseShiftLine` parser:
+ // `[[pref-โ€ฆ|principle]] <from> -> <to> (applied: N, violated: M)`.
+ summaryBody["confidence_shifts"] = refresh.bandDrops.map((d) =>
+ [
+ renderPrefLink({ id: d.id, principle: d.principle }),
+ d.previous,
+ "->",
+ d.next,
+ `(applied: ${d.applied}, violated: ${d.violated})`,
+ ].join(" "),
+ );
+ }
+ if (isNonPrimary) {
+ // Audit-trail row matching the structured warning. Stored
+ // alongside `run_id` so a non-primary dream pass is greppable in
+ // the log without parsing the structured warnings array.
+ summaryBody["non_primary_agent"] = callerAgent;
+ }
writeEvent(vault, {
timestamp: nextStamp(),
@@ -471,6 +562,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
suppressed: plan.signalsSuppressed.map((s) =>
s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),
),
+ warnings: Object.freeze([...warnings]),
...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),
...(dryRun
? { dry_run: true }
@@ -536,6 +628,8 @@ function scanBrain(vault: string): ScanResult {
const [meta] = parseFrontmatter(full);
const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";
const id = typeof meta["id"] === "string" ? meta["id"] : "";
+ const principle =
+ typeof meta["principle"] === "string" ? meta["principle"] : "";
const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;
const userReason =
typeof meta["user_rejected_reason"] === "string"
@@ -546,6 +640,7 @@ function scanBrain(vault: string): ScanResult {
path: full,
topic,
id,
+ principle,
...(scope ? { scope } : {}),
...(userReason ? { user_rejected_reason: userReason } : {}),
});
@@ -584,6 +679,7 @@ interface PlanState {
interface SignalSuppressedPlan {
readonly signal: string;
+ /** Pre-rendered `[[ret-slug|principle]]` wikilink for the suppressor. */
readonly retired: string;
readonly reason: string;
readonly topic: string;
@@ -607,16 +703,24 @@ interface NewUnconfirmedPlan {
interface RetirePlan {
readonly slug: string;
+ /**
+ * Principle of the preference being retired, captured at plan time
+ * so the dream summary log payload can render a titled wikilink
+ * (`[[ret-slug|principle]]`) without re-reading the file after move.
+ */
+ readonly principle: string;
readonly reason: BrainRetiredReason;
readonly supersededBy?: string;
}
interface NotedRedundantPlan {
+ /** Pre-rendered `[[pref-id|principle]]` wikilink for the active pref. */
readonly preference: string;
readonly signal: string;
}
interface RetainPinnedPlan {
+ /** Pre-rendered `[[pref-id|principle]]` wikilink for the pinned pref. */
readonly preference: string;
readonly reason: BrainRetiredReason;
}
@@ -725,7 +829,10 @@ function planTopics(
}
plan.signalsSuppressed.push({
signal: `[[${sig.signal.id}]]`,
- retired: `[[${suppressor.id}]]`,
+ retired: renderPrefLink({
+ id: suppressor.id,
+ principle: suppressor.principle,
+ }),
reason: suppressor.user_rejected_reason!,
topic,
});
@@ -767,6 +874,9 @@ function planTopics(
// include the minority signals so the audit trail preserves the
// contradiction story even after the file moves to processed/.
const evidencedBy = windowedSigs.map((s) => `[[${s.signal.id}]]`);
+ const supersedesRecord = supersedes
+ ? retiredForTopic!.find((r) => r.id === supersedes)
+ : undefined;
plan.newUnconfirmed.push({
slug,
topic,
@@ -774,7 +884,14 @@ function planTopics(
principle,
evidencedBy,
sign,
- ...(supersedes ? { supersedes: `[[${supersedes}]]` } : {}),
+ ...(supersedesRecord
+ ? {
+ supersedes: renderPrefLink({
+ id: supersedesRecord.id,
+ principle: supersedesRecord.principle,
+ }),
+ }
+ : {}),
});
// Every contributing signal in the window gets moved.
for (const s of windowedSigs) {
@@ -861,7 +978,10 @@ function handleSignalsOnActivePref(
// Same-sign โ†’ note redundant + move to processed.
for (const s of sameSign) {
plan.notedRedundant.push({
- preference: `[[${active.pref.id}]]`,
+ preference: renderPrefLink({
+ id: active.pref.id,
+ principle: active.pref.principle,
+ }),
signal: `[[${s.signal.id}]]`,
});
recordSignalMove(plan, s);
@@ -874,7 +994,10 @@ function handleSignalsOnActivePref(
: active.pref.id;
if (isPinned(active.pref)) {
plan.retainPinned.push({
- preference: `[[${active.pref.id}]]`,
+ preference: renderPrefLink({
+ id: active.pref.id,
+ principle: active.pref.principle,
+ }),
reason: BRAIN_RETIRED_REASON.rebutted,
});
// Rebuttal signals on a pinned pref still get moved out โ€” they
@@ -884,6 +1007,7 @@ function handleSignalsOnActivePref(
} else {
plan.retires.push({
slug,
+ principle: active.pref.principle,
reason: BRAIN_RETIRED_REASON.rebutted,
});
for (const s of opposing) recordSignalMove(plan, s);
@@ -905,7 +1029,10 @@ function handleSignalsOnActivePref(
principle,
evidencedBy,
sign: oppositeSign,
- supersedes: `[[${active.pref.id}]]`,
+ supersedes: renderPrefLink({
+ id: active.pref.id,
+ principle: active.pref.principle,
+ }),
});
}
} else if (opposing.length > 0) {
@@ -986,14 +1113,37 @@ interface RefreshUpdate {
readonly violated_count: number;
readonly last_evidence_at: string | null;
readonly confidence: BrainConfidence;
+ readonly confidence_value: number;
readonly pinned: boolean;
}
+/**
+ * Pref โ†’ recorded band drop within the current dream pass. Captured
+ * during refresh so the digest can render a `## Confidence drops`
+ * section without re-deriving transitions from the log.
+ */
+export interface RefreshBandDrop {
+ readonly id: string;
+ readonly principle: string;
+ readonly previous: BrainConfidence;
+ readonly next: BrainConfidence;
+ readonly applied: number;
+ readonly violated: number;
+ readonly previous_value: number | null;
+ readonly next_value: number;
+}
+
interface RefreshResult {
/** Slugs transitioning unconfirmed โ†’ confirmed in THIS run. */
readonly confirmed: Set<string>;
/** Slug โ†’ full updated frontmatter to write. */
readonly updated: Map<string, RefreshUpdate>;
+ /**
+ * Preferences whose `confidence` band dropped (e.g. `high โ†’ medium`)
+ * during the refresh phase. Newest-first stable order (insertion
+ * order at construction).
+ */
+ readonly bandDrops: RefreshBandDrop[];
}
interface ApplyEvidenceEntry {
@@ -1047,6 +1197,7 @@ function planRefresh(
): RefreshResult {
const confirmed = new Set<string>();
const updated = new Map<string, RefreshUpdate>();
+ const bandDrops: RefreshBandDrop[] = [];
// Index evidence by slug.
const bySlug = new Map<string, ApplyEvidenceEntry[]>();
@@ -1087,6 +1238,7 @@ function planRefresh(
if (outdatedCount > 0) {
plan.retires.push({
slug,
+ principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.supersededByContext,
});
continue;
@@ -1116,12 +1268,16 @@ function planRefresh(
if (newViolated) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
- preference: `[[${rec.pref.id}]]`,
+ preference: renderPrefLink({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ }),
reason: BRAIN_RETIRED_REASON.quarantineViolated,
});
} else {
plan.retires.push({
slug,
+ principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.quarantineViolated,
});
// Skip refresh โ€” moveToRetired will read the on-disk
@@ -1133,7 +1289,7 @@ function planRefresh(
}
}
- const confidenceValue = computeConfidence(
+ const confidence = computeConfidence(
applied,
violated,
lastEvidence,
@@ -1148,13 +1304,24 @@ function planRefresh(
// forward โ€” a pref whose counters are stable but whose body
// still has the v0.9.x placeholder will fail the body check and
// get rewritten on the next pass.
+ const previousValue = rec.pref.confidence_value;
+ // For numeric drift, `null` on disk (legacy pre-v0.10.3 file) is
+ // treated as "matches whatever we just computed" so a no-op
+ // rerun stays a no-op. The body-bytes check in
+ // `wouldRewritePreference` below still triggers the one-off
+ // migration write because the legacy frontmatter shape will not
+ // match the new one byte-for-byte.
+ const valueDifferent =
+ previousValue !== null
+ && Math.abs(previousValue - confidence.value) > 1e-6;
const countersChanged =
applied !== rec.pref.applied_count ||
violated !== rec.pref.violated_count ||
lastEvidence !== rec.pref.last_evidence_at ||
status !== rec.pref.status ||
confirmedAt !== rec.pref.confirmed_at ||
- confidenceValue !== rec.pref.confidence;
+ confidence.band !== rec.pref.confidence ||
+ valueDifferent;
const prospective = {
slug,
@@ -1169,7 +1336,8 @@ function planRefresh(
applied_count: applied,
violated_count: violated,
last_evidence_at: lastEvidence,
- confidence: confidenceValue,
+ confidence: confidence.band,
+ confidence_value: confidence.value,
pinned: rec.pref.pinned,
};
@@ -1190,42 +1358,147 @@ function planRefresh(
}
updated.set(slug, prospective);
+
+ // Capture band drops for the digest. A drop is any transition
+ // where the new band ranks lower than the previous (high โ†’
+ // medium, medium โ†’ low, high โ†’ low). Stable across re-runs as
+ // long as the underlying counters do โ€” the digest only renders
+ // it when a real transition occurred in this pass.
+ if (BAND_RANK[confidence.band] < BAND_RANK[rec.pref.confidence]) {
+ bandDrops.push(
+ Object.freeze({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ previous: rec.pref.confidence,
+ next: confidence.band,
+ applied,
+ violated,
+ previous_value: rec.pref.confidence_value,
+ next_value: confidence.value,
+ }),
+ );
+ }
}
- return { confirmed, updated };
+ return { confirmed, updated, bandDrops };
+}
+
+/**
+ * Confidence computation. Returns both the categorical band (the
+ * existing agent-visible contract) and the numeric value behind it
+ * (ยง10 Tier-A addition).
+ *
+ * The numeric value is `Wilson 95% lower bound ร— freshness decay`:
+ *
+ * - `wilson_low(applied, n)` where `n = applied + violated` โ€”
+ * a conservative lower bound on the application rate. `n == 0`
+ * yields `0`.
+ * - `freshness` linearly decays from `1.0` at age 0 to `0.0` at
+ * `retire.stale_evidence_days`. `null` last_evidence_at โ†’ `0`.
+ *
+ * Band derivation is the **max** of two views:
+ *
+ * 1. The legacy step-function (kept verbatim) โ€” preserves every
+ * published boundary so existing tests and agent contracts stay
+ * intact: `applied <= low_max_applied` โ‡’ `low`,
+ * `violated >= applied` โ‡’ `low`, `applied >= high_min_applied โˆง
+ * violated == 0 โˆง fresh` โ‡’ `high`, else `medium`.
+ * 2. The numeric thresholds (`medium_min`, `high_min`) applied to
+ * `value` โ€” gives a `low | medium | high` view that can only
+ * lift the legacy band, never lower it.
+ *
+ * Taking the max means a future operator can lower `high_min` to
+ * promote `medium` prefs to `high` based on observed performance,
+ * without ever demoting a pref that the legacy view already calls
+ * `high` (because the legacy floor sticks). The numeric value is
+ * always returned and is what the digest's drop tracker compares
+ * across runs.
+ */
+export interface ConfidenceComputeResult {
+ readonly value: number;
+ readonly band: BrainConfidence;
}
-function computeConfidence(
+const BAND_RANK: Readonly<Record<BrainConfidence, number>> = Object.freeze({
+ low: 0,
+ medium: 1,
+ high: 2,
+});
+
+export function computeConfidence(
applied: number,
violated: number,
lastEvidenceAt: string | null,
cfg: BrainConfig,
now: Date,
-): BrainConfidence {
- // From ยง7.4:
- // if applied <= low_max_applied or (applied > 0 and violated >= applied):
- // confidence = low
- // elif applied >= high_min_applied and violated == 0 and fresh:
- // confidence = high
- // else:
- // confidence = medium
- if (applied <= cfg.confidence.low_max_applied) return BRAIN_CONFIDENCE.low;
- if (applied > 0 && violated >= applied) return BRAIN_CONFIDENCE.low;
- let fresh = false;
+): ConfidenceComputeResult {
+ const n = applied + violated;
+ let wilsonLow = 0;
+ if (n > 0) {
+ const z = 1.96;
+ const z2 = z * z;
+ const pHat = applied / n;
+ const denom = 1 + z2 / n;
+ const centre = (pHat + z2 / (2 * n)) / denom;
+ const margin =
+ (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;
+ wilsonLow = Math.max(0, centre - margin);
+ }
+ let freshness = 0;
if (lastEvidenceAt) {
const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
- const freshLimitMs =
- cfg.retire.stale_evidence_days *
- cfg.confidence.high_freshness_factor *
- 24 *
- 3600 *
- 1000;
- fresh = Number.isFinite(ageMs) && ageMs < freshLimitMs;
+ if (Number.isFinite(ageMs)) {
+ const limitMs = cfg.retire.stale_evidence_days * 24 * 3600 * 1000;
+ if (limitMs > 0) {
+ freshness = Math.max(0, Math.min(1, 1 - ageMs / limitMs));
+ }
+ }
}
- if (applied >= cfg.confidence.high_min_applied && violated === 0 && fresh) {
- return BRAIN_CONFIDENCE.high;
+ const rawValue = wilsonLow * freshness;
+ const value = Math.round(rawValue * 10000) / 10000;
+
+ // Legacy step-function band (the published contract).
+ let legacyBand: BrainConfidence = BRAIN_CONFIDENCE.medium;
+ if (applied <= cfg.confidence.low_max_applied) {
+ legacyBand = BRAIN_CONFIDENCE.low;
+ } else if (applied > 0 && violated >= applied) {
+ legacyBand = BRAIN_CONFIDENCE.low;
+ } else {
+ let highEligibleFresh = false;
+ if (lastEvidenceAt) {
+ const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
+ const freshLimitMs =
+ cfg.retire.stale_evidence_days *
+ cfg.confidence.high_freshness_factor *
+ 24 *
+ 3600 *
+ 1000;
+ highEligibleFresh = Number.isFinite(ageMs) && ageMs < freshLimitMs;
+ }
+ if (
+ applied >= cfg.confidence.high_min_applied
+ && violated === 0
+ && highEligibleFresh
+ ) {
+ legacyBand = BRAIN_CONFIDENCE.high;
+ } else {
+ legacyBand = BRAIN_CONFIDENCE.medium;
+ }
+ }
+
+ // Numeric-threshold band (can only lift legacy when paired via max).
+ let numericBand: BrainConfidence;
+ if (value >= cfg.confidence.high_min) {
+ numericBand = BRAIN_CONFIDENCE.high;
+ } else if (value >= cfg.confidence.medium_min) {
+ numericBand = BRAIN_CONFIDENCE.medium;
+ } else {
+ numericBand = BRAIN_CONFIDENCE.low;
}
- return BRAIN_CONFIDENCE.medium;
+
+ const band =
+ BAND_RANK[numericBand] > BAND_RANK[legacyBand] ? numericBand : legacyBand;
+ return Object.freeze({ value, band });
}
// ----- Auto-retires (expired-unconfirmed, stale-no-evidence) --------------
@@ -1259,12 +1532,16 @@ function planAutoRetires(
if (Number.isFinite(deadline) && now.getTime() > deadline) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
- preference: `[[${rec.pref.id}]]`,
+ preference: renderPrefLink({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ }),
reason: BRAIN_RETIRED_REASON.expiredUnconfirmed,
});
} else {
plan.retires.push({
slug,
+ principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.expiredUnconfirmed,
});
// Remove the refresh update โ€” no point writing immediately
@@ -1297,12 +1574,16 @@ function planAutoRetires(
if (days > cfg.retire.stale_evidence_days) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
- preference: `[[${rec.pref.id}]]`,
+ preference: renderPrefLink({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ }),
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
});
} else {
plan.retires.push({
slug,
+ principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
});
refresh.updated.delete(slug);
@@ -1314,12 +1595,16 @@ function planAutoRetires(
if (days > cfg.retire.stale_evidence_days) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
- preference: `[[${rec.pref.id}]]`,
+ preference: renderPrefLink({
+ id: rec.pref.id,
+ principle: rec.pref.principle,
+ }),
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
});
} else {
plan.retires.push({
slug,
+ principle: rec.pref.principle,
reason: BRAIN_RETIRED_REASON.staleNoEvidence,
});
refresh.updated.delete(slug);
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 1ed6256e..32a544b2 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -40,7 +40,10 @@ import {
brainManualPath,
vaultRelative,
} from "./paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "./policy.ts";
+import {
+ DEFAULT_BRAIN_CONFIG_YAML,
+ formatPrimaryAgentYamlValue,
+} from "./policy.ts";
import type { BrainConfig } from "./types.ts";
import { DEFAULT_BRAIN_CONFIG } from "./policy.ts";
@@ -76,6 +79,15 @@ export interface BootstrapBrainOptions {
* (`OPEN_SECOND_BRAIN_CONFIG` env โ†’ XDG โ†’ `~/.config`).
*/
readonly configPath?: string;
+ /**
+ * Optional primary-agent declaration for the vault. When provided on
+ * a fresh init (or with `force`), the value is written into
+ * `_brain.yaml.primary_agent`. On a re-run against an already
+ * initialised `_brain.yaml` the value is ignored โ€” use
+ * `o2b brain set-primary` to mutate an existing config (it is
+ * idempotent and won't disturb the rest of the file).
+ */
+ readonly primaryAgent?: string;
}
export interface BootstrapBrainResult {
@@ -133,18 +145,22 @@ export function bootstrapBrain(
mkdirSync(dir, { recursive: true });
}
- // 2. `_brain.yaml` โ€” default config.
+ // 2. `_brain.yaml` โ€” default config (with optional primary_agent).
const brainYamlPath = brainConfigPath(vault);
const brainYamlRel = vaultRelative(brainYamlPath, vault);
+ const initialYaml = applyPrimaryAgentToYaml(
+ DEFAULT_BRAIN_CONFIG_YAML,
+ opts.primaryAgent,
+ );
if (existsSync(brainYamlPath)) {
if (force) {
- atomicWriteFileSync(brainYamlPath, DEFAULT_BRAIN_CONFIG_YAML);
+ atomicWriteFileSync(brainYamlPath, initialYaml);
overwritten.push(brainYamlRel);
} else {
skipped.push(brainYamlRel);
}
} else {
- atomicWriteFileSync(brainYamlPath, DEFAULT_BRAIN_CONFIG_YAML);
+ atomicWriteFileSync(brainYamlPath, initialYaml);
created.push(brainYamlRel);
}
@@ -248,6 +264,26 @@ function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+/**
+ * Replace the `primary_agent: null` line in the default `_brain.yaml`
+ * body with the operator-supplied value, when provided. Trimmed,
+ * empty-string-rejecting (the validator would catch that at load time,
+ * but we fail loud here so an init that intended to declare a primary
+ * does not silently fall back to `null`).
+ *
+ * The substitution is anchored on the literal `^primary_agent:` line
+ * so re-running the helper against an already-customised YAML stays
+ * idempotent for the relevant slot.
+ */
+function applyPrimaryAgentToYaml(
+ yamlBody: string,
+ primaryAgent: string | undefined,
+): string {
+ if (primaryAgent === undefined) return yamlBody;
+ const line = `primary_agent: ${formatPrimaryAgentYamlValue(primaryAgent)}`;
+ return yamlBody.replace(/^primary_agent:.*$/m, line);
+}
+
/**
* Best-effort display name for the vault: the trailing directory name
* with separators stripped. Falls back to the literal `Second Brain`
@@ -258,4 +294,3 @@ function vaultDisplayName(vault: string): string {
const last = parts.length > 0 ? parts[parts.length - 1]! : "";
return last !== "" ? last : "Second Brain";
}
-
diff --git a/src/core/brain/pin.ts b/src/core/brain/pin.ts
index de105517..fb9fa40a 100644
--- a/src/core/brain/pin.ts
+++ b/src/core/brain/pin.ts
@@ -36,6 +36,7 @@ import { parsePreference } from "./preference.ts";
import { preferencePath, validateSlug } from "./paths.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, type BrainPreference } from "./types.ts";
+import { renderPrefLink } from "./wikilink.ts";
import { BrainPreferenceNotFoundError } from "./apply-evidence.ts";
export interface SetPinnedOptions {
@@ -123,7 +124,10 @@ export function setPinned(
timestamp: isoSecond(now),
eventType: value ? BRAIN_LOG_EVENT_KIND.pin : BRAIN_LOG_EVENT_KIND.unpin,
body: {
- preference: `[[pref-${slug}]]`,
+ preference: renderPrefLink({
+ id: `pref-${slug}`,
+ principle: current.principle,
+ }),
agent: (opts.agent ?? "cli").trim() || "cli",
},
};
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 583b71cc..6b25723e 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -34,6 +34,7 @@ export const BRAIN_CONFIG_SUPPORTED_VERSIONS: ReadonlyArray<number> = [1];
*/
export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
schema_version: 1,
+ primary_agent: null,
dream: Object.freeze({
candidate_threshold: 3,
unconfirmed_window_days: 14,
@@ -46,6 +47,8 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
low_max_applied: 2,
high_min_applied: 10,
high_freshness_factor: 0.8,
+ medium_min: 0.40,
+ high_min: 0.75,
}),
snapshots: Object.freeze({
retention_count: 10,
@@ -59,6 +62,12 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
*/
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
@@ -71,11 +80,55 @@ confidence:
low_max_applied: 2
high_min_applied: 10
high_freshness_factor: 0.8
+ # Derived-band thresholds on the numeric confidence_value (Wilson
+ # lower bound ร— freshness decay). The count-based hard floors
+ # above still take precedence: low_max_applied / violated >=
+ # applied / missing-fresh keep a rule at low / medium regardless
+ # of the numeric value.
+ medium_min: 0.40
+ high_min: 0.75
snapshots:
retention_count: 10
`;
+const YAML_STRING_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
+
+/**
+ * Format a `primary_agent` value for the small `_brain.yaml` subset.
+ *
+ * We quote non-null values so spaces / `#` / `:` round-trip as data
+ * instead of being interpreted as comments or YAML structure. Since the
+ * parser intentionally does not implement escape sequences, reject bytes
+ * that would require escaping rather than writing a value that cannot
+ * be read back exactly.
+ */
+export function formatPrimaryAgentYamlValue(
+ value: string | null,
+ source: string | null = null,
+): string {
+ if (value === null) return "null";
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "must be either null or a non-empty string",
+ "primary_agent",
+ source,
+ );
+ }
+ for (const bad of YAML_STRING_REJECTED_CHARS) {
+ if (trimmed.includes(bad)) {
+ throw new BrainConfigError(
+ `contains a disallowed character ${JSON.stringify(bad)}; ` +
+ "use a simple one-line agent id",
+ "primary_agent",
+ source,
+ );
+ }
+ }
+ return `"${trimmed}"`;
+}
+
/**
* Warnings collected during validation. Forward-compat tolerates unknown
* top-level keys but surfaces them so a typo doesn't go unnoticed.
@@ -219,6 +272,46 @@ export function validateBrainConfigDetailed(
);
}
+ // `primary_agent` โ€” optional scalar (null or non-empty string).
+ // Defaults to null when absent so existing vaults are unaffected.
+ // Loader enforces the same character constraints as the writer
+ // (`formatPrimaryAgentYamlValue`) so a hand-edited file that the
+ // writer would later refuse to emit fails fast at load time
+ // instead of round-tripping into a state we cannot persist.
+ let primaryAgent: string | null = DEFAULT_BRAIN_CONFIG.primary_agent;
+ if ("primary_agent" in obj) {
+ const v = obj["primary_agent"];
+ if (v === null || v === undefined) {
+ primaryAgent = null;
+ } else if (typeof v === "string") {
+ const trimmed = v.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "must be either null or a non-empty string",
+ "primary_agent",
+ source,
+ );
+ }
+ for (const bad of YAML_STRING_REJECTED_CHARS) {
+ if (trimmed.includes(bad)) {
+ throw new BrainConfigError(
+ `contains a disallowed character ${JSON.stringify(bad)}; ` +
+ "use a simple one-line agent id",
+ "primary_agent",
+ source,
+ );
+ }
+ }
+ primaryAgent = trimmed;
+ } else {
+ throw new BrainConfigError(
+ `must be either null or a non-empty string; got ${describe(v)}`,
+ "primary_agent",
+ source,
+ );
+ }
+ }
+
// Each block is optional; missing blocks inherit the default. We
// merge field-by-field so a user can override one threshold without
// having to re-state the rest.
@@ -268,6 +361,26 @@ export function validateBrainConfigDetailed(
source,
);
}
+ requireUnitInterval(
+ "confidence.medium_min",
+ confidence.medium_min,
+ source,
+ );
+ requireUnitInterval(
+ "confidence.high_min",
+ confidence.high_min,
+ source,
+ );
+ if (
+ (confidence.medium_min as number) >= (confidence.high_min as number)
+ ) {
+ throw new BrainConfigError(
+ `medium_min must be strictly less than high_min; got ` +
+ `medium_min=${confidence.medium_min}, high_min=${confidence.high_min}`,
+ "confidence.medium_min",
+ source,
+ );
+ }
const snapshots = mergeBlock(
"snapshots",
@@ -280,6 +393,7 @@ export function validateBrainConfigDetailed(
// Forward-compat: unknown top-level keys โ†’ warning, not error.
const known = new Set([
"schema_version",
+ "primary_agent",
"dream",
"retire",
"confidence",
@@ -296,6 +410,7 @@ export function validateBrainConfigDetailed(
const config: BrainConfig = {
schema_version: schemaVersion,
+ primary_agent: primaryAgent,
dream: {
candidate_threshold: dream.candidate_threshold as number,
unconfirmed_window_days: dream.unconfirmed_window_days as number,
@@ -308,6 +423,8 @@ export function validateBrainConfigDetailed(
low_max_applied: confidence.low_max_applied as number,
high_min_applied: confidence.high_min_applied as number,
high_freshness_factor: confidence.high_freshness_factor as number,
+ medium_min: confidence.medium_min as number,
+ high_min: confidence.high_min as number,
},
snapshots: {
retention_count: snapshots.retention_count as number,
@@ -376,6 +493,25 @@ function requireNonNegativeInteger(
}
}
+function requireUnitInterval(
+ field: string,
+ value: unknown,
+ source: string | null,
+): void {
+ if (
+ typeof value !== "number" ||
+ !Number.isFinite(value) ||
+ value < 0 ||
+ value > 1
+ ) {
+ throw new BrainConfigError(
+ `must be a number in [0, 1]; got ${describe(value)}`,
+ field,
+ source,
+ );
+ }
+}
+
function describe(value: unknown): string {
if (value === null) return "null";
if (value === undefined) return "undefined";
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 1cb40cd3..05f1b0c1 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -123,6 +123,13 @@ export interface WritePreferenceInput {
readonly violated_count?: number;
readonly last_evidence_at?: string | null;
readonly confidence?: BrainConfidence;
+ /**
+ * Numeric `confidence_value` (Wilson lower bound ร— freshness
+ * decay). `null` or absent leaves the on-disk field as `null`,
+ * signalling "not yet computed" to downstream readers. Dream's
+ * refresh pass always supplies a finite value.
+ */
+ readonly confidence_value?: number | null;
readonly pinned?: boolean;
readonly supersedes?: string;
readonly aliases?: ReadonlyArray<string>;
@@ -292,6 +299,15 @@ function preferenceFrontmatter(
const pinned = input.pinned ?? false;
const applied = input.applied_count ?? 0;
const violated = input.violated_count ?? 0;
+ // Round numeric confidence to 4 decimals so a no-op rerun produces
+ // byte-identical YAML even if upstream callers pass a value with
+ // floating-point jitter. `null` sentinel mirrors the other Group C
+ // null-encoded fields so the simple parser keeps round-tripping.
+ const confidenceValueRaw = input.confidence_value;
+ const confidenceValueField =
+ confidenceValueRaw === undefined || confidenceValueRaw === null
+ ? "null"
+ : Math.round(confidenceValueRaw * 10000) / 10000;
// ยง24: Group C derived fields gain `_` prefix so the visual
// boundary between "what dream owns" and "what the user owns"
@@ -318,6 +334,7 @@ function preferenceFrontmatter(
_violated_count: violated,
_last_evidence_at: input.last_evidence_at ?? "null",
_confidence: confidence,
+ _confidence_value: confidenceValueField,
pinned,
};
if (input.scope?.trim()) metadata["scope"] = input.scope.trim();
@@ -429,6 +446,7 @@ export const DERIVED_FIELDS: ReadonlyArray<string> = Object.freeze([
"applied_count",
"violated_count",
"confidence",
+ "confidence_value",
"evidenced_by",
"contradicted_by",
]);
@@ -527,6 +545,7 @@ export function parsePreference(path: string): BrainPreference {
violated_count: optionalNumber(meta, "violated_count", 0),
last_evidence_at,
confidence: parseConfidence(meta, path),
+ confidence_value: parseConfidenceValue(meta, path),
pinned: parsePinned(meta),
...(optionalScalarString(meta, "scope") !== undefined
? { scope: optionalScalarString(meta, "scope") }
@@ -602,6 +621,7 @@ export function parseRetired(path: string): BrainRetired {
violated_count: optionalNumber(meta, "violated_count", 0),
last_evidence_at: optionalNullableString(meta, "last_evidence_at"),
confidence: parseConfidence(meta, path),
+ confidence_value: parseConfidenceValue(meta, path),
pinned: parsePinned(meta),
...(optionalScalarString(meta, "scope") !== undefined
? { scope: optionalScalarString(meta, "scope") }
@@ -988,6 +1008,43 @@ function parseConfidence(
return v as BrainConfidence;
}
+/**
+ * Parse the numeric `confidence_value` field.
+ *
+ * Returns `null` when the field is absent, empty, or carries the
+ * literal sentinel `"null"` (the writer's null encoding for the
+ * simple YAML formatter). Otherwise must be a finite number in
+ * `[0, 1]`; out-of-range / non-finite / non-numeric values raise a
+ * hard parse error โ€” drifting numeric confidence into `> 1` or
+ * `NaN` would corrupt every downstream comparison silently.
+ */
+function parseConfidenceValue(
+ meta: Record<string, unknown>,
+ path: string,
+): number | null {
+ const v = meta["confidence_value"];
+ if (v === undefined || v === null || v === "" || v === "null") return null;
+ let n: number | null = null;
+ if (typeof v === "number") {
+ n = v;
+ } else if (typeof v === "string") {
+ const trimmed = v.trim();
+ // Whitespace-only string is the "null" sentinel in disguise.
+ // `Number("")` coerces to `0`, which would otherwise smuggle in a
+ // confident-zero band for a file the writer never produced a
+ // value for.
+ if (trimmed.length === 0 || trimmed === "null") return null;
+ const candidate = Number(trimmed);
+ if (Number.isFinite(candidate)) n = candidate;
+ }
+ if (n === null || !Number.isFinite(n) || n < 0 || n > 1) {
+ throw new Error(
+ `preference field 'confidence_value' must be a number in [0, 1]; got ${JSON.stringify(v)} (${path})`,
+ );
+ }
+ return n;
+}
+
/**
* Coerce `pinned` to boolean with a hard default of `false`. Accepts
* the literal string forms ("true"/"false") emitted by the simple
diff --git a/src/core/brain/set-primary.ts b/src/core/brain/set-primary.ts
new file mode 100644
index 00000000..804cb4f2
--- /dev/null
+++ b/src/core/brain/set-primary.ts
@@ -0,0 +1,126 @@
+/**
+ * Idempotent edit of the `primary_agent` line in `Brain/_brain.yaml`.
+ *
+ * The `primary_agent` field declares which runtime owns the `dream`
+ * consolidation pass for a vault. This module exists so the CLI verb
+ * `o2b brain set-primary` can flip the declaration without rewriting
+ * the entire YAML (which would forget user-overridden thresholds in
+ * adjacent blocks).
+ *
+ * Surface:
+ *
+ * - {@link setPrimaryAgent} reads the existing config, replaces the
+ * `^primary_agent:` line (or inserts it after `schema_version:`
+ * when absent), and writes back atomically. Returns the previous
+ * and next values plus a `changed` flag so callers can shape an
+ * exit message without a second read.
+ *
+ * - The function re-validates the config after the edit by piping it
+ * through {@link validateBrainConfig}. A non-conforming source file
+ * (someone broke the YAML by hand) surfaces as a typed
+ * {@link BrainConfigError} pointing at the offending field, with
+ * the live file untouched.
+ *
+ * Pure I/O โ€” no logging side effects. The CLI wraps the call in a
+ * `log` event when it wants the audit trail.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { brainConfigPath } from "./paths.ts";
+import {
+ BrainConfigError,
+ formatPrimaryAgentYamlValue,
+ parseBrainYaml,
+ validateBrainConfig,
+} from "./policy.ts";
+
+/**
+ * Result of {@link setPrimaryAgent}. `previous` is the value on disk
+ * before the call (parsed and trimmed; `null` when the file lacked the
+ * field or carried `null`). `next` is the value the file now carries.
+ * `changed` is `true` iff the on-disk bytes were rewritten.
+ */
+export interface SetPrimaryAgentResult {
+ readonly previous: string | null;
+ readonly next: string | null;
+ readonly changed: boolean;
+}
+
+const LINE_RE = /^primary_agent:.*$/m;
+
+/**
+ * Set or clear the vault's `primary_agent` declaration.
+ *
+ * Pass `null` (or omit the second argument by spelling `null`) to
+ * clear an existing declaration.
+ *
+ * Re-validates the YAML after substitution so a malformed source file
+ * surfaces as a typed error instead of writing back something that
+ * the loader will reject on the next read.
+ */
+export function setPrimaryAgent(
+ vault: string,
+ name: string | null,
+): SetPrimaryAgentResult {
+ const path = brainConfigPath(vault);
+ if (!existsSync(path)) {
+ throw new BrainConfigError(
+ "config file does not exist; run `o2b brain init` first",
+ null,
+ path,
+ );
+ }
+ const text = readFileSync(path, "utf8");
+
+ // Normalise the target value: trim non-null strings; reject empty
+ // strings explicitly so an accidental `--primary-agent ""` from the
+ // CLI never silently clears the field (the user must use `--clear`).
+ let nextValue: string | null;
+ if (name === null) {
+ nextValue = null;
+ } else {
+ const trimmed = name.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "primary agent name must be non-empty; use --clear to remove the declaration",
+ "primary_agent",
+ path,
+ );
+ }
+ nextValue = trimmed;
+ }
+
+ // Parse to recover the current value (also validates the source).
+ // We deliberately load the full config rather than peeking at the
+ // line: a malformed neighbouring block should surface here, before
+ // the write, rather than masking corruption.
+ const parsed = parseBrainYaml(text);
+ const currentCfg = validateBrainConfig(parsed, path);
+ const previous = currentCfg.primary_agent;
+
+ if (previous === nextValue) {
+ return Object.freeze({ previous, next: nextValue, changed: false });
+ }
+
+ const replacement = `primary_agent: ${formatPrimaryAgentYamlValue(nextValue, path)}`;
+
+ let updated: string;
+ if (LINE_RE.test(text)) {
+ updated = text.replace(LINE_RE, replacement);
+ } else {
+ // Insert after the schema_version line โ€” keeps top-of-file order
+ // predictable when a hand-edited config skipped the optional key.
+ const sv = /^schema_version:.*$/m;
+ updated = sv.test(text)
+ ? text.replace(sv, (m) => `${m}\n\n${replacement}`)
+ : `${replacement}\n\n${text}`;
+ }
+
+ // Verify the rewritten YAML still validates before persisting.
+ validateBrainConfig(parseBrainYaml(updated), path);
+
+ atomicWriteFileSync(path, updated);
+ return Object.freeze({ previous, next: nextValue, changed: true });
+}
diff --git a/src/core/brain/snapshot-diff-render.ts b/src/core/brain/snapshot-diff-render.ts
new file mode 100644
index 00000000..76e066fb
--- /dev/null
+++ b/src/core/brain/snapshot-diff-render.ts
@@ -0,0 +1,141 @@
+/**
+ * Render a {@link BrainTreeDiff} as Markdown (for human consumption)
+ * or as the raw structured object (for `--json` callers).
+ *
+ * Pure functions โ€” no I/O. Tests pin the markdown shape so a future
+ * cron or CI integration can grep against a stable byte layout.
+ */
+
+import { renderPrefLink } from "./wikilink.ts";
+import type {
+ BrainFieldChange,
+ BrainTreeChange,
+ BrainTreeDiff,
+ BrainTreeEntry,
+ BrainTreeEntryKind,
+} from "./snapshot-diff.ts";
+
+const SECTION_ORDER: ReadonlyArray<BrainTreeEntryKind> = Object.freeze([
+ "preference",
+ "retired",
+ "signal",
+ "log",
+ "config",
+ "other",
+]);
+
+const SECTION_TITLE: Readonly<Record<BrainTreeEntryKind, string>> =
+ Object.freeze({
+ preference: "Preferences",
+ retired: "Retired",
+ signal: "Signals",
+ log: "Logs",
+ config: "Config",
+ other: "Other",
+ });
+
+export interface RenderDiffMarkdownOptions {
+ /** Display label for the "A" side (typically a run id). */
+ readonly aLabel?: string;
+ /** Display label for the "B" side (typically a run id or `"live"`). */
+ readonly bLabel?: string;
+}
+
+/**
+ * Render a {@link BrainTreeDiff} as a Markdown document grouped by
+ * artifact kind. Empty sections are still emitted with a `(no
+ * changes)` line so the operator can confirm at a glance that the
+ * differ examined every category.
+ */
+export function renderDiffMarkdown(
+ diff: BrainTreeDiff,
+ opts: RenderDiffMarkdownOptions = {},
+): string {
+ const aLabel = opts.aLabel ?? "A";
+ const bLabel = opts.bLabel ?? "B";
+ const lines: string[] = [];
+ lines.push("# Brain snapshot diff");
+ lines.push("");
+ lines.push(`- A: ${aLabel}`);
+ lines.push(`- B: ${bLabel}`);
+ lines.push("");
+
+ for (const kind of SECTION_ORDER) {
+ const sectionLines = renderSection(diff, kind);
+ lines.push(`## ${SECTION_TITLE[kind]}`);
+ if (sectionLines.length === 0) {
+ lines.push("(no changes)");
+ } else {
+ lines.push(...sectionLines);
+ }
+ lines.push("");
+ }
+ return lines.join("\n").replace(/\n+$/, "\n");
+}
+
+/**
+ * Identity render for the structured payload โ€” the differ already
+ * produces the exact shape JSON callers expect. Kept as a function
+ * (rather than passing the diff through directly) so future
+ * formatting changes have a single hook.
+ */
+export function renderDiffJson(diff: BrainTreeDiff): BrainTreeDiff {
+ return diff;
+}
+
+// ----- Internal helpers ----------------------------------------------------
+
+function renderSection(
+ diff: BrainTreeDiff,
+ kind: BrainTreeEntryKind,
+): string[] {
+ const out: string[] = [];
+ for (const entry of diff.added.filter((e) => e.kind === kind)) {
+ out.push(`- + ${renderEntryRef(entry)} (added)`);
+ }
+ for (const entry of diff.removed.filter((e) => e.kind === kind)) {
+ out.push(`- - ${renderEntryRef(entry)} (removed)`);
+ }
+ for (const change of diff.modified.filter((c) => c.entry.kind === kind)) {
+ out.push(...renderModified(change));
+ }
+ return out;
+}
+
+function renderEntryRef(entry: BrainTreeEntry): string {
+ if (
+ (entry.kind === "preference" || entry.kind === "retired")
+ && entry.id !== null
+ ) {
+ return renderPrefLink({ id: entry.id, principle: entry.principle });
+ }
+ if (entry.id !== null) {
+ return `[[${entry.id}]]`;
+ }
+ return entry.path;
+}
+
+function renderModified(change: BrainTreeChange): string[] {
+ const out: string[] = [];
+ const ref = renderEntryRef(change.entry);
+ if (change.fields.length === 0) {
+ if (change.bodyChanged) {
+ out.push(`- ~ ${ref} (body changed)`);
+ }
+ return out;
+ }
+ out.push(`- ~ ${ref}:`);
+ for (const field of change.fields) {
+ out.push(` - ${renderField(field)}`);
+ }
+ return out;
+}
+
+function renderField(field: BrainFieldChange): string {
+ return `${field.field}: ${formatValue(field.before)} โ†’ ${formatValue(field.after)}`;
+}
+
+function formatValue(v: string | number | boolean | null): string {
+ if (v === null) return "null";
+ return String(v);
+}
diff --git a/src/core/brain/snapshot-diff.ts b/src/core/brain/snapshot-diff.ts
new file mode 100644
index 00000000..4781aad7
--- /dev/null
+++ b/src/core/brain/snapshot-diff.ts
@@ -0,0 +1,404 @@
+/**
+ * Read-only diff between two materialised `Brain/` trees.
+ *
+ * Used by both `o2b brain snapshot diff <a> [<b>]` and
+ * `o2b brain rollback --dry-run <id>` โ€” they share the same tree-
+ * comparison primitive; the renderer (markdown / json) is split out
+ * into `snapshot-diff-render.ts` so the differ stays purely
+ * computational.
+ *
+ * The walker classifies every file under each root into one of six
+ * artifact kinds (preference, retired, signal, log, config, other).
+ * Preferences and retired files get a typed field-level diff for the
+ * canonical set of derived/identity fields; everything else compares
+ * by byte equality so the renderer can flag "log file body changed"
+ * without listing every byte.
+ *
+ * Inputs are expected to be Brain/ root directories (not vault
+ * roots). Callers feed `extractSnapshotToTemp(...).brainRoot` for
+ * snapshots and `<vault>/Brain` for the live tree.
+ */
+
+import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { parsePreference, parseRetired } from "./preference.ts";
+import type { BrainPreference, BrainRetired } from "./types.ts";
+
+// ----- Public types --------------------------------------------------------
+
+export type BrainTreeEntryKind =
+ | "preference"
+ | "retired"
+ | "signal"
+ | "log"
+ | "config"
+ | "other";
+
+export interface BrainTreeEntry {
+ /** Vault-relative path under `Brain/<โ€ฆ>`. */
+ readonly path: string;
+ readonly kind: BrainTreeEntryKind;
+ /** Artifact id when applicable (`pref-foo`, `ret-bar`, `sig-โ€ฆ`). */
+ readonly id: string | null;
+ /**
+ * Human-readable title sourced from `principle` for preference and
+ * retired entries โ€” the markdown renderer uses it to build titled
+ * wikilinks (ยง27). Empty string for other kinds and for entries
+ * that failed to parse.
+ */
+ readonly principle: string;
+}
+
+export interface BrainFieldChange {
+ readonly field: string;
+ readonly before: string | number | boolean | null;
+ readonly after: string | number | boolean | null;
+}
+
+export interface BrainTreeChange {
+ readonly entry: BrainTreeEntry;
+ /** Empty when only the body bytes differ. */
+ readonly fields: ReadonlyArray<BrainFieldChange>;
+ readonly bodyChanged: boolean;
+}
+
+export interface BrainTreeDiff {
+ readonly added: ReadonlyArray<BrainTreeEntry>;
+ readonly removed: ReadonlyArray<BrainTreeEntry>;
+ readonly modified: ReadonlyArray<BrainTreeChange>;
+}
+
+const TRACKED_PREF_FIELDS: ReadonlyArray<keyof BrainPreference> = Object.freeze([
+ "status",
+ "applied_count",
+ "violated_count",
+ "confidence",
+ "confidence_value",
+ "pinned",
+ "last_evidence_at",
+ "confirmed_at",
+]);
+
+const TRACKED_RETIRED_FIELDS: ReadonlyArray<keyof BrainRetired> = Object.freeze([
+ "retired_reason",
+ "applied_count",
+ "violated_count",
+ "confidence",
+ "confidence_value",
+ "pinned",
+ "last_evidence_at",
+ "superseded_by",
+]);
+
+// ----- Public API ----------------------------------------------------------
+
+/**
+ * Compute the artifact-level diff between two `Brain/` trees.
+ *
+ * Both roots must exist; missing files inside either root are
+ * treated as "not present", not as errors. The function never
+ * mutates either tree. Returned arrays are frozen for caller safety.
+ */
+export function diffBrainTrees(
+ rootA: string,
+ rootB: string,
+): BrainTreeDiff {
+ const a = walkBrain(rootA);
+ const b = walkBrain(rootB);
+
+ const aByPath = new Map<string, ScannedFile>();
+ const bByPath = new Map<string, ScannedFile>();
+ for (const f of a) aByPath.set(f.entry.path, f);
+ for (const f of b) bByPath.set(f.entry.path, f);
+
+ const added: BrainTreeEntry[] = [];
+ const removed: BrainTreeEntry[] = [];
+ const modified: BrainTreeChange[] = [];
+
+ for (const f of b) {
+ if (!aByPath.has(f.entry.path)) {
+ added.push(f.entry);
+ }
+ }
+ for (const f of a) {
+ if (!bByPath.has(f.entry.path)) {
+ removed.push(f.entry);
+ }
+ }
+ for (const f of a) {
+ const right = bByPath.get(f.entry.path);
+ if (!right) continue;
+ const change = diffFile(f, right);
+ if (change !== null) modified.push(change);
+ }
+
+ // Deterministic ordering: kind ascending, then path ascending. Two
+ // runs on identical inputs must produce identical output bytes so
+ // operators can grep a stable diff.
+ const sortFn = (
+ x: { readonly path: string; readonly kind: BrainTreeEntryKind },
+ y: { readonly path: string; readonly kind: BrainTreeEntryKind },
+ ): number => {
+ if (x.kind !== y.kind) return x.kind.localeCompare(y.kind);
+ return x.path.localeCompare(y.path);
+ };
+ added.sort((x, y) => sortFn(x, y));
+ removed.sort((x, y) => sortFn(x, y));
+ modified.sort((x, y) => sortFn(x.entry, y.entry));
+
+ return Object.freeze({
+ added: Object.freeze(added),
+ removed: Object.freeze(removed),
+ modified: Object.freeze(modified),
+ });
+}
+
+// ----- Walker + classifier -------------------------------------------------
+
+interface ScannedFile {
+ readonly entry: BrainTreeEntry;
+ readonly absolutePath: string;
+ readonly pref?: BrainPreference;
+ readonly retired?: BrainRetired;
+ readonly bytes?: string;
+}
+
+function walkBrain(root: string): ReadonlyArray<ScannedFile> {
+ if (!existsSync(root)) return [];
+ const out: ScannedFile[] = [];
+ const stack: string[] = [root];
+ while (stack.length > 0) {
+ const dir = stack.pop()!;
+ let entries: ReadonlyArray<string>;
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ continue;
+ }
+ for (const name of entries) {
+ const abs = join(dir, name);
+ let st;
+ try {
+ // `lstatSync` (NOT `statSync`) so we never follow a symlink.
+ // A malicious snapshot tarball that contained a symlink
+ // under `Brain/` pointing at `/etc/passwd` would otherwise
+ // have the walker read the target file as if it were a
+ // Brain artifact and surface its bytes inside the diff.
+ // Skipping symlinks is the cheapest, most honest defense.
+ st = lstatSync(abs);
+ } catch {
+ continue;
+ }
+ if (st.isSymbolicLink()) continue;
+ const rel = relative(root, abs).replaceAll("\\", "/");
+ // `.snapshots/` is the snapshot family itself โ€” comparing
+ // archives across snapshots is not meaningful (each snapshot
+ // owns its own archive set). Skip the tree entirely.
+ if (rel === ".snapshots" || rel.startsWith(".snapshots/")) continue;
+ // Defense-in-depth: an entry whose relative path escapes the
+ // walker root (`..` segment) cannot legitimately be inside
+ // a Brain snapshot โ€” drop it rather than classify under a
+ // bogus path. `relative()` returning `..` is the canonical
+ // marker for "out of root".
+ if (rel.startsWith("..")) continue;
+ if (st.isDirectory()) {
+ stack.push(abs);
+ continue;
+ }
+ if (!st.isFile()) continue;
+ out.push(scanFile(root, abs, rel));
+ }
+ }
+ return out;
+}
+
+function scanFile(_root: string, abs: string, rel: string): ScannedFile {
+ const baseName = rel.split("/").pop() ?? rel;
+ if (rel.startsWith("preferences/") && baseName.startsWith("pref-")) {
+ try {
+ const pref = parsePreference(abs);
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "preference",
+ id: pref.id,
+ principle: pref.principle,
+ },
+ absolutePath: abs,
+ pref,
+ bytes: readFileSafe(abs),
+ };
+ } catch {
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "preference",
+ id: baseName.replace(/\.md$/, ""),
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+ }
+ }
+ if (rel.startsWith("retired/") && baseName.startsWith("ret-")) {
+ try {
+ const retired = parseRetired(abs);
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "retired",
+ id: retired.id,
+ principle: retired.principle,
+ },
+ absolutePath: abs,
+ retired,
+ bytes: readFileSafe(abs),
+ };
+ } catch {
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "retired",
+ id: baseName.replace(/\.md$/, ""),
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+ }
+ }
+ if (
+ (rel.startsWith("inbox/") || rel.startsWith("processed/"))
+ && baseName.startsWith("sig-")
+ ) {
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "signal",
+ id: baseName.replace(/\.md$/, ""),
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+ }
+ if (rel.startsWith("log/") && /^log\/\d{4}-\d{2}-\d{2}\.md$/.test(rel)) {
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "log",
+ id: null,
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+ }
+ if (
+ rel === "_brain.yaml"
+ || rel === "_BRAIN.md"
+ || rel === "active.md"
+ || rel === "_OPEN_SECOND_BRAIN.md"
+ ) {
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "config",
+ id: null,
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+ }
+ return {
+ entry: {
+ path: `Brain/${rel}`,
+ kind: "other",
+ id: null,
+ principle: "",
+ },
+ absolutePath: abs,
+ bytes: readFileSafe(abs),
+ };
+}
+
+function readFileSafe(path: string): string {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return "";
+ }
+}
+
+// ----- Per-file diff -------------------------------------------------------
+
+function diffFile(a: ScannedFile, b: ScannedFile): BrainTreeChange | null {
+ // Bytes-equal is the cheapest path. Both sides identical โ†’ no
+ // change row in the diff.
+ if (a.bytes !== undefined && b.bytes !== undefined && a.bytes === b.bytes) {
+ return null;
+ }
+ if (a.entry.kind === "preference" && a.pref && b.pref) {
+ return diffPreference(a, b);
+ }
+ if (a.entry.kind === "retired" && a.retired && b.retired) {
+ return diffRetired(a, b);
+ }
+ // Signals, logs, config, other โ€” body-only diff.
+ return {
+ entry: b.entry.principle.length > 0 ? b.entry : a.entry,
+ fields: [],
+ bodyChanged: true,
+ };
+}
+
+function diffPreference(a: ScannedFile, b: ScannedFile): BrainTreeChange {
+ const fields: BrainFieldChange[] = [];
+ if (a.pref && b.pref) {
+ for (const field of TRACKED_PREF_FIELDS) {
+ const before = normaliseValue(a.pref[field]);
+ const after = normaliseValue(b.pref[field]);
+ if (before !== after) {
+ fields.push({ field, before, after });
+ }
+ }
+ }
+ // Strip frontmatter region from the byte comparison so a pure
+ // body change is still visible without claiming "fields changed".
+ // The cheap heuristic: when the rendered field set is empty but
+ // bytes differ, mark `bodyChanged: true`.
+ const bodyChanged = fields.length === 0 && a.bytes !== b.bytes;
+ return { entry: b.entry, fields, bodyChanged };
+}
+
+function diffRetired(a: ScannedFile, b: ScannedFile): BrainTreeChange {
+ const fields: BrainFieldChange[] = [];
+ if (a.retired && b.retired) {
+ for (const field of TRACKED_RETIRED_FIELDS) {
+ const before = normaliseValue(a.retired[field]);
+ const after = normaliseValue(b.retired[field]);
+ if (before !== after) {
+ fields.push({ field, before, after });
+ }
+ }
+ }
+ const bodyChanged = fields.length === 0 && a.bytes !== b.bytes;
+ return { entry: b.entry, fields, bodyChanged };
+}
+
+function normaliseValue(
+ v: unknown,
+): string | number | boolean | null {
+ if (v === undefined) return null;
+ if (v === null) return null;
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
+ return v;
+ }
+ // Arrays / objects are not currently in TRACKED_*_FIELDS; collapse
+ // anything unexpected to a JSON string so the diff stays
+ // human-readable rather than emitting `[object Object]`.
+ return JSON.stringify(v);
+}
diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.ts
index 2391ce09..c30628c5 100644
--- a/src/core/brain/snapshot.ts
+++ b/src/core/brain/snapshot.ts
@@ -429,12 +429,39 @@ export function pruneSnapshots(
* extracted one into place.
* 5. Clean up the temp dir.
*/
-export function restoreSnapshot(
+/**
+ * Result of {@link extractSnapshotToTemp}. `brainRoot` is the
+ * extracted `Brain/` directory (sibling to the live tree, inside a
+ * private tmp dir); `tmpRoot` is the parent directory the caller
+ * owns. {@link cleanup} removes the tmp dir best-effort.
+ */
+export interface ExtractSnapshotResult {
+ readonly tmpRoot: string;
+ readonly brainRoot: string;
+ readonly cleanup: () => void;
+}
+
+/**
+ * Extract a snapshot archive into a private tmp directory and return
+ * pointers to the materialised tree. The caller is responsible for
+ * invoking {@link ExtractSnapshotResult.cleanup} once the data is no
+ * longer needed.
+ *
+ * Used by:
+ * - {@link restoreSnapshot} โ€” actually replaces the live tree.
+ * - `o2b brain rollback --dry-run` โ€” previews the restore plan.
+ * - `o2b brain snapshot diff` โ€” read-only inspector across two
+ * snapshots or a snapshot and the live tree.
+ *
+ * Shared so the tar / zstd / gzip decompression logic stays in one
+ * place. Throws {@link BrainSnapshotError} on archive corruption /
+ * missing root, {@link BrainSnapshotToolingMissingError} when the
+ * host lacks the required external tool.
+ */
+export function extractSnapshotToTemp(
vault: string,
runId: string,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- reserved for future log emission
- _opts: { now?: Date } = {},
-): RestoreSnapshotResult {
+): ExtractSnapshotResult {
validateRunId(runId);
const archive = snapshotPath(vault, runId);
if (!existsSync(archive)) {
@@ -448,8 +475,14 @@ export function restoreSnapshot(
);
}
- const dirs = brainDirs(vault);
- const tmp = mkdtempSync(join(tmpdir(), `o2b-brain-restore-${runId}-`));
+ const tmp = mkdtempSync(join(tmpdir(), `o2b-brain-extract-${runId}-`));
+ const cleanup = (): void => {
+ try {
+ rmSync(tmp, { recursive: true, force: true });
+ } catch {
+ // tmp cleanup is best-effort; the OS will reclaim it eventually.
+ }
+ };
try {
// Probe the magic bytes to decide how to decompress. zstd starts
// with `28 B5 2F FD`; gzip with `1F 8B`. Anything else is rejected
@@ -469,8 +502,6 @@ export function restoreSnapshot(
}
if (decompressor === "zstd") {
- // Use shell pipe-free composition: zstd writes tar bytes to
- // stdout; we feed them into tar via stdin.
const zstd = spawnSync("zstd", ["-d", "-c", archive], {
maxBuffer: 256 * 1024 * 1024,
stdio: ["ignore", "pipe", "pipe"],
@@ -482,7 +513,10 @@ export function restoreSnapshot(
runId,
);
}
- const tar = spawnSync("tar", ["-x", "-C", tmp], {
+ // `-f -` is explicit stdin: GNU tar defaults to stdin without
+ // it, but BSD tar and busybox tar do not, so passing the flag
+ // keeps the extraction portable across hosts.
+ const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tmp], {
input: zstd.stdout,
stdio: ["pipe", "inherit", "pipe"],
});
@@ -494,7 +528,6 @@ export function restoreSnapshot(
);
}
} else {
- // gzip route โ€” let tar do the decompression directly via `-z`.
const tar = spawnSync("tar", ["-x", "-z", "-f", archive, "-C", tmp], {
stdio: ["ignore", "inherit", "pipe"],
});
@@ -507,10 +540,6 @@ export function restoreSnapshot(
}
}
- // The extracted layout must contain a top-level `Brain/`. If the
- // archive was written from outside the design (e.g. someone
- // manually placed an unrelated `.tar.zst` in `.snapshots/`), we
- // refuse to proceed rather than scattering files.
const extractedBrain = join(tmp, "Brain");
if (!existsSync(extractedBrain)) {
throw new BrainSnapshotError(
@@ -518,23 +547,34 @@ export function restoreSnapshot(
runId,
);
}
+ return Object.freeze({ tmpRoot: tmp, brainRoot: extractedBrain, cleanup });
+ } catch (err) {
+ cleanup();
+ throw err;
+ }
+}
+export function restoreSnapshot(
+ vault: string,
+ runId: string,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- reserved for future log emission
+ _opts: { now?: Date } = {},
+): RestoreSnapshotResult {
+ const dirs = brainDirs(vault);
+ const ext = extractSnapshotToTemp(vault, runId);
+ try {
// Replace every top-level entry under Brain/, EXCEPT `.snapshots/`.
// The exclusion is the load-bearing safety guarantee: rolling back
// an older state must not erase newer snapshots, otherwise the
// operator is one click away from losing their forward path.
- const replacementEntries = readdirSync(extractedBrain).filter(
+ const replacementEntries = readdirSync(ext.brainRoot).filter(
(e) => e !== ".snapshots",
);
- // First, remove top-level entries under live Brain/ that are NOT
- // `.snapshots/` and ARE present in the snapshot. (We do not delete
- // entries unique to the live tree โ€” that would be a stronger
- // semantic than "restore", since restore should converge the live
- // tree to the snapshot.) Actually the correct semantics ARE
- // "live tree == snapshot tree minus .snapshots/". So we delete
- // every live top-level entry except `.snapshots/`, then copy in
- // from the extracted Brain/. This makes restore deterministic.
+ // The correct semantics are "live tree == snapshot tree minus
+ // `.snapshots/`". Delete every live top-level entry except
+ // `.snapshots/`, then copy in from the extracted Brain/. This
+ // makes restore deterministic.
const liveEntries = existsSync(dirs.brain)
? readdirSync(dirs.brain).filter((e) => e !== ".snapshots")
: [];
@@ -554,18 +594,14 @@ export function restoreSnapshot(
let restoredFiles = 0;
mkdirSync(dirs.brain, { recursive: true });
for (const name of replacementEntries) {
- const from = join(extractedBrain, name);
+ const from = join(ext.brainRoot, name);
const to = join(dirs.brain, name);
cpSync(from, to, { recursive: true });
restoredFiles += countFiles(to);
}
return { restored_files: restoredFiles };
} finally {
- try {
- rmSync(tmp, { recursive: true, force: true });
- } catch {
- // tmp cleanup is best-effort; the OS will reclaim it eventually.
- }
+ ext.cleanup();
}
}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index dfecf4aa..be2bf4e1 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -253,7 +253,22 @@ export interface BrainPreference {
readonly violated_count: number;
/** ISO-8601 UTC of most recent `apply-evidence` entry. */
readonly last_evidence_at: string | null;
+ /**
+ * Categorical band โ€” `low | medium | high`. Derived from
+ * {@link confidence_value} after the count-based hard floors
+ * (`applied <= low_max_applied`, `violated >= applied`, etc.) are
+ * applied. Stays on the public type so MCP / digest consumers that
+ * predate the numeric field keep working unchanged.
+ */
readonly confidence: BrainConfidence;
+ /**
+ * Continuous Wilson-95% lower bound on `applied / (applied +
+ * violated)`, modulated by freshness decay over
+ * `retire.stale_evidence_days`. `null` on legacy files written by
+ * pre-v0.10.3 dream passes; downstream code that needs a numeric
+ * value must tolerate the `null` and fall back to the band.
+ */
+ readonly confidence_value: number | null;
/**
* If `true`, exempt from automatic retire reasons (`stale-no-evidence`,
* `expired-unconfirmed`, `rebutted`). Defaults to `false` when a parsed
@@ -297,6 +312,12 @@ export interface BrainRetired {
readonly violated_count: number;
readonly last_evidence_at: string | null;
readonly confidence: BrainConfidence;
+ /**
+ * Snapshot of the numeric `confidence_value` at retire time.
+ * `null` on retired files produced by pre-v0.10.3 dream passes;
+ * downstream code must tolerate the `null`.
+ */
+ readonly confidence_value: number | null;
readonly pinned: boolean;
readonly aliases?: ReadonlyArray<string>;
/**
@@ -506,6 +527,19 @@ export interface BrainConfidenceConfig {
* stale_evidence_days * high_freshness_factor`. Must be in `(0, 1]`.
*/
readonly high_freshness_factor: number;
+ /**
+ * Lower threshold on the numeric `confidence_value` for the
+ * derived `medium` band. Anything below this lands as `low` after
+ * the legacy count-based hard floors. Must be in `[0, 1]` and
+ * strictly less than {@link high_min}.
+ */
+ readonly medium_min: number;
+ /**
+ * Lower threshold on the numeric `confidence_value` for the
+ * derived `high` band. Must be in `[0, 1]` and strictly greater
+ * than {@link medium_min}.
+ */
+ readonly high_min: number;
}
export interface BrainSnapshotsConfig {
@@ -517,9 +551,19 @@ export interface BrainSnapshotsConfig {
* Root of `Brain/_brain.yaml`. `schema_version` is mandatory; unknown
* top-level keys are tolerated as forward-compat (logged as a warning by
* the validator, not an error).
+ *
+ * `primary_agent` declares which runtime owns the `dream` consolidation
+ * pass for this vault. Multi-device setups (e.g. Syncthing-shared
+ * vaults) benefit from a single dream-running host so signal
+ * processing stays serialised. `null` (the default) means "no primary
+ * declared" โ€” every dream invocation runs without an identity check.
+ * When set, dream runs from a different `agent_name` emit a stderr
+ * warning and a `non_primary_agent` log-payload row but still
+ * complete: enforcement is observability, not access control.
*/
export interface BrainConfig {
readonly schema_version: number;
+ readonly primary_agent: string | null;
readonly dream: BrainDreamConfig;
readonly retire: BrainRetireConfig;
readonly confidence: BrainConfidenceConfig;
diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.ts
index fab00b32..f9cbb334 100644
--- a/src/core/brain/wikilink.ts
+++ b/src/core/brain/wikilink.ts
@@ -181,6 +181,75 @@ export function parseArtifactRef(value: string): ArtifactRefParse {
return { raw, target, rangeText, range };
}
+/**
+ * Maximum length of the wikilink title rendered by {@link renderPrefLink}
+ * before truncation kicks in. Chosen so a `[[pref-โ€ฆ|title]]` link fits on
+ * one Obsidian list-row at typical viewport widths.
+ */
+export const MAX_PREF_LINK_TITLE_LEN = 80;
+
+/**
+ * Render a wikilink to a Brain preference or retired artifact with a
+ * human-readable title sourced from the `principle` field.
+ *
+ * The title is NFC-normalised, whitespace-collapsed, sanitised of
+ * wikilink-breaking characters (`[`, `]`, `|`), and truncated to
+ * {@link MAX_PREF_LINK_TITLE_LEN} at a word boundary (ellipsised when
+ * cut). When the principle is missing or becomes empty after
+ * sanitisation, the helper falls back to the bare `[[id]]` form so the
+ * link remains resolvable through {@link normaliseWikilinkTarget} and
+ * {@link parseWikilink} (both of which already strip `|alias`).
+ *
+ * Used by every Brain writer that emits a pref / retired reference;
+ * signal and external-artifact wikilinks stay bare-id because they have
+ * no useful title source.
+ */
+export function renderPrefLink(input: {
+ readonly id: string;
+ readonly principle?: string;
+}): string {
+ const raw = input.principle ?? "";
+ // Sanitisation pipeline, in order:
+ // 1. NFC normalise so visually-equal inputs hash to the same bytes.
+ // 2. Strip C0/C1 control chars except tab/newline (the whitespace
+ // collapse below handles those), zero-width joiners, BiDi
+ // overrides โ€” these can spoof or break Obsidian rendering.
+ // 3. Replace wikilink-breaking glyphs (`[`, `]`, `|`) with spaces.
+ // 4. Collapse all whitespace runs to a single space, trim.
+ const title = raw
+ .normalize("NFC")
+ .replace(/\r\n?/g, "\n")
+ // C0 controls (00-1F) except \t \n; DEL (7F); C1 controls (80-9F).
+ // eslint-disable-next-line no-control-regex
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, " ")
+ // Format / BiDi-override characters that can cause visual spoofing
+ // in Obsidian: zero-width space/joiner, LRM/RLM, BiDi embedding +
+ // override + isolates, soft hyphen, BOM.
+ .replace(/[โ€‹-โ€โ€ช-โ€ฎโฆ-โฉยญ๏ปฟ]/g, " ")
+ .replace(/[\[\]|]/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (title.length === 0) return `[[${input.id}]]`;
+ // Measure the cap against code-point count (Array.from yields one
+ // entry per Unicode scalar) rather than UTF-16 code units so a
+ // string of 50 astral glyphs (100 code units, 50 code points) is
+ // not forced into the truncation path when the cap is 80.
+ const codepoints = Array.from(title);
+ if (codepoints.length <= MAX_PREF_LINK_TITLE_LEN) {
+ return `[[${input.id}|${title}]]`;
+ }
+ // Truncate to the cap, then back off to the previous word boundary โ€”
+ // but only when one exists inside the window. A single oversized token
+ // (no space inside the cap) gets a hard cut so we still produce a link
+ // rather than dropping back to the bare-id fallback. Slicing happens
+ // on code points so an emoji or astral glyph never gets bisected
+ // into a lone surrogate before the ellipsis.
+ let cutPoints = codepoints.slice(0, MAX_PREF_LINK_TITLE_LEN);
+ const lastSpace = cutPoints.lastIndexOf(" ");
+ if (lastSpace > 0) cutPoints = cutPoints.slice(0, lastSpace);
+ return `[[${input.id}|${cutPoints.join("")}โ€ฆ]]`;
+}
+
function validateRangeText(text: string): ArtifactRange | null {
// Accepts `N` or `N-N`, both with 1-based positive integers and
// `end >= start`. Anything else fails (zero, negative numbers,
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index a99e6fe5..68f3f596 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -319,10 +319,15 @@ async function toolBrainDream(
): Promise<Record<string, unknown>> {
const dryRun = coerceBool(args, "dry_run");
const nowDate = coerceIsoDate(args, "now");
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ normalizeAgentArgument(agentArg)
+ ?? resolveAgentName(ctx.configPath ?? undefined);
const summary = dream(ctx.vault, {
dryRun,
...(nowDate ? { now: nowDate } : {}),
+ ...(agent ? { agentName: agent } : {}),
});
// The summary is already a Plain Old Frozen Object โ€” JSON-serialise
@@ -337,6 +342,7 @@ async function toolBrainDream(
retired: summary.retired.map((r) => ({ id: r.id, reason: r.reason })),
contradictions: [...summary.contradictions],
moved_to_processed: [...summary.moved_to_processed],
+ warnings: summary.warnings.map((w) => ({ code: w.code, message: w.message })),
snapshot_path: summary.snapshot_path
? vaultRelativeSafe(ctx.vault, summary.snapshot_path)
: null,
@@ -591,6 +597,7 @@ function serializePreference(
violated_count: p.violated_count,
last_evidence_at: p.last_evidence_at,
confidence: p.confidence,
+ confidence_value: p.confidence_value,
pinned: p.pinned,
tags: [...p.tags],
...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),
@@ -611,6 +618,7 @@ function serializePreference(
violated_count: p.violated_count,
last_evidence_at: p.last_evidence_at,
confidence: p.confidence,
+ confidence_value: p.confidence_value,
pinned: p.pinned,
tags: [...p.tags],
...(p.supersedes !== undefined ? { supersedes: p.supersedes } : {}),
@@ -753,6 +761,11 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"Optional ISO-8601 timestamp used as the wall clock for the run (testing / replay).",
},
+ agent: {
+ type: "string",
+ description:
+ "Optional caller identity. Compared against `Brain/_brain.yaml.primary_agent`; a mismatch emits a `non-primary-dream-run` warning in the response. Defaults to the server-resolved agent name.",
+ },
},
additionalProperties: false,
},
diff --git a/tests/cli/brain.snapshot-diff.test.ts b/tests/cli/brain.snapshot-diff.test.ts
new file mode 100644
index 00000000..240bcd8a
--- /dev/null
+++ b/tests/cli/brain.snapshot-diff.test.ts
@@ -0,0 +1,295 @@
+/**
+ * CLI coverage for `o2b brain snapshot diff` and the new
+ * `--dry-run` mode of `o2b brain rollback`.
+ *
+ * Both surfaces share the same diff renderer, so the assertions
+ * here focus on argument handling, exit codes, and the integration
+ * between `extractSnapshotToTemp`, `diffBrainTrees`, and the
+ * markdown / JSON output channels.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-snapdiff-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ const brainInit = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(brainInit.returncode).toBe(0);
+}
+
+async function seedDream(): Promise<string> {
+ for (const slug of ["a", "b", "c"]) {
+ const r = await runCli(
+ [
+ "brain", "feedback",
+ "--vault", vault,
+ "--topic", "diff-demo",
+ "--signal", "positive",
+ "--principle", "Take care",
+ "--slug", `diff-demo-${slug}`,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ }
+ const d = await runCli(["brain", "dream", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(d.returncode).toBe(0);
+ const list = await runCli(
+ ["brain", "rollback", "--list", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(list.returncode).toBe(0);
+ const snaps = JSON.parse(list.stdout) as ReadonlyArray<{ run_id: string }>;
+ expect(snaps.length).toBeGreaterThan(0);
+ return snaps[0]!.run_id;
+}
+
+describe("brain rollback --dry-run", () => {
+ test("prints diff without modifying Brain/", async () => {
+ await bootstrap();
+ const runId = await seedDream();
+ // Add a fresh pref AFTER the snapshot so the diff has content
+ // (the "added" side appears in live but not in the snapshot).
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-extra.md"),
+ `---
+kind: brain-preference
+id: pref-extra
+created_at: 2026-05-17T10:00:00Z
+_confirmed_at: "null"
+unconfirmed_until: 2026-06-17T10:00:00Z
+tags: [brain, brain/preference]
+topic: extra
+_status: unconfirmed
+principle: Added after snapshot
+_evidenced_by: []
+_applied_count: 0
+_violated_count: 0
+_last_evidence_at: "null"
+_confidence: low
+_confidence_value: 0
+pinned: false
+---
+`,
+ "utf8",
+ );
+ const r = await runCli(
+ ["brain", "rollback", runId, "--dry-run", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toMatch(/^# Brain snapshot diff$/m);
+ expect(r.stdout).toMatch(/^- A: live$/m);
+ expect(r.stdout).toContain(`- B: ${runId}`);
+ expect(r.stdout).toMatch(/^- - \[\[pref-extra\|Added after snapshot\]\] \(removed\)$/m);
+ // Live tree must NOT have been touched.
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-extra.md")))
+ .toBe(true);
+ });
+
+ test("--dry-run + --yes is an error", async () => {
+ await bootstrap();
+ const runId = await seedDream();
+ const r = await runCli(
+ ["brain", "rollback", runId, "--dry-run", "--yes", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toMatch(/mutually exclusive/);
+ });
+
+ test("--dry-run --json returns parseable JSON", async () => {
+ await bootstrap();
+ const runId = await seedDream();
+ const r = await runCli(
+ ["brain", "rollback", runId, "--dry-run", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload).toHaveProperty("added");
+ expect(payload).toHaveProperty("removed");
+ expect(payload).toHaveProperty("modified");
+ });
+
+ test("unknown run_id exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "rollback", "no-such-run", "--dry-run", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ });
+});
+
+describe("brain snapshot diff", () => {
+ test("snapshot vs live", async () => {
+ await bootstrap();
+ const runId = await seedDream();
+ // Mutate live so the diff has content.
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-added.md"),
+ `---
+kind: brain-preference
+id: pref-added
+created_at: 2026-05-17T10:00:00Z
+_confirmed_at: "null"
+unconfirmed_until: 2026-06-17T10:00:00Z
+tags: [brain, brain/preference]
+topic: added
+_status: unconfirmed
+principle: Added principle
+_evidenced_by: []
+_applied_count: 0
+_violated_count: 0
+_last_evidence_at: "null"
+_confidence: low
+_confidence_value: 0
+pinned: false
+---
+`,
+ "utf8",
+ );
+ const r = await runCli(
+ ["brain", "snapshot", "diff", runId, "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toMatch(/^- B: live$/m);
+ expect(r.stdout).toMatch(/\[\[pref-added\|Added principle\]\]/);
+ });
+
+ test("two snapshots", async () => {
+ await bootstrap();
+ const first = await seedDream();
+ // Add evidence and run dream again so a second snapshot is created.
+ const fb = await runCli(
+ [
+ "brain", "feedback",
+ "--vault", vault,
+ "--topic", "again",
+ "--signal", "positive",
+ "--principle", "Be careful",
+ "--slug", "again-1",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(fb.returncode).toBe(0);
+ for (const s of ["2", "3"]) {
+ const seed = await runCli(
+ [
+ "brain", "feedback",
+ "--vault", vault,
+ "--topic", "again",
+ "--signal", "positive",
+ "--principle", "Be careful",
+ "--slug", `again-${s}`,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(seed.returncode).toBe(0);
+ }
+ const d2 = await runCli(["brain", "dream", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(d2.returncode).toBe(0);
+ const list = await runCli(
+ ["brain", "rollback", "--list", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const snaps = JSON.parse(list.stdout) as ReadonlyArray<{ run_id: string }>;
+ expect(snaps.length).toBeGreaterThanOrEqual(2);
+ const second = snaps.find((s) => s.run_id !== first)!.run_id;
+ const r = await runCli(
+ ["brain", "snapshot", "diff", first, second, "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(`- A: ${first}`);
+ expect(r.stdout).toContain(`- B: ${second}`);
+ });
+
+ test("--json returns parseable JSON", async () => {
+ await bootstrap();
+ const runId = await seedDream();
+ const r = await runCli(
+ ["brain", "snapshot", "diff", runId, "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed).toHaveProperty("added");
+ });
+
+ test("missing positional arg exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "snapshot", "diff", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ });
+
+ test("unknown run_id exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "snapshot", "diff", "no-such-run", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ });
+
+ test("snapshot help exits 0", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "snapshot", "--help", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ // Without --help arg โ†’ return 2; WITH --help โ†’ 0.
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("o2b brain snapshot");
+ expect(r.stdout).toContain("diff");
+ });
+
+ test("unknown sub-verb exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "snapshot", "no-such-verb", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ });
+});
+
+// Silence the unused-import warning when test fixtures change.
+void readFileSync;
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index 4cc0c049..d509610f 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -140,6 +140,97 @@ describe("brain init", () => {
expect(r.returncode).toBe(1);
expect(r.stderr.toLowerCase()).toContain("o2b init");
});
+
+ test("--primary-agent threads value into _brain.yaml", async () => {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ const r = await runCli(
+ ["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);
+ });
+
+ test("--primary-agent empty value exits 1", async () => {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ const r = await runCli(
+ ["brain", "init", "--vault", vault, "--primary-agent", " "],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr.toLowerCase()).toContain("primary-agent");
+ });
+});
+
+describe("brain set-primary", () => {
+ test("writes the agent name into _brain.yaml", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "set-primary", "hermes-vps", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("primary_agent: null โ†’ hermes-vps");
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);
+ });
+
+ test("repeat call is a no-op", async () => {
+ await bootstrap();
+ await runCli(
+ ["brain", "set-primary", "hermes-vps", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const r = await runCli(
+ ["brain", "set-primary", "hermes-vps", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("already set to hermes-vps");
+ });
+
+ test("--clear restores null", async () => {
+ await bootstrap();
+ await runCli(
+ ["brain", "set-primary", "hermes-vps", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const r = await runCli(
+ ["brain", "set-primary", "--clear", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("hermes-vps โ†’ null");
+ });
+
+ test("missing positional and missing --clear exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "set-primary", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ });
+
+ test("--json emits structured output", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "set-primary", "hermes-vps", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.previous).toBeNull();
+ expect(parsed.next).toBe("hermes-vps");
+ expect(parsed.changed).toBe(true);
+ });
});
describe("brain feedback", () => {
@@ -286,6 +377,16 @@ describe("brain dream", () => {
expect(r.returncode).toBe(1);
expect(r.stderr).toContain("--now");
});
+
+ test("blank --agent exits 1 instead of falling back to the resolved default", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "dream", "--vault", vault, "--agent", " "],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("--agent");
+ });
});
describe("brain apply-evidence", () => {
@@ -371,7 +472,7 @@ describe("brain apply-evidence", () => {
expect(logs.length).toBe(1);
const body = readFileSync(join(vault, "Brain", "log", logs[0]!), "utf8");
expect(body).toContain("apply-evidence");
- expect(body).toContain("[[pref-fast]]");
+ expect(body).toContain("[[pref-fast|");
});
});
diff --git a/tests/core/brain.apply-evidence.test.ts b/tests/core/brain.apply-evidence.test.ts
index d9f80e4d..71890570 100644
--- a/tests/core/brain.apply-evidence.test.ts
+++ b/tests/core/brain.apply-evidence.test.ts
@@ -74,7 +74,7 @@ describe("appendApplyEvidence โ€” happy path", () => {
const e = entries[0]!;
expect(e.eventType).toBe("apply-evidence");
expect(e.timestamp).toBe("2026-05-14T14:22:00Z");
- expect(e.body["preference"]).toBe("[[pref-no-internal-abbrev]]");
+ expect(e.body["preference"]).toBe("[[pref-no-internal-abbrev|Rule for no-internal-abbrev]]");
expect(e.body["artifact"]).toBe("[[Daily/2026.05.14#section]]");
expect(e.body["agent"]).toBe("claude");
expect(e.body["result"]).toBe("applied");
@@ -94,7 +94,7 @@ describe("appendApplyEvidence โ€” happy path", () => {
{ now: new Date("2026-05-14T10:00:00Z") },
);
const bytes = readFileSync(res.log_path, "utf8");
- expect(bytes).toContain("preference: [[pref-foo-rule]]");
+ expect(bytes).toContain("preference: [[pref-foo-rule|Rule for foo-rule]]");
expect(bytes).toContain("result: violated");
});
});
diff --git a/tests/core/brain.body-hygiene.test.ts b/tests/core/brain.body-hygiene.test.ts
index a0699410..108fc76d 100644
--- a/tests/core/brain.body-hygiene.test.ts
+++ b/tests/core/brain.body-hygiene.test.ts
@@ -265,7 +265,7 @@ describe("ยง6 signal suppression", () => {
const logPath = join(vault, "Brain", "log", "2026-05-16.md");
const log = readFileSync(logPath, "utf8");
expect(log).toContain("signal-suppressed");
- expect(log).toContain("[[ret-noisy]]");
+ expect(log).toContain("[[ret-noisy|stop spamming]]");
expect(log).toContain("rule was wrong");
});
diff --git a/tests/core/brain.confidence-value.test.ts b/tests/core/brain.confidence-value.test.ts
new file mode 100644
index 00000000..5223d1ca
--- /dev/null
+++ b/tests/core/brain.confidence-value.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Numeric `confidence_value` โ€” Wilson 95% lower bound ร— freshness
+ * decay. Tests pin the formula at notable boundaries and confirm
+ * the on-disk `_confidence_value` field round-trips through the
+ * writer / parser / refresh pipeline.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ computeConfidence,
+ type ConfidenceComputeResult,
+} from "../../src/core/brain/dream.ts";
+import { DEFAULT_BRAIN_CONFIG } from "../../src/core/brain/policy.ts";
+
+const cfg = DEFAULT_BRAIN_CONFIG;
+const NOW = new Date("2026-05-15T00:00:00Z");
+
+function iso(d: string): string {
+ return new Date(d).toISOString();
+}
+
+describe("computeConfidence โ€” numeric value", () => {
+ test("zero evidence โ†’ value 0 and band low", () => {
+ const r: ConfidenceComputeResult = computeConfidence(0, 0, null, cfg, NOW);
+ expect(r.value).toBe(0);
+ expect(r.band).toBe("low");
+ });
+
+ test("Wilson lower bound shrinks as n grows from 1 โ†’ 100", () => {
+ const tiny = computeConfidence(1, 0, iso("2026-05-15"), cfg, NOW).value;
+ const huge = computeConfidence(100, 0, iso("2026-05-15"), cfg, NOW).value;
+ // Wilson lower bound for pฬ‚=1 monotonically increases toward 1
+ // as n grows. The freshness=1 boundary makes the comparison
+ // honest: identical age, identical pHat, only n changes.
+ expect(huge).toBeGreaterThan(tiny);
+ });
+
+ test("freshness decays linearly to 0 at retire.stale_evidence_days", () => {
+ const half = computeConfidence(
+ 10,
+ 0,
+ iso("2026-03-31"),
+ cfg,
+ NOW,
+ ).value;
+ const stale = computeConfidence(
+ 10,
+ 0,
+ iso("2026-02-14"),
+ cfg,
+ NOW,
+ ).value;
+ // 45 days vs 90 days at 90-day decay โ†’ 0.5x vs 0.0x freshness.
+ expect(half).toBeGreaterThan(stale + 0.001);
+ });
+
+ test("rounded to 4 decimals for YAML stability", () => {
+ const r = computeConfidence(7, 1, iso("2026-05-10"), cfg, NOW);
+ // Multiply by 10000 must produce an integer (within JS float
+ // tolerance) โ€” the writer's rounding contract.
+ expect(Math.round(r.value * 10000) / 10000).toBe(r.value);
+ });
+
+ test("hard floor: applied <= low_max_applied keeps band low", () => {
+ const r = computeConfidence(2, 0, iso("2026-05-15"), cfg, NOW);
+ expect(r.band).toBe("low");
+ });
+
+ test("hard floor: violated >= applied keeps band low", () => {
+ const r = computeConfidence(5, 5, iso("2026-05-15"), cfg, NOW);
+ expect(r.band).toBe("low");
+ });
+
+ test("step-function eligibility: 10 applied / no violated / fresh โ†’ high", () => {
+ const r = computeConfidence(10, 0, iso("2026-05-15"), cfg, NOW);
+ expect(r.band).toBe("high");
+ });
+
+ test("step-function eligibility lost when stale โ†’ falls to medium", () => {
+ // last evidence ~78 days ago โ€” past high_freshness_factor cutoff
+ // but not past stale_evidence_days.
+ const r = computeConfidence(10, 0, iso("2026-02-26"), cfg, NOW);
+ expect(r.band).toBe("medium");
+ });
+
+ test("numeric band max-lift: legacy=medium + numeric=high โ†’ high", () => {
+ // Lower high_min so a 9-applied / 0-violated / fresh pref crosses
+ // the numeric threshold even though legacy step-function would
+ // cap it at medium (needs applied >= 10).
+ const tunedCfg = {
+ ...cfg,
+ confidence: {
+ ...cfg.confidence,
+ high_min: 0.5,
+ medium_min: 0.30,
+ },
+ };
+ const r = computeConfidence(9, 0, iso("2026-05-15"), tunedCfg, NOW);
+ expect(r.band).toBe("high");
+ });
+
+ test("numeric never demotes a legacy-high band", () => {
+ // Legacy step โ†’ high; tighten numeric thresholds to demand
+ // 0.99. Max-with-legacy keeps band at high.
+ const strictCfg = {
+ ...cfg,
+ confidence: {
+ ...cfg.confidence,
+ high_min: 0.99,
+ medium_min: 0.99,
+ },
+ };
+ const r = computeConfidence(10, 0, iso("2026-05-15"), strictCfg, NOW);
+ expect(r.band).toBe("high");
+ });
+
+ test("value is in [0, 1]", () => {
+ const tries = [
+ [1, 0, "2026-05-15"],
+ [50, 50, "2026-05-15"],
+ [0, 0, "2026-05-15"],
+ [100, 0, "2026-05-15"],
+ [10, 10, "2026-01-01"],
+ ] as const;
+ for (const [a, v, d] of tries) {
+ const r = computeConfidence(a, v, iso(d), cfg, NOW);
+ expect(r.value).toBeGreaterThanOrEqual(0);
+ expect(r.value).toBeLessThanOrEqual(1);
+ }
+ });
+});
diff --git a/tests/core/brain.digest.test.ts b/tests/core/brain.digest.test.ts
index 5921d80e..b9b9d5c1 100644
--- a/tests/core/brain.digest.test.ts
+++ b/tests/core/brain.digest.test.ts
@@ -113,7 +113,7 @@ describe("New (unconfirmed, in trial) section", () => {
expect(res.empty).toBe(false);
expect(res.content).toContain("## New (unconfirmed, in trial)");
expect(res.content).toContain(
- "[[pref-no-internal-abbrev]] โ€” writing, 3 signals, trial ends 2026-05-28",
+ "[[pref-no-internal-abbrev|Principle for no-internal-abbrev]] โ€” writing, 3 signals, trial ends 2026-05-28",
);
});
@@ -124,7 +124,7 @@ describe("New (unconfirmed, in trial) section", () => {
);
const res = renderDigest(tmp, { since: SINCE, until: UNTIL });
expect(res.empty).toBe(true);
- expect(res.content).not.toContain("[[pref-old]]");
+ expect(res.content).not.toMatch(/\[\[pref-old[\]|]/);
});
});
@@ -152,7 +152,7 @@ describe("Confirmed section", () => {
const res = renderDigest(tmp, { since: SINCE, until: UNTIL });
expect(res.content).toContain("## Confirmed");
expect(res.content).toContain(
- "[[pref-prefer-typed-errors]] โ€” writing, first applied in [[Daily/2026.05.14]]",
+ "[[pref-prefer-typed-errors|Principle for prefer-typed-errors]] โ€” writing, first applied in [[Daily/2026.05.14]]",
);
});
});
@@ -176,7 +176,7 @@ describe("Retired section", () => {
expect(res.content).toContain("## Retired");
// 2026-02-12 โ†’ 2026-05-14 = 91 days.
expect(res.content).toMatch(
- /\[\[ret-prefer-bullets-over-prose\]\] โ€” writing, stale-no-evidence \(91 days\)/,
+ /\[\[ret-prefer-bullets-over-prose\|Principle for prefer-bullets-over-prose\]\] โ€” writing, stale-no-evidence \(91 days\)/,
);
});
@@ -187,7 +187,7 @@ describe("Retired section", () => {
retired_by: "[[Brain/log/2026-05-14]]",
});
const res = renderDigest(tmp, { since: SINCE, until: UNTIL });
- expect(res.content).toContain("[[ret-rebut-me]] โ€” writing, rebutted");
+ expect(res.content).toContain("[[ret-rebut-me|Principle for rebut-me]] โ€” writing, rebutted");
expect(res.content).not.toMatch(/rebutted\s*\(\d+ days\)/);
});
});
@@ -235,10 +235,10 @@ describe("Markdown โ†” JSON parity", () => {
expect(parsed.new_unconfirmed.map((x) => x.id)).toEqual(["pref-aaa"]);
expect(parsed.confirmed.map((x) => x.id)).toEqual(["pref-bbb"]);
expect(parsed.retired.map((x) => x.id)).toEqual(["ret-ccc"]);
- // Markdown contains every id too.
- expect(md.content).toContain("[[pref-aaa]]");
- expect(md.content).toContain("[[pref-bbb]]");
- expect(md.content).toContain("[[ret-ccc]]");
+ // Markdown contains every id too โ€” titled wikilink form.
+ expect(md.content).toContain("[[pref-aaa|");
+ expect(md.content).toContain("[[pref-bbb|");
+ expect(md.content).toContain("[[ret-ccc|");
});
});
@@ -250,8 +250,8 @@ describe("window filtering", () => {
);
writePreference(tmp, basePref("inside-window"));
const res = renderDigest(tmp, { since: SINCE, until: UNTIL });
- expect(res.content).toContain("[[pref-inside-window]]");
- expect(res.content).not.toContain("[[pref-before-window]]");
+ expect(res.content).toContain("[[pref-inside-window|");
+ expect(res.content).not.toMatch(/\[\[pref-before-window[\]|]/);
});
test("the upper bound is exclusive โ€” until timestamp itself is dropped", () => {
@@ -337,8 +337,8 @@ describe("`empty` flag semantics", () => {
basePref("old", { created_at: "2026-04-01T00:00:00Z" }),
);
const res = renderDigest(tmp, { until: now });
- expect(res.content).toContain("[[pref-recent]]");
- expect(res.content).not.toContain("[[pref-old]]");
+ expect(res.content).toContain("[[pref-recent|");
+ expect(res.content).not.toMatch(/\[\[pref-old[\]|]/);
});
});
@@ -433,8 +433,8 @@ describe("top_applied / top_referenced sections", () => {
);
const r = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "markdown" });
expect(r.content).toContain("## Top applied (2)");
- expect(r.content).toContain("[[pref-hot]]");
- expect(r.content).toContain("[[pref-quar]]");
+ expect(r.content).toContain("[[pref-hot|");
+ expect(r.content).toContain("[[pref-quar|");
expect(r.content).toContain("[quarantine]");
});
diff --git a/tests/core/brain.dream.non-primary.test.ts b/tests/core/brain.dream.non-primary.test.ts
new file mode 100644
index 00000000..ab0d5f52
--- /dev/null
+++ b/tests/core/brain.dream.non-primary.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Non-primary dream warning channel.
+ *
+ * Covers the ยง21 contract: when `Brain/_brain.yaml.primary_agent` is
+ * set and the dream run is invoked from a different agent, the run
+ * still completes but emits:
+ *
+ * 1. A structured warning entry on `DreamRunSummary.warnings`.
+ * 2. A `non_primary_agent: <name>` payload row inside the `dream`
+ * log event for the run.
+ *
+ * Matching agents do NOT warn, and an unset primary (null) never
+ * warns. The dream pass remains advisory, not enforcing โ€” these tests
+ * lock that contract.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+ readFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { dream } from "../../src/core/brain/dream.ts";
+import { brainDirs } from "../../src/core/brain/paths.ts";
+import { setPrimaryAgent } from "../../src/core/brain/set-primary.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-brain-nonprim-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-nonprim-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ mkdirSync(configHome, { recursive: true });
+ writeFileSync(configPath, `vault: "${vault}"\n`, "utf8");
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function seedSignals(): void {
+ // Three same-sign signals so the planner crosses the default
+ // candidate_threshold (3) and dream actually performs writes โ€” the
+ // path that emits the summary log event with the warning payload.
+ const dirs = brainDirs(vault);
+ for (const slug of ["a", "b", "c"]) {
+ const id = `sig-2026-05-17-foo-${slug}`;
+ writeFileSync(
+ join(dirs.inbox, `${id}.md`),
+ [
+ "---",
+ "kind: brain-signal",
+ `id: ${id}`,
+ "created_at: 2026-05-17T10:00:00Z",
+ "tags: [brain, brain/signal, brain/topic/foo]",
+ "topic: foo",
+ "signal: positive",
+ "agent: tester",
+ "principle: foo bar",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ }
+}
+
+function readTodayLog(): string {
+ return readFileSync(join(brainDirs(vault).log, "2026-05-17.md"), "utf8");
+}
+
+const NOW = new Date("2026-05-17T11:00:00Z");
+
+describe("dream โ€” non-primary warning channel", () => {
+ test("emits non-primary-dream-run warning when agent differs from primary", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ seedSignals();
+ const r = dream(vault, { agentName: "claude-vps-agent", now: NOW });
+ const codes = r.warnings.map((w) => w.code);
+ expect(codes).toContain("non-primary-dream-run");
+ const warn = r.warnings.find((w) => w.code === "non-primary-dream-run")!;
+ expect(warn.message).toContain("claude-vps-agent");
+ expect(warn.message).toContain("hermes-vps");
+ });
+
+ test("matching agent does NOT warn", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ seedSignals();
+ const r = dream(vault, { agentName: "hermes-vps", now: NOW });
+ expect(r.warnings.find((w) => w.code === "non-primary-dream-run"))
+ .toBeUndefined();
+ });
+
+ test("primary_agent: null never warns regardless of caller agent", () => {
+ // Default state after bootstrap is null.
+ seedSignals();
+ const r = dream(vault, { agentName: "anyone-at-all", now: NOW });
+ expect(r.warnings).toEqual([]);
+ });
+
+ test("absent agentName option does not warn (back-compat)", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ seedSignals();
+ const r = dream(vault, { now: NOW });
+ expect(r.warnings).toEqual([]);
+ });
+
+ test("non_primary_agent payload row appears in the dream log event", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ seedSignals();
+ dream(vault, { agentName: "claude-vps-agent", now: NOW });
+ const log = readTodayLog();
+ expect(log).toMatch(/^- non_primary_agent: claude-vps-agent$/m);
+ });
+
+ test("matching agent leaves the log without non_primary_agent row", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ seedSignals();
+ dream(vault, { agentName: "hermes-vps", now: NOW });
+ const log = readTodayLog();
+ expect(log).not.toMatch(/^- non_primary_agent:/m);
+ });
+
+ test("warning fires even on a no-op run (no signals)", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = dream(vault, { agentName: "claude-vps-agent", now: NOW });
+ expect(r.changed).toBe(false);
+ expect(r.warnings.map((w) => w.code)).toContain("non-primary-dream-run");
+ });
+});
diff --git a/tests/core/brain.dream.test.ts b/tests/core/brain.dream.test.ts
index 898c8da3..28f02bb1 100644
--- a/tests/core/brain.dream.test.ts
+++ b/tests/core/brain.dream.test.ts
@@ -710,7 +710,7 @@ describe("dream โ€” quarantine โ†’ retired (quarantine-violated)", () => {
const blocked = log.entries.find(
(e) =>
e.eventType === "retire" &&
- e.body["preference"] === "[[pref-pinned-quar]]" &&
+ e.body["preference"] === "[[pref-pinned-quar|Pinned rule]]" &&
e.body["blocked"] === "pinned",
);
expect(blocked).toBeDefined();
diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.ts
index 5645f232..1ce26077 100644
--- a/tests/core/brain.init.test.ts
+++ b/tests/core/brain.init.test.ts
@@ -168,6 +168,56 @@ describe("bootstrapBrain โ€” force overwrite", () => {
});
});
+describe("bootstrapBrain โ€” primary_agent option", () => {
+ test("fresh init writes the supplied primary_agent into _brain.yaml", () => {
+ bootstrapBrain(vault, { configPath, primaryAgent: "hermes-vps" });
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);
+ expect(yaml).not.toMatch(/^primary_agent: null$/m);
+ });
+
+ test("fresh init preserves comment-like primary_agent values by quoting", () => {
+ bootstrapBrain(vault, {
+ configPath,
+ primaryAgent: "hermes lead # primary",
+ });
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "hermes lead # primary"$/m);
+ });
+
+ test("default keeps primary_agent: null", () => {
+ bootstrapBrain(vault, { configPath });
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: null$/m);
+ });
+
+ test("re-run without primaryAgent preserves the existing line", () => {
+ bootstrapBrain(vault, { configPath, primaryAgent: "hermes-vps" });
+ bootstrapBrain(vault, { configPath });
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);
+ });
+
+ test("force rewrite with primaryAgent overrides the file", () => {
+ bootstrapBrain(vault, { configPath });
+ bootstrapBrain(vault, { configPath, force: true, primaryAgent: "claude-vps" });
+ const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");
+ expect(yaml).toMatch(/^primary_agent: "claude-vps"$/m);
+ });
+
+ test("empty-string primaryAgent throws (fail loud, not silent fallback)", () => {
+ expect(() =>
+ bootstrapBrain(vault, { configPath, primaryAgent: " " }),
+ ).toThrow(/primary_agent/);
+ });
+
+ test("primaryAgent with a line break is rejected instead of corrupting YAML", () => {
+ expect(() =>
+ bootstrapBrain(vault, { configPath, primaryAgent: "agent\nsnapshots:" }),
+ ).toThrow(/disallowed character/);
+ });
+});
+
describe("bootstrapBrain โ€” missing machine config", () => {
test("throws an error naming `o2b init` when the plugin config does not exist", () => {
const missing = join(configHome, "does-not-exist.yaml");
diff --git a/tests/core/brain.pin.test.ts b/tests/core/brain.pin.test.ts
index 0edc678b..10cbd3a2 100644
--- a/tests/core/brain.pin.test.ts
+++ b/tests/core/brain.pin.test.ts
@@ -64,7 +64,7 @@ describe("setPinned โ€” happy paths", () => {
const { entries } = parseLogDay(vault, "2026-05-14");
expect(entries).toHaveLength(1);
expect(entries[0]!.eventType).toBe("pin");
- expect(entries[0]!.body["preference"]).toBe("[[pref-flippable]]");
+ expect(entries[0]!.body["preference"]).toBe("[[pref-flippable|Rule for flippable]]");
expect(entries[0]!.body["agent"]).toBe("claude");
});
@@ -170,6 +170,7 @@ describe("isPinned โ€” accessor", () => {
violated_count: 0,
last_evidence_at: null,
confidence: "low",
+ confidence_value: null,
pinned: false,
});
expect(isPinned(fake)).toBe(false);
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index fc02cc7d..1b701ed5 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -8,6 +8,7 @@ import {
BrainConfigError,
DEFAULT_BRAIN_CONFIG,
DEFAULT_BRAIN_CONFIG_YAML,
+ formatPrimaryAgentYamlValue,
loadBrainConfig,
loadBrainConfigDetailed,
parseBrainYaml,
@@ -36,6 +37,7 @@ function writeBrainYaml(vault: string, body: string): string {
describe("DEFAULT_BRAIN_CONFIG", () => {
test("matches the values listed in ยง10 of the design doc", () => {
expect(DEFAULT_BRAIN_CONFIG.schema_version).toBe(1);
+ expect(DEFAULT_BRAIN_CONFIG.primary_agent).toBeNull();
expect(DEFAULT_BRAIN_CONFIG.dream.candidate_threshold).toBe(3);
expect(DEFAULT_BRAIN_CONFIG.dream.unconfirmed_window_days).toBe(14);
expect(DEFAULT_BRAIN_CONFIG.dream.contradiction_window_days).toBe(14);
@@ -46,6 +48,12 @@ describe("DEFAULT_BRAIN_CONFIG", () => {
expect(DEFAULT_BRAIN_CONFIG.snapshots.retention_count).toBe(10);
});
+ test("primary_agent default is null and YAML round-trips", () => {
+ const parsed = parseBrainYaml(DEFAULT_BRAIN_CONFIG_YAML);
+ const config = validateBrainConfig(parsed, "<default>");
+ expect(config.primary_agent).toBeNull();
+ });
+
test("BRAIN_CONFIG_SUPPORTED_VERSIONS includes 1", () => {
expect(BRAIN_CONFIG_SUPPORTED_VERSIONS).toContain(1);
});
@@ -89,6 +97,86 @@ describe("validateBrainConfig โ€” happy path", () => {
});
});
+describe("validateBrainConfig โ€” primary_agent", () => {
+ test("absent โ†’ null (default)", () => {
+ const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");
+ expect(cfg.primary_agent).toBeNull();
+ });
+
+ test("explicit null is accepted", () => {
+ const cfg = validateBrainConfig(
+ { schema_version: 1, primary_agent: null },
+ "<test>",
+ );
+ expect(cfg.primary_agent).toBeNull();
+ });
+
+ test("non-empty string is preserved and trimmed", () => {
+ const cfg = validateBrainConfig(
+ { schema_version: 1, primary_agent: " hermes-vps " },
+ "<test>",
+ );
+ expect(cfg.primary_agent).toBe("hermes-vps");
+ });
+
+ test("empty string rejected with named field", () => {
+ try {
+ validateBrainConfig(
+ { schema_version: 1, primary_agent: "" },
+ "<test>",
+ );
+ throw new Error("should have thrown");
+ } catch (err) {
+ expect(err).toBeInstanceOf(BrainConfigError);
+ expect((err as BrainConfigError).field).toBe("primary_agent");
+ }
+ });
+
+ test("whitespace-only string rejected", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, primary_agent: " " },
+ "<test>",
+ ),
+ ).toThrow(/primary_agent/);
+ });
+
+ test("non-string non-null rejected", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, primary_agent: 42 },
+ "<test>",
+ ),
+ ).toThrow(/primary_agent/);
+ });
+});
+
+describe("formatPrimaryAgentYamlValue", () => {
+ test("quotes strings so comment-like content round-trips", () => {
+ const scalar = formatPrimaryAgentYamlValue("hermes lead # primary");
+ expect(scalar).toBe("\"hermes lead # primary\"");
+ const cfg = validateBrainConfig(
+ parseBrainYaml(`schema_version: 1\nprimary_agent: ${scalar}\n`),
+ );
+ expect(cfg.primary_agent).toBe("hermes lead # primary");
+ });
+
+ test("rejects values that would need escaping in the tiny YAML parser", () => {
+ expect(() => formatPrimaryAgentYamlValue("agent\nnext")).toThrow(
+ /disallowed character/,
+ );
+ expect(() => formatPrimaryAgentYamlValue("agent\rnext")).toThrow(
+ /disallowed character/,
+ );
+ expect(() => formatPrimaryAgentYamlValue("agent\\path")).toThrow(
+ /disallowed character/,
+ );
+ expect(() => formatPrimaryAgentYamlValue('agent "quoted"')).toThrow(
+ /disallowed character/,
+ );
+ });
+});
+
describe("validateBrainConfig โ€” error cases", () => {
test("missing schema_version โ†’ error naming the field", () => {
expect(() => validateBrainConfig({}, "<test>")).toThrow(BrainConfigError);
diff --git a/tests/core/brain.set-primary.test.ts b/tests/core/brain.set-primary.test.ts
new file mode 100644
index 00000000..b86258f6
--- /dev/null
+++ b/tests/core/brain.set-primary.test.ts
@@ -0,0 +1,166 @@
+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 { brainConfigPath } from "../../src/core/brain/paths.ts";
+import {
+ BrainConfigError,
+ validateBrainConfig,
+ parseBrainYaml,
+} from "../../src/core/brain/policy.ts";
+import { setPrimaryAgent } from "../../src/core/brain/set-primary.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-brain-setprim-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-setprim-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ mkdirSync(configHome, { recursive: true });
+ writeFileSync(configPath, `vault: "${vault}"\n`, "utf8");
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function readPrimary(): string | null {
+ const text = readFileSync(brainConfigPath(vault), "utf8");
+ return validateBrainConfig(parseBrainYaml(text), brainConfigPath(vault))
+ .primary_agent;
+}
+
+describe("setPrimaryAgent โ€” happy path", () => {
+ test("writes a non-null value into _brain.yaml", () => {
+ const r = setPrimaryAgent(vault, "hermes-vps");
+ expect(r.previous).toBeNull();
+ expect(r.next).toBe("hermes-vps");
+ expect(r.changed).toBe(true);
+ expect(readPrimary()).toBe("hermes-vps");
+ expect(readFileSync(brainConfigPath(vault), "utf8")).toMatch(
+ /^primary_agent: "hermes-vps"$/m,
+ );
+ });
+
+ test("quotes values so inline-comment text round-trips", () => {
+ const r = setPrimaryAgent(vault, "hermes lead # primary");
+ expect(r.next).toBe("hermes lead # primary");
+ expect(readPrimary()).toBe("hermes lead # primary");
+ expect(readFileSync(brainConfigPath(vault), "utf8")).toMatch(
+ /^primary_agent: "hermes lead # primary"$/m,
+ );
+ });
+
+ test("trims whitespace around the new value", () => {
+ setPrimaryAgent(vault, " hermes-vps ");
+ expect(readPrimary()).toBe("hermes-vps");
+ });
+
+ test("no-op repeat returns changed: false and leaves bytes intact", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const before = readFileSync(brainConfigPath(vault), "utf8");
+ const r = setPrimaryAgent(vault, "hermes-vps");
+ const after = readFileSync(brainConfigPath(vault), "utf8");
+ expect(r.previous).toBe("hermes-vps");
+ expect(r.next).toBe("hermes-vps");
+ expect(r.changed).toBe(false);
+ expect(after).toBe(before);
+ });
+
+ test("clears via null", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const r = setPrimaryAgent(vault, null);
+ expect(r.previous).toBe("hermes-vps");
+ expect(r.next).toBeNull();
+ expect(r.changed).toBe(true);
+ expect(readPrimary()).toBeNull();
+ });
+
+ test("clear on already-null is a no-op", () => {
+ const r = setPrimaryAgent(vault, null);
+ expect(r.previous).toBeNull();
+ expect(r.next).toBeNull();
+ expect(r.changed).toBe(false);
+ });
+
+ test("preserves neighbouring blocks (dream/retire/confidence/snapshots)", () => {
+ // Custom edit to a different block, then set primary.
+ const cfgPath = brainConfigPath(vault);
+ const original = readFileSync(cfgPath, "utf8")
+ .replace(/^ candidate_threshold: 3$/m, " candidate_threshold: 5");
+ writeFileSync(cfgPath, original, "utf8");
+
+ setPrimaryAgent(vault, "hermes-vps");
+ const final = readFileSync(cfgPath, "utf8");
+ expect(final).toMatch(/^primary_agent: "hermes-vps"$/m);
+ expect(final).toMatch(/^ candidate_threshold: 5$/m);
+ });
+});
+
+describe("setPrimaryAgent โ€” error cases", () => {
+ test("throws BrainConfigError when _brain.yaml does not exist", () => {
+ const fresh = mkdtempSync(join(tmpdir(), "o2b-brain-setprim-empty-"));
+ try {
+ expect(() => setPrimaryAgent(fresh, "anything")).toThrow(BrainConfigError);
+ } finally {
+ rmSync(fresh, { recursive: true, force: true });
+ }
+ });
+
+ test("empty-string name is rejected (use --clear instead)", () => {
+ expect(() => setPrimaryAgent(vault, " ")).toThrow(/non-empty/);
+ });
+
+ test("line breaks are rejected rather than written into YAML", () => {
+ expect(() => setPrimaryAgent(vault, "agent\nsnapshots:")).toThrow(
+ /disallowed character/,
+ );
+ });
+
+ test("rewritten file still validates against the schema", () => {
+ setPrimaryAgent(vault, "hermes-vps");
+ const cfg = validateBrainConfig(
+ parseBrainYaml(readFileSync(brainConfigPath(vault), "utf8")),
+ brainConfigPath(vault),
+ );
+ expect(cfg.primary_agent).toBe("hermes-vps");
+ expect(cfg.dream.candidate_threshold).toBe(3); // defaults intact
+ });
+});
+
+describe("setPrimaryAgent โ€” missing primary_agent line", () => {
+ test("inserts the declaration after schema_version when absent", () => {
+ // Hand-craft a YAML missing the primary_agent line entirely.
+ const cfgPath = brainConfigPath(vault);
+ const trimmed = readFileSync(cfgPath, "utf8").replace(
+ /^# Optional.*\nprimary_agent: null\n\n/m,
+ "",
+ );
+ writeFileSync(cfgPath, trimmed, "utf8");
+
+ setPrimaryAgent(vault, "hermes-vps");
+ const text = readFileSync(cfgPath, "utf8");
+ expect(text).toMatch(/^primary_agent: "hermes-vps"$/m);
+ expect(text.indexOf("schema_version:")).toBeLessThan(
+ text.indexOf("primary_agent:"),
+ );
+ });
+});
diff --git a/tests/core/brain.snapshot-diff.test.ts b/tests/core/brain.snapshot-diff.test.ts
new file mode 100644
index 00000000..80114b09
--- /dev/null
+++ b/tests/core/brain.snapshot-diff.test.ts
@@ -0,0 +1,341 @@
+/**
+ * Tests for `src/core/brain/snapshot-diff.ts` and its renderer.
+ *
+ * Fixture-driven: each test builds two on-disk Brain/ subtrees from
+ * scratch (no real snapshot archive needed โ€” the differ takes any
+ * two roots), runs `diffBrainTrees`, and asserts on the structured
+ * payload. Markdown rendering is locked separately to keep parser
+ * regressions visible without re-deriving the structured shape.
+ */
+
+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 { diffBrainTrees } from "../../src/core/brain/snapshot-diff.ts";
+import {
+ renderDiffJson,
+ renderDiffMarkdown,
+} from "../../src/core/brain/snapshot-diff-render.ts";
+
+let scratch: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(tmpdir(), "o2b-brain-snapdiff-"));
+});
+
+afterEach(() => {
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+interface PrefShape {
+ readonly slug: string;
+ readonly principle?: string;
+ readonly status?: "unconfirmed" | "confirmed" | "quarantine";
+ readonly applied?: number;
+ readonly violated?: number;
+ readonly confidence?: "low" | "medium" | "high";
+ readonly confidence_value?: number | null;
+ readonly pinned?: boolean;
+}
+
+function makeRoot(name: string): string {
+ const root = join(scratch, name);
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(root, sub), { recursive: true });
+ }
+ return root;
+}
+
+function writePref(root: string, s: PrefShape): void {
+ const id = `pref-${s.slug}`;
+ const path = join(root, "preferences", `${id}.md`);
+ const body = `---
+kind: brain-preference
+id: ${id}
+created_at: 2026-05-01T00:00:00Z
+_confirmed_at: ${s.status === "confirmed" ? "2026-05-02T00:00:00Z" : "null"}
+unconfirmed_until: 2026-05-30T00:00:00Z
+tags: [brain, brain/preference, brain/topic/${s.slug}]
+topic: ${s.slug}
+_status: ${s.status ?? "unconfirmed"}
+principle: ${s.principle ?? `principle for ${s.slug}`}
+_evidenced_by: []
+_applied_count: ${s.applied ?? 0}
+_violated_count: ${s.violated ?? 0}
+_last_evidence_at: null
+_confidence: ${s.confidence ?? "low"}
+_confidence_value: ${
+ s.confidence_value === undefined
+ ? 0
+ : s.confidence_value === null
+ ? "null"
+ : s.confidence_value
+ }
+pinned: ${s.pinned ?? false}
+---
+`;
+ writeFileSync(path, body, "utf8");
+}
+
+function writeSig(root: string, slug: string): void {
+ const id = `sig-2026-05-01-${slug}`;
+ const path = join(root, "inbox", `${id}.md`);
+ writeFileSync(
+ path,
+ `---
+kind: brain-signal
+id: ${id}
+created_at: 2026-05-01T00:00:00Z
+tags: [brain, brain/signal]
+topic: ${slug}
+signal: positive
+agent: tester
+principle: rule
+---
+`,
+ "utf8",
+ );
+}
+
+function writeLog(root: string, day: string, body: string): void {
+ writeFileSync(
+ join(root, "log", `${day}.md`),
+ `---\nkind: brain-log\ndate: ${day}\ntags: [brain, brain/log]\n---\n\n${body}\n`,
+ "utf8",
+ );
+}
+
+describe("diffBrainTrees โ€” adds and removes", () => {
+ test("preference added in B only", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(a, { slug: "alpha" });
+ writePref(b, { slug: "alpha" });
+ writePref(b, { slug: "beta", principle: "Beta principle" });
+ const d = diffBrainTrees(a, b);
+ expect(d.removed).toEqual([]);
+ expect(d.modified).toEqual([]);
+ expect(d.added).toHaveLength(1);
+ expect(d.added[0]!.id).toBe("pref-beta");
+ expect(d.added[0]!.kind).toBe("preference");
+ expect(d.added[0]!.principle).toBe("Beta principle");
+ });
+
+ test("preference removed in B", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(a, { slug: "gone" });
+ const d = diffBrainTrees(a, b);
+ expect(d.added).toEqual([]);
+ expect(d.modified).toEqual([]);
+ expect(d.removed).toHaveLength(1);
+ expect(d.removed[0]!.id).toBe("pref-gone");
+ });
+
+ test("signal added/removed (immutable, no field-diff)", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writeSig(a, "old");
+ writeSig(b, "new");
+ const d = diffBrainTrees(a, b);
+ expect(d.added.map((e) => e.id)).toEqual(["sig-2026-05-01-new"]);
+ expect(d.removed.map((e) => e.id)).toEqual(["sig-2026-05-01-old"]);
+ expect(d.modified.find((c) => c.entry.kind === "signal")).toBeUndefined();
+ });
+});
+
+describe("diffBrainTrees โ€” field-level modifications", () => {
+ test("preference status + applied_count change", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(a, {
+ slug: "rule",
+ principle: "Rule",
+ status: "confirmed",
+ applied: 4,
+ violated: 0,
+ confidence: "medium",
+ });
+ writePref(b, {
+ slug: "rule",
+ principle: "Rule",
+ status: "quarantine",
+ applied: 7,
+ violated: 3,
+ confidence: "low",
+ });
+ const d = diffBrainTrees(a, b);
+ expect(d.added).toEqual([]);
+ expect(d.removed).toEqual([]);
+ expect(d.modified).toHaveLength(1);
+ const change = d.modified[0]!;
+ expect(change.entry.id).toBe("pref-rule");
+ expect(change.bodyChanged).toBe(false);
+ const fieldNames = change.fields.map((f) => f.field).sort();
+ expect(fieldNames).toEqual([
+ "applied_count",
+ "confidence",
+ "confirmed_at",
+ "status",
+ "violated_count",
+ ]);
+ });
+
+ test("byte-equal preferences produce no change", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(a, { slug: "stable" });
+ writePref(b, { slug: "stable" });
+ const d = diffBrainTrees(a, b);
+ expect(d.added).toEqual([]);
+ expect(d.removed).toEqual([]);
+ expect(d.modified).toEqual([]);
+ });
+
+ test("log body change marks bodyChanged=true with no fields", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writeLog(a, "2026-05-14", "## 10:00 โ€” feedback\n- x: 1");
+ writeLog(b, "2026-05-14", "## 10:00 โ€” feedback\n- x: 2");
+ const d = diffBrainTrees(a, b);
+ expect(d.modified).toHaveLength(1);
+ expect(d.modified[0]!.entry.kind).toBe("log");
+ expect(d.modified[0]!.fields).toEqual([]);
+ expect(d.modified[0]!.bodyChanged).toBe(true);
+ });
+});
+
+describe("diffBrainTrees โ€” ignored regions", () => {
+ test("entries under .snapshots/ are skipped", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ mkdirSync(join(a, ".snapshots"), { recursive: true });
+ mkdirSync(join(b, ".snapshots"), { recursive: true });
+ writeFileSync(join(a, ".snapshots", "x.tar.zst"), "old", "utf8");
+ writeFileSync(join(b, ".snapshots", "y.tar.zst"), "new", "utf8");
+ const d = diffBrainTrees(a, b);
+ expect(
+ d.added.find((e) => e.path.includes(".snapshots/")),
+ ).toBeUndefined();
+ expect(
+ d.removed.find((e) => e.path.includes(".snapshots/")),
+ ).toBeUndefined();
+ });
+
+ test("symlinks are not followed (defense against malicious snapshot tarballs)", async () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ // Plant a real file outside the walker root, and a symlink under
+ // Brain/preferences/ pointing at it. A naive `statSync`-based
+ // walker would dereference the symlink and surface the target's
+ // bytes as a "preference" inside the diff.
+ const secret = join(scratch, "secret.txt");
+ writeFileSync(secret, "SECRET_TOKEN_DO_NOT_LEAK", "utf8");
+ const { symlinkSync } = await import("node:fs");
+ symlinkSync(secret, join(b, "preferences", "pref-trojan.md"));
+ const d = diffBrainTrees(a, b);
+ // The symlink must not appear in any diff section.
+ const allEntries = [
+ ...d.added,
+ ...d.removed,
+ ...d.modified.map((c) => c.entry),
+ ];
+ expect(allEntries.find((e) => e.path.includes("pref-trojan"))).toBeUndefined();
+ });
+});
+
+describe("diffBrainTrees โ€” output ordering", () => {
+ test("entries sort deterministically by kind then path", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(b, { slug: "zeta" });
+ writePref(b, { slug: "alpha" });
+ writeSig(b, "later");
+ writeSig(b, "earlier");
+ const d = diffBrainTrees(a, b);
+ const addedKinds = d.added.map((e) => e.kind);
+ // 'preference' < 'signal' alphabetically โ€” preferences come first.
+ expect(addedKinds).toEqual([
+ "preference",
+ "preference",
+ "signal",
+ "signal",
+ ]);
+ expect(d.added.map((e) => e.id)).toEqual([
+ "pref-alpha",
+ "pref-zeta",
+ "sig-2026-05-01-earlier",
+ "sig-2026-05-01-later",
+ ]);
+ });
+});
+
+describe("renderDiffMarkdown / renderDiffJson", () => {
+ test("markdown body groups by kind and emits A/B labels", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(b, { slug: "added-rule", principle: "Use spaces" });
+ const md = renderDiffMarkdown(diffBrainTrees(a, b), {
+ aLabel: "run-x",
+ bLabel: "live",
+ });
+ expect(md).toMatch(/^# Brain snapshot diff$/m);
+ expect(md).toMatch(/^- A: run-x$/m);
+ expect(md).toMatch(/^- B: live$/m);
+ expect(md).toMatch(/^## Preferences$/m);
+ expect(md).toMatch(/^- \+ \[\[pref-added-rule\|Use spaces\]\] \(added\)$/m);
+ });
+
+ test("modified row lists field deltas", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(a, {
+ slug: "rule",
+ principle: "Rule",
+ applied: 4,
+ confidence: "medium",
+ });
+ writePref(b, {
+ slug: "rule",
+ principle: "Rule",
+ applied: 7,
+ confidence: "high",
+ });
+ const md = renderDiffMarkdown(diffBrainTrees(a, b), {
+ aLabel: "old",
+ bLabel: "new",
+ });
+ expect(md).toMatch(/^- ~ \[\[pref-rule\|Rule\]\]:$/m);
+ expect(md).toMatch(/^ {2}- applied_count: 4 โ†’ 7$/m);
+ expect(md).toMatch(/^ {2}- confidence: medium โ†’ high$/m);
+ });
+
+ test("section without entries renders '(no changes)'", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ const md = renderDiffMarkdown(diffBrainTrees(a, b), {});
+ expect(md).toMatch(/^## Preferences$/m);
+ expect(md).toMatch(/^\(no changes\)$/m);
+ });
+
+ test("json renderer returns the diff verbatim", () => {
+ const a = makeRoot("a");
+ const b = makeRoot("b");
+ writePref(b, { slug: "x" });
+ const diff = diffBrainTrees(a, b);
+ expect(renderDiffJson(diff)).toBe(diff);
+ });
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index effaaf26..0fcb44ff 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -113,6 +113,7 @@ describe("interface shape smoke (compile-time)", () => {
violated_count: 0,
last_evidence_at: null,
confidence: BRAIN_CONFIDENCE.low,
+ confidence_value: null,
pinned: false,
} as const satisfies BrainPreference;
expect(unconfirmed.confirmed_at).toBeNull();
@@ -148,6 +149,7 @@ describe("interface shape smoke (compile-time)", () => {
violated_count: 0,
last_evidence_at: "2026-05-14T10:42:00Z",
confidence: BRAIN_CONFIDENCE.low,
+ confidence_value: null,
pinned: false,
} as const satisfies BrainRetired;
expect(retired.status).toBe("retired");
@@ -172,6 +174,7 @@ describe("interface shape smoke (compile-time)", () => {
test("BrainConfig with defaults compiles", () => {
const cfg = {
schema_version: 1,
+ primary_agent: null,
dream: {
candidate_threshold: 3,
unconfirmed_window_days: 14,
@@ -182,10 +185,13 @@ describe("interface shape smoke (compile-time)", () => {
low_max_applied: 2,
high_min_applied: 10,
high_freshness_factor: 0.8,
+ medium_min: 0.40,
+ high_min: 0.75,
},
snapshots: { retention_count: 10 },
} as const satisfies BrainConfig;
expect(cfg.schema_version).toBe(1);
+ expect(cfg.primary_agent).toBeNull();
expect(cfg.snapshots.retention_count).toBe(10);
});
});
diff --git a/tests/core/brain.wikilink.test.ts b/tests/core/brain.wikilink.test.ts
index ca1f95a1..512ee82f 100644
Binary files a/tests/core/brain.wikilink.test.ts and b/tests/core/brain.wikilink.test.ts differ
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index 9cc36327..d35cd259 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -367,7 +367,7 @@ describe("brain_apply_evidence", () => {
expect(s.agent).toBe("claude");
const file = join(vault, s.log_path);
const text = readFileSync(file, "utf8");
- expect(text).toContain("[[pref-no-internal-abbrev]]");
+ expect(text).toContain("[[pref-no-internal-abbrev|");
expect(text).toContain("applied");
expect(text).toContain("Expanded OSB on first use.");
});