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.6: Logging discipline, manifest-backed snapshots, explorer polish, export (#21)

Sol Aitken4ca3809a02b4
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 3dbb0f85..b8a92a8b 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.5",
+ "version": "0.10.6",
"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 16e233e8..3396eb42 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.5",
+ "version": "0.10.6",
"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 dd8f788a..268e2336 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,135 @@ 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.6] - 2026-05-18
+
+Five tracks from `Projects/OpenSecondBrain/Features/_summary` shipped
+under one release: Β§30 Β§A+Β§C (agent logging discipline), Β§22 + Β§5-tail
+(`o2b brain upgrade` and manifest-backed rollback drift detection),
+Β§14 polish (keyboard-accessible Brain Explorer listbox plus
+`localStorage` layout / filter persistence), Β§28
+(`o2b brain export`), and Β§31 CR cleanup from PR #20.
+
+No vault data migration is required. Snapshots taken before v0.10.6
+keep working β€” `rollback` emits a stderr warning and falls back to the
+legacy direct-restore path. New snapshots (taken by `dream`, `merge`,
+`migrate-frontmatter`, or `upgrade`) ship with a `<run-id>.manifest.json`
+sidecar that powers drift detection.
+
+### Added
+
+- Β§22 β€” `o2b brain upgrade [--dry-run] [--apply] [--yes] [--check]
+ [--json]` migrates the three release-owned files
+ (`Brain/_brain.yaml`, `Brain/_BRAIN.md`,
+ `AI Wiki/_OPEN_SECOND_BRAIN.md`) forward when the installed
+ open-second-brain version changes them. `_brain.yaml` merge is
+ purely additive β€” missing schema keys and sections are appended,
+ user values stay. `_BRAIN.md` and `_OPEN_SECOND_BRAIN.md` are
+ byte-compared against the rendered template and overwritten on
+ apply. `--apply` always takes a pre-apply snapshot named
+ `upgrade-<ts>` (rollback via run id). The new
+ `BRAIN_LOG_EVENT_KIND.upgrade` records the run.
+- Β§5-tail β€” `createSnapshot` writes a SHA-256 manifest sidecar
+ `<vault>/Brain/.snapshots/<run-id>.manifest.json` alongside every
+ archive. `o2b brain rollback` reads it back and exits 2 with a
+ drift diff when the live `Brain/` tree differs from the snapshot
+ moment. The new `--force-rollback` overrides the abort and the
+ rollback log entry then records `drift_overridden: true`.
+ Snapshots without a sidecar (legacy) skip the check with a stderr
+ warning. `pruneSnapshots` removes the sidecar alongside the
+ archive; `listSnapshots` surfaces `manifest_path`.
+- Β§28 β€” `o2b brain export --format json|llms-txt [--out <path>]
+ [--force]` produces a read-only dump of active preferences
+ (`confirmed | unconfirmed | quarantine`) from
+ `Brain/preferences/`. Retired and signal artifacts are not
+ included. Default sink is stdout; `--out` writes a file
+ (atomically), refusing to overwrite without `--force`. The
+ llms-txt output follows the [llmstxt.org](https://llmstxt.org)
+ H1 + summary + H2-section shape.
+- Β§14 polish β€” Brain Explorer template (`templates/brain-explorer.html`)
+ ships a keyboard-accessible `<ul role="listbox">` mirror of the
+ visible nodes alongside the canvas. ArrowUp / ArrowDown / Home /
+ End / Enter / Escape navigate; `aria-activedescendant` tracks
+ focus; pointer click on canvas keeps both surfaces in sync via a
+ single `selectNode(id)` unifier. Layout + filter state persists to
+ `localStorage` under `osb-explorer-layout:<vault_basename>` so
+ positions, status filters, and the search box survive reloads. A
+ "Reset layout" button clears the key.
+- New module `src/core/brain/manifest.ts` (`buildManifest`,
+ `diffManifests`, sidecar I/O, drift renderers).
+- New module `src/core/brain/upgrade.ts` (`planUpgrade`,
+ `applyUpgrade`, text-level `mergeBrainYaml`).
+- New module `src/core/brain/export.ts` (JSON + llms-txt
+ serialisers).
+- New module `src/core/brain/templates.ts` β€” `init.ts` no longer
+ owns template paths or rendering primitives; both `init` (first
+ install) and `upgrade` (subsequent migrations) consume the same
+ `renderBrainManual` / `renderLegacyOverview` helpers so the two
+ paths cannot drift.
+
+### Changed
+
+- Β§30 Β§A β€” `hooks/lib/detect.ts` broadens the brain-event detection
+ regex from `event_log_append` to any of `event_log_append`,
+ `brain_feedback`, `brain_apply_evidence` (both MCP names and CLI
+ bash invocations). `hooks/stop-log-guardrail.ts` now clears on any
+ of the three. `TurnSummary.hadLog` was renamed to
+ `hadBrainEvent`; `isLogToolName` was renamed to
+ `isBrainEventToolName`. The stop-guardrail reason text lists all
+ three tools explicitly.
+- Β§30 Β§C β€” `skills/brain-memory/SKILL.md` description and "When NOT
+ to call" section reformulate the trigger: when a preference
+ plausibly applies but you are unsure, record with `note:
+ "speculative; <reason>"` instead of skipping. The dream pass
+ filters single-event speculative entries that do not recur, so
+ coverage costs less than missing the signal.
+ `hooks/lib/messages.ts:postWriteReminder` mirrors the new wording.
+- `o2b brain rollback` gains `--force-rollback`, drift detection,
+ and updated help text. The rollback log payload optionally
+ records `drift_overridden`.
+- `_BRAIN.md` template (`src/core/brain/templates/_BRAIN.md.tpl`)
+ lists `o2b brain upgrade` and `o2b brain export` under the
+ Escape-hatches CLI surface, and mentions the v0.10.6 sidecar
+ manifest behaviour on rollback. This is the canonical v0.10.6
+ template change β€” pre-v0.10.6 vaults see the diff under
+ `o2b brain upgrade --dry-run`.
+
+### Internal
+
+- `SnapshotInfo` gains `manifest_path: string | null`.
+- `BRAIN_LOG_EVENT_KIND.upgrade = "upgrade"`,
+ `BrainUpgradeLogEvent` joins the `BrainLogEvent` union.
+- `init.ts` slimmed down β€” template rendering primitives moved to
+ the dedicated `templates.ts` module (DRY across init and
+ upgrade).
+
+### Tests
+
+- `tests/core/brain/manifest.test.ts`
+- `tests/core/brain/upgrade.test.ts`
+- `tests/core/brain/export.test.ts`
+- `tests/core/brain.snapshot.test.ts` (extended for sidecar +
+ legacy prune)
+- `tests/cli/brain-upgrade.test.ts`
+- `tests/cli/brain-export.test.ts`
+- `tests/cli/brain.test.ts` (extended with rollback drift +
+ legacy-snapshot scenarios)
+- `tests/hooks/detect.test.ts` (extended for `brain_feedback` /
+ `brain_apply_evidence` MCP names and bash needles)
+- `tests/core/brain/explorer.test.ts` (extended with listbox /
+ localStorage smoke checks)
+- `tests/scripts/macos-sqlite-shim.test.ts` (one new case for
+ `DYLD_LIBRARY_PATH=""`)
+
+### Docs
+
+- MD040 language tags added to
+ `docs/plans/2026-05-18-brain-maturity-design.md`,
+ `docs/plans/2026-05-18-brain-maturity-impl.md`,
+ `skills/embeddings-setup/SKILL.md`.
+- `docs/plans/2026-05-18-v0.10.6-design.md` and
+ `docs/plans/2026-05-18-v0.10.6-impl.md` document the release.
+
## [0.10.5] - 2026-05-18
Brings the v0.10.5 "Brain maturity + embeddings activation"
@@ -1673,6 +1802,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.6]: https://github.com/itechmeat/open-second-brain/compare/v0.10.5...v0.10.6
[0.10.5]: https://github.com/itechmeat/open-second-brain/compare/v0.10.4...v0.10.5
[0.10.4]: https://github.com/itechmeat/open-second-brain/compare/v0.10.3...v0.10.4
[0.10.3]: https://github.com/itechmeat/open-second-brain/compare/v0.10.2...v0.10.3
diff --git a/README.md b/README.md
index a43b186b..2c81dd0f 100644
--- a/README.md
+++ b/README.md
@@ -130,8 +130,10 @@ o2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain
o2b brain protect (CLI-only) Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
o2b brain unprotect (CLI-only) Remove the OSB-managed deny rules for the chosen target
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 explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file
+o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot (--dry-run previews; drift abort vs --force-rollback)
+o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes
+o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])
+o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence.
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, …)
@@ -235,11 +237,11 @@ o2b brain digest --vault /path/to/vault --silent-if-empty
The Brain verbs in full: `init`, `feedback`, `dream`,
`apply-evidence`, `digest`, `query`, `reject`, `merge`, `pin`,
`unpin`, `set-primary`, `protect`, `unprotect`, `snapshot diff`,
-`rollback`, `doctor`, `backlinks`, `scan-inline`,
-`import-session`, `migrate-frontmatter`, `explorer`. 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.
+`rollback`, `upgrade`, `export`, `doctor`, `backlinks`,
+`scan-inline`, `import-session`, `migrate-frontmatter`,
+`explorer`. 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
@@ -499,10 +501,17 @@ you want to.
context. They never write to the vault directly β€” every Brain
entry goes through `brain_feedback` / `brain_apply_evidence`
(MCP) or the equivalent CLI (`o2b brain *`).
-- Brain mutations (`o2b brain dream`) take an automatic pre-run
+- Brain mutations (`o2b brain dream`, `merge`,
+ `migrate-frontmatter`, `upgrade`) take an automatic pre-run
snapshot (`Brain/.snapshots/<run_id>.tar.zst`) before any state
- change. `o2b brain rollback <run_id>` restores from a snapshot;
- retention is configurable in `_brain.yaml`.
+ change. From v0.10.6 the snapshot ships with a SHA-256 sidecar
+ manifest (`<run_id>.manifest.json`); `o2b brain rollback`
+ compares it against the live tree and aborts with exit 2 on
+ drift (typically a Syncthing-delivered edit on another device
+ between snapshot and rollback). Pass `--force-rollback` to
+ overwrite anyway. Legacy snapshots without sidecar fall back to
+ the pre-v0.10.6 direct-restore path with a stderr warning.
+ Retention is configurable in `_brain.yaml`.
## Repository
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 9e368e12..d6dec4a7 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -361,8 +361,10 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Merge near-duplicate prefs | `o2b brain merge <keep> <drop>` | β€” (CLI-only) | folds `evidenced_by` and counters into `keep`; `drop` retires with reason `merged-into`; surfaced as candidates in `brain_digest` |
| Toggle pin | `o2b brain pin / unpin` | β€” (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |
| Protect Brain/ | `o2b brain protect / unprotect` | β€” (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |
-| Restore snapshot | `o2b brain rollback` | β€” (CLI-only) | overwrites Brain/ from snapshot |
-| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β€” (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend |
+| Restore snapshot | `o2b brain rollback` | β€” (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |
+| Upgrade managed files | `o2b brain upgrade` | β€” (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. |
+| Export active prefs | `o2b brain export --format json\|llms-txt` | β€” (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. |
+| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β€” (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |
Operations that change the **protected set** (`pin`, `unpin`,
`reject`, `rollback`) and the **index lifecycle** (`search index`,
@@ -408,6 +410,23 @@ 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.
+From v0.10.6 every snapshot ships with a SHA-256 sidecar manifest
+(`Brain/.snapshots/<run_id>.manifest.json`) listing every regular
+file under `Brain/` and its hash. `o2b brain rollback` reads the
+sidecar back, rebuilds a fresh manifest from the live tree, and
+compares: any added / removed / changed entry aborts the rollback
+with exit code 2 and a compact drift report on stderr. The intent
+is to refuse silent overwrites of Syncthing-delivered edits made on
+another device between snapshot and rollback. Pass
+`--force-rollback` to override; the resulting rollback log row
+records `drift_overridden: true`. Snapshots predating v0.10.6 have
+no sidecar β€” rollback emits a stderr warning, skips the drift
+check, and falls through to the legacy direct-restore path so old
+archives still recover cleanly. The same sidecar primitive backs
+`o2b brain upgrade --dry-run`'s per-file diff: both features share
+`src/core/brain/manifest.ts` as the single source of truth for
+"what does `Brain/` look like right now".
+
### Read-only inspectors over the snapshot family
Two CLI surfaces share the same diff renderer over the snapshot
diff --git a/docs/plans/2026-05-18-brain-maturity-design.md b/docs/plans/2026-05-18-brain-maturity-design.md
index 5461025a..9cdcd75f 100644
--- a/docs/plans/2026-05-18-brain-maturity-design.md
+++ b/docs/plans/2026-05-18-brain-maturity-design.md
@@ -98,7 +98,7 @@ same commit so it survives across planning sessions.
### Surface
-```
+```bash
o2b brain explorer # live, default port 7777
o2b brain explorer --port 8080 # live on a different port
o2b brain explorer --export <path> # static single-file HTML
@@ -119,7 +119,7 @@ existing `fs-atomic` helper.
### Modules
-```
+```ts
src/core/brain/explorer.ts
- collectExplorerData(vault: string): ExplorerGraph // pure read
- renderExportedHtml(graph: ExplorerGraph): string // template + inline JSON
@@ -247,7 +247,7 @@ edge styles) and counts (N preferences, M retired, K edges).
### Surface
-```
+```bash
o2b brain merge <keep-pref-id> <drop-pref-id> [--dry-run] [--force] [--vault <path>]
```
@@ -329,7 +329,7 @@ flow already sets β€” same convention as `o2b brain reject`.
### `merge-candidates` detector
-```
+```text
src/core/brain/merge-candidates.ts
- findMergeCandidates(vault: string, opts?: { threshold?: number }):
ReadonlyArray<MergeCandidate>
@@ -443,7 +443,7 @@ Claude Code picks it up on the next `SessionStart` (the
### `detectHookRuntime`
-```
+```text
hooks/lib/detect.ts
- type HookRuntime = "claudecode" | "codex" | "unknown"
- function detectHookRuntime(payload: unknown): HookRuntime
@@ -510,7 +510,7 @@ cadence block:
### Call-site updates
-```
+```text
hooks/post-write-reminder.ts
- import detectHookRuntime
- const runtime = detectHookRuntime(payload)
@@ -607,7 +607,7 @@ expect the field are unaffected (additive).
New flag on the existing `reindex` verb:
-```
+```bash
o2b search reindex --cron-template [--interval <duration>] [--vault <path>]
```
diff --git a/docs/plans/2026-05-18-brain-maturity-impl.md b/docs/plans/2026-05-18-brain-maturity-impl.md
index bbac40ab..21157d71 100644
--- a/docs/plans/2026-05-18-brain-maturity-impl.md
+++ b/docs/plans/2026-05-18-brain-maturity-impl.md
@@ -95,7 +95,7 @@ These apply to every task; do not re-state per step.
New files (count: 12):
-```
+```text
docs/plans/2026-05-18-brain-maturity-impl.md # this file
src/core/brain/similarity.ts # Β§12 lift
src/core/brain/merge-candidates.ts # Β§12 detector
@@ -112,7 +112,7 @@ tests/cli/brain-explorer.test.ts # Β§14
Modified files (count: 15):
-```
+```text
src/core/brain/doctor.ts # Β§12 import from similarity.ts
src/core/brain/digest.ts # Β§12 merge_suggestions section
src/core/brain/types.ts # Β§12 new reason + event kind
@@ -132,7 +132,7 @@ package.json # Phase 5 only (version
Version-mirror files (touched once in Phase 5 via `bun run sync-version`):
-```
+```text
.claude-plugin/plugin.json
.codex-plugin/plugin.json
plugins/codex/.codex-plugin/plugin.json
@@ -211,7 +211,7 @@ describe("jaccard", () => {
**Step 2: Run test to verify failure**
-```
+```bash
bun test tests/core/brain/similarity.test.ts
```
Expected: FAIL β€” module not found.
@@ -262,7 +262,7 @@ export function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number
**Step 5: Run tests to verify pass and no doctor regression**
-```
+```bash
bun test tests/core/brain/similarity.test.ts
bun test tests/core/brain/doctor.test.ts
```
@@ -307,7 +307,7 @@ In the existing const block (after `migrateFrontmatter`):
**Step 3: Typecheck**
-```
+```bash
bun run typecheck
```
Expected: PASS.
@@ -429,7 +429,7 @@ describe("findMergeCandidates", () => {
**Step 2: Run test to verify failure**
-```
+```bash
bun test tests/core/brain/merge-candidates.test.ts
```
Expected: FAIL β€” module not found.
@@ -553,7 +553,7 @@ export function findMergeCandidates(
**Step 4: Run tests to verify pass**
-```
+```bash
bun test tests/core/brain/merge-candidates.test.ts
```
Expected: 3 passed.
@@ -665,7 +665,7 @@ Append two test cases in `tests/core/brain/digest.test.ts`:
**Step 6: Run tests**
-```
+```bash
bun test tests/core/brain/digest.test.ts
```
Expected: all previous tests still green plus the two new ones.
@@ -787,7 +787,7 @@ required for `BrainPreference` parsing (`evidenced_by` array,
**Step 3: Verify failure**
-```
+```bash
bun test tests/core/brain/merge.test.ts
```
Expected: FAIL β€” module not found.
@@ -829,7 +829,7 @@ Implementation outline (translate to TS, ~180 lines):
**Step 5: Run tests**
-```
+```bash
bun test tests/core/brain/merge.test.ts
```
Expected: 8 passed (6 guards + 2 happy-path).
@@ -896,14 +896,14 @@ fixture vault, asserts exit code, stdout/stderr, and on-disk effect
**Step 4: Verify**
-```
+```bash
bun test tests/cli/brain-merge.test.ts
```
Expected: 7 passed.
**Step 5: Phase 1 typecheck and full test**
-```
+```bash
bun run typecheck
bun test
```
@@ -963,7 +963,7 @@ describe("collectExplorerData", () => {
**Step 2: Verify failure**
-```
+```bash
bun test tests/core/brain/explorer.test.ts
```
Expected: FAIL.
@@ -1017,7 +1017,7 @@ function returns `Map<targetId, refs[]>` β€” count = `refs.length`).
**Step 4: Verify**
-```
+```bash
bun test tests/core/brain/explorer.test.ts
```
Expected: 8 passed.
@@ -1145,7 +1145,7 @@ test("template carries the placeholder before substitution", () => {
**Step 4: Verify**
-```
+```bash
bun test tests/core/brain/explorer.test.ts
```
Expected: all previous tests still green plus the two new ones.
@@ -1318,14 +1318,14 @@ For the live test, use a high random port (e.g. `30000 + Math.floor(Math.random(
**Step 4: Verify**
-```
+```bash
bun test tests/cli/brain-explorer.test.ts
```
Expected: 6 passed.
**Step 5: Phase 2 typecheck and full test**
-```
+```bash
bun run typecheck
bun test
```
@@ -1428,7 +1428,7 @@ export function detectHookRuntime(payload: unknown): HookRuntime {
**Step 3: Verify**
-```
+```bash
bun test tests/hooks/detect.test.ts
```
Expected: existing tests still green plus 5 new.
@@ -1619,7 +1619,7 @@ Symmetric three tests in `tests/hooks/stop-log-guardrail.test.ts`.
**Step 4: Verify**
-```
+```bash
bun test tests/hooks/
bun run typecheck
```
@@ -1673,7 +1673,7 @@ fits in ~25 lines. Comment header describes WHY (Apple's
**Step 4: Run tests.**
-```
+```bash
bun test tests/scripts/macos-sqlite-shim.test.ts
```
@@ -1771,7 +1771,7 @@ function renderCheckHuman(r: IndexCheckReport): string {
**Step 5: Verify.**
-```
+```bash
bun test tests/core/search/check-recommendations.test.ts
bun test tests/cli/search.test.ts # may surface a renderer regression
```
@@ -1828,7 +1828,7 @@ async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {
**Step 4: Verify.**
-```
+```bash
bun test tests/cli/search-cron-template.test.ts
```
@@ -1853,7 +1853,7 @@ with explicit triggers (verbatim phrases the agent watches for).
After Tasks 6.1–6.4:
-```
+```bash
bun run typecheck
bun test
```
@@ -2013,13 +2013,13 @@ the existing script.
**Step 2: Run sync**
-```
+```bash
bun run sync-version
```
**Step 3: Verify drift gone**
-```
+```bash
bun run sync-version:check
```
Expected: exit 0.
@@ -2088,14 +2088,14 @@ vault.
**Step 1: Typecheck**
-```
+```bash
bun run typecheck
```
Expected: PASS.
**Step 2: Test**
-```
+```bash
bun test
```
Expected: all green. Note the new test counts:
diff --git a/docs/plans/2026-05-18-v0.10.6-design.md b/docs/plans/2026-05-18-v0.10.6-design.md
new file mode 100644
index 00000000..693e1888
--- /dev/null
+++ b/docs/plans/2026-05-18-v0.10.6-design.md
@@ -0,0 +1,944 @@
+# v0.10.6 β€” Logging discipline, manifest-backed snapshots, explorer polish, export
+
+Status: draft
+Owners: TBD
+Source:
+- `Projects/OpenSecondBrain/Features/_summary.md` Β§30, Β§22 + Β§5-tail, Β§14 polish, Β§28, Β§31.
+- `Projects/OpenSecondBrain/Plan/3. Agent logging discipline.md` Β§A + Β§C.
+- `Projects/OpenSecondBrain/Plan/4. v0.10.5 review followups.md` Β§1, Β§2, Β§4.
+
+## Context
+
+Five tracks ship under v0.10.6. They are independent in surface but
+share two cross-cutting artifacts that justify a single PR rather
+than five:
+
+- **Brain manifest.** A single file-listing primitive (`{ vault-relative
+ path β†’ sha256, size }` across `Brain/` minus `.snapshots/`) underlies
+ both Β§22 (`o2b brain upgrade` builds the current state to compare
+ against the target template) and Β§5-tail (`o2b brain rollback` uses
+ the snapshot's stored manifest to detect drift before overwriting
+ the live tree). Building this twice would be copy-paste; introducing
+ it once keeps the system honest.
+- **Agent logging discipline (Β§30).** The stop guardrail currently
+ fires only on missing `event_log_append`. Β§A extends it to accept any
+ of three brain-event tools (`event_log_append`, `brain_feedback`,
+ `brain_apply_evidence`) and their CLI equivalents. Β§C reformulates
+ the SKILL trigger so the default for an uncertain match is "record
+ with `note: speculative`", not "skip" β€” the dream pass already
+ filters one-off speculative entries that do not recur.
+
+The other three tracks (Β§14 explorer polish, Β§28 export, Β§31 CR
+cleanup) ride along because they are small and finish work already
+deferred from v0.10.4 / v0.10.5.
+
+## Goals
+
+- **G1.** Reformulate `skills/brain-memory/SKILL.md` so the default
+ for an uncertain (preference, artifact) match is to record with
+ `note: "speculative; ..."` rather than to skip. Mirror the change
+ in the post-write hook reminder text so the agent receives the same
+ guidance live.
+- **G2.** Extend `hooks/stop-log-guardrail.ts` so any of
+ `event_log_append`, `brain_feedback`, `brain_apply_evidence` (as MCP
+ tool call or `o2b brain feedback|apply-evidence` bash invocation)
+ clears the guardrail. The block text lists all three explicitly.
+- **G3.** Introduce `src/core/brain/manifest.ts` with
+ `buildManifest(brainRoot)`, `diffManifests(a, b)`, and sidecar I/O
+ helpers. SHA-256 per regular file under `Brain/` excluding
+ `.snapshots/`, symlinks skipped.
+- **G4.** Make `createSnapshot` write a sidecar
+ `<run-id>.manifest.json` next to each archive. `listSnapshots`
+ surfaces `manifest_path`. `pruneSnapshots` removes both files in
+ pair. Failure to write the sidecar leaves the archive valid and
+ surfaces a non-fatal warning.
+- **G5.** Add `o2b brain upgrade [--dry-run] [--apply] [--yes]
+ [--check] [--json] [--vault <path>]`. The verb manages three vault
+ files (`_brain.yaml`, `_BRAIN.md`, `AI Wiki/_OPEN_SECOND_BRAIN.md`)
+ and uses the existing snapshot infrastructure to take a pre-apply
+ snapshot named `upgrade-<ts>`. `--dry-run` prints a per-file diff;
+ `--check` exits 2 on pending updates (CI-friendly).
+- **G6.** Extend `o2b brain rollback` with drift detection. Before
+ extraction, compare the snapshot's stored manifest against a
+ freshly-built manifest of the live `Brain/`. If they differ, exit
+ 2 with a diff unless `--force-rollback` is passed. Legacy snapshots
+ without a sidecar manifest skip drift detection with a stderr
+ warning.
+- **G7.** Update `templates/brain-explorer.html` with a focusable
+ `<ul role="listbox">` over the visible nodes, ArrowUp / ArrowDown
+ / Enter / Escape handlers, and `aria-activedescendant` tracking.
+ Listbox is the accessible source of truth; the canvas remains a
+ visual surface.
+- **G8.** Persist explorer layout in `localStorage` under
+ `osb-explorer-layout:<vault_basename>`. Stored: per-node `[x, y]`,
+ status filter set, search string. Boot restores positions before
+ physics starts; new nodes fall back to `placeInitial`. A "Reset
+ layout" button clears the key.
+- **G9.** Add `o2b brain export --format json|llms-txt [--out <path>]
+ [--force] [--vault <path>]`. Read-only dump of
+ `Brain/preferences/` (`confirmed | unconfirmed | quarantine`); no
+ retired, no signals. Stdout by default; `--out` writes a file.
+- **G10.** Update `_BRAIN.md` template to mention `o2b brain upgrade`
+ and `o2b brain export`. This produces a real, testable
+ diff for existing vaults so the `upgrade` flow has a non-trivial
+ fixture.
+- **G11.** CR cleanup: MD040 language tags in
+ `docs/plans/2026-05-18-brain-maturity-design.md`,
+ `docs/plans/2026-05-18-brain-maturity-impl.md`,
+ `skills/embeddings-setup/SKILL.md`. Add one extra
+ `tests/scripts/macos-sqlite-shim.test.ts` case covering
+ `DYLD_LIBRARY_PATH=""` preservation.
+
+## Non-goals (explicitly deferred)
+
+Each entry below is recorded in `_summary.md β†’ ## Deferred work` or
+in the respective Plan/ doc in the same commit so it survives across
+planning sessions.
+
+- **Β§30 Β§B β€” Promote `brain_feedback` / `brain_apply_evidence` from
+ deferred MCP to always-loaded.** Belongs to the MCP server surface
+ (`plugin.yaml` / `mcp/server.ts`) and is orthogonal to hook /
+ SKILL changes. Stays in `Plan/3 Β§B` with the same trigger.
+- **Β§30 Β§D β€” Session-end sanity check via cron.** Hermes-side
+ job (or Claude Code SessionEnd hook) that compares artifact count
+ vs brain-event count and pings on drift. Out of v0.10.6 scope β€”
+ belongs to the runtime layer. Stays in `Plan/3 Β§D`.
+- **Β§30 Β§E β€” Claude Code MEMORY ↔ OSB Brain bridge.** Either
+ `o2b brain import-claude-memory` or a SessionStart hook that
+ injects `~/.claude/.../memory/MEMORY.md` alongside `Brain/active.md`.
+ Distinct scope and surface. Stays in `Plan/3 Β§E`.
+- **Β§22 β€” Interactive upgrade wizard.** Not in v0.10.6. The verb is
+ non-interactive by default; `--apply` requires `--yes` in
+ non-interactive mode mirroring `migrate-frontmatter` / `rollback`.
+- **Β§28 β€” Retired and signal export, GraphML / Marp / JSON-LD
+ formats.** `_summary.md` Β§28 explicitly marks the latter three as
+ "not needed". Retired / signal export is on demand: add when a
+ user case appears.
+- **Β§14 β€” Obsidian deep-link, live-refresh, Freeze-layout toggle.**
+ Already deferred in v0.10.5; remain deferred. Triggers in
+ `_summary.md β†’ Deferred work`.
+
+## Β§30 β€” Agent logging discipline
+
+### Β§A β€” Stop guardrail accepts any brain-event
+
+`hooks/lib/detect.ts`:
+
+- Rename `LOG_NAME_SUFFIX` to `BRAIN_EVENT_NAME_SUFFIX` and broaden:
+
+ ```ts
+ const BRAIN_EVENT_NAME_SUFFIX =
+ /(?:^|__)(event_log_append|brain_feedback|brain_apply_evidence)$/;
+ ```
+
+- `isLogToolName` is renamed to `isBrainEventToolName`. Hooks /
+ callers update accordingly. No external consumer (the file is
+ internal to `hooks/`).
+- `LOG_BASH_NEEDLES` becomes `BRAIN_EVENT_BASH_NEEDLES` and gains
+ two entries:
+
+ ```ts
+ const BRAIN_EVENT_BASH_NEEDLES = [
+ "o2b append-event",
+ "vault-log ",
+ "o2b brain feedback",
+ "o2b brain apply-evidence",
+ ];
+ ```
+
+ The `vault-log` trailing space rule stays β€” distinguishes the CLI
+ invocation from a literal log path substring.
+- `summarizeTurn`'s `hadLog` field stays in shape; it now means "any
+ brain-event landed". Rename to `hadBrainEvent` to keep call sites
+ honest. Single consumer (`stop-log-guardrail.ts`) updates with it.
+
+`hooks/lib/messages.ts:stopGuardrailReason`:
+
+- Body changes from "did not call `event_log_append`" to an explicit
+ three-tool list. Sketch:
+
+ ```text
+ Open Second Brain hook: this turn touched files
+ (Write / Edit / MultiEdit / apply_patch) but did not call any of:
+
+ - `event_log_append` β€” durable session-summary line for the day log
+ - `brain_apply_evidence` β€” evidence trail when an active preference
+ scoped to the artifact
+ - `brain_feedback` β€” new taste correction the user just expressed
+
+ If the turn produced a durable artifact, pick whichever fits and
+ finish. If the change is trivial, just send your reply again β€” this
+ guardrail fires at most once per turn and will let the second Stop
+ through.
+ ```
+
+- Per-runtime cadence lines (`claudecode`, `codex`, `unknown`) stay
+ exactly as today; they are interpolated between the heading and
+ the tool list.
+
+### Β§C β€” Reformulate SKILL trigger
+
+`skills/brain-memory/SKILL.md`:
+
+- Frontmatter `description` tail switches from "SKIP when not
+ confident; A misrecorded signal is worse than a missed one" to
+ the speculative-mark policy:
+
+ > SKIP for casual chat, exploration without a stated rule,
+ > read-only inspection, and trivial edits. When a preference
+ > plausibly applies but you are unsure, RECORD with `note:
+ > "speculative; <reason>"` rather than skipping β€” the dream pass
+ > discards single-event speculative entries that do not recur, so
+ > coverage costs less than missing the signal.
+
+- `## When NOT to call` section: the fifth bullet ("Cases where a
+ preference *might* apply but you are not confident β€” skip rather
+ than fabricate a match") is replaced by an inverse rule:
+
+ > - Cases where a preference *might* apply but you are unsure:
+ > record with `note: "speculative; <reason>"` and let the dream
+ > pass filter one-off entries. Skip only the four bullets above.
+
+- Closing sentence "A false-positive signal eventually distorts the
+ rule set; a missed signal is recovered on repeat. Prefer
+ precision." is removed.
+- New paragraph in `## When to call brain_apply_evidence β†’ Optional`
+ documents the `note: "speculative; ..."` convention as the
+ recommended escape hatch.
+
+`hooks/lib/messages.ts:postWriteReminder`:
+
+- Final paragraph rewords from "A misrecorded signal is worse than
+ a missed one β€” skip when not confident; the dream pass will pick
+ up patterns from repeats" to:
+
+ > When a preference plausibly applies but you are unsure, record
+ > with `note: "speculative; <reason>"`. The dream pass discards
+ > single-event speculative entries that do not recur.
+
+### Tests
+
+- `tests/hooks/detect.test.ts` (new or extended): every name and
+ bash needle case β€” positive and negative β€” for the broadened
+ `BRAIN_EVENT_NAME_SUFFIX` and `BRAIN_EVENT_BASH_NEEDLES`.
+- `tests/hooks/stop-log-guardrail.test.ts` (extend if exists,
+ otherwise new): full transcript-driven cases for Claude Code and
+ Codex. Each test asserts whether the guardrail emits `{decision:
+ "block"}` or stays silent.
+- `tests/hooks/messages.test.ts`: snapshot of the three reminder /
+ guardrail texts (Claude Code, Codex, unknown) including the
+ three-tool list.
+- `tests/skills/brain-memory.test.ts` (light textual): the
+ `description` frontmatter and `## When NOT to call` body match
+ the new wording verbatim. Guards against accidental regression.
+
+## Β§22 + Β§5-tail β€” Manifest, upgrade, drift detection
+
+### Manifest module
+
+New file `src/core/brain/manifest.ts`:
+
+```ts
+export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;
+
+export interface BrainManifestEntry {
+ readonly sha256: string; // lowercase hex
+ readonly size: number; // bytes
+}
+
+export interface BrainManifest {
+ readonly schema_version: 1;
+ readonly generated_at: string; // ISO-8601 UTC, second precision
+ readonly brain_root: "Brain"; // forward-compat anchor
+ readonly files: Readonly<Record<string, BrainManifestEntry>>;
+}
+
+export interface BrainManifestDiffEntry {
+ readonly path: string;
+ readonly before: BrainManifestEntry | null;
+ readonly after: BrainManifestEntry | null;
+}
+
+export interface BrainManifestDiff {
+ readonly added: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly removed: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly changed: ReadonlyArray<BrainManifestDiffEntry>;
+}
+
+export function buildManifest(brainRoot: string): BrainManifest;
+export function diffManifests(a: BrainManifest, b: BrainManifest): BrainManifestDiff;
+
+export function manifestSidecarPath(vault: string, runId: string): string;
+export function readManifestSidecar(vault: string, runId: string): BrainManifest | null;
+export function writeManifestSidecar(vault: string, runId: string, m: BrainManifest): void;
+```
+
+Walk semantics mirror `src/core/brain/snapshot-diff.ts:walkBrain`:
+
+- `lstatSync` (never follow symlinks).
+- Skip `.snapshots/` entirely.
+- Drop `..` escapes (defense-in-depth).
+- Keys sorted lexicographically before serialisation so the JSON file
+ is byte-stable across filesystems.
+
+SHA-256 via `node:crypto.createHash("sha256")` over `readFileSync`.
+The whole walk holds at most one file in memory at a time; Brain
+trees stay well under 10 MB in practice.
+
+Sidecar I/O uses the existing `atomicWriteFileSync`. JSON is
+pretty-printed with 2-space indent so a manual `git diff` (or
+operator `cat`) is readable.
+
+### Snapshot module changes
+
+`src/core/brain/snapshot.ts`:
+
+- `createSnapshot(vault, runId)`:
+ 1. Build archive (existing path).
+ 2. After the archive lands, build a manifest of the **live** tree
+ (post-snapshot but pre-mutation; for `dream` and `upgrade` the
+ snapshot is taken before mutation, so the live tree at this
+ moment equals the snapshot contents).
+ 3. Write sidecar `<run-id>.manifest.json`.
+ 4. On manifest write failure, emit a non-fatal stderr warning;
+ the archive remains valid. Downstream rollback skips
+ drift-check for that snapshot (the legacy path).
+- `SnapshotInfo` gains `manifest_path: string | null`.
+- `pruneSnapshots(vault, retentionCount)`: when removing a victim
+ archive, also `rmSync` the sibling manifest if present.
+- `listSnapshots(vault)`: populates `manifest_path` by
+ `existsSync(manifestSidecarPath(vault, runId))`.
+
+### `o2b brain upgrade`
+
+New module `src/core/brain/upgrade.ts`:
+
+```ts
+export interface UpgradeFilePlan {
+ readonly path: string; // vault-relative
+ readonly status: "noop" | "update";
+ readonly before: string; // current bytes (utf8)
+ readonly after: string; // target bytes (utf8)
+}
+
+export interface UpgradePlan {
+ readonly files: ReadonlyArray<UpgradeFilePlan>;
+ readonly pending: number; // count where status === "update"
+}
+
+export interface UpgradeApplyResult {
+ readonly run_id: string; // upgrade-<ts>
+ readonly snapshot_path: string;
+ readonly files_updated: ReadonlyArray<string>;
+}
+
+export function planUpgrade(vault: string): UpgradePlan;
+export function applyUpgrade(
+ vault: string,
+ opts: { agent: string; now?: Date },
+): UpgradeApplyResult;
+```
+
+#### Managed files
+
+| Path | Source of truth | Merge strategy |
+|-----------------------------------|---------------------------------------------------|--------------------------------------------------|
+| `Brain/_brain.yaml` | `DEFAULT_BRAIN_CONFIG_YAML` + user overrides | Schema-key merge: add new top-level / nested keys present in default but absent in user file. Preserve user values for keys present in both. Comments survive untouched. |
+| `Brain/_BRAIN.md` | `BRAIN_MANUAL_TEMPLATE_PATH` rendered with current substitutions | Full overwrite. Operator-edited copies are flagged in the diff but still overwritten on `--apply`. |
+| `AI Wiki/_OPEN_SECOND_BRAIN.md` | `LEGACY_OVERVIEW_TEMPLATE_PATH` rendered | Full overwrite (same as `init.ts` does today). |
+
+`_brain.yaml` merge is the only path with non-trivial logic. The
+existing parser (`loadBrainConfig`) is strict and the file carries
+hand-written comments, so re-serialising from the parsed object
+would destroy formatting. Approach is text-level and conservative:
+
+1. Read the live `_brain.yaml` text.
+2. Parse with the existing config loader for validity. If the file
+ is malformed, `planUpgrade` returns `status: "error"` for that
+ path with the parser's message; `--apply` refuses to proceed.
+3. Walk `DEFAULT_BRAIN_CONFIG_YAML` block by block. For each
+ top-level section (`dream:`, `retire:`, `confidence:`,
+ `snapshots:`, …) and for top-level scalars (`schema_version`,
+ `primary_agent`):
+ - **Section absent in live file**: append the canonical block
+ (with its inline comments and default values) at the end of
+ the file, separated by one blank line.
+ - **Section present, missing a nested key**: append the missing
+ nested line at the end of *that* section's block, matching
+ the existing indentation. The walker locates the section's
+ end by scanning forward until it hits a non-indented line or
+ EOF; the new key inserts before that boundary.
+ - **All nested keys present**: no change.
+4. Top-level scalars use the same rule: missing scalar appends at
+ end-of-file; present scalar is left untouched.
+5. If no insertions, return `status: noop`. Existing values and
+ ordering are never rewritten.
+
+Edge case: an operator manually duplicated a key (`primary_agent:`
+twice). The parser already rejects this on load; `planUpgrade`
+surfaces the same error and `--apply` refuses.
+
+For `_BRAIN.md` and `AI Wiki/_OPEN_SECOND_BRAIN.md`, comparison is
+byte-equality after rendering substitutions. Any byte difference
+triggers `status: update`.
+
+#### CLI
+
+`src/cli/brain.ts:cmdBrainUpgrade`:
+
+- Flags: `--vault`, `--dry-run` (default), `--apply`, `--yes`,
+ `--json`, `--check`.
+- `--dry-run` (or default): prints a per-file plan. For each
+ `update`, renders a unified diff. Exit 0.
+- `--check`: same as `--dry-run` but returns exit 2 when `pending >
+ 0`. Wires into CI for "are vaults drifted from the canonical
+ templates" gates.
+- `--apply`: validates `--yes` in non-interactive mode (`--json` or
+ non-TTY stdin), then:
+ 1. `createSnapshot(vault, "upgrade-<ts>")` β€” sidecar manifest
+ comes along automatically.
+ 2. `atomicWriteFileSync` each `update` file.
+ 3. Append a `BRAIN_LOG_EVENT_KIND.upgrade` log row.
+- `--apply` interactive prompt: like `rollback`, shows the file list
+ and asks for `y/N`.
+
+JSON output for `--dry-run`:
+
+```json
+{
+ "schema": 1,
+ "pending": 1,
+ "files": [
+ { "path": "Brain/_brain.yaml", "status": "noop" },
+ { "path": "Brain/_BRAIN.md", "status": "update", "before_sha256": "...", "after_sha256": "..." },
+ { "path": "AI Wiki/_OPEN_SECOND_BRAIN.md", "status": "noop" }
+ ]
+}
+```
+
+`BRAIN_HELP` and `VERB_HELP.upgrade` updated.
+
+#### Real template change in v0.10.6
+
+`src/core/brain/templates/_BRAIN.md` (or wherever the template
+lives β€” see `BRAIN_MANUAL_TEMPLATE_PATH`) adds two new CLI surface
+lines:
+
+```text
+- `o2b brain upgrade` β€” apply schema and template updates from the
+ installed open-second-brain version; --dry-run for a per-file plan.
+- `o2b brain export` β€” read-only dump of active preferences in JSON
+ or llms-txt format.
+```
+
+This guarantees `o2b brain upgrade` has a real diff on any
+pre-v0.10.6 vault. Tests can reproduce it deterministically:
+init an empty vault with the v0.10.5 template (captured as a
+fixture), run `o2b brain upgrade --dry-run`, assert the plan
+contains exactly the two-line additions on `_BRAIN.md`.
+
+### Rollback drift detection
+
+`src/cli/brain.ts:cmdBrainRollback`:
+
+- New flag: `--force-rollback`. Distinct from `--yes` (which is
+ about prompt confirmation) β€” `--force-rollback` specifically
+ overrides drift detection.
+- Sequence:
+ 1. Validate runId, locate archive.
+ 2. `readManifestSidecar(vault, runId)`:
+ - **Sidecar exists**: build a fresh manifest from live `Brain/`,
+ `diffManifests(stored, live)`. If any added / removed /
+ changed entry exists and `--force-rollback` not passed β†’
+ print the drift diff (compact, grouped by category), exit 2
+ with a one-line hint about `--force-rollback`.
+ - **No sidecar** (legacy snapshot): stderr warning
+ "no manifest sidecar for snapshot `<run-id>`; drift detection
+ skipped (snapshot predates v0.10.6)". Continue.
+ 3. Existing `--dry-run` path still uses `extractSnapshotToTemp` +
+ `diffBrainTrees` to show what would change.
+ 4. Existing rollback path proceeds.
+
+The rollback log event gains an optional `drift_overridden: "true"`
+payload field when `--force-rollback` was used. Default omitted.
+
+#### Drift diff output (markdown mode)
+
+```text
+Drift detected between snapshot 'dream-2026-05-17T04-00-00Z' and the
+live Brain/ tree. Pass --force-rollback to overwrite anyway.
+
+Added (3):
+ - Brain/preferences/pref-imperative-prompts.md
+ - Brain/log/2026-05-18.md
+ - Brain/inbox/sig-2026-05-18-mocking.md
+Changed (1):
+ - Brain/_brain.yaml
+Removed (0):
+ (none)
+```
+
+JSON mode emits the same structure as `BrainManifestDiff` plus a
+top-level `drift: true` / `false` flag.
+
+### Tests
+
+- `tests/core/brain/manifest.test.ts`: `buildManifest` against a
+ fixture tree; symlinks skipped; `.snapshots/` excluded; key order
+ stable; `diffManifests` over added/removed/changed; sidecar I/O
+ roundtrip.
+- `tests/core/brain/snapshot-manifest.test.ts`: `createSnapshot`
+ writes both archive and sidecar; sidecar write failure leaves
+ archive valid and emits warning; `pruneSnapshots` removes both;
+ legacy snapshot (archive without sidecar) listed correctly.
+- `tests/core/brain/upgrade.test.ts`: fixture vault with old
+ `_BRAIN.md`; `planUpgrade` returns one `update`;
+ `applyUpgrade` writes new bytes, takes snapshot named
+ `upgrade-<ts>`, appends `upgrade` log event; idempotent re-run is
+ `noop`. `_brain.yaml` merge: adding a new section to the default
+ appends it at end-of-file with comments; existing values preserved.
+- `tests/cli/brain-upgrade.test.ts`: `--dry-run` exit codes,
+ `--check` exit 2 on pending, `--apply --yes` end-to-end,
+ `--apply` without `--yes` in non-interactive errors out, `--json`
+ shapes.
+- `tests/cli/brain-rollback-drift.test.ts`: snapshot with manifest
+ + drifted live tree β†’ exit 2; same with `--force-rollback` β†’
+ proceeds; legacy snapshot without manifest β†’ warning + proceeds.
+
+## Β§14 polish β€” keyboard a11y + layout persistence
+
+All changes confined to `templates/brain-explorer.html`. No new
+server endpoint, no schema change to `ExplorerGraph`.
+
+### Listbox accessibility
+
+DOM additions inside the existing right `<aside id="details">`:
+
+```html
+<h3>Nodes</h3>
+<div id="node-list-wrap">
+ <ul
+ id="node-list"
+ role="listbox"
+ tabindex="0"
+ aria-label="Brain preferences"
+ aria-activedescendant=""
+ ></ul>
+</div>
+<button id="reset-layout" type="button" class="id-copy">Reset layout</button>
+<hr />
+<div id="details-body">
+ <p class="panel-empty">Select a node to inspect.</p>
+</div>
+```
+
+The existing details panel becomes `#details-body` so the listbox
+sits above it without colliding with the inspect markup.
+
+CSS additions (minimal):
+
+```css
+#node-list { list-style: none; margin: 0; padding: 0; max-height: 220px; overflow: auto; border: 1px solid var(--border); border-radius: 4px; }
+#node-list li { padding: 4px 8px; cursor: pointer; }
+#node-list li[aria-selected="true"] { background: var(--accent); color: #fff; }
+#node-list:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
+```
+
+Behaviour (in the existing IIFE):
+
+- `renderNodeList()`: rebuilds the `<ul>` over visible nodes (the
+ same predicate as `applyFilters`). Each `<li>` gets `id="node-opt-${nodeId}"`,
+ `role="option"`, `aria-selected="false"`, and a stable order: by
+ `topic` ascending, then `id` ascending. Called from `applyFilters`.
+- Focus model: `<ul>` is in the tab order (`tabindex="0"`). When
+ focused, the keyboard handler intercepts ArrowDown / ArrowUp /
+ Home / End / Enter / Space / Escape.
+- Selection model: a `focusedNodeId` variable tracks the currently
+ highlighted `<li>`. ArrowKeys move it; `aria-activedescendant`
+ follows. Enter / Space commit: sets `selectedId = focusedNodeId`,
+ calls `renderPanel(nodeById.get(selectedId))`, ensures the canvas
+ redraw highlights the node. Escape resets `focusedNodeId` to
+ `null` and the panel back to empty.
+- Click on a `<li>` selects the corresponding node (commit semantics,
+ same as Enter).
+- Pointer click on canvas (existing behaviour) updates both
+ `selectedId` and `focusedNodeId`, scrolls the listbox so the
+ matching `<li>` is visible, so the two surfaces stay in sync.
+
+### Layout persistence
+
+Storage key:
+
+```text
+osb-explorer-layout:<vault_basename>
+```
+
+Storage shape:
+
+```json
+{
+ "schema": 1,
+ "positions": { "pref-foo": [123.4, 456.7], "pref-bar": [...] },
+ "filters": { "status": ["confirmed", "quarantine"], "search": "mock" }
+}
+```
+
+Boot order changes:
+
+1. Parse `localStorage[key]`. If malformed or `schema !== 1`,
+ discard silently.
+2. Initialise `statusFilters` and `searchTerm` from stored filters
+ (fall back to current defaults).
+3. `placeInitial()` produces the topic-clustered defaults.
+4. For each node, if `positions[id]` exists, overwrite `n.x` / `n.y`
+ with the stored coordinates and zero its `vx` / `vy`. The physics
+ engine "warms" from the saved layout instead of jittering from
+ scratch.
+
+Save policy:
+
+- A `saveLayout()` function serialises the current state and writes
+ to `localStorage`.
+- Called: (a) on `pagehide` (catches both reload and tab close);
+ (b) on filter / search input commit (debounced 500 ms);
+ (c) once after physics damps below a threshold (βˆ‘ |v| < 0.5)
+ to capture the natural-rest layout.
+
+Reset button:
+
+- `#reset-layout` removes the key, resets filters / search to
+ defaults, calls `placeInitial()` and `renderNodeList()`.
+
+Failure modes:
+
+- `localStorage` blocked (private browsing / quota): wrap every
+ read/write in try/catch, log to `console.warn` once, fall through
+ to non-persistent mode. No user-visible error.
+
+### Tests
+
+The explorer is HTML / vanilla JS in a single template file. We do
+not introduce a browser test runner. Instead:
+
+- `tests/core/brain/explorer-template.test.ts`: a smoke that loads
+ the rendered HTML and asserts the listbox markup is present
+ (regex on `<ul id="node-list"`, `role="listbox"`,
+ `aria-activedescendant`, `Reset layout` button).
+- `tests/core/brain/explorer-template.test.ts` extends to check
+ that the layout-persistence boot code references
+ `osb-explorer-layout:` literally β€” guards against accidental
+ rename.
+
+Manual QA notes captured in the PR description for the keyboard
+flow itself (cannot reasonably be automated without a browser).
+
+## Β§28 β€” `o2b brain export`
+
+### Module
+
+New file `src/core/brain/export.ts`:
+
+```ts
+export interface ExportedPreferencesJson {
+ readonly schema: 1;
+ readonly generated_at: string; // ISO-8601 UTC
+ readonly vault_basename: string;
+ readonly preferences: ReadonlyArray<ExportedPreferenceRow>;
+}
+
+export interface ExportedPreferenceRow {
+ // Full BrainPreference frontmatter, with confidence_value preserved
+ // and dates kept as ISO strings.
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly status: "confirmed" | "unconfirmed" | "quarantine";
+ readonly principle: string;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly confidence: "low" | "medium" | "high";
+ readonly confidence_value: number | null;
+ readonly pinned: boolean;
+ readonly last_evidence_at: string | null;
+ readonly created_at: string;
+ readonly confirmed_at: string | null;
+ readonly aliases: ReadonlyArray<string> | null;
+ readonly tags: ReadonlyArray<string>;
+ readonly evidenced_by: ReadonlyArray<string>;
+ readonly body: string; // markdown after frontmatter
+}
+
+export function exportPreferencesJson(vault: string): ExportedPreferencesJson;
+export function exportPreferencesLlmsTxt(vault: string): string;
+```
+
+JSON shape rationale:
+
+- Single top-level object so a future export schema change can land
+ via `schema: 2` without breaking diff-friendly stable output.
+- One row per preference. No retired, no signals β€” matches the
+ decision recorded in `_summary.md` Β§28.
+- Frontmatter fields are explicit; consumer code does not need to
+ parse YAML.
+
+llms-txt shape (per [llmstxt.org](https://llmstxt.org/)):
+
+```text
+# <vault_basename> β€” Brain preferences
+
+> Active preferences captured by Open Second Brain. Auto-generated
+> by `o2b brain export --format llms-txt`. Read-only dump; the
+> canonical files live under `<vault>/Brain/preferences/`.
+
+## Confirmed
+
+- pref-no-simply-word (topic: writing-style, scope: writing): Do not use 'simply' in technical documentation; it minimises reader effort.
+- pref-no-em-dashes (topic: russian-writing, scope: writing): Do not use em-dashes in Russian prose for this vault; use ' - '.
+- ...
+
+## Unconfirmed
+
+- pref-... (topic: ...): ...
+- ...
+
+## Quarantine
+
+- pref-... (topic: ...): ...
+- ...
+```
+
+Section headings are emitted only when the corresponding set is
+non-empty. Within a section, rows are sorted by `id` ascending so
+output is deterministic.
+
+### CLI
+
+`src/cli/brain.ts:cmdBrainExport`:
+
+- Flags: `--format json|llms-txt` (required, no default β€” explicit
+ choice avoids ambiguity if we add formats later), `--out <path>`,
+ `--force`, `--vault`.
+- Default sink: stdout. JSON is single-line for pipe-friendliness
+ (matches other `--json` outputs); llms-txt has a trailing newline
+ for shell convention.
+- `--out <path>`: refuses to overwrite without `--force`; uses
+ `atomicWriteFileSync`.
+- `--out` and stdout are mutually exclusive only in implementation
+ routing (stdout when `--out` absent); they are not exclusive flags
+ the operator sets directly.
+- No `--json` flag here (the format choice replaces it). All other
+ brain verbs that take `--json` keep theirs unchanged.
+
+`BRAIN_HELP` gains `export`. New `VERB_HELP.export`:
+
+```text
+usage: o2b brain export --format json|llms-txt [--out <path>] [--force]
+ [--vault <path>]
+Read-only dump of active preferences (confirmed | unconfirmed |
+quarantine) from Brain/preferences/. Retired and signal entries are
+not included. JSON is single-line; llms-txt follows the
+llmstxt.org H1 + summary + H2-section shape.
+Default sink is stdout; --out writes to <path> (refuses to overwrite
+without --force).
+```
+
+### Tests
+
+- `tests/core/brain/export.test.ts`: fixture vault with preferences
+ across all three statuses + one retired (should be excluded) +
+ one signal (should be excluded). Asserts JSON shape (schema,
+ generated_at format, row count, field set per row) and
+ llms-txt rendering (section presence/absence, sort order).
+- `tests/cli/brain-export.test.ts`: stdout vs `--out` paths, JSON
+ parsing roundtrip, `--out` refuses to overwrite without `--force`,
+ `--format` required.
+
+## Β§31 β€” CR cleanup
+
+### Β§31.1 β€” MD040 in planning docs
+
+Manual sweep across:
+
+- `docs/plans/2026-05-18-brain-maturity-design.md`
+- `docs/plans/2026-05-18-brain-maturity-impl.md`
+- `skills/embeddings-setup/SKILL.md`
+
+Per-block decision:
+
+- Shell / bash output β†’ ` ```bash`
+- TypeScript snippets β†’ ` ```ts`
+- YAML / `_brain.yaml` excerpts β†’ ` ```yaml`
+- Markdown samples β†’ ` ```markdown`
+- Plain output, ASCII tables, log lines β†’ ` ```text`
+- JSON examples β†’ ` ```json`
+
+No `sed` / bulk script β€” the wrong tag is worse than a missing one
+because it changes syntax highlighting in renderers that respect
+the hint.
+
+### Β§31.2 β€” macOS shim test for empty DYLD_LIBRARY_PATH
+
+`tests/scripts/macos-sqlite-shim.test.ts` gains one case:
+
+```ts
+test("Darwin + explicit empty DYLD_LIBRARY_PATH β†’ preserved verbatim", async () => {
+ const fakePrefix = join(tmp, "homebrew-sqlite-lib");
+ mkdirSync(fakePrefix, { recursive: true });
+ const out = await runShim({
+ O2B_MACOS_FORCE_PLATFORM: "Darwin",
+ O2B_MACOS_SQLITE_PREFIXES_OVERRIDE: fakePrefix,
+ DYLD_LIBRARY_PATH: "",
+ });
+ expect(out).toBe(""); // unchanged, not auto-populated
+});
+```
+
+Covers the `${VAR+set}` branch added in v0.10.5 CR fixes.
+
+### Β§31.3 β€” Keyboard a11y
+
+Subsumed by Β§14 polish above. CHANGELOG groups them under Β§14;
+no separate `Β§31.3` entry needed.
+
+## Updates to plans / summary
+
+`Projects/OpenSecondBrain/Features/_summary.md`:
+
+- Β§5 β€” mark as fully shipped (manifest + abort drift detection
+ delivered in v0.10.6). Update tail text.
+- Β§14 β€” append "v0.10.6: keyboard-доступная инспСкция ΡƒΠ·Π»ΠΎΠ² ΠΈ
+ layout-state persistence Ρ‡Π΅Ρ€Π΅Π· localStorage". Remove the two
+ matching items from `## Deferred work` and from the Β§14 inline
+ parenthetical.
+- Β§22 β€” replace "6" header with "βœ… … *(Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ Π² v0.10.6)*".
+- Β§28 β€” same: "βœ… … *(Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ Π² v0.10.6)*".
+- Β§30 β€” "βœ… Agent logging discipline β€” Β§A + Β§C *(Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ Π²
+ v0.10.6: stop-guardrail Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ Π½Π° brain-events, SKILL trigger
+ ΠΏΠ΅Ρ€Π΅Ρ„ΠΎΡ€ΠΌΡƒΠ»ΠΈΡ€ΠΎΠ²Π°Π½; Β§B / Β§D / Β§E ΠΎΡΡ‚Π°ΡŽΡ‚ΡΡ ΠΎΡ‚ΠΊΡ€Ρ‹Ρ‚Ρ‹ΠΌΠΈ)*".
+- Β§31 β€” "βœ… v0.10.5 review followups *(Π·Π°ΠΊΡ€Ρ‹Ρ‚ΠΎ Π² v0.10.6: MD040 Π²
+ Ρ‚Ρ€Ρ‘Ρ… planning-Π΄ΠΎΠΊΠ°Ρ…, Π΄ΠΎΠΏ. тСст Π½Π° пустой DYLD_LIBRARY_PATH;
+ keyboard a11y Π΄Π΅Π»Ρ‘Π½ Β§14 polish)*".
+
+`Projects/OpenSecondBrain/Plan/3. Agent logging discipline.md`:
+
+- Add `shipped: Β§A, Β§C (v0.10.6)` line near top.
+- Β§B / Β§D / Β§E sections explicitly tagged `status: open`.
+
+`Projects/OpenSecondBrain/Plan/4. v0.10.5 review followups.md`:
+
+- Β§1 / Β§2 / Β§4 tagged shipped. Β§3 was already done.
+
+## CHANGELOG
+
+`CHANGELOG.md` gains a single new entry above the v0.10.5 block:
+
+```markdown
+## [0.10.6] - 2026-05-18
+
+Logging discipline, manifest-backed snapshots, explorer polish, export.
+
+### Added
+- Β§22 + Β§5-tail β€” `o2b brain upgrade [--dry-run] [--apply] [--yes]
+ [--check] [--json]` …
+- Β§28 β€” `o2b brain export --format json|llms-txt [--out <path>]
+ [--force]` …
+- Β§14 β€” keyboard listbox over Brain Explorer nodes; layout and
+ filter state persisted to localStorage; "Reset layout" button.
+- Snapshot sidecar manifest `<run-id>.manifest.json` written by
+ `createSnapshot`; used by `o2b brain rollback` for drift detection.
+
+### Changed
+- Β§30 Β§A β€” `hooks/stop-log-guardrail.ts` clears on any of
+ `event_log_append`, `brain_feedback`, `brain_apply_evidence` (MCP
+ or CLI form). Block text lists all three.
+- Β§30 Β§C β€” `skills/brain-memory/SKILL.md` and `hooks/lib/messages.ts`
+ default to "record with `note: speculative; ...`" rather than skip
+ on uncertain matches.
+- `o2b brain rollback` aborts with exit 2 on drift detected against
+ the snapshot's manifest; `--force-rollback` overrides.
+- `_BRAIN.md` template lists `o2b brain upgrade` and
+ `o2b brain export`.
+
+### Internal
+- New module `src/core/brain/manifest.ts` (sha256 file inventory,
+ diff helpers, sidecar I/O).
+- New module `src/core/brain/upgrade.ts` (managed-file plan + apply).
+- New module `src/core/brain/export.ts` (JSON and llms-txt
+ serialisation).
+- `BRAIN_LOG_EVENT_KIND.upgrade = "upgrade"`.
+- `SnapshotInfo` gains `manifest_path: string | null`.
+
+### Tests
+- `tests/core/brain/manifest.test.ts`
+- `tests/core/brain/snapshot-manifest.test.ts`
+- `tests/core/brain/upgrade.test.ts`
+- `tests/core/brain/export.test.ts`
+- `tests/cli/brain-upgrade.test.ts`
+- `tests/cli/brain-export.test.ts`
+- `tests/cli/brain-rollback-drift.test.ts`
+- `tests/hooks/detect.test.ts` (extended)
+- `tests/hooks/stop-log-guardrail.test.ts` (extended)
+- `tests/hooks/messages.test.ts` (extended)
+- `tests/core/brain/explorer-template.test.ts` (extended)
+- `tests/scripts/macos-sqlite-shim.test.ts` (one new case)
+
+### Docs
+- MD040 language tags added to
+ `docs/plans/2026-05-18-brain-maturity-design.md`,
+ `docs/plans/2026-05-18-brain-maturity-impl.md`,
+ `skills/embeddings-setup/SKILL.md`.
+
+[0.10.6]: https://github.com/itechmeat/open-second-brain/compare/v0.10.5...v0.10.6
+```
+
+## Migration
+
+No vault data migration is required:
+
+- Existing snapshots without sidecar manifests stay valid; rollback
+ falls back to the legacy no-drift-check path with a warning.
+- `o2b brain upgrade` is opt-in (default `--dry-run`).
+- `o2b brain export` is read-only.
+- `_BRAIN.md` template change is picked up only when an operator
+ runs `o2b brain upgrade --apply`.
+
+## Risk and known-unknowns
+
+- **Manifest cost on large vaults.** sha256-hashing every file under
+ `Brain/` on every snapshot. Vaults with thousands of preferences
+ remain well under one second on commodity hardware (Brain trees
+ are kilobytes, not megabytes). If a future vault grows past a
+ threshold we will add `manifest_skip` for known-derived files; not
+ in v0.10.6.
+- **Drift detection false positives.** Two snapshots taken seconds
+ apart by separate runs would normally drift only on log files.
+ Drift detection runs at `rollback` time, not on every snapshot β€”
+ so this is observably benign (operator sees what differs and
+ decides). Documenting this in the rollback help text.
+- **`_brain.yaml` merge ambiguity.** If the user already added a
+ custom key that later collides with a new default key, the
+ result would be a duplicated key. The strict YAML parser raises on
+ reading such a file, so the collision surfaces as `status:
+ "error"` (collapsed under the same bucket as parse errors and
+ read failures) and `--apply` refuses to proceed; the operator
+ resolves manually. We chose not to split a dedicated
+ `"conflict"` status because the parser's own duplicate-key
+ detection catches the case earlier in the same code path, and
+ the operator-visible outcome is identical.
+- **Listbox + canvas synchronisation.** Pointer click on canvas and
+ keyboard selection in listbox must stay in lockstep. The
+ implementation funnels both through a single `selectNode(id)`
+ function β€” both surfaces update from it.
+- **localStorage quota.** With 500 nodes the layout payload is
+ ~30 KB; well under the 5 MB origin quota every browser ships.
+
+## Out-of-scope (followups)
+
+- `o2b brain upgrade --interactive` wizard.
+- Cron / SessionEnd sanity check on brain-event count (Β§30 Β§D).
+- MEMORY ↔ Brain bridge (Β§30 Β§E).
+- Always-loaded MCP promotion for `brain_feedback` and
+ `brain_apply_evidence` (Β§30 Β§B).
+- Retired / signal export for Β§28.
+- Live-refresh, Obsidian deep-link, freeze-layout toggle in
+ Brain Explorer.
diff --git a/docs/plans/2026-05-18-v0.10.6-impl.md b/docs/plans/2026-05-18-v0.10.6-impl.md
new file mode 100644
index 00000000..55844851
--- /dev/null
+++ b/docs/plans/2026-05-18-v0.10.6-impl.md
@@ -0,0 +1,1435 @@
+# v0.10.6 Implementation Plan
+
+> **For the implementer:** the user explicitly forbids any active git
+> action (commit, push, branch, tag, amend). Every "Pause for review"
+> step below means: stop, surface the diff, wait for the user to
+> stage / commit themselves. Do not run `git add`, `git commit`,
+> `git push`, `git stash`, `git tag`, or any history-rewriting
+> command without an explicit per-action ask.
+
+**Goal:** Ship `v0.10.6` of `open-second-brain` covering five tracks
+from `Projects/OpenSecondBrain/Features/_summary.md`: Β§30 (logging
+discipline), Β§22 + Β§5-tail (manifest-backed snapshots and upgrade),
+Β§14 polish (explorer keyboard a11y + layout persistence), Β§28
+(`o2b brain export`), Β§31 (CR cleanup).
+
+**Architecture:** A new `src/core/brain/manifest.ts` (SHA-256 file
+inventory of `Brain/` minus `.snapshots/`) underlies both upgrade and
+rollback drift detection. `src/core/brain/upgrade.ts` plus the new
+`o2b brain upgrade` CLI verb consume it. `src/core/brain/export.ts`
+plus `o2b brain export` give a read-only dump. Hook reminders
+(`hooks/lib/detect.ts`, `hooks/lib/messages.ts`) and the `brain-memory`
+SKILL get reworded so any of three brain-events clears the stop
+guardrail and uncertain matches default to a `speculative` record.
+Browser-side, `templates/brain-explorer.html` gains a listbox surface
+and `localStorage` persistence.
+
+**Tech Stack:** Bun β‰₯ 1.1, TypeScript (strict), `bun test`, `bun:sqlite`
+(unchanged). No new runtime dependencies. SHA-256 via `node:crypto`.
+Hooks are plain TS, executed under Claude Code's PostToolUse / Stop
+hook protocols.
+
+**Design source:** `docs/plans/2026-05-18-v0.10.6-design.md`. Refer
+back for rationale; this file is the step-by-step.
+
+---
+
+## Phase 0 β€” Baseline check
+
+### Task 0.1: Verify clean baseline
+
+**Objective:** Confirm `main` is green before any change lands.
+
+**Steps:**
+
+1. Run `bun test` from `/srv/projects/open-second-brain`. Expected:
+ all tests pass.
+2. Run `bun run typecheck`. Expected: zero errors.
+3. Record the current `package.json` version (should read `0.10.5`).
+
+**Pause for review.** Do not change anything yet.
+
+---
+
+## Phase 1 β€” Manifest infrastructure (Β§22 + Β§5-tail foundation)
+
+### Task 1.1: Manifest types and empty `buildManifest`
+
+**Objective:** Land the public API surface of the manifest module
+with one failing test.
+
+**Files:**
+- Create: `src/core/brain/manifest.ts`
+- Create: `tests/core/brain/manifest.test.ts`
+
+**Step 1: Write failing test** β€” `tests/core/brain/manifest.test.ts`:
+
+```ts
+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 {
+ BRAIN_MANIFEST_SCHEMA_VERSION,
+ buildManifest,
+} from "../../../src/core/brain/manifest.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-manifest-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+describe("buildManifest", () => {
+ test("empty Brain β†’ empty files map, schema_version 1", () => {
+ const m = buildManifest(join(vault, "Brain"));
+ expect(m.schema_version).toBe(BRAIN_MANIFEST_SCHEMA_VERSION);
+ expect(m.brain_root).toBe("Brain");
+ expect(Object.keys(m.files)).toEqual([]);
+ expect(typeof m.generated_at).toBe("string");
+ });
+});
+```
+
+**Step 2: Run test, expect FAIL** β€” `bun test tests/core/brain/manifest.test.ts`
+fails on missing module.
+
+**Step 3: Minimal implementation** β€” `src/core/brain/manifest.ts`:
+
+```ts
+export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;
+
+export interface BrainManifestEntry {
+ readonly sha256: string;
+ readonly size: number;
+}
+
+export interface BrainManifest {
+ readonly schema_version: typeof BRAIN_MANIFEST_SCHEMA_VERSION;
+ readonly generated_at: string;
+ readonly brain_root: "Brain";
+ readonly files: Readonly<Record<string, BrainManifestEntry>>;
+}
+
+export function buildManifest(_brainRoot: string): BrainManifest {
+ return {
+ schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
+ generated_at: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
+ brain_root: "Brain",
+ files: Object.freeze({}),
+ };
+}
+```
+
+**Step 4: Run test, expect PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 1.2: Walk `Brain/`, sha256 every regular file
+
+**Objective:** Real implementation of `buildManifest`.
+
+**Files:**
+- Modify: `src/core/brain/manifest.ts`
+- Modify: `tests/core/brain/manifest.test.ts` (add cases)
+
+**Step 1: Add failing tests** for: (a) two files in `preferences/`
+produce two entries with stable order; (b) symlink is skipped;
+(c) `.snapshots/` is skipped; (d) two runs over identical bytes
+produce identical sha256 values; (e) byte-identical generated JSON
+across runs (modulo `generated_at`).
+
+Sketch:
+
+```ts
+test("two preferences β†’ two entries sorted by path", () => {
+ mkdirSync(join(vault, "Brain", "preferences"));
+ writeFileSync(join(vault, "Brain", "preferences", "pref-a.md"), "alpha\n");
+ writeFileSync(join(vault, "Brain", "preferences", "pref-b.md"), "beta\n");
+ const m = buildManifest(join(vault, "Brain"));
+ expect(Object.keys(m.files)).toEqual([
+ "preferences/pref-a.md",
+ "preferences/pref-b.md",
+ ]);
+ expect(m.files["preferences/pref-a.md"]!.size).toBe(6);
+ expect(m.files["preferences/pref-a.md"]!.sha256).toMatch(/^[0-9a-f]{64}$/);
+});
+
+test("symlink under Brain/ is skipped", () => { /* symlinkSync */ });
+test(".snapshots/ tree is excluded", () => { /* mkdir + file + assert absent */ });
+test("identical bytes β†’ identical sha256", () => { /* two roots */ });
+```
+
+**Step 2: Run, expect FAIL.**
+
+**Step 3: Implement** the walker following the design doc Β§22
+"Walk semantics" β€” `lstatSync`, skip symlinks, skip `.snapshots/`,
+drop `..` escapes, sort keys lexicographically, hash via
+`node:crypto.createHash("sha256")`. Use insertion order on a fresh
+object to materialise the sorted key order.
+
+**Step 4: Run, expect PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 1.3: `diffManifests`
+
+**Objective:** Pure comparator with added / removed / changed buckets.
+
+**Files:**
+- Modify: `src/core/brain/manifest.ts`
+- Modify: `tests/core/brain/manifest.test.ts`
+
+**Step 1: Add failing tests** covering:
+- two identical manifests β†’ empty diff in all three buckets;
+- left has extra file β†’ `removed`;
+- right has extra file β†’ `added`;
+- same path different sha256 β†’ `changed`;
+- same path same sha256 different size (impossible in practice but
+ defensive) β†’ `changed` still surfaces as differing.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add types:
+
+```ts
+export interface BrainManifestDiffEntry {
+ readonly path: string;
+ readonly before: BrainManifestEntry | null;
+ readonly after: BrainManifestEntry | null;
+}
+
+export interface BrainManifestDiff {
+ readonly added: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly removed: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly changed: ReadonlyArray<BrainManifestDiffEntry>;
+}
+
+export function diffManifests(
+ a: BrainManifest,
+ b: BrainManifest,
+): BrainManifestDiff { /* … */ }
+```
+
+Implement with a `Set` union of keys, three classification passes,
+each bucket sorted by `path`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 1.4: Sidecar I/O helpers
+
+**Objective:** `manifestSidecarPath`, `readManifestSidecar`,
+`writeManifestSidecar`.
+
+**Files:**
+- Modify: `src/core/brain/manifest.ts`
+- Modify: `tests/core/brain/manifest.test.ts`
+
+**Step 1: Failing tests**:
+- `manifestSidecarPath(vault, "abc")` returns the
+ `Brain/.snapshots/abc.manifest.json` path;
+- write then read roundtrip yields equal-by-deep-equality object;
+- read of missing path returns `null`;
+- read of malformed JSON returns `null` and does NOT throw;
+- read of valid JSON with wrong `schema_version` returns `null`.
+
+**Step 2: FAIL.**
+
+**Step 3:** Implementation uses the existing
+`atomicWriteFileSync` (under `src/core/fs-atomic.ts`). JSON is
+pretty-printed two-space. `readManifestSidecar` swallows all
+errors and returns `null`.
+
+```ts
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { brainDirs } from "./paths.ts";
+// ...
+
+export function manifestSidecarPath(vault: string, runId: string): string {
+ return join(brainDirs(vault).snapshots, `${runId}.manifest.json`);
+}
+```
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+## Phase 2 β€” Snapshot sidecar manifest (Β§5-tail)
+
+### Task 2.1: `SnapshotInfo` gains `manifest_path`
+
+**Objective:** Forward-compat shape change; legacy snapshots get
+`manifest_path: null`.
+
+**Files:**
+- Modify: `src/core/brain/snapshot.ts`
+- Modify: `tests/core/brain/snapshot.test.ts` (if exists; otherwise
+ extend the closest existing snapshot test)
+
+**Step 1: Failing test** β€” `listSnapshots` over a fixture with two
+archives, one with sidecar, one without, returns
+`manifest_path: <abs>` for the first and `null` for the second.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add `manifest_path: string | null` to `SnapshotInfo`.
+In `listSnapshots`, after pushing an info row, set
+`manifest_path` from `existsSync(manifestSidecarPath(vault, runId))`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 2.2: `createSnapshot` writes sidecar
+
+**Files:**
+- Modify: `src/core/brain/snapshot.ts`
+- Modify: `tests/core/brain/snapshot.test.ts`
+
+**Step 1: Failing test** β€” call `createSnapshot(vault, "run-x")` on
+a fixture vault with two preference files; assert sidecar exists,
+parse it back via `readManifestSidecar`, assert it lists those two
+files with their sha256.
+
+**Step 2: FAIL.**
+
+**Step 3:** After the archive write succeeds (right before the
+`return { path: outPath }`), call:
+
+```ts
+try {
+ const manifest = buildManifest(dirs.brain);
+ writeManifestSidecar(vault, runId, manifest);
+} catch (err) {
+ process.stderr.write(
+ `warning: manifest sidecar write failed for ${runId}: ` +
+ `${(err as Error).message ?? String(err)}; ` +
+ `rollback drift detection will be skipped for this snapshot.\n`,
+ );
+}
+```
+
+**Step 4: PASS.** Add a second test for the failure-path: pre-create
+the sidecar path as a directory (so `writeFileSync` fails), confirm
+archive still lands and the warning fired on stderr (capture via
+`Bun.spawn` if necessary; otherwise mock writeManifestSidecar).
+
+**Pause for review.**
+
+---
+
+### Task 2.3: `pruneSnapshots` removes sidecar
+
+**Files:**
+- Modify: `src/core/brain/snapshot.ts`
+- Modify: `tests/core/brain/snapshot.test.ts`
+
+**Step 1: Failing test** β€” create 12 snapshots (each with sidecar)
+in a fixture, call `pruneSnapshots(vault, 10)`, assert two oldest
+archives AND their sidecars are gone; remaining 10 + 10 stay.
+
+**Step 2: FAIL.**
+
+**Step 3:** Inside the loop that removes victim archives, also call
+`rmSync(manifestSidecarPath(vault, v.run_id), { force: true })`.
+Wrap in its own try/catch β€” a missing sidecar (legacy snapshot)
+must not abort the prune.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+## Phase 3 β€” Rollback drift detection (Β§5-tail)
+
+### Task 3.1: Add `--force-rollback` flag scaffolding
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Modify: `tests/cli/brain.test.ts` (or `tests/cli/brain.rollback.test.ts`)
+
+**Step 1: Failing test** β€” `o2b brain rollback <run> --force-rollback`
+on a clean snapshot still succeeds; flag is recognised by the parser
+(unknown-flag error would surface otherwise).
+
+**Step 2: FAIL.**
+
+**Step 3:** In `cmdBrainRollback`'s `parse(...)` call, add
+`"force-rollback": { type: "boolean" }`. Plumb a `forceRollback`
+local variable through to the new drift-check (added in Task 3.2).
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 3.2: Drift check when sidecar exists
+
+**Files:**
+- Modify: `src/cli/brain.ts:cmdBrainRollback`
+- Modify: `tests/cli/brain.rollback.test.ts`
+
+**Step 1: Failing tests**:
+- snapshot taken at T1, live tree mutated at T2, `o2b brain rollback
+ <run>` (no `--force-rollback`) exits 2, stderr lists the drifted
+ files;
+- same scenario with `--force-rollback` proceeds and writes the log
+ event with `drift_overridden: "true"` in the payload;
+- `--dry-run` mode also reports drift but exits 0 (informational).
+
+**Step 2: FAIL.**
+
+**Step 3:** Before `restoreSnapshot(...)`, after the runId/archive
+existence check:
+
+```ts
+const stored = readManifestSidecar(vault, runId);
+if (stored !== null) {
+ const live = buildManifest(brainDirs(vault).brain);
+ const drift = diffManifests(stored, live);
+ const hasDrift =
+ drift.added.length > 0 ||
+ drift.removed.length > 0 ||
+ drift.changed.length > 0;
+ if (hasDrift && !forceRollback && !flags["dry-run"]) {
+ // Render the drift, exit 2 with --force-rollback hint.
+ return fail(renderDriftMarkdown(drift, runId));
+ }
+ // Either no drift, --force-rollback, or --dry-run: keep going,
+ // but stash the diff for the log payload further down.
+}
+```
+
+Render helper goes in `src/core/brain/manifest.ts` or a new
+`src/core/brain/manifest-render.ts` (decide based on size; keep it
+inside `manifest.ts` if under ~40 lines).
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 3.3: Legacy snapshot (no sidecar) emits warning, proceeds
+
+**Files:**
+- Modify: `src/cli/brain.ts:cmdBrainRollback`
+- Modify: `tests/cli/brain.rollback.test.ts`
+
+**Step 1: Failing test** β€” snapshot archive present without sidecar,
+`o2b brain rollback <run>` succeeds (with `--yes`) and stderr
+contains the legacy-warning line.
+
+**Step 2: FAIL.**
+
+**Step 3:** In the same block from Task 3.2, the `null` branch:
+
+```ts
+if (stored === null) {
+ process.stderr.write(
+ `warning: no manifest sidecar for snapshot '${runId}'; ` +
+ `drift detection skipped (snapshot predates v0.10.6).\n`,
+ );
+}
+```
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 3.4: Log `drift_overridden` on `--force-rollback`
+
+**Files:**
+- Modify: `src/cli/brain.ts:cmdBrainRollback` (the final
+ `appendLogEvent` call site)
+- Modify: `src/core/brain/types.ts:BrainRollbackLogEvent` (extend
+ the payload type)
+
+**Step 1: Failing test** β€” after `--force-rollback`, the log row in
+`Brain/log/<today>.md` contains `drift_overridden: true`.
+
+**Step 2: FAIL.**
+
+**Step 3:** Extend `BrainRollbackLogEvent.body` type to include
+optional `drift_overridden: string` ("true" when applicable; omit
+otherwise to keep the legacy shape clean). In the CLI, populate
+when `forceRollback && hasDrift`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+## Phase 4 β€” Upgrade core (Β§22)
+
+### Task 4.1: Upgrade types + skeleton
+
+**Files:**
+- Create: `src/core/brain/upgrade.ts`
+- Create: `tests/core/brain/upgrade.test.ts`
+
+**Step 1: Failing test** β€” `planUpgrade` over a fresh
+`o2b init`-style vault returns `pending: 0`, three files all
+`status: "noop"`.
+
+**Step 2: FAIL.**
+
+**Step 3:** Stub `planUpgrade` returning a hardcoded noop result so
+the test passes; real comparison comes in the next tasks. Surface
+`UpgradeFilePlan`, `UpgradePlan`, `UpgradeApplyResult` types from
+the design doc.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 4.2: `_brain.yaml` text-level merge
+
+**Files:**
+- Modify: `src/core/brain/upgrade.ts`
+- Modify: `tests/core/brain/upgrade.test.ts`
+
+**Step 1: Failing tests**:
+- fixture vault where `_brain.yaml` is missing the `snapshots:`
+ block β†’ `planUpgrade` returns `status: "update"` for
+ `Brain/_brain.yaml`, the `after` text contains the canonical
+ `snapshots:` block at end-of-file;
+- fixture missing a nested key (`confidence.high_min`) β†’
+ `status: "update"`, the missing line is inserted at the end of
+ the `confidence:` block with two-space indent;
+- fixture with all keys present β†’ `status: "noop"`;
+- fixture with malformed YAML β†’ `status: "error"` and the message
+ surfaces the parser error;
+- fixture with duplicated key (`primary_agent:` twice) β†’
+ `status: "error"`.
+
+**Step 2: FAIL.**
+
+**Step 3:** Implement the text-level walker described in the
+design doc Β§22 "Managed files" β†’ `_brain.yaml` merge. Source of
+truth for keys is `DEFAULT_BRAIN_CONFIG_YAML` from
+`src/core/brain/policy.ts`. Parsing for validity uses the existing
+`loadBrainConfig` (catch its error to emit `status: "error"`).
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 4.3: `_BRAIN.md` and `_OPEN_SECOND_BRAIN.md` byte comparison
+
+**Files:**
+- Modify: `src/core/brain/upgrade.ts`
+- Modify: `tests/core/brain/upgrade.test.ts`
+
+**Step 1: Failing tests**:
+- fixture where `_BRAIN.md` matches the rendered template byte for
+ byte β†’ `status: "noop"`;
+- fixture where `_BRAIN.md` is the v0.10.5 body (missing the new
+ upgrade/export lines added in Task 5.5) β†’ `status: "update"` with
+ unified-diff-ready `before` / `after`;
+- same for `AI Wiki/_OPEN_SECOND_BRAIN.md`.
+
+(The v0.10.5 fixture body is captured under
+`tests/fixtures/upgrade/brain-md-v0.10.5.md` β€” copy the literal
+bytes that `init.ts` would have written before Task 5.5 lands.)
+
+**Step 2: FAIL.**
+
+**Step 3:** Reuse `renderTemplate(readTemplate(...), substitutions)`
+from `init.ts` (lift to a shared helper if not already exported).
+Compare the rendered target bytes to the live file bytes.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 4.4: `applyUpgrade` β€” snapshot + write + log
+
+**Files:**
+- Modify: `src/core/brain/upgrade.ts`
+- Modify: `tests/core/brain/upgrade.test.ts`
+
+**Step 1: Failing tests**:
+- end-to-end on a fixture with one pending update: post-call the
+ three managed files match the canonical template; a snapshot
+ named `upgrade-<ts>` exists under `.snapshots/` along with its
+ sidecar manifest; `Brain/log/<today>.md` contains an `upgrade`
+ log row;
+- idempotent: a second call returns `files_updated: []` and writes
+ no log row.
+
+**Step 2: FAIL.**
+
+**Step 3:** Implementation order inside `applyUpgrade`:
+
+1. Compute the plan; if `pending === 0`, short-circuit and return
+ without touching disk.
+2. Compose `run_id = "upgrade-" + isoSecond(now)`.
+3. `createSnapshot(vault, run_id)` β€” sidecar manifest comes along.
+4. `atomicWriteFileSync` each `update` file.
+5. `appendLogEvent` with the `upgrade` event kind (added in
+ Task 4.5) and a payload describing the run_id, agent, updated
+ files.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 4.5: `BRAIN_LOG_EVENT_KIND.upgrade` and log payload type
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+- Modify: `src/core/brain/log.ts` (if it does the event-kind
+ validation; otherwise no-op)
+- Modify: `tests/core/brain/log.test.ts` (if exists)
+
+**Step 1: Failing test** β€” `BrainLogEvent` discriminated union
+includes a `kind: "upgrade"` member with `run_id`, `agent`, and
+`files` payload keys.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add:
+
+```ts
+export const BRAIN_LOG_EVENT_KIND = {
+ // ... existing entries
+ upgrade: "upgrade",
+} as const;
+
+export interface BrainUpgradeLogEvent extends BrainLogEventBase {
+ readonly eventType: "upgrade";
+ readonly body: {
+ readonly run_id: string;
+ readonly agent: string;
+ readonly snapshot: string;
+ readonly files: ReadonlyArray<string>;
+ };
+}
+```
+
+Extend the `BrainLogEvent` union.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+## Phase 5 β€” Upgrade CLI (Β§22)
+
+### Task 5.1: `cmdBrainUpgrade` with `--dry-run` (default)
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Create: `tests/cli/brain-upgrade.test.ts`
+
+**Step 1: Failing test** β€” `o2b brain upgrade --vault <path>` over
+a fixture with one pending update prints the per-file diff to
+stdout and exits 0.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add `cmdBrainUpgrade` mirroring the shape of
+`cmdBrainMigrateFrontmatter`. Flags: `--vault`, `--dry-run`,
+`--apply`, `--yes`, `--check`, `--json`. Default to dry-run when
+neither `--apply` nor `--check` is passed. Render unified diffs via
+a small helper (or reuse the existing snapshot-diff renderer if the
+shape lines up β€” likely not, since this is per-file rather than
+per-frontmatter-field; keep a small ad-hoc renderer in the CLI
+file).
+
+Wire it into the dispatcher:
+
+```ts
+case "upgrade":
+ return await cmdBrainUpgrade(rest);
+```
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 5.2: `--check` returns exit 2 on pending updates
+
+**Files:**
+- Modify: `src/cli/brain.ts:cmdBrainUpgrade`
+- Modify: `tests/cli/brain-upgrade.test.ts`
+
+**Step 1: Failing test** β€” `--check` over a fixture with pending
+updates exits 2; over a clean vault exits 0.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add the `--check` branch returning `plan.pending > 0 ? 2 : 0`.
+Validate mutual exclusion with `--apply` (`--apply` and `--check`
+together is an error).
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 5.3: `--apply --yes` end-to-end
+
+**Files:**
+- Modify: `src/cli/brain.ts:cmdBrainUpgrade`
+- Modify: `tests/cli/brain-upgrade.test.ts`
+
+**Step 1: Failing tests**:
+- `--apply --yes` over a fixture with pending updates: managed files
+ rewritten, snapshot created, log entry appended, exit 0;
+- `--apply` without `--yes` in non-interactive mode (no TTY or
+ `--json`) returns exit 1 with the same error pattern as
+ `migrate-frontmatter`;
+- interactive prompt path (mocked stdin) accepts `y` and proceeds,
+ rejects `n` cleanly.
+
+**Step 2: FAIL.**
+
+**Step 3:** Apply path: validate `--yes` in non-interactive mode,
+prompt otherwise (reuse `readSingleLine` helper). Call
+`applyUpgrade`. Emit human or `--json` output.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 5.4: Help text wiring
+
+**Files:**
+- Modify: `src/cli/brain.ts` (`BRAIN_HELP` body, `VERB_HELP.upgrade`)
+- Modify: `tests/cli/brain.test.ts` (or add to `brain-upgrade.test.ts`)
+
+**Step 1: Failing test** β€” `o2b brain upgrade --help` prints the
+upgrade-specific block and exits 0; `o2b brain --help` lists
+`upgrade` among the verbs.
+
+**Step 2: FAIL.**
+
+**Step 3:** Update the strings per the design doc Β§22 "CLI".
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 5.5: Update `_BRAIN.md` template (the v0.10.6 real change)
+
+**Files:**
+- Modify: `src/core/brain/templates/_BRAIN.md` (or the equivalent
+ templates path β€” confirm via `init.ts:BRAIN_MANUAL_TEMPLATE_PATH`)
+- Modify: `tests/core/brain/upgrade.test.ts` (the v0.10.5-fixture
+ scenario from Task 4.3 starts surfacing a real diff)
+
+**Step 1: Re-run** the v0.10.5-fixture test from Task 4.3. With the
+template change, it should now see the two added lines in the diff.
+
+**Step 2: Add two lines** to the template's "Brain CLI surface"
+section (or analogous spot near the existing CLI listing):
+
+```text
+- `o2b brain upgrade` β€” apply schema and template updates from the
+ installed open-second-brain version; --dry-run for a per-file plan.
+- `o2b brain export` β€” read-only dump of active preferences in JSON
+ or llms-txt format.
+```
+
+Locate the right insertion point by reading the template first; the
+existing CLI section is the natural anchor.
+
+**Step 3: Run the full test suite** β€” `bun test`. Verify the v0.10.6
+template renders without breaking any `init.ts` test.
+
+**Step 4: Update** the v0.10.5 fixture in `tests/fixtures/upgrade/`
+if needed so it pins the pre-change body exactly.
+
+**Pause for review.**
+
+---
+
+## Phase 6 β€” Β§30 Β§A: stop guardrail broadening
+
+### Task 6.1: Broaden `BRAIN_EVENT_NAME_SUFFIX`
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Modify: `tests/hooks/detect.test.ts`
+
+**Step 1: Failing tests** β€” `isBrainEventToolName` returns `true`
+for:
+- `event_log_append`,
+- `mcp__plugin_open-second-brain_open-second-brain__event_log_append`,
+- `brain_feedback`,
+- `mcp__plugin_open-second-brain_open-second-brain__brain_feedback`,
+- `brain_apply_evidence`,
+- `mcp__plugin_open-second-brain_open-second-brain__brain_apply_evidence`,
+and `false` for other names.
+
+**Step 2: FAIL** (function not defined yet under the new name).
+
+**Step 3:** Rename `LOG_NAME_SUFFIX` β†’ `BRAIN_EVENT_NAME_SUFFIX`,
+broaden the regex per the design doc Β§30 Β§A. Rename
+`isLogToolName` β†’ `isBrainEventToolName`. Single in-tree consumer
+(`summarizeTurn`) updates with it.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 6.2: Extend `BRAIN_EVENT_BASH_NEEDLES`
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Modify: `tests/hooks/detect.test.ts`
+
+**Step 1: Failing tests** β€” bash commands `o2b brain feedback ...`
+and `o2b brain apply-evidence ...` count as brain-event needles;
+random `o2b brain query ...` does not; trailing-space rule for
+`vault-log ` still holds.
+
+**Step 2: FAIL.**
+
+**Step 3:** Rename and extend the array:
+
+```ts
+const BRAIN_EVENT_BASH_NEEDLES = [
+ "o2b append-event",
+ "vault-log ",
+ "o2b brain feedback",
+ "o2b brain apply-evidence",
+];
+```
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 6.3: `summarizeTurn` field rename + propagation
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Modify: `hooks/stop-log-guardrail.ts`
+- Modify: `tests/hooks/detect.test.ts`
+- Modify: `tests/hooks/stop-log-guardrail.test.ts`
+
+**Step 1: Failing tests** β€” `TurnSummary.hadBrainEvent` exposed by
+`summarizeTurn`; `stop-log-guardrail.ts` reads
+`summary.hadBrainEvent` instead of `summary.hadLog`.
+
+**Step 2: FAIL.**
+
+**Step 3:** Rename `hadLog` β†’ `hadBrainEvent` on the public type
+and at the single consumer.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 6.4: New `stopGuardrailReason` text
+
+**Files:**
+- Modify: `hooks/lib/messages.ts`
+- Modify: `tests/hooks/messages.test.ts`
+
+**Step 1: Failing test** β€” `stopGuardrailReason("claudecode")` now
+contains the strings `"event_log_append"`, `"brain_apply_evidence"`,
+and `"brain_feedback"` in that order. The Codex variant likewise.
+The `unknown` branch contains all three but no cadence line.
+
+**Step 2: FAIL.**
+
+**Step 3:** Replace the body per the design doc Β§30 Β§A "Body text"
+section. Keep cadence lines exactly as today.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 6.5: End-to-end guardrail scenarios
+
+**Files:**
+- Modify: `tests/hooks/stop-log-guardrail.test.ts`
+
+**Step 1: Add scenarios** for the broadened semantics:
+- artifact + `brain_feedback` MCP call β†’ silent;
+- artifact + `brain_apply_evidence` MCP call β†’ silent;
+- artifact + `o2b brain feedback` bash β†’ silent;
+- artifact + no brain-event β†’ block with the new text;
+- back-compat: artifact + `event_log_append` only β†’ silent.
+
+**Step 2: Run** `bun test tests/hooks/`. Expected: all pass.
+
+**Pause for review.**
+
+---
+
+## Phase 7 β€” Β§30 Β§C: SKILL + reminder reformulation
+
+### Task 7.1: SKILL frontmatter description
+
+**Files:**
+- Modify: `skills/brain-memory/SKILL.md`
+- Create: `tests/skills/brain-memory.test.ts`
+
+**Step 1: Failing test** β€” reads `skills/brain-memory/SKILL.md`,
+asserts the frontmatter `description:` contains the new
+"speculative" wording verbatim and does NOT contain "A misrecorded
+signal is worse than a missed one".
+
+**Step 2: FAIL.**
+
+**Step 3:** Rewrite the `description:` field per the design doc
+Β§30 Β§C. Keep all other frontmatter keys unchanged.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 7.2: SKILL body β€” "When NOT to call" rewrite
+
+**Files:**
+- Modify: `skills/brain-memory/SKILL.md`
+- Modify: `tests/skills/brain-memory.test.ts`
+
+**Step 1: Failing test** β€” the body no longer contains
+"any case where you are not confident β€” skip rather than fabricate"
+and now contains the speculative-record bullet from the design.
+Closing sentence "A false-positive signal eventually distorts the
+rule set; a missed signal is recovered on repeat. Prefer
+precision." is absent.
+
+**Step 2: FAIL.**
+
+**Step 3:** Apply the body edits per design Β§30 Β§C.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 7.3: `postWriteReminder` tail update
+
+**Files:**
+- Modify: `hooks/lib/messages.ts`
+- Modify: `tests/hooks/messages.test.ts`
+
+**Step 1: Failing test** β€” `postWriteReminder({ … runtime: "unknown" })`
+no longer contains "A misrecorded signal is worse than a missed
+one" and now contains the speculative-record phrasing.
+
+**Step 2: FAIL.**
+
+**Step 3:** Edit the final paragraph in `postWriteReminder`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+## Phase 8 β€” Β§14 polish, part 1: listbox accessibility
+
+### Task 8.1: Listbox DOM and styles
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+- Modify: `tests/core/brain/explorer.test.ts` (or add a sibling
+ `tests/core/brain/explorer-template.test.ts`)
+
+**Step 1: Failing test** β€” `renderExportedHtml(graph)` output
+contains:
+- `id="node-list"`,
+- `role="listbox"`,
+- `aria-activedescendant=""`,
+- a `Reset layout` button.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add the listbox markup, CSS, and "Reset layout" button
+per design Β§14 "Listbox accessibility". The existing
+`#details` content slides into `#details-body`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 8.2: `renderNodeList` + filter integration
+
+**Objective:** Make the listbox track visible nodes.
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1: No automated test** (browser-side rendering). Manual QA
+steps documented in the PR description. Add an inline note in the
+template's `applyFilters` function pointing at the new
+`renderNodeList()` call.
+
+**Step 2:** Implement `renderNodeList()` per design β€” sorts by
+`topic` then `id`, builds `<li role="option" id="node-opt-${id}"
+aria-selected="false">${topic} β€” ${principle}</li>`. Called from
+`applyFilters`.
+
+**Step 3:** Manual smoke: `o2b brain explorer` against a small
+fixture vault; listbox populates on first paint and on filter
+input.
+
+**Pause for review.**
+
+---
+
+### Task 8.3: Keyboard handlers
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** Implement handlers per design Β§14:
+- ArrowUp / ArrowDown (with wrap-around);
+- Home / End;
+- Enter / Space β†’ `selectNode(focusedNodeId)`;
+- Escape β†’ reset focus + empty `#details-body`;
+- listbox focus shows visible outline.
+
+**Step 2:** Manual QA against the live vault. Note in the PR
+description: "tested ArrowUp/Down/Enter/Escape/Home/End under
+Chromium, listbox is reachable via Tab from the search input".
+
+**Pause for review.**
+
+---
+
+### Task 8.4: Unify canvas + listbox via `selectNode(id)`
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** Refactor existing `canvas.addEventListener("click", …)`
+handler so it calls `selectNode(node.id)` instead of inlining
+`selectedId = …; renderPanel(…)`. `selectNode` updates
+`selectedId`, calls `renderPanel`, scrolls the listbox to the
+matching `<li>`, updates `aria-activedescendant`, redraws canvas
+highlight.
+
+**Step 2:** Manual QA: click on canvas updates listbox visible
+selection and vice versa.
+
+**Pause for review.**
+
+---
+
+## Phase 9 β€” Β§14 polish, part 2: layout persistence
+
+### Task 9.1: localStorage schema + helper
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** Define inline:
+
+```js
+const STORAGE_KEY = "osb-explorer-layout:" + (graph.vault_basename || "default");
+const SCHEMA = 1;
+
+function loadStored() { /* try/catch JSON.parse, schema check */ }
+function saveStored(state) { /* try/catch JSON.stringify + setItem */ }
+```
+
+Failures from `localStorage` (quota, private mode) are caught and
+the helpers fall back to no-op.
+
+**Step 2:** Manual QA: open DevTools β†’ Application β†’ Local Storage
+and confirm the key materialises on first load.
+
+**Pause for review.**
+
+---
+
+### Task 9.2: Boot order β€” restore positions
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** After `placeInitial()` and before the first physics
+step, walk the stored positions: for each node, if
+`stored.positions[id]` exists, set `n.x / n.y` to the stored coords
+and zero `vx / vy`. Apply stored filters before `applyFilters()` is
+called.
+
+**Step 2:** Manual QA: reload the page, layout stays near previous
+positions.
+
+**Pause for review.**
+
+---
+
+### Task 9.3: Save triggers
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** Wire three triggers:
+1. `window.addEventListener("pagehide", saveLayout)`;
+2. Filter / search inputs `change` event β†’ debounced
+ `saveLayout` (500 ms);
+3. Once the physics damps (`βˆ‘|v| < 0.5` over the last frame) β†’
+ `saveLayout` and clear a `pendingSave` flag.
+
+**Step 2:** Manual QA: change a filter, reload, filter state
+restores. Move a node by drag (if drag exists) or wait for
+stabilisation, reload, positions stick.
+
+**Pause for review.**
+
+---
+
+### Task 9.4: "Reset layout" button wiring
+
+**Files:**
+- Modify: `templates/brain-explorer.html`
+
+**Step 1:** `document.getElementById("reset-layout").addEventListener("click", () => { localStorage.removeItem(STORAGE_KEY); location.reload(); });`
+
+**Step 2:** Manual QA: click button, page reloads with fresh
+`placeInitial` layout.
+
+**Pause for review.**
+
+---
+
+## Phase 10 β€” Β§28 export
+
+### Task 10.1: `exportPreferencesJson`
+
+**Files:**
+- Create: `src/core/brain/export.ts`
+- Create: `tests/core/brain/export.test.ts`
+
+**Step 1: Failing tests**:
+- empty preferences/ β†’ `preferences: []`, valid `generated_at`,
+ `vault_basename`;
+- mixed statuses (confirmed / unconfirmed / quarantine + one
+ retired + one signal in inbox) β†’ exactly the three active rows
+ appear, retired and signal excluded;
+- row fields match the design's `ExportedPreferenceRow` shape;
+- two runs over the same vault return identical `preferences`
+ arrays (ordering by `id` ascending).
+
+**Step 2: FAIL.**
+
+**Step 3:** Walk `Brain/preferences/`, `parsePreference`, sort by
+`id`, project to the export row shape. Body text after frontmatter
+captured via existing `parsePreference` return (extend if it
+currently drops the body β€” confirm before coding). Use
+`vaultDisplayName` from `init.ts` (lift to a small shared util if
+needed; preserve the existing exporter elsewhere) for
+`vault_basename`.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 10.2: `exportPreferencesLlmsTxt`
+
+**Files:**
+- Modify: `src/core/brain/export.ts`
+- Modify: `tests/core/brain/export.test.ts`
+
+**Step 1: Failing tests**:
+- empty preferences β†’ only the H1 + summary block, no H2 sections;
+- mixed statuses β†’ three `## Confirmed / ## Unconfirmed / ##
+ Quarantine` sections in fixed order;
+- only one non-empty status β†’ only that section appears;
+- a row's bullet is exactly
+ `- <pref-id> (topic: <topic>, scope: <scope>): <principle>`;
+- scope missing β†’ omit the `, scope:` slot.
+
+**Step 2: FAIL.**
+
+**Step 3:** Implementation follows the design doc Β§28 "llms-txt
+shape" verbatim. Use template literals; no external markdown lib.
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 10.3: `cmdBrainExport` CLI
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Create: `tests/cli/brain-export.test.ts`
+
+**Step 1: Failing tests**:
+- `o2b brain export --format json --vault <path>` over a fixture
+ prints JSON to stdout; parse roundtrip works;
+- `o2b brain export --format llms-txt --vault <path>` prints
+ the expected H1 + sections;
+- `--out <path>` writes a file; refuses to overwrite without
+ `--force`;
+- missing `--format` β†’ exit 2 with usage hint.
+
+**Step 2: FAIL.**
+
+**Step 3:** Add `cmdBrainExport(argv)`. Flags per the design.
+Single-line JSON, trailing newline on llms-txt. Wire into the
+dispatcher (`case "export": return await cmdBrainExport(rest);`).
+
+**Step 4: PASS.**
+
+**Pause for review.**
+
+---
+
+### Task 10.4: Help text wiring
+
+**Files:**
+- Modify: `src/cli/brain.ts` (`BRAIN_HELP`, `VERB_HELP.export`)
+
+**Step 1:** Update help strings per the design doc Β§28 "VERB_HELP".
+
+**Step 2:** Run `o2b brain --help` and `o2b brain export --help`
+manually to confirm. Run the help-text test from Task 10.3 if
+written there; otherwise add one assertion.
+
+**Pause for review.**
+
+---
+
+## Phase 11 β€” Β§31 CR cleanup
+
+### Task 11.1: MD040 fix in `docs/plans/2026-05-18-brain-maturity-design.md`
+
+**Files:**
+- Modify: `docs/plans/2026-05-18-brain-maturity-design.md`
+
+**Step 1:** Read the file, identify every fenced code block lacking
+a language tag. For each block:
+- shell / bash output β†’ ` ```bash`
+- TypeScript β†’ ` ```ts`
+- YAML β†’ ` ```yaml`
+- Markdown samples β†’ ` ```markdown`
+- JSON examples β†’ ` ```json`
+- Plain output / ASCII tables β†’ ` ```text`
+
+**Step 2:** Apply edits. No `sed` β€” block-by-block review.
+
+**Step 3:** Visually skim the rendered Markdown (in Obsidian or VS
+Code preview) to confirm no syntax highlighting regressions.
+
+**Pause for review.**
+
+---
+
+### Task 11.2: MD040 fix in `docs/plans/2026-05-18-brain-maturity-impl.md`
+
+Same procedure as Task 11.1 against the impl plan file.
+
+**Pause for review.**
+
+---
+
+### Task 11.3: MD040 fix in `skills/embeddings-setup/SKILL.md`
+
+Same procedure. SKILL.md is user-facing through the skill scanner β€”
+extra care that fenced-language hints are *correct*, not "guessed".
+
+**Pause for review.**
+
+---
+
+### Task 11.4: macOS shim β€” `DYLD_LIBRARY_PATH=""` test
+
+**Files:**
+- Modify: `tests/scripts/macos-sqlite-shim.test.ts`
+
+**Step 1: Add failing test** at the end of the `describe(...)`
+block:
+
+```ts
+test("Darwin + explicit empty DYLD_LIBRARY_PATH β†’ preserved verbatim", async () => {
+ const fakePrefix = join(tmp, "homebrew-sqlite-lib");
+ mkdirSync(fakePrefix, { recursive: true });
+ const out = await runShim({
+ O2B_MACOS_FORCE_PLATFORM: "Darwin",
+ O2B_MACOS_SQLITE_PREFIXES_OVERRIDE: fakePrefix,
+ DYLD_LIBRARY_PATH: "",
+ });
+ expect(out).toBe(""); // unchanged
+});
+```
+
+**Step 2: Run** `bun test tests/scripts/macos-sqlite-shim.test.ts`.
+Expected: PASS on the first run (the shim already handles `${VAR+set}`
+per v0.10.5 CR fix β€” this test ratchets the contract). If it fails,
+the shim has regressed and that becomes the bug to fix.
+
+**Pause for review.**
+
+---
+
+## Phase 12 β€” Plans, summary, CHANGELOG, version
+
+### Task 12.1: Update `CHANGELOG.md`
+
+**Files:**
+- Modify: `CHANGELOG.md`
+
+**Step 1:** Insert the new `## [0.10.6] - 2026-05-18` block above
+`## [0.10.5]` per design doc "CHANGELOG" section. No `[Unreleased]`
+heading (project convention). Add the link-footer line
+`[0.10.6]: https://github.com/itechmeat/open-second-brain/compare/v0.10.5...v0.10.6`.
+
+**Step 2:** Run `grep -n "Unreleased" CHANGELOG.md`. Expected:
+zero matches.
+
+**Pause for review.**
+
+---
+
+### Task 12.2: Update `_summary.md` (vault, plain Markdown edit)
+
+**Files:**
+- Modify: `/root/vault/Projects/OpenSecondBrain/Features/_summary.md`
+
+**Step 1:** Apply marks per design "Updates to plans / summary"
+section:
+- Β§5: mark fully shipped (manifest + abort drift detection).
+- Β§14: append v0.10.6 keyboard + layout-persistence note. Remove
+ the two matching items from `## Deferred work`.
+- Β§22, Β§28: prepend `βœ… … *(Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ Π² v0.10.6)*`.
+- Β§30: mark Β§A + Β§C shipped, leave Β§B / Β§D / Β§E open.
+- Β§31: mark Β§31.1 + Β§31.2 closed, Β§31.3 subsumed by Β§14 polish.
+
+**Step 2:** Russian prose stays Russian; no em-dashes (project
+convention from user memory).
+
+**Pause for review.**
+
+---
+
+### Task 12.3: Update `Plan/3` and `Plan/4` (vault)
+
+**Files:**
+- Modify: `/root/vault/Projects/OpenSecondBrain/Plan/3. Agent logging discipline.md`
+- Modify: `/root/vault/Projects/OpenSecondBrain/Plan/4. v0.10.5 review followups.md`
+
+**Step 1:** In `Plan/3`, add a top-of-doc `shipped:` frontmatter
+line listing `Β§A, Β§C (v0.10.6)`. Mark Β§B, Β§D, Β§E with `status:
+open`.
+
+**Step 2:** In `Plan/4`, mark Β§1, Β§2, Β§4 as shipped in v0.10.6.
+Β§3 already marked done.
+
+**Pause for review.**
+
+---
+
+### Task 12.4: Bump `package.json` version
+
+**Files:**
+- Modify: `package.json`
+
+**Step 1:** Change `"version": "0.10.5"` β†’ `"version": "0.10.6"`.
+
+**Step 2:** Run `bun run sync-version` (or the equivalent script
+that propagates version constants β€” check `scripts/sync-version.ts`
+for outputs). Expected: any mirrored constants update consistently.
+
+**Step 3:** Run `bun run sync-version:check`. Expected: PASS.
+
+**Pause for review.**
+
+---
+
+### Task 12.5: Full-suite verification
+
+**Steps:**
+
+1. `bun run typecheck` β€” zero errors.
+2. `bun test` β€” every test passes; warnings only on the legacy
+ snapshot path stderr line are acceptable and expected.
+3. `o2b brain upgrade --dry-run --vault <fixture>` β€” manually
+ inspect the diff. Expected: only `_BRAIN.md` shows an `update`
+ on the v0.10.5 fixture (the two added CLI lines).
+4. `o2b brain export --format llms-txt --vault <real-vault>` β€”
+ manually inspect the output for shape.
+5. Open `o2b brain explorer --port 7777` against a local vault.
+ Tab into the listbox, confirm Arrow keys move focus and Enter
+ selects. Reload, confirm layout persists.
+
+**Pause for final review.** Hand the diff to the user for
+inspection; they decide on the commit / push / tag flow.
+
+---
+
+## Final checklist
+
+- [ ] All new tests pass under `bun test`.
+- [ ] `bun run typecheck` clean.
+- [ ] `o2b brain upgrade --dry-run` shows the expected diff on the
+ v0.10.5 fixture.
+- [ ] `o2b brain export --format json|llms-txt` round-trips.
+- [ ] `o2b brain rollback` aborts on drift; `--force-rollback`
+ proceeds and logs `drift_overridden: true`.
+- [ ] Stop guardrail blocks when none of three brain-events fired;
+ stays silent when any one fired.
+- [ ] `skills/brain-memory/SKILL.md` and `hooks/lib/messages.ts`
+ use the new "speculative" wording.
+- [ ] Brain Explorer keyboard listbox reachable via Tab; arrows /
+ Enter / Escape behave per design.
+- [ ] localStorage layout + filter persistence works in Chromium.
+- [ ] CHANGELOG `[0.10.6]` block present, no `[Unreleased]`.
+- [ ] `_summary.md`, `Plan/3`, `Plan/4` updated and consistent.
+- [ ] `package.json` version `0.10.6`; `sync-version:check` green.
+- [ ] No git operations performed by the implementer; the diff is
+ handed to the user for commit / push.
diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.ts
index b159485e..3943859c 100644
--- a/hooks/lib/detect.ts
+++ b/hooks/lib/detect.ts
@@ -30,41 +30,58 @@ const NATIVE_ARTIFACT_NAMES = new Set<string>([
"apply_patch",
]);
-// Tool-name suffixes that mean "the agent logged this turn", regardless
-// of any runtime-injected MCP prefix:
-// Codex: `event_log_append` (bare; verified live).
-// Claude Code: `mcp__plugin_open-second-brain_open-second-brain__event_log_append`
-// (the runtime decorates plugin-provided MCP tools with
-// `mcp__plugin_<plugin>_<server>__` β€” verified live in
-// `~/.claude/projects/-root/*.jsonl`).
+// Tool-name suffixes that count as "the agent logged this turn",
+// regardless of any runtime-injected MCP prefix.
//
-// We match the trailing `event_log_append` token after either the start
-// of the name or a `__` separator so any future prefix change (Claude
-// has rebranded this twice in two months) keeps working without an
-// emergency patch.
-const LOG_NAME_SUFFIX = /(?:^|__)event_log_append$/;
-
-// Bash command substrings that indicate the agent called the CLI
-// equivalent of `event_log_append`. We deliberately keep this list
-// narrow: anything matched here suppresses the guardrail. Spawning
-// the MCP server (`o2b mcp …`) does NOT log on its own, so it is not
-// in the list β€” only the explicit append commands are.
-const LOG_BASH_NEEDLES = [
+// Β§30 Β§A (v0.10.6) broadens the set from `event_log_append` only to
+// any of the three brain-event tools β€” `event_log_append` itself
+// (durable session summary), `brain_feedback` (new taste signal),
+// `brain_apply_evidence` (evidence trail against an active
+// preference). Either of these landing in a turn that produced a
+// durable artifact is enough to clear the stop guardrail.
+//
+// Names appear bare in Codex transcripts and decorated as
+// `mcp__plugin_<plugin>_<server>__<name>` or `mcp__<server>__<name>`
+// in Claude Code transcripts. The regex anchors on either string
+// start or a `__` separator so a future prefix change keeps working
+// without an emergency patch.
+const BRAIN_EVENT_NAME_SUFFIX =
+ /(?:^|__)(event_log_append|brain_feedback|brain_apply_evidence)$/;
+
+// Bash command substrings that count as a brain-event call from the
+// CLI. We deliberately keep this list narrow: anything matched here
+// suppresses the guardrail. Spawning the MCP server (`o2b mcp …`)
+// does NOT log on its own, so it stays out of the list β€” only the
+// explicit event-emitting commands are in.
+const BRAIN_EVENT_BASH_NEEDLES = [
"o2b append-event",
"vault-log ", // trailing space distinguishes the CLI from a literal log path
+ "o2b brain feedback",
+ "o2b brain apply-evidence",
];
export function isArtifactToolName(name: string): boolean {
return NATIVE_ARTIFACT_NAMES.has(name);
}
-export function isLogToolName(name: string): boolean {
- return LOG_NAME_SUFFIX.test(name);
+/**
+ * True when `name` is one of the three brain-event tools (or a
+ * runtime-decorated form thereof). The renamed-from `isLogToolName`
+ * β€” kept tightly aligned with Β§30 Β§A's broadened semantics.
+ */
+export function isBrainEventToolName(name: string): boolean {
+ return BRAIN_EVENT_NAME_SUFFIX.test(name);
}
export interface TurnSummary {
readonly hadArtifact: boolean;
- readonly hadLog: boolean;
+ /**
+ * True when any of `event_log_append`, `brain_feedback`,
+ * `brain_apply_evidence` (MCP call or CLI invocation) landed in
+ * this turn. Renamed from `hadLog` in v0.10.6 Β§30 Β§A so the stop
+ * guardrail's correctness rests on the broader signal.
+ */
+ readonly hadBrainEvent: boolean;
}
export function summarizeTurn(
@@ -72,20 +89,20 @@ export function summarizeTurn(
bashCommandsThisTurn: readonly string[] = [],
): TurnSummary {
let hadArtifact = false;
- let hadLog = false;
+ let hadBrainEvent = false;
for (const tc of toolCalls) {
if (isArtifactToolName(tc.name)) hadArtifact = true;
- if (isLogToolName(tc.name)) hadLog = true;
+ if (isBrainEventToolName(tc.name)) hadBrainEvent = true;
}
- if (!hadLog) {
+ if (!hadBrainEvent) {
for (const cmd of bashCommandsThisTurn) {
- if (LOG_BASH_NEEDLES.some((n) => cmd.includes(n))) {
- hadLog = true;
+ if (BRAIN_EVENT_BASH_NEEDLES.some((n) => cmd.includes(n))) {
+ hadBrainEvent = true;
break;
}
}
}
- return { hadArtifact, hadLog };
+ return { hadArtifact, hadBrainEvent };
}
// ---- Runtime detection (Β§4-tail) ---------------------------------------
diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.ts
index 397a9c51..cc1c1a21 100644
--- a/hooks/lib/messages.ts
+++ b/hooks/lib/messages.ts
@@ -71,8 +71,10 @@ export function postWriteReminder({
"dream pass can update confidence and retire stale rules.",
"",
"Trivial edits (typo fix, pure formatting) don't need either call.",
- "A misrecorded signal is worse than a missed one β€” skip when not",
- "confident; the dream pass will pick up patterns from repeats.",
+ "When a preference plausibly applies but you are unsure, record",
+ "the event with `note: \"speculative; <reason>\"` instead of",
+ "skipping β€” the dream pass discards single-event speculative",
+ "entries that do not recur.",
);
return parts.join("\n");
}
@@ -92,19 +94,26 @@ export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {
const cadence = stopGuardrailCadenceLine(runtime);
const parts: string[] = [
"Open Second Brain hook: this turn touched files",
- "(Write / Edit / MultiEdit / apply_patch) but did not call",
- "`event_log_append`.",
+ "(Write / Edit / MultiEdit / apply_patch) but did not call any of:",
+ "",
+ "- `event_log_append` β€” durable session-summary line for the day log",
+ "- `brain_apply_evidence` β€” evidence trail when an active preference",
+ " in `Brain/preferences/` scopes to the artifact you just produced",
+ "- `brain_feedback` β€” new taste correction the user expressed in this",
+ " turn (one signal per file, see the `brain-memory` skill)",
"",
];
if (cadence !== "") parts.push(cadence, "");
parts.push(
- "If the change is a durable artifact you want future sessions to",
- "be able to search for, call `event_log_append` with a one-line",
- "message describing what landed, then finish.",
+ "Pick whichever fits this turn:",
+ "- a durable artifact future sessions need to find β†’ `event_log_append`",
+ "- an active preference applied or violated by the change β†’",
+ " `brain_apply_evidence` with `result: applied | violated`",
+ "- a new rule the user just stated β†’ `brain_feedback`",
"",
- "If the change is trivial and not worth logging, just send your",
- "reply again β€” this guardrail fires at most once per turn and",
- "will let the second Stop through.",
+ "If the change is trivial and not worth recording, just send your",
+ "reply again β€” this guardrail fires at most once per turn and the",
+ "second Stop passes through silently.",
);
return parts.join("\n");
}
diff --git a/hooks/stop-log-guardrail.ts b/hooks/stop-log-guardrail.ts
index 2d6f3505..0865be67 100755
--- a/hooks/stop-log-guardrail.ts
+++ b/hooks/stop-log-guardrail.ts
@@ -51,7 +51,7 @@ async function main(): Promise<void> {
}
const summary = summarizeTurn(signal.toolCalls, signal.bashCommands);
- if (!summary.hadArtifact || summary.hadLog) return;
+ if (!summary.hadArtifact || summary.hadBrainEvent) return;
const runtime = detectHookRuntime(payload);
const out = {
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 59b971c2..4f3bf804 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.5",
+ "version": "0.10.6",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 858e90fd..48144e8d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.5",
+ "version": "0.10.6",
"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 78f3991b..11a085b2 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.5"
+version: "0.10.6"
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 b17d5caf..3b44d21d 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.5",
+ "version": "0.10.6",
"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 f01828ee..3351d966 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.5"
+version: "0.10.6"
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 35101f1b..e1132537 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.5"
+version = "0.10.6"
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/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.md
index 94942676..12ff502a 100644
--- a/skills/brain-memory/SKILL.md
+++ b/skills/brain-memory/SKILL.md
@@ -1,6 +1,6 @@
---
name: brain-memory
-description: Record taste signals and apply-evidence events into the Brain observing-memory layer of Open Second Brain. INVOKE this skill (and call `brain_feedback`) the moment the user expresses a preference, dislike, correction, or rule in dialogue β€” "don't do X", "use A instead of B", "I prefer Y", "X is wrong here", or any explicit imperative that should outlive the current turn. SEPARATELY invoke (and call `brain_apply_evidence`) right after you produce a durable artifact (code shipped, file written, content drafted, config change) and at least one preference in `Brain/preferences/` has a `scope` that plausibly applies β€” record whether you `applied` or `violated` it. SKIP for casual chat, exploration without a stated rule, read-only inspection, trivial edits, and any case where you are not confident a preference applies. WRITE the `principle` and `note` fields in the same natural language the user has been speaking in this session; technical identifiers (`topic` slug, `pref_id`, `scope`) stay English. A misrecorded signal is worse than a missed one β€” the dream pass eventually surfaces real patterns from repeat events, so prefer precision over coverage.
+description: Record taste signals and apply-evidence events into the Brain observing-memory layer of Open Second Brain. INVOKE this skill (and call `brain_feedback`) the moment the user expresses a preference, dislike, correction, or rule in dialogue β€” "don't do X", "use A instead of B", "I prefer Y", "X is wrong here", or any explicit imperative that should outlive the current turn. SEPARATELY invoke (and call `brain_apply_evidence`) right after you produce a durable artifact (code shipped, file written, content drafted, config change) and at least one preference in `Brain/preferences/` has a `scope` that plausibly applies β€” record whether you `applied` or `violated` it. SKIP only for casual chat, exploration without a stated rule, read-only inspection, and trivial edits. When a preference plausibly applies but you are unsure, RECORD with `note: "speculative; <reason>"` rather than skipping β€” the dream pass discards single-event speculative entries that do not recur, so coverage costs less than missing the signal. WRITE the `principle` and `note` fields in the same natural language the user has been speaking in this session; technical identifiers (`topic` slug, `pref_id`, `scope`) stay English.
---
# Brain Memory
@@ -60,6 +60,7 @@ Parameters:
Optional:
- `note`: one-line context if useful ("expanded 'OSB' to 'Open Second Brain' on first use", "README diff still contained unexplained 'FT'").
+- `note: "speculative; <reason>"` when the preference's `scope` plausibly applies but you are unsure (e.g. a `writing` rule against a docstring inside a source file). The dream pass filters single-event speculative records that do not recur β€” recording the uncertainty costs less than missing the signal.
`applied_count` and `violated_count` on the preference are recomputed by `dream`; you write only the per-event evidence record.
@@ -69,9 +70,8 @@ Optional:
- Brainstorming, idea exploration, design discussion that has not concluded in a rule.
- Read-only inspection (running `git log`, `o2b status`, `vault_health`).
- Trivial edits (typo, whitespace, formatting only).
-- Cases where a preference *might* apply but you are not confident β€” skip rather than fabricate a match.
-A false-positive signal eventually distorts the rule set; a missed signal is recovered on repeat. Prefer precision.
+When a preference *might* apply but you are unsure, do not skip β€” record the event with `note: "speculative; <reason>"` so the dream pass sees the signal. A one-off speculative entry that does not recur is filtered out by dream; the cost of writing is one MCP call, the cost of missing is a silent gap in the evidence trail. The "do not call" list above is exhaustive on purpose: outside those four bullets, record.
## Language
diff --git a/skills/embeddings-setup/SKILL.md b/skills/embeddings-setup/SKILL.md
index 50f150f4..0fe0ba70 100644
--- a/skills/embeddings-setup/SKILL.md
+++ b/skills/embeddings-setup/SKILL.md
@@ -14,7 +14,7 @@ rather than waiting for explicit instruction.
## Step 1 β€” Always start with `o2b search check`
-```
+```bash
o2b search check
```
@@ -69,7 +69,7 @@ The `o2b` wrapper auto-detects Homebrew SQLite on Darwin and exports
manual patching of the wrapper script is needed (the v0.10.5 shim
`scripts/_macos-sqlite.sh` handles it). Verify with:
-```
+```bash
o2b search check
```
@@ -93,7 +93,7 @@ unusual.
## Step 5 β€” Compute the first vectors
-```
+```bash
o2b search reindex --embeddings
```
@@ -103,7 +103,7 @@ typically lands in a few seconds.
Verify semantic search works:
-```
+```bash
o2b search "preferences for code review"
```
@@ -116,7 +116,7 @@ The vault keeps changing β€” other agents add notes, the user edits
existing ones. Without periodic refresh the embeddings drift behind
the keyword index.
-```
+```bash
o2b search reindex --cron-template
```
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index dd10226f..29a9fa9c 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -90,12 +90,31 @@ import {
restoreSnapshot,
type ExtractSnapshotResult,
} from "../core/brain/snapshot.ts";
+import {
+ buildManifest,
+ diffManifests,
+ manifestDiffHasDrift,
+ readManifestSidecar,
+ renderManifestDriftJson,
+ renderManifestDriftMarkdown,
+} from "../core/brain/manifest.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 {
+ BrainUpgradeError,
+ applyUpgrade,
+ planUpgrade,
+ type UpgradeFilePlan,
+ type UpgradePlan,
+} from "../core/brain/upgrade.ts";
+import {
+ exportPreferencesJson,
+ exportPreferencesLlmsTxt,
+} from "../core/brain/export.ts";
import {
BRAIN_LOG_EVENT_KIND,
BRAIN_PREFERENCE_STATUS,
@@ -1232,10 +1251,12 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
list: { type: "boolean" },
yes: { type: "boolean" },
"dry-run": { type: "boolean" },
+ "force-rollback": { type: "boolean" },
json: { type: "boolean" },
});
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const forceRollback = Boolean(flags["force-rollback"]);
// `--list` shows available snapshots in newest-first order, with size
// for the operator's mental model. Idempotent and read-only.
@@ -1273,6 +1294,46 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
return 2;
}
+ // Drift detection (Β§5-tail). When a sidecar manifest accompanies
+ // the snapshot we compare it against a freshly-built manifest of
+ // the live Brain/ tree. If they differ and the operator did not
+ // pass --force-rollback, we abort with exit 2 so a Syncthing-
+ // delivered edit on another device is not silently clobbered. For
+ // legacy snapshots (no sidecar β€” produced before v0.10.6) we emit
+ // a stderr warning and fall through to the pre-v0.10.6 path.
+ // Skip the full sha-256 walk for `--dry-run` β€” that path already
+ // shows the operator everything via `diffBrainTrees` and never
+ // writes, so drift detection adds no signal.
+ const driftDiff = flags["dry-run"]
+ ? null
+ : (() => {
+ const stored = readManifestSidecar(vault, runId);
+ if (stored === null) {
+ process.stderr.write(
+ `warning: no manifest sidecar for snapshot '${runId}'; ` +
+ `drift detection skipped (snapshot predates v0.10.6).\n`,
+ );
+ return null;
+ }
+ const live = buildManifest(brainDirs(vault).brain);
+ return diffManifests(stored, live);
+ })();
+ const drift = driftDiff !== null && manifestDiffHasDrift(driftDiff);
+ if (drift && !forceRollback) {
+ // Abort path. --json emits the structured drift payload; the
+ // human path emits the markdown rendering. Either way the exit
+ // code is 2 and Brain/ stays untouched.
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(renderManifestDriftJson(driftDiff!, runId), null, 2) +
+ "\n",
+ );
+ return 2;
+ }
+ process.stderr.write(renderManifestDriftMarkdown(driftDiff!, runId) + "\n");
+ 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
@@ -1336,13 +1397,20 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
// Log the rollback event so the audit trail shows the time-shift.
try {
+ const body: Record<string, string> = {
+ run_id: runId,
+ restored_files: String(result.restored_files),
+ };
+ // Record `drift_overridden` only when --force-rollback actually
+ // bypassed a real drift β€” the absence of the key keeps the
+ // common-case shape minimal.
+ if (drift && forceRollback) {
+ body["drift_overridden"] = "true";
+ }
appendLogEvent(vault, {
timestamp: isoSecond(new Date()),
eventType: BRAIN_LOG_EVENT_KIND.rollback,
- body: {
- run_id: runId,
- restored_files: String(result.restored_files),
- },
+ body,
});
} catch (err) {
// Non-fatal: the snapshot was already restored on disk; surface so
@@ -1740,6 +1808,263 @@ async function cmdBrainMigrateFrontmatter(argv: string[]): Promise<number> {
return 0;
}
+/**
+ * `o2b brain upgrade` β€” migrate release-owned files (`_brain.yaml`,
+ * `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward when a new
+ * open-second-brain version ships. Default is `--dry-run`; `--apply`
+ * (with `--yes` in non-interactive mode) rewrites the files after a
+ * pre-apply snapshot.
+ */
+async function cmdBrainUpgrade(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ check: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ // Flag matrix. `--dry-run` + `--apply` is contradictory. `--check`
+ // is a CI shorthand for "dry-run with non-zero exit on pending";
+ // combining it with `--apply` is also contradictory.
+ if (flags["dry-run"] && flags["apply"]) {
+ return fail("brain upgrade: --dry-run and --apply are mutually exclusive");
+ }
+ if (flags["check"] && flags["apply"]) {
+ return fail("brain upgrade: --check and --apply are mutually exclusive");
+ }
+
+ let plan: UpgradePlan;
+ try {
+ plan = planUpgrade(vault);
+ } catch (exc) {
+ return fail(`upgrade plan failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ // `--check` is the CI gate: print a one-line summary and exit 2
+ // when there is anything to do. Stays read-only.
+ if (flags["check"]) {
+ if (flags["json"]) {
+ okJson(renderUpgradePlanJson(plan));
+ } else {
+ printUpgradePlanText(plan);
+ }
+ return plan.pending > 0 || plan.errors > 0 ? 2 : 0;
+ }
+
+ // Default and `--dry-run` share the same output. Exit 0 either
+ // way β€” `--check` is the gate variant.
+ if (!flags["apply"]) {
+ if (flags["json"]) {
+ okJson(renderUpgradePlanJson(plan));
+ } else {
+ printUpgradePlanText(plan);
+ }
+ return 0;
+ }
+
+ // Apply path.
+ if (plan.errors > 0) {
+ return fail(
+ `upgrade aborted: ${plan.errors} file(s) failed to plan; ` +
+ `run with --dry-run to inspect the error.`,
+ );
+ }
+ if (plan.pending === 0) {
+ if (flags["json"]) {
+ okJson({ run_id: "", snapshot_path: "", files_updated: [] });
+ } else {
+ ok("upgrade: nothing to do; all managed files match the current release.");
+ }
+ return 0;
+ }
+ if (!flags["yes"]) {
+ if (flags["json"] || !process.stdin.isTTY) {
+ return fail(
+ "brain upgrade --apply requires --yes in non-interactive mode " +
+ "(--json or non-TTY stdin)",
+ );
+ }
+ process.stderr.write(
+ `About to rewrite ${plan.pending} managed file(s):\n` +
+ plan.files
+ .filter((f) => f.status === "update")
+ .map((f) => ` - ${f.path}\n`)
+ .join("") +
+ `A pre-apply snapshot will be taken (rollback via run id).\n` +
+ `Proceed? [y/N] `,
+ );
+ const ans = await readSingleLine();
+ if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") {
+ ok("upgrade cancelled");
+ return 0;
+ }
+ }
+
+ let result;
+ try {
+ result = applyUpgrade(vault, { now: new Date() });
+ } catch (exc) {
+ if (exc instanceof BrainUpgradeError) {
+ process.stderr.write(`error: ${exc.message}\n`);
+ return 1;
+ }
+ return fail(`upgrade failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ okJson({
+ run_id: result.run_id,
+ snapshot_path: result.snapshot_path,
+ files_updated: result.files_updated,
+ });
+ } else {
+ ok(`run_id: ${result.run_id}`);
+ ok(`snapshot: ${result.snapshot_path}`);
+ for (const p of result.files_updated) ok(` updated: ${p}`);
+ }
+ return 0;
+}
+
+function renderUpgradePlanJson(plan: UpgradePlan): {
+ pending: number;
+ errors: number;
+ files: ReadonlyArray<{
+ path: string;
+ status: UpgradeFilePlan["status"];
+ before_size: number;
+ after_size: number;
+ error?: string;
+ }>;
+} {
+ return {
+ pending: plan.pending,
+ errors: plan.errors,
+ files: plan.files.map((f) => ({
+ path: f.path,
+ status: f.status,
+ before_size: f.before.length,
+ after_size: f.after.length,
+ ...(f.error ? { error: f.error } : {}),
+ })),
+ };
+}
+
+function printUpgradePlanText(plan: UpgradePlan): void {
+ for (const f of plan.files) {
+ if (f.status === "noop") {
+ ok(` ${f.path}: up to date`);
+ continue;
+ }
+ if (f.status === "error") {
+ info(` ${f.path}: ERROR ${f.error}`);
+ continue;
+ }
+ info(` ${f.path}: update (${f.before.length} β†’ ${f.after.length} bytes)`);
+ info(renderUnifiedDiff(f.before, f.after, f.path));
+ }
+ if (plan.pending === 0 && plan.errors === 0) {
+ ok("upgrade: all managed files match the current release.");
+ } else if (plan.pending > 0) {
+ ok(
+ `upgrade: ${plan.pending} pending update(s); ` +
+ `re-run with --apply --yes when ready.`,
+ );
+ }
+}
+
+/**
+ * Bare-bones unified diff renderer. Good enough for human-eye review
+ * inside the CLI. We intentionally avoid pulling a dependency for a
+ * cosmetic feature; the algorithm is line-by-line with a small
+ * sliding window so identical leading / trailing lines collapse
+ * naturally.
+ */
+function renderUnifiedDiff(before: string, after: string, label: string): string {
+ if (before === after) return "";
+ const a = before.split("\n");
+ const b = after.split("\n");
+ const lines: string[] = [`--- ${label} (live)`, `+++ ${label} (release)`];
+ // Skip the matching prefix to keep the diff tight.
+ let head = 0;
+ while (head < a.length && head < b.length && a[head] === b[head]) head++;
+ let tailA = a.length;
+ let tailB = b.length;
+ while (
+ tailA > head &&
+ tailB > head &&
+ a[tailA - 1] === b[tailB - 1]
+ ) {
+ tailA--;
+ tailB--;
+ }
+ if (head > 0) {
+ lines.push(`@@ context: ${head} matching line(s) above @@`);
+ }
+ for (let i = head; i < tailA; i++) lines.push(`- ${a[i]}`);
+ for (let i = head; i < tailB; i++) lines.push(`+ ${b[i]}`);
+ if (tailA < a.length || tailB < b.length) {
+ const tailCount = Math.max(a.length - tailA, b.length - tailB);
+ lines.push(`@@ context: ${tailCount} matching line(s) below @@`);
+ }
+ return lines.join("\n");
+}
+
+/**
+ * `o2b brain export` (Β§28) β€” read-only dump of active preferences in
+ * either JSON or llms-txt format. Default sink is stdout; `--out`
+ * writes to a file (refusing to overwrite without `--force`).
+ */
+async function cmdBrainExport(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ format: { type: "string" },
+ out: { type: "string" },
+ force: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const format = flags["format"] as string | undefined;
+ if (format !== "json" && format !== "llms-txt") {
+ process.stderr.write(
+ "error: --format is required and must be one of json|llms-txt\n",
+ );
+ return 2;
+ }
+
+ let body: string;
+ try {
+ if (format === "json") {
+ body = JSON.stringify(exportPreferencesJson(vault)) + "\n";
+ } else {
+ body = exportPreferencesLlmsTxt(vault);
+ }
+ } catch (exc) {
+ return fail(`export failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ const outPath = flags["out"] as string | undefined;
+ if (outPath === undefined) {
+ process.stdout.write(body);
+ return 0;
+ }
+ if (existsSync(outPath) && !flags["force"]) {
+ return fail(`${outPath} exists; pass --force to overwrite`);
+ }
+ try {
+ atomicWriteFileSync(outPath, body);
+ } catch (exc) {
+ return fail(
+ `failed to write ${outPath}: ${(exc as Error).message ?? exc}`,
+ );
+ }
+ ok(`wrote ${outPath}`);
+ return 0;
+}
+
async function cmdBrainDoctor(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
@@ -1805,6 +2130,8 @@ Brain verbs (observing memory):
protect Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
unprotect Remove OSB-managed deny rules for the chosen target (--target)
merge Merge two near-duplicate preferences (<keep> <drop>; --dry-run, --force)
+ upgrade Migrate release-owned files forward (--dry-run by default; --apply --yes)
+ export Dump active preferences (--format json|llms-txt [--out <path>])
explorer Launch the loopback HTML explorer; --export <path> writes a single offline file
snapshot diff Read-only diff between two snapshots, or snapshot vs live
rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
@@ -1855,12 +2182,22 @@ const VERB_HELP: Record<string, string> = {
"usage: o2b brain unpin --id <pref-id> [--vault <path>] [--json]\n" +
"Clear pinned: true. Idempotent.\n",
rollback:
- "usage: o2b brain rollback <run_id> [--vault <path>] [--yes] [--json]\n" +
+ "usage: o2b brain rollback <run_id> [--vault <path>] [--yes]\n" +
+ " [--force-rollback] [--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" +
"--dry-run prints the would-be restore plan as live β†’ snapshot\n" +
- "diff and exits 0 without writing.\n",
+ "diff and exits 0 without writing.\n" +
+ "From v0.10.6 each snapshot carries a sidecar sha256 manifest of\n" +
+ "the Brain/ tree captured at snapshot time. rollback compares it\n" +
+ "against the current Brain/ and aborts with exit 2 if they\n" +
+ "differ β€” typically because another device (Syncthing) edited the\n" +
+ "vault between snapshot and rollback. Pass --force-rollback to\n" +
+ "overwrite anyway; the log entry records `drift_overridden: true`.\n" +
+ "Snapshots produced before v0.10.6 have no sidecar; rollback emits\n" +
+ "a stderr warning and falls through to the legacy direct-restore\n" +
+ "path.\n",
snapshot:
"usage: o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" +
" [--vault <path>] [--json]\n" +
@@ -1914,6 +2251,34 @@ const VERB_HELP: Record<string, string> = {
"--dry-run prints the plan and writes nothing.\n" +
"--force skips the interactive prompt but does NOT bypass invariant\n" +
"guards (topic/scope mismatch, pin parity).\n",
+ export:
+ "usage: o2b brain export --format json|llms-txt [--vault <path>]\n" +
+ " [--out <path>] [--force]\n" +
+ "Read-only dump of active preferences (confirmed | unconfirmed |\n" +
+ "quarantine) from Brain/preferences/. Retired and signal entries\n" +
+ "are not included. JSON is single-line; llms-txt follows the\n" +
+ "llmstxt.org H1 + summary + H2-section shape.\n" +
+ "Default sink is stdout; --out writes to <path> (refuses to\n" +
+ "overwrite without --force).\n",
+ upgrade:
+ "usage: o2b brain upgrade [--vault <path>] [--dry-run | --apply | --check]\n" +
+ " [--yes] [--json]\n" +
+ "Migrate the three release-owned files (`Brain/_brain.yaml`,\n" +
+ "`Brain/_BRAIN.md`, `AI Wiki/_OPEN_SECOND_BRAIN.md`) forward to the\n" +
+ "shape the installed open-second-brain release ships.\n" +
+ "User-owned content (preferences/, retired/, inbox/, log/) is\n" +
+ "never touched.\n" +
+ "--dry-run (default) prints a per-file plan with a unified diff\n" +
+ "for every pending update. Exit 0 regardless of pending count.\n" +
+ "--check is dry-run + exit 2 when anything is pending or in error\n" +
+ "(CI-friendly).\n" +
+ "--apply takes a pre-apply snapshot named upgrade-<ts> (rollback\n" +
+ "via run_id) and rewrites every pending file. Requires --yes in\n" +
+ "non-interactive mode (--json or non-TTY stdin).\n" +
+ "_brain.yaml merge is purely additive: missing schema-keys are\n" +
+ "appended, existing values stay. _BRAIN.md and\n" +
+ "_OPEN_SECOND_BRAIN.md are byte-compared against the rendered\n" +
+ "template and overwritten when they differ.\n",
explorer:
"usage: o2b brain explorer [--port <n>] [--vault <path>]\n" +
" o2b brain explorer --export <path> [--force] [--vault <path>]\n" +
@@ -1999,6 +2364,10 @@ export async function handleBrainSubcommand(
return await cmdBrainImportSession(rest);
case "merge":
return await cmdBrainMerge(rest);
+ case "upgrade":
+ return await cmdBrainUpgrade(rest);
+ case "export":
+ return await cmdBrainExport(rest);
case "explorer":
return await cmdBrainExplorer(rest);
default:
diff --git a/src/core/brain/export.ts b/src/core/brain/export.ts
new file mode 100644
index 00000000..b2bccffa
--- /dev/null
+++ b/src/core/brain/export.ts
@@ -0,0 +1,177 @@
+/**
+ * Read-only export of `Brain/preferences/` for backup, prompt
+ * injection, or sharing. Only the three active statuses
+ * (`confirmed | unconfirmed | quarantine`) are included; retired
+ * and signal artifacts are deliberately excluded.
+ *
+ * llms-txt follows the [llmstxt.org](https://llmstxt.org) shape;
+ * empty status sections are omitted so a single-status vault
+ * renders one H2 rather than three.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { parsePreference } from "./preference.ts";
+import { brainDirs } from "./paths.ts";
+import { vaultDisplayName } from "./templates.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_PREFERENCE_STATUS, type BrainPreference } from "./types.ts";
+import { parseFrontmatter } from "../vault.ts";
+
+export const BRAIN_EXPORT_SCHEMA_VERSION = 1 as const;
+
+export type ExportFormat = "json" | "llms-txt";
+
+export interface ExportedPreferenceRow {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly status: BrainPreference["status"];
+ readonly principle: string;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly confidence: BrainPreference["confidence"];
+ readonly confidence_value: number | null;
+ readonly pinned: boolean;
+ readonly last_evidence_at: string | null;
+ readonly created_at: string;
+ readonly confirmed_at: string | null;
+ readonly aliases: ReadonlyArray<string> | null;
+ readonly tags: ReadonlyArray<string>;
+ readonly evidenced_by: ReadonlyArray<string>;
+ /**
+ * Markdown body after the frontmatter β€” carries the `## Principle`,
+ * `## Origin`, `## How to apply` (and similar) narrative sections.
+ * The `principle` field above is the headline copy; the body is the
+ * fuller context a consumer needs when sharing or injecting the
+ * rule into a system prompt.
+ */
+ readonly body: string;
+}
+
+export interface ExportedPreferencesJson {
+ readonly schema: typeof BRAIN_EXPORT_SCHEMA_VERSION;
+ readonly generated_at: string;
+ readonly vault_basename: string;
+ readonly preferences: ReadonlyArray<ExportedPreferenceRow>;
+}
+
+/**
+ * Walk `Brain/preferences/`, parse every `pref-*.md`, and project to
+ * the export row shape sorted by `id` for deterministic output.
+ * Files that fail to parse are silently skipped β€” the doctor surface
+ * is the canonical place for surfacing those, not the read-only
+ * exporter.
+ */
+export function collectExportRows(vault: string): ReadonlyArray<ExportedPreferenceRow> {
+ const dir = brainDirs(vault).preferences;
+ if (!existsSync(dir)) return [];
+ const rows: ExportedPreferenceRow[] = [];
+ let entries: ReadonlyArray<string>;
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return [];
+ }
+ for (const name of entries) {
+ if (!name.startsWith("pref-") || !name.endsWith(".md")) continue;
+ const abs = join(dir, name);
+ let pref: BrainPreference;
+ try {
+ pref = parsePreference(abs);
+ } catch {
+ continue;
+ }
+ // `parsePreference` deliberately drops the body. We re-parse the
+ // file here to capture the markdown sections the agent wrote
+ // (`## Principle`, `## Origin`, …) β€” those are the bytes a
+ // consumer wants when sharing or system-prompt-injecting the
+ // rule. A read failure here drops the row entirely.
+ let body = "";
+ try {
+ const [, parsedBody] = parseFrontmatter(abs);
+ body = parsedBody;
+ } catch {
+ continue;
+ }
+ rows.push(toRow(pref, body));
+ }
+ rows.sort((a, b) => a.id.localeCompare(b.id));
+ return rows;
+}
+
+function toRow(p: BrainPreference, body: string): ExportedPreferenceRow {
+ return Object.freeze({
+ id: p.id,
+ topic: p.topic,
+ scope: p.scope ?? null,
+ status: p.status,
+ principle: p.principle,
+ applied_count: p.applied_count,
+ violated_count: p.violated_count,
+ confidence: p.confidence,
+ confidence_value: p.confidence_value,
+ pinned: p.pinned,
+ last_evidence_at: p.last_evidence_at,
+ created_at: p.created_at,
+ confirmed_at: p.confirmed_at,
+ aliases: p.aliases ? Object.freeze([...p.aliases]) : null,
+ tags: Object.freeze([...p.tags]),
+ evidenced_by: Object.freeze([...p.evidenced_by]),
+ body,
+ });
+}
+
+export function exportPreferencesJson(vault: string): ExportedPreferencesJson {
+ return Object.freeze({
+ schema: BRAIN_EXPORT_SCHEMA_VERSION,
+ generated_at: isoSecond(),
+ vault_basename: vaultDisplayName(vault),
+ preferences: collectExportRows(vault),
+ });
+}
+
+const LLMS_TXT_SECTION_ORDER: ReadonlyArray<BrainPreference["status"]> = [
+ BRAIN_PREFERENCE_STATUS.confirmed,
+ BRAIN_PREFERENCE_STATUS.unconfirmed,
+ BRAIN_PREFERENCE_STATUS.quarantine,
+];
+
+const LLMS_TXT_SECTION_LABEL: Readonly<Record<BrainPreference["status"], string>> = {
+ [BRAIN_PREFERENCE_STATUS.confirmed]: "Confirmed",
+ [BRAIN_PREFERENCE_STATUS.unconfirmed]: "Unconfirmed",
+ [BRAIN_PREFERENCE_STATUS.quarantine]: "Quarantine",
+};
+
+/**
+ * Render the export as an [llmstxt.org](https://llmstxt.org) markdown
+ * file: H1 title, blockquote summary, then an H2 per non-empty
+ * status. Each preference becomes one bullet line of the form
+ * `- <id> (topic: <topic>[, scope: <scope>]): <principle>`. Status
+ * sections without any rows are omitted entirely.
+ */
+export function exportPreferencesLlmsTxt(vault: string): string {
+ const rows = collectExportRows(vault);
+ const name = vaultDisplayName(vault);
+ const lines: string[] = [
+ `# ${name} β€” Brain preferences`,
+ "",
+ `> Active preferences captured by Open Second Brain. Auto-generated`,
+ `> by \`o2b brain export --format llms-txt\`. The canonical files`,
+ `> live under \`<vault>/Brain/preferences/\`.`,
+ "",
+ ];
+ for (const status of LLMS_TXT_SECTION_ORDER) {
+ const subset = rows.filter((r) => r.status === status);
+ if (subset.length === 0) continue;
+ lines.push(`## ${LLMS_TXT_SECTION_LABEL[status]}`);
+ lines.push("");
+ for (const r of subset) {
+ const scopeBit = r.scope ? `, scope: ${r.scope}` : "";
+ lines.push(`- ${r.id} (topic: ${r.topic}${scopeBit}): ${r.principle}`);
+ }
+ lines.push("");
+ }
+ return lines.join("\n");
+}
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 88d778fb..38ac67b1 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -32,7 +32,6 @@ import {
cpSync,
existsSync,
mkdirSync,
- readFileSync,
readdirSync,
statSync,
} from "node:fs";
@@ -41,7 +40,6 @@ import { fileURLToPath } from "node:url";
import { defaultConfigPath } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
-import { escapeRegex } from "../strings.ts";
import {
brainConfigPath,
brainDirs,
@@ -52,8 +50,11 @@ import {
DEFAULT_BRAIN_CONFIG_YAML,
formatPrimaryAgentYamlValue,
} from "./policy.ts";
-import type { BrainConfig } from "./types.ts";
-import { DEFAULT_BRAIN_CONFIG } from "./policy.ts";
+import {
+ LEGACY_OVERVIEW_REL_PATH,
+ renderBrainManual,
+ renderLegacyOverview,
+} from "./templates.ts";
const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;
@@ -170,22 +171,6 @@ export function copyStarterBundle(
return Object.freeze({ copied });
}
-// Resolve template paths relative to this source file. `import.meta.url`
-// is stable under both `bun run` (TS source) and any future build that
-// keeps the template files alongside the bundled JS.
-const TEMPLATE_DIR = resolve(
- dirname(fileURLToPath(import.meta.url)),
- "templates",
-);
-
-const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");
-const LEGACY_OVERVIEW_TEMPLATE_PATH = join(
- TEMPLATE_DIR,
- "_OPEN_SECOND_BRAIN.md.tpl",
-);
-
-/** Vault-relative target for the legacy-overview replacement. */
-const LEGACY_OVERVIEW_REL_PATH = join("AI Wiki", "_OPEN_SECOND_BRAIN.md");
export interface BootstrapBrainOptions {
/** Overwrite `_brain.yaml` and `_BRAIN.md` if they already exist. */
@@ -299,10 +284,7 @@ export function bootstrapBrain(
// 3. `Brain/_BRAIN.md` β€” operating manual rendered from template.
const manualPath = brainManualPath(vault);
const manualRel = vaultRelative(manualPath, vault);
- const manualBody = renderTemplate(
- readTemplate(BRAIN_MANUAL_TEMPLATE_PATH),
- buildSubstitutions(vault, DEFAULT_BRAIN_CONFIG),
- );
+ const manualBody = renderBrainManual(vault);
if (existsSync(manualPath)) {
if (force) {
atomicWriteFileSync(manualPath, manualBody);
@@ -324,10 +306,7 @@ export function bootstrapBrain(
const overviewPath = join(vault, LEGACY_OVERVIEW_REL_PATH);
const overviewRel = LEGACY_OVERVIEW_REL_PATH;
mkdirSync(dirname(overviewPath), { recursive: true });
- const overviewBody = renderTemplate(
- readTemplate(LEGACY_OVERVIEW_TEMPLATE_PATH),
- buildSubstitutions(vault, DEFAULT_BRAIN_CONFIG),
- );
+ const overviewBody = renderLegacyOverview(vault);
const overviewExisted = existsSync(overviewPath);
atomicWriteFileSync(overviewPath, overviewBody);
if (overviewExisted) {
@@ -346,59 +325,6 @@ export function bootstrapBrain(
return { created, overwritten, skipped };
}
-/**
- * Read a template file from disk. Wrapped so a missing template (which
- * would indicate a broken build / packaging) surfaces with a clear
- * pointer rather than the bare `ENOENT` Node throws.
- */
-function readTemplate(path: string): string {
- try {
- return readFileSync(path, "utf8");
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- throw new Error(
- `Failed to load Brain template at ${path}: ${message}. ` +
- "This indicates a broken open-second-brain install β€” the " +
- "src/core/brain/templates/ directory must ship alongside init.ts.",
- );
- }
-}
-
-/**
- * Compute `{{key}}` substitutions for the current vault. Kept tiny on
- * purpose: the templates carry static prose and only need to thread a
- * couple of contextual values (vault name, schema version). Adding more
- * substitutions later is a one-line change here.
- */
-function buildSubstitutions(
- vault: string,
- config: BrainConfig,
-): ReadonlyMap<string, string> {
- return new Map<string, string>([
- ["vault_name", vaultDisplayName(vault)],
- ["schema_version", String(config.schema_version)],
- ]);
-}
-
-/**
- * Apply `{{key}}` substitutions to `template`. Unknown placeholders are
- * left intact so a typo surfaces in the rendered file (and in the
- * line-count test) rather than disappearing silently.
- */
-function renderTemplate(
- template: string,
- substitutions: ReadonlyMap<string, string>,
-): string {
- let out = template;
- for (const [key, value] of substitutions) {
- // Escape regex metachars in the key in case future keys carry
- // anything other than `[a-z_]`. Today they don't; defensive anyway.
- const pattern = new RegExp(`\\{\\{\\s*${escapeRegex(key)}\\s*\\}\\}`, "g");
- out = out.replace(pattern, value);
- }
- return out;
-}
-
/**
* Replace the `primary_agent: null` line in the default `_brain.yaml`
* body with the operator-supplied value, when provided. Trimmed,
@@ -418,14 +344,3 @@ function applyPrimaryAgentToYaml(
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`
- * if the vault path has no usable basename.
- */
-function vaultDisplayName(vault: string): string {
- const parts = vault.split(/[\\/]/).filter((p) => p.length > 0);
- const last = parts.length > 0 ? parts[parts.length - 1]! : "";
- return last !== "" ? last : "Second Brain";
-}
diff --git a/src/core/brain/manifest.ts b/src/core/brain/manifest.ts
new file mode 100644
index 00000000..0c18b5bc
--- /dev/null
+++ b/src/core/brain/manifest.ts
@@ -0,0 +1,325 @@
+/**
+ * SHA-256 file inventory over `Brain/` minus `.snapshots/`.
+ *
+ * Symlinks are dropped via `lstatSync` β€” a malicious snapshot archive
+ * planting a symlink under `Brain/` must not let the walker hash
+ * `/etc/passwd`. Output is sorted by path so two runs against
+ * identical bytes produce byte-identical JSON on disk.
+ */
+
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ lstatSync,
+ readFileSync,
+ readdirSync,
+} from "node:fs";
+import { join, relative } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { brainDirs } from "./paths.ts";
+import { isoSecond } from "./time.ts";
+
+export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;
+
+export interface BrainManifestEntry {
+ readonly sha256: string;
+ readonly size: number;
+}
+
+export interface BrainManifest {
+ readonly schema_version: typeof BRAIN_MANIFEST_SCHEMA_VERSION;
+ /** ISO-8601 UTC, second precision. */
+ readonly generated_at: string;
+ readonly brain_root: "Brain";
+ /** Keys are vault-relative paths under `Brain/`, sorted lexicographically. */
+ readonly files: Readonly<Record<string, BrainManifestEntry>>;
+}
+
+export interface BrainManifestDiffEntry {
+ readonly path: string;
+ readonly before: BrainManifestEntry | null;
+ readonly after: BrainManifestEntry | null;
+}
+
+export interface BrainManifestDiff {
+ readonly added: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly removed: ReadonlyArray<BrainManifestDiffEntry>;
+ readonly changed: ReadonlyArray<BrainManifestDiffEntry>;
+}
+
+// ---------- buildManifest --------------------------------------------------
+
+/**
+ * Walk `brainRoot` (the `<vault>/Brain/` directory) and hash every
+ * regular file. The caller is responsible for pointing at the
+ * `Brain/` directory itself β€” passing a vault root would silently
+ * include sibling content like `Daily/` or `AI Wiki/`.
+ *
+ * The walker is iterative (explicit stack) to keep recursion depth
+ * predictable on deeply-nested vault trees. Files are hashed
+ * one-at-a-time; Brain trees in practice stay well under 10 MB.
+ */
+export function buildManifest(brainRoot: string): BrainManifest {
+ const generated_at = isoSecond();
+ const collected = new Map<string, BrainManifestEntry>();
+
+ if (!existsSync(brainRoot)) {
+ return freezeManifest(generated_at, collected);
+ }
+
+ const stack: string[] = [brainRoot];
+ 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 {
+ st = lstatSync(abs);
+ } catch {
+ continue;
+ }
+ // Skip symlinks unconditionally β€” see module docstring.
+ if (st.isSymbolicLink()) continue;
+ const rel = relative(brainRoot, abs).replaceAll("\\", "/");
+ // `.snapshots/` is the snapshot family's home; including its
+ // contents in the manifest would either explode the listing or
+ // create a self-referential loop on rotate.
+ if (rel === ".snapshots" || rel.startsWith(".snapshots/")) continue;
+ // Defense-in-depth: a `..` path *segment* cannot legitimately
+ // appear inside a sane Brain tree. We anchor on the segment
+ // boundary so an otherwise-valid filename like `..notes.md`
+ // (legal as a Unix dotfile) is not silently dropped from
+ // manifest coverage.
+ if (rel === ".." || rel.startsWith("../")) continue;
+ if (st.isDirectory()) {
+ stack.push(abs);
+ continue;
+ }
+ if (!st.isFile()) continue;
+ collected.set(rel, hashFile(abs));
+ }
+ }
+
+ return freezeManifest(generated_at, collected);
+}
+
+function hashFile(abs: string): BrainManifestEntry {
+ // Derive size from the actually-hashed bytes rather than the
+ // pre-read `lstat` so the (sha256, size) pair always describes
+ // the same payload. If the file changed between stat and read,
+ // the stat-based size could disagree with the hash and confuse a
+ // future drift comparison.
+ const buf = readFileSync(abs);
+ const sha256 = createHash("sha256").update(buf).digest("hex");
+ return Object.freeze({ sha256, size: buf.byteLength });
+}
+
+function freezeManifest(
+ generated_at: string,
+ entries: Map<string, BrainManifestEntry>,
+): BrainManifest {
+ // Materialise in sorted key order so JSON.stringify yields stable
+ // bytes across runs.
+ const sorted = Array.from(entries.keys()).sort();
+ const files: Record<string, BrainManifestEntry> = {};
+ for (const k of sorted) files[k] = entries.get(k)!;
+ return Object.freeze({
+ schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
+ generated_at,
+ brain_root: "Brain",
+ files: Object.freeze(files),
+ });
+}
+
+// ---------- diffManifests --------------------------------------------------
+
+/**
+ * Compute the path-keyed diff between two manifests. Order of the
+ * arguments matters: `before β†’ after` is the conventional direction
+ * (left is the older state).
+ *
+ * Each bucket is sorted by `path` ascending for stable rendering.
+ */
+export function diffManifests(
+ before: BrainManifest,
+ after: BrainManifest,
+): BrainManifestDiff {
+ const added: BrainManifestDiffEntry[] = [];
+ const removed: BrainManifestDiffEntry[] = [];
+ const changed: BrainManifestDiffEntry[] = [];
+ const seen = new Set<string>();
+
+ for (const path of Object.keys(before.files)) {
+ seen.add(path);
+ const left = before.files[path]!;
+ const right = after.files[path];
+ if (right === undefined) {
+ removed.push({ path, before: left, after: null });
+ continue;
+ }
+ if (left.sha256 !== right.sha256 || left.size !== right.size) {
+ changed.push({ path, before: left, after: right });
+ }
+ }
+ for (const path of Object.keys(after.files)) {
+ if (seen.has(path)) continue;
+ const right = after.files[path]!;
+ added.push({ path, before: null, after: right });
+ }
+
+ const cmp = (a: BrainManifestDiffEntry, b: BrainManifestDiffEntry): number =>
+ a.path.localeCompare(b.path);
+ added.sort(cmp);
+ removed.sort(cmp);
+ changed.sort(cmp);
+ return Object.freeze({
+ added: Object.freeze(added),
+ removed: Object.freeze(removed),
+ changed: Object.freeze(changed),
+ });
+}
+
+/** Convenience: `true` when any of the three buckets is non-empty. */
+export function manifestDiffHasDrift(diff: BrainManifestDiff): boolean {
+ return (
+ diff.added.length > 0 ||
+ diff.removed.length > 0 ||
+ diff.changed.length > 0
+ );
+}
+
+/**
+ * Compact human-readable render of a manifest diff for the rollback
+ * drift-detection abort message. Sections are emitted only when their
+ * bucket is non-empty so the operator's eye lands on real differences.
+ */
+export function renderManifestDriftMarkdown(
+ diff: BrainManifestDiff,
+ runId: string,
+): string {
+ const lines: string[] = [
+ `Drift detected between snapshot '${runId}' and the live Brain/ tree.`,
+ `Pass --force-rollback to overwrite anyway.`,
+ ``,
+ ];
+ if (diff.added.length > 0) {
+ lines.push(`Added in live (${diff.added.length}):`);
+ for (const e of diff.added) lines.push(` - ${e.path}`);
+ }
+ if (diff.removed.length > 0) {
+ lines.push(`Removed from live (${diff.removed.length}):`);
+ for (const e of diff.removed) lines.push(` - ${e.path}`);
+ }
+ if (diff.changed.length > 0) {
+ lines.push(`Changed in live (${diff.changed.length}):`);
+ for (const e of diff.changed) lines.push(` - ${e.path}`);
+ }
+ return lines.join("\n");
+}
+
+/** Structured form of {@link renderManifestDriftMarkdown} for `--json`. */
+export function renderManifestDriftJson(
+ diff: BrainManifestDiff,
+ runId: string,
+): {
+ run_id: string;
+ drift: boolean;
+ added: ReadonlyArray<string>;
+ removed: ReadonlyArray<string>;
+ changed: ReadonlyArray<string>;
+} {
+ return {
+ run_id: runId,
+ drift: manifestDiffHasDrift(diff),
+ added: diff.added.map((e) => e.path),
+ removed: diff.removed.map((e) => e.path),
+ changed: diff.changed.map((e) => e.path),
+ };
+}
+
+// ---------- Sidecar I/O ----------------------------------------------------
+
+/**
+ * Path of the sidecar manifest for a given snapshot run id. Lives in
+ * `<vault>/Brain/.snapshots/<run-id>.manifest.json` so list and prune
+ * operations stay symmetrical with the archive itself.
+ */
+export function manifestSidecarPath(vault: string, runId: string): string {
+ return join(brainDirs(vault).snapshots, `${runId}.manifest.json`);
+}
+
+/**
+ * Read the sidecar manifest for `runId`. Returns `null` when the file
+ * is missing, unreadable, malformed JSON, or carries an unknown
+ * schema_version β€” callers fall back to the legacy "no drift check"
+ * path on a null return.
+ */
+export function readManifestSidecar(
+ vault: string,
+ runId: string,
+): BrainManifest | null {
+ const path = manifestSidecarPath(vault, runId);
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (parsed === null || typeof parsed !== "object") return null;
+ const obj = parsed as Record<string, unknown>;
+ if (obj["schema_version"] !== BRAIN_MANIFEST_SCHEMA_VERSION) return null;
+ if (obj["brain_root"] !== "Brain") return null;
+ if (typeof obj["generated_at"] !== "string") return null;
+ const files = obj["files"];
+ if (files === null || typeof files !== "object") return null;
+ // Validate every entry shape. The sidecar lives on the same
+ // distribution channel as the live tree (Syncthing, manual
+ // backups, hand-edited by an operator who lost their nerves) β€”
+ // we never trust the on-disk bytes without checking. A single
+ // malformed entry forces the whole manifest to `null` so the
+ // rollback path degrades to the legacy "no drift check" branch
+ // instead of crashing in `diffManifests` later.
+ const entries: Record<string, BrainManifestEntry> = {};
+ for (const [path, raw] of Object.entries(files as Record<string, unknown>)) {
+ if (raw === null || typeof raw !== "object") return null;
+ const entry = raw as Record<string, unknown>;
+ if (typeof entry["sha256"] !== "string") return null;
+ if (typeof entry["size"] !== "number") return null;
+ entries[path] = Object.freeze({
+ sha256: entry["sha256"],
+ size: entry["size"],
+ });
+ }
+ return Object.freeze({
+ schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
+ generated_at: obj["generated_at"],
+ brain_root: "Brain",
+ files: Object.freeze(entries),
+ });
+}
+
+/**
+ * Write the sidecar manifest atomically. Pretty-printed with two-space
+ * indent so a manual `cat` or `git diff` stays readable.
+ */
+export function writeManifestSidecar(
+ vault: string,
+ runId: string,
+ manifest: BrainManifest,
+): void {
+ const path = manifestSidecarPath(vault, runId);
+ atomicWriteFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
+}
diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.ts
index c30628c5..3b9962d4 100644
--- a/src/core/brain/snapshot.ts
+++ b/src/core/brain/snapshot.ts
@@ -49,6 +49,11 @@ import {
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
+import {
+ buildManifest,
+ manifestSidecarPath,
+ writeManifestSidecar,
+} from "./manifest.ts";
import { brainDirs, snapshotPath, validateRunId } from "./paths.ts";
// ----- Errors ---------------------------------------------------------------
@@ -94,6 +99,12 @@ export interface SnapshotInfo {
/** ISO-8601 UTC mtime of the archive file. */
readonly created_at: string;
readonly size_bytes: number;
+ /**
+ * Absolute path of the sidecar manifest, or `null` when the
+ * archive predates v0.10.6 (legacy snapshot without drift-check
+ * support). Rollback gracefully degrades on `null`.
+ */
+ readonly manifest_path: string | null;
}
export interface PruneSnapshotsResult {
@@ -222,6 +233,23 @@ export function createSnapshot(
runId,
);
}
+
+ // Sidecar manifest (Β§22 + Β§5-tail). Failure is non-fatal: the
+ // archive is the load-bearing artifact, and a snapshot without a
+ // manifest just degrades rollback's drift detection to the
+ // pre-v0.10.6 silent-overwrite path (with a warning at rollback
+ // time). The alternative β€” failing the whole snapshot because the
+ // sidecar could not be written β€” would block dream from making any
+ // progress on a read-only `.snapshots/` directory.
+ try {
+ writeManifestSidecar(vault, runId, buildManifest(dirs.brain));
+ } catch (err) {
+ process.stderr.write(
+ `warning: manifest sidecar write failed for snapshot ` +
+ `'${runId}': ${(err as Error).message ?? String(err)}; ` +
+ `rollback drift detection will be skipped for this snapshot.\n`,
+ );
+ }
return { path: outPath };
}
@@ -364,11 +392,13 @@ export function listSnapshots(vault: string): SnapshotInfo[] {
} catch {
continue;
}
+ const sidecar = manifestSidecarPath(vault, runId);
infos.push({
run_id: runId,
path: full,
created_at: new Date(st.mtimeMs).toISOString(),
size_bytes: st.size,
+ manifest_path: existsSync(sidecar) ? sidecar : null,
});
}
// Sort newest-first by mtime. We deliberately avoid lexicographic
@@ -407,6 +437,16 @@ export function pruneSnapshots(
// Best-effort: a snapshot we can't delete (permission error)
// stays put. The next dream run will try again.
}
+ // Remove the matching sidecar manifest if present. Independent
+ // try/catch: a missing sidecar (legacy snapshot from pre-v0.10.6)
+ // must not abort the prune of subsequent victims.
+ if (v.manifest_path !== null) {
+ try {
+ rmSync(v.manifest_path, { force: true });
+ } catch {
+ // Same rationale as above β€” best-effort.
+ }
+ }
}
return { deleted };
}
diff --git a/src/core/brain/templates.ts b/src/core/brain/templates.ts
new file mode 100644
index 00000000..ff1a6c7c
--- /dev/null
+++ b/src/core/brain/templates.ts
@@ -0,0 +1,136 @@
+/**
+ * Managed-template resolution and rendering primitives shared by
+ * `init.ts` (first install) and `upgrade.ts` (subsequent
+ * migrations). Keeping them here means the two paths cannot drift
+ * on which file is "managed" or how its `{{key}}` placeholders are
+ * filled.
+ *
+ * Unknown placeholders are left intact so a typo surfaces in the
+ * rendered file rather than disappearing silently.
+ */
+
+import { readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { escapeRegex } from "../strings.ts";
+import { DEFAULT_BRAIN_CONFIG } from "./policy.ts";
+import type { BrainConfig } from "./types.ts";
+
+// Template files ship in the same directory as the source so a future
+// bundled build that keeps assets alongside the JS output keeps
+// working without path surgery.
+const TEMPLATE_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "templates",
+);
+
+/** Operating manual rendered at `Brain/_BRAIN.md`. */
+export const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");
+
+/**
+ * Brain-first overview rendered at `AI Wiki/_OPEN_SECOND_BRAIN.md`.
+ * The legacy file's prior content is not preserved on render β€” the
+ * file is the agent's first-read surface and must match the
+ * release.
+ */
+export const LEGACY_OVERVIEW_TEMPLATE_PATH = join(
+ TEMPLATE_DIR,
+ "_OPEN_SECOND_BRAIN.md.tpl",
+);
+
+/** Vault-relative path of the legacy-overview target file. */
+export const LEGACY_OVERVIEW_REL_PATH = join("AI Wiki", "_OPEN_SECOND_BRAIN.md");
+
+/**
+ * Read a template file from disk. A missing template would indicate a
+ * broken open-second-brain install β€” the message names the canonical
+ * cause so the operator does not chase an opaque `ENOENT`.
+ */
+export function readTemplate(path: string): string {
+ try {
+ return readFileSync(path, "utf8");
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ throw new Error(
+ `Failed to load Brain template at ${path}: ${message}. ` +
+ "This indicates a broken open-second-brain install β€” the " +
+ "src/core/brain/templates/ directory must ship alongside templates.ts.",
+ );
+ }
+}
+
+/**
+ * Compute `{{key}}` substitutions for the given vault. Kept tiny on
+ * purpose; new substitutions are a one-line change here.
+ */
+export function buildSubstitutions(
+ vault: string,
+ config: BrainConfig = DEFAULT_BRAIN_CONFIG,
+): ReadonlyMap<string, string> {
+ return new Map<string, string>([
+ ["vault_name", vaultDisplayName(vault)],
+ ["schema_version", String(config.schema_version)],
+ ]);
+}
+
+/**
+ * Apply `{{key}}` substitutions to `template`. Unknown placeholders
+ * are left intact so a typo surfaces in the rendered file rather
+ * than disappearing silently.
+ */
+export function renderTemplate(
+ template: string,
+ substitutions: ReadonlyMap<string, string>,
+): string {
+ let out = template;
+ for (const [key, value] of substitutions) {
+ const pattern = new RegExp(`\\{\\{\\s*${escapeRegex(key)}\\s*\\}\\}`, "g");
+ // Function form keeps the substitution literal β€” string-form
+ // `replace` interprets `$&` / `$1` / `$n` / `$$` in `value` as
+ // backreference syntax. A vault name like `pay-$1` or
+ // `team-$everyone` would otherwise be silently mangled.
+ out = out.replace(pattern, () => value);
+ }
+ return out;
+}
+
+/**
+ * Render the operating manual the way the current release ships it
+ * for `vault`. Used by both `bootstrapBrain` (first write) and
+ * `planUpgrade` (drift check).
+ */
+export function renderBrainManual(
+ vault: string,
+ config: BrainConfig = DEFAULT_BRAIN_CONFIG,
+): string {
+ return renderTemplate(
+ readTemplate(BRAIN_MANUAL_TEMPLATE_PATH),
+ buildSubstitutions(vault, config),
+ );
+}
+
+/**
+ * Render the Brain-first overview the way the current release ships
+ * it for `vault`. Used by both `bootstrapBrain` and `planUpgrade`.
+ */
+export function renderLegacyOverview(
+ vault: string,
+ config: BrainConfig = DEFAULT_BRAIN_CONFIG,
+): string {
+ return renderTemplate(
+ readTemplate(LEGACY_OVERVIEW_TEMPLATE_PATH),
+ buildSubstitutions(vault, config),
+ );
+}
+
+/**
+ * Best-effort display name for the vault: the trailing directory name
+ * with separators stripped. Falls back to the literal `Second Brain`
+ * if the vault path has no usable basename.
+ */
+export function vaultDisplayName(vault: string): string {
+ const parts = vault.split(/[\\/]/).filter((p) => p.length > 0);
+ const last = parts.length > 0 ? parts[parts.length - 1]! : "";
+ return last !== "" ? last : "Second Brain";
+}
diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tpl
index 72aaace0..e56b0736 100644
--- a/src/core/brain/templates/_BRAIN.md.tpl
+++ b/src/core/brain/templates/_BRAIN.md.tpl
@@ -133,8 +133,19 @@ them as part of normal agent work.
preference requires `--yes` and prints a warning.
- `o2b brain rollback <run_id>` β€” restore Brain from a snapshot.
Interactive by default; `--list` enumerates available snapshots.
+ From v0.10.6 a snapshot ships with a sha256 sidecar manifest so
+ rollback aborts when the live tree drifted from the snapshot moment;
+ pass `--force-rollback` to override.
- `o2b brain pin <pref-id>` / `unpin <pref-id>` β€” protect a preference
from automatic retirement (still subject to explicit reject).
+- `o2b brain upgrade` β€” migrate the release-owned files (`_brain.yaml`,
+ `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward when a new
+ open-second-brain version ships. `--dry-run` (default) prints a
+ per-file plan; `--apply` rewrites the files after taking a snapshot
+ named `upgrade-<ts>`.
+- `o2b brain export --format json|llms-txt` β€” read-only dump of active
+ preferences (`confirmed | unconfirmed | quarantine`) for backup,
+ prompt injection, or sharing.
The full CLI surface is documented in `docs/plans/2026-05-15-brain-observing-memory.md`
section 9; the MCP tool surface mirrors it for the most common verbs
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 66a51636..18da7b97 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -173,6 +173,12 @@ export const BRAIN_LOG_EVENT_KIND = {
* and the summed counters as raw integers for audit grepping.
*/
merge: "merge",
+ /**
+ * `upgrade` (Β§22) β€” operator ran `o2b brain upgrade --apply`. Payload
+ * carries the pre-apply snapshot run id, agent identity, and the
+ * vault-relative paths of every managed file that was rewritten.
+ */
+ upgrade: "upgrade",
} as const;
export type BrainLogEventKind =
(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -508,6 +514,17 @@ export interface BrainMergeLogEvent extends BrainLogEventBase {
readonly agent: string;
}
+/**
+ * `upgrade` entry β€” operator ran `o2b brain upgrade --apply`.
+ * Payload carries the upgrade run id (`upgrade-<ts>`), agent
+ * identity, the pre-apply snapshot path, and the vault-relative
+ * paths of every managed file the run rewrote.
+ */
+export interface BrainUpgradeLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.upgrade;
+ readonly run_id: string;
+}
+
/** Discriminated union of every concrete log event type. */
export type BrainLogEvent =
| BrainDreamLogEvent
@@ -525,7 +542,8 @@ export type BrainLogEvent =
| BrainScanInlineLogEvent
| BrainImportSessionLogEvent
| BrainMigrateFrontmatterLogEvent
- | BrainMergeLogEvent;
+ | BrainMergeLogEvent
+ | BrainUpgradeLogEvent;
// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------
diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.ts
new file mode 100644
index 00000000..9fda7926
--- /dev/null
+++ b/src/core/brain/upgrade.ts
@@ -0,0 +1,564 @@
+/**
+ * Brain managed-file upgrade for the three release-owned files in
+ * `Brain/` (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`).
+ * User-owned content (`preferences/`, `retired/`, `inbox/`, `log/`)
+ * is never touched.
+ *
+ * Key design choice: `_brain.yaml` is text-walked rather than
+ * re-serialised through the strict parser, because the live file
+ * carries hand-written comments the parser drops. Existing values,
+ * ordering, and comments stay untouched; only missing schema keys
+ * and sections are appended. A malformed source surfaces as
+ * `status: "error"` so `--apply` refuses to half-merge.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { defaultConfigPath, resolveAgentName } from "../config.ts";
+import { appendLogEvent } from "./log.ts";
+import {
+ brainConfigPath,
+ brainManualPath,
+ vaultRelative,
+} from "./paths.ts";
+import {
+ BrainConfigError,
+ DEFAULT_BRAIN_CONFIG_YAML,
+ loadBrainConfig,
+} from "./policy.ts";
+import { createSnapshot } from "./snapshot.ts";
+import {
+ LEGACY_OVERVIEW_REL_PATH,
+ renderBrainManual,
+ renderLegacyOverview,
+} from "./templates.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+
+// ----- Public types --------------------------------------------------------
+
+export type UpgradeFileStatus = "noop" | "update" | "error";
+
+export interface UpgradeFilePlan {
+ /** Vault-relative path, e.g. `Brain/_brain.yaml`. */
+ readonly path: string;
+ readonly status: UpgradeFileStatus;
+ /** Current bytes on disk. Empty when the file does not exist yet. */
+ readonly before: string;
+ /** Target bytes for the file under the current release. */
+ readonly after: string;
+ /**
+ * Diagnostic message when `status === "error"`. Empty for `noop`
+ * and `update`.
+ */
+ readonly error: string;
+}
+
+export interface UpgradePlan {
+ readonly files: ReadonlyArray<UpgradeFilePlan>;
+ /** Count of `status === "update"` files. */
+ readonly pending: number;
+ /** Count of `status === "error"` files. */
+ readonly errors: number;
+}
+
+export interface UpgradeApplyResult {
+ readonly run_id: string;
+ readonly snapshot_path: string;
+ /** Vault-relative paths of files rewritten by this run. */
+ readonly files_updated: ReadonlyArray<string>;
+}
+
+export class BrainUpgradeError extends Error {
+ /**
+ * The `upgrade-<ts>` snapshot run id when the failure happened
+ * after the pre-apply snapshot was taken. `null` for failures
+ * during planning (malformed `_brain.yaml`, read errors) β€” those
+ * never wrote anything, so there is nothing to roll back.
+ */
+ readonly runId: string | null;
+
+ constructor(message: string, runId: string | null = null) {
+ super(message);
+ this.name = "BrainUpgradeError";
+ this.runId = runId;
+ }
+}
+
+// ----- planUpgrade ---------------------------------------------------------
+
+/**
+ * Compute the upgrade plan for `vault` without touching disk.
+ *
+ * Order of files in `plan.files` is fixed: `_brain.yaml`,
+ * `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`. This is the order the CLI
+ * renders the per-file diff so the operator's eye lands at the same
+ * spot on every run.
+ */
+export function planUpgrade(vault: string): UpgradePlan {
+ const files: UpgradeFilePlan[] = [
+ planBrainYaml(vault),
+ planManagedPath(
+ vault,
+ brainManualPath(vault),
+ vaultRelative(brainManualPath(vault), vault),
+ () => renderBrainManual(vault),
+ ),
+ planManagedPath(
+ vault,
+ join(vault, LEGACY_OVERVIEW_REL_PATH),
+ LEGACY_OVERVIEW_REL_PATH,
+ () => renderLegacyOverview(vault),
+ ),
+ ];
+ const pending = files.filter((f) => f.status === "update").length;
+ const errors = files.filter((f) => f.status === "error").length;
+ return Object.freeze({
+ files: Object.freeze(files),
+ pending,
+ errors,
+ });
+}
+
+// ----- applyUpgrade --------------------------------------------------------
+
+/**
+ * Apply every pending update from {@link planUpgrade}.
+ *
+ * Sequence:
+ * 1. Compute the plan. If `errors > 0`, throw β€” never touch disk
+ * when the schema source is malformed.
+ * 2. If `pending === 0`, return early without taking a snapshot or
+ * appending a log row. Idempotent re-run is free.
+ * 3. `createSnapshot(vault, run_id)` β€” sidecar manifest comes
+ * along automatically. The run id includes a `upgrade-` prefix
+ * so the operator can spot upgrade snapshots in `--list`.
+ * 4. Write each `update` file via `atomicWriteFileSync`.
+ * 5. Append a `BRAIN_LOG_EVENT_KIND.upgrade` event.
+ *
+ * On any write failure mid-step we throw β€” the snapshot already
+ * persisted is the recovery path (`o2b brain rollback upgrade-<ts>`).
+ */
+export function applyUpgrade(
+ vault: string,
+ opts: { agent?: string; now?: Date } = {},
+): UpgradeApplyResult {
+ const plan = planUpgrade(vault);
+ if (plan.errors > 0) {
+ const messages = plan.files
+ .filter((f) => f.status === "error")
+ .map((f) => `${f.path}: ${f.error}`)
+ .join("; ");
+ throw new BrainUpgradeError(
+ `upgrade aborted: ${plan.errors} file(s) failed to plan β€” ${messages}`,
+ );
+ }
+ if (plan.pending === 0) {
+ return Object.freeze({
+ run_id: "",
+ snapshot_path: "",
+ files_updated: Object.freeze([] as ReadonlyArray<string>),
+ });
+ }
+
+ const now = opts.now ?? new Date();
+ const runId = `upgrade-${isoSecondCompact(now)}`;
+ const snap = createSnapshot(vault, runId);
+
+ const updated: string[] = [];
+ for (const file of plan.files) {
+ if (file.status !== "update") continue;
+ try {
+ atomicWriteFileSync(join(vault, file.path), file.after);
+ } catch (err) {
+ // Mid-apply failure: one or more files have already been
+ // rewritten under the new release, the rest still match the
+ // old. The pre-apply snapshot is the recovery path β€” embed
+ // its run id so the operator does not need to grep
+ // `.snapshots/` to find it.
+ throw new BrainUpgradeError(
+ `upgrade aborted mid-apply at ${file.path}: ` +
+ `${(err as Error).message ?? String(err)}. ` +
+ `${updated.length} file(s) already rewritten; ` +
+ `roll back via \`o2b brain rollback ${runId} --force-rollback\` ` +
+ `before re-running.`,
+ runId,
+ );
+ }
+ updated.push(file.path);
+ }
+
+ const agent =
+ opts.agent ?? resolveAgentName(defaultConfigPathOrEmpty());
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.upgrade,
+ body: {
+ run_id: runId,
+ agent,
+ snapshot: snap.path,
+ files: updated,
+ },
+ });
+ } catch (err) {
+ // Audit-only failure β€” the files are already on disk. Surface so
+ // the operator can record manually if needed.
+ process.stderr.write(
+ `warning: append upgrade log failed: ${(err as Error).message}\n`,
+ );
+ }
+
+ return Object.freeze({
+ run_id: runId,
+ snapshot_path: snap.path,
+ files_updated: Object.freeze(updated),
+ });
+}
+
+// ----- Internal helpers ----------------------------------------------------
+
+function planBrainYaml(vault: string): UpgradeFilePlan {
+ const path = brainConfigPath(vault);
+ const rel = vaultRelative(path, vault);
+ let before: string;
+ try {
+ before = readFileSync(path, "utf8");
+ } catch (err) {
+ const e = err as NodeJS.ErrnoException;
+ if (e.code === "ENOENT") {
+ // The file vanished from a `o2b brain init`-bootstrapped
+ // vault. Same recovery shape as `planManagedPath`: treat
+ // missing as an update from empty so `--apply` restores the
+ // canonical body. Refusing here would block every other
+ // managed-file update behind one missing config.
+ return makeUpdate(rel, "", DEFAULT_BRAIN_CONFIG_YAML);
+ }
+ return makeError(rel, `read failed: ${e.message ?? String(err)}`);
+ }
+ // Validate the live file with the strict parser. A malformed source
+ // is surfaced as `error` so the operator fixes it manually before
+ // `--apply` runs β€” a half-merged YAML is worse than a refusal.
+ try {
+ loadBrainConfig(vault);
+ } catch (err) {
+ if (err instanceof BrainConfigError) {
+ return makeError(rel, err.message);
+ }
+ return makeError(rel, (err as Error).message ?? String(err));
+ }
+ const after = mergeBrainYaml(before, DEFAULT_BRAIN_CONFIG_YAML);
+ if (after === before) {
+ return makeNoop(rel);
+ }
+ return makeUpdate(rel, before, after);
+}
+
+function planManagedPath(
+ _vault: string,
+ absolutePath: string,
+ relPath: string,
+ renderTarget: () => string,
+): UpgradeFilePlan {
+ const after = renderTarget();
+ if (!existsSync(absolutePath)) {
+ // File missing entirely: an upgrade should restore it. Treat as
+ // update with empty `before` so the diff shows the full body.
+ return makeUpdate(relPath, "", after);
+ }
+ let before: string;
+ try {
+ before = readFileSync(absolutePath, "utf8");
+ } catch (err) {
+ return makeError(relPath, `read failed: ${(err as Error).message}`);
+ }
+ if (before === after) {
+ return makeNoop(relPath);
+ }
+ return makeUpdate(relPath, before, after);
+}
+
+function makeNoop(path: string): UpgradeFilePlan {
+ // `noop` rows never expose `before` / `after` bodies β€” the CLI
+ // diff renderer and JSON output only consult `.length`/`.status`
+ // for noops, so carrying the full file body here would waste memory
+ // on every plan invocation (planUpgrade is read-only and may be
+ // called from JSON/CI paths repeatedly).
+ return Object.freeze({
+ path,
+ status: "noop" as const,
+ before: "",
+ after: "",
+ error: "",
+ });
+}
+
+function makeUpdate(
+ path: string,
+ before: string,
+ after: string,
+): UpgradeFilePlan {
+ return Object.freeze({
+ path,
+ status: "update" as const,
+ before,
+ after,
+ error: "",
+ });
+}
+
+function makeError(path: string, message: string): UpgradeFilePlan {
+ return Object.freeze({
+ path,
+ status: "error" as const,
+ before: "",
+ after: "",
+ error: message,
+ });
+}
+
+/**
+ * Compact ISO without colons or `Z` suffix so the run id is
+ * filesystem-safe under every snapshot validator.
+ */
+function isoSecondCompact(d: Date): string {
+ return isoSecond(d).replace(/[:Z]/g, "");
+}
+
+/**
+ * `applyUpgrade` is callable from tests that may not have set up a
+ * real plugin config. Fall back to an empty path string so
+ * `resolveAgentName` returns its built-in default rather than
+ * throwing on a missing file.
+ */
+function defaultConfigPathOrEmpty(): string {
+ try {
+ return defaultConfigPath();
+ } catch {
+ return "";
+ }
+}
+
+// ----- `_brain.yaml` text-level merge --------------------------------------
+
+/**
+ * Append missing top-level sections / scalars and missing nested keys
+ * from `target` (the default YAML the current release ships) into a
+ * copy of `live` (the user's current file). Existing values are
+ * never rewritten; comments and ordering are preserved.
+ *
+ * Algorithm:
+ * 1. Walk `target` block-by-block. A top-level section is a key
+ * followed by `:` at column 0; a top-level scalar is a key
+ * followed by `: <value>` at column 0.
+ * 2. For each top-level scalar in `target`: if the same key
+ * appears at column 0 in `live`, leave it alone. Otherwise
+ * append the line at end-of-file.
+ * 3. For each top-level section in `target`: if the section
+ * header is absent from `live`, append the whole block
+ * (header + indented body + leading comment block, if any) at
+ * end-of-file. If present, compute the missing nested keys
+ * (keys present in the target's block but absent in live's
+ * block) and insert each missing line at the end of the live
+ * block.
+ *
+ * The merge is purely additive β€” we never delete, reorder, or
+ * rewrite. Comment-only lines and blank lines from `target` are
+ * carried along with their adjacent section so the inserted block
+ * reads the same as the canonical template.
+ */
+export function mergeBrainYaml(live: string, target: string): string {
+ const targetBlocks = parseYamlBlocks(target);
+ const liveBlocks = parseYamlBlocks(live);
+ const liveByName = new Map(liveBlocks.map((b) => [b.name, b]));
+ const liveScalars = new Set(
+ liveBlocks.filter((b) => b.kind === "scalar").map((b) => b.name),
+ );
+ const liveSections = new Map(
+ liveBlocks
+ .filter((b) => b.kind === "section")
+ .map((b) => [b.name, b] as const),
+ );
+
+ let result = live;
+ // Pass 1: append missing top-level scalars / sections.
+ for (const tb of targetBlocks) {
+ if (tb.kind === "scalar" && !liveScalars.has(tb.name)) {
+ result = appendBlockAtEnd(result, tb.text);
+ } else if (tb.kind === "section" && !liveSections.has(tb.name)) {
+ result = appendBlockAtEnd(result, tb.text);
+ }
+ }
+
+ // Pass 2: for each section present in both, splice missing nested
+ // keys into the existing live block.
+ for (const tb of targetBlocks) {
+ if (tb.kind !== "section") continue;
+ const live = liveByName.get(tb.name);
+ if (!live || live.kind !== "section") continue;
+ const liveKeys = new Set(live.nestedKeys);
+ // Only consider lines that are real key declarations. Blank
+ // lines and comment lines return an empty `extractKey`, which
+ // would otherwise look "missing from liveKeys" and inflate the
+ // diff with whitespace.
+ const missing = tb.nestedLines.filter((line) => {
+ const key = extractKey(line);
+ return key.length > 0 && !liveKeys.has(key);
+ });
+ if (missing.length === 0) continue;
+ result = insertLinesAtSectionEnd(result, tb.name, missing);
+ }
+
+ return result;
+}
+
+interface YamlBlock {
+ readonly kind: "scalar" | "section" | "comment";
+ /** Identifier key for scalar/section; `""` for comment-only block. */
+ readonly name: string;
+ /** Block source text including trailing newline. */
+ readonly text: string;
+ /** Lines under a section (indented), in source order. Empty for scalar / comment. */
+ readonly nestedLines: ReadonlyArray<string>;
+ /** Convenience: keys extracted from `nestedLines` (one per indented key line). */
+ readonly nestedKeys: ReadonlyArray<string>;
+}
+
+function parseYamlBlocks(yaml: string): YamlBlock[] {
+ const lines = yaml.split("\n");
+ const blocks: YamlBlock[] = [];
+ let i = 0;
+ // Buffer comment / blank lines so they attach to the next block
+ // header β€” that way an inserted section copies its leading
+ // commentary verbatim.
+ let preface: string[] = [];
+ while (i < lines.length) {
+ const line = lines[i]!;
+ if (line.trimEnd() === "" || /^\s*#/.test(line)) {
+ preface.push(line);
+ i++;
+ continue;
+ }
+ const m = /^([A-Za-z_][A-Za-z0-9_]*):(.*)$/.exec(line);
+ if (m && !line.startsWith(" ") && !line.startsWith("\t")) {
+ const key = m[1]!;
+ const rest = m[2]!;
+ const trimmedRest = rest.trim();
+ // Scalar: `key: value`. Section: `key:` (rest is empty after
+ // colon) followed by indented continuation.
+ if (trimmedRest === "") {
+ // Section header. Consume continuation lines (indented or blank).
+ const start = i;
+ i++;
+ const nestedLines: string[] = [];
+ while (i < lines.length) {
+ const next = lines[i]!;
+ if (next.startsWith(" ") || next.startsWith("\t")) {
+ nestedLines.push(next);
+ i++;
+ continue;
+ }
+ if (next.trim() === "") {
+ // Trailing blank line belongs to the section block.
+ nestedLines.push(next);
+ i++;
+ // The next non-blank determines whether we are still
+ // inside the section.
+ if (i < lines.length && !/^[ \t]/.test(lines[i]!)) break;
+ continue;
+ }
+ break;
+ }
+ const text =
+ [...preface, lines[start]!, ...nestedLines].join("\n") + "\n";
+ preface = [];
+ blocks.push({
+ kind: "section",
+ name: key,
+ text,
+ nestedLines: nestedLines.filter((l) => l.trim() !== ""),
+ nestedKeys: nestedLines
+ .filter((l) => /^\s+[A-Za-z_]/.test(l))
+ .map(extractKey),
+ });
+ continue;
+ }
+ // Scalar at column 0.
+ const text = [...preface, line].join("\n") + "\n";
+ preface = [];
+ blocks.push({
+ kind: "scalar",
+ name: key,
+ text,
+ nestedLines: [],
+ nestedKeys: [],
+ });
+ i++;
+ continue;
+ }
+ // Unrecognised top-level line (e.g. a stray non-key). Treat as
+ // commentary so we never silently drop it.
+ preface.push(line);
+ i++;
+ }
+ if (preface.length > 0) {
+ blocks.push({
+ kind: "comment",
+ name: "",
+ text: preface.join("\n") + (preface.at(-1) === "" ? "" : "\n"),
+ nestedLines: [],
+ nestedKeys: [],
+ });
+ }
+ return blocks;
+}
+
+function extractKey(indentedLine: string): string {
+ const m = /^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:/.exec(indentedLine);
+ return m ? m[1]! : "";
+}
+
+function appendBlockAtEnd(yaml: string, block: string): string {
+ // Ensure exactly one blank line between the existing content and
+ // the new block, and exactly one trailing newline overall.
+ const trimmedTail = yaml.replace(/\s+$/, "");
+ const trimmedBlock = block.replace(/\s+$/, "");
+ return `${trimmedTail}\n\n${trimmedBlock}\n`;
+}
+
+function insertLinesAtSectionEnd(
+ yaml: string,
+ sectionName: string,
+ newLines: ReadonlyArray<string>,
+): string {
+ const lines = yaml.split("\n");
+ const header = `${sectionName}:`;
+ const headerIdx = lines.findIndex(
+ (l) => l === header || l.startsWith(`${header} `) || l === header.trimEnd(),
+ );
+ if (headerIdx === -1) {
+ // Section not in live (shouldn't happen given the caller guard);
+ // append the lines at end-of-file as a fallback.
+ return appendBlockAtEnd(yaml, newLines.join("\n"));
+ }
+ // Find the end of the section: first column-0 non-blank line after
+ // the header.
+ let end = headerIdx + 1;
+ while (end < lines.length) {
+ const l = lines[end]!;
+ if (l !== "" && !/^[ \t]/.test(l)) break;
+ end++;
+ }
+ // Insert the new keys right before `end`, after stripping any
+ // trailing blank lines inside the section so the inserted lines
+ // land flush with the existing keys.
+ let insertAt = end;
+ while (insertAt > headerIdx + 1 && lines[insertAt - 1]!.trim() === "") {
+ insertAt--;
+ }
+ const before = lines.slice(0, insertAt);
+ const after = lines.slice(insertAt);
+ return [...before, ...newLines, ...after].join("\n");
+}
diff --git a/templates/brain-explorer.html b/templates/brain-explorer.html
index d6b405a6..3b8da48d 100644
--- a/templates/brain-explorer.html
+++ b/templates/brain-explorer.html
@@ -62,6 +62,17 @@
ul.edge-list li { padding: 2px 0; }
ul.edge-list .kind { color: var(--muted); font-size: 11px; }
button.id-copy { font-size: 11px; padding: 1px 6px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--text); cursor: pointer; }
+ /* Β§14 polish: keyboard-accessible node listbox. The canvas remains
+ the visual surface; this listbox is the accessible source of
+ truth so screen readers and keyboard-only operators can
+ navigate the graph. */
+ #node-list { list-style: none; margin: 0 0 6px 0; padding: 0; max-height: 220px; overflow: auto; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); }
+ #node-list li { padding: 4px 8px; cursor: pointer; font-size: 12px; border-bottom: 1px solid transparent; }
+ #node-list li .topic { color: var(--muted); font-size: 11px; margin-right: 4px; }
+ #node-list li[aria-selected="true"] { background: var(--accent); color: #fff; }
+ #node-list li[aria-selected="true"] .topic { color: rgba(255,255,255,0.85); }
+ #node-list:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
+ #node-list-empty { padding: 6px 8px; color: var(--muted); font-style: italic; font-size: 12px; }
</style>
</head>
<body>
@@ -90,7 +101,19 @@
<canvas id="canvas"></canvas>
</main>
<aside id="details" class="right">
- <p class="panel-empty">Select a node to inspect.</p>
+ <h3>Nodes</h3>
+ <ul
+ id="node-list"
+ role="listbox"
+ tabindex="0"
+ aria-label="Brain preferences"
+ aria-activedescendant=""
+ ></ul>
+ <button id="reset-layout" type="button" class="id-copy">Reset layout</button>
+ <hr />
+ <div id="details-body">
+ <p class="panel-empty">Select a node to inspect.</p>
+ </div>
</aside>
<script type="application/json" id="brain-data">__GRAPH_JSON__</script>
@@ -103,7 +126,7 @@
try {
graph = JSON.parse(dataEl.textContent);
} catch (e) {
- document.getElementById("details").textContent = "Failed to parse graph data: " + e.message;
+ document.getElementById("details-body").textContent = "Failed to parse graph data: " + e.message;
return;
}
@@ -151,6 +174,35 @@
const statusFilters = new Set(["confirmed", "unconfirmed", "quarantine", "retired"]);
let searchTerm = "";
+ // Β§14 polish: layout + filter persistence (localStorage). Per-vault
+ // key so multiple explorer tabs against different vaults stay
+ // separate. Stored shape:
+ // { schema: 1, positions: { id: [x, y] }, filters: { status: [...], search: string } }
+ // Failures (private mode, quota, malformed JSON) degrade silently
+ // to a non-persistent session.
+ const STORAGE_KEY =
+ "osb-explorer-layout:" + (graph.vault_basename || "default");
+ const STORAGE_SCHEMA = 1;
+ let storedLayout = null;
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (raw !== null) {
+ const parsed = JSON.parse(raw);
+ if (parsed && parsed.schema === STORAGE_SCHEMA) storedLayout = parsed;
+ }
+ } catch (e) {
+ storedLayout = null;
+ }
+ if (storedLayout && storedLayout.filters) {
+ if (Array.isArray(storedLayout.filters.status)) {
+ statusFilters.clear();
+ for (const s of storedLayout.filters.status) statusFilters.add(s);
+ }
+ if (typeof storedLayout.filters.search === "string") {
+ searchTerm = storedLayout.filters.search;
+ }
+ }
+
// ---- Layout -----------------------------------------------------------
function placeInitial() {
const w = canvas.width;
@@ -172,6 +224,54 @@
n.x = t.x + (Math.random() - 0.5) * 80;
n.y = t.y + (Math.random() - 0.5) * 80;
}
+ // Overlay stored positions on top of the topic-based seed. New
+ // nodes (no entry in the stored map) keep their topic-anchored
+ // placement; previously-seen nodes warm-start to the last
+ // observed location so the layout no longer "jumps" between
+ // reloads. We zero velocity so the physics relaxes from rest.
+ if (storedLayout && storedLayout.positions) {
+ for (const n of nodes) {
+ const stored = storedLayout.positions[n.id];
+ if (Array.isArray(stored) && stored.length === 2
+ && Number.isFinite(stored[0]) && Number.isFinite(stored[1])) {
+ n.x = stored[0];
+ n.y = stored[1];
+ n.vx = 0;
+ n.vy = 0;
+ }
+ }
+ }
+ }
+
+ function saveLayout() {
+ try {
+ const positions = {};
+ for (const n of nodes) {
+ if (Number.isFinite(n.x) && Number.isFinite(n.y)) {
+ positions[n.id] = [Math.round(n.x * 10) / 10, Math.round(n.y * 10) / 10];
+ }
+ }
+ const payload = {
+ schema: STORAGE_SCHEMA,
+ positions,
+ filters: {
+ status: Array.from(statusFilters),
+ search: searchTerm,
+ },
+ };
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
+ } catch (e) {
+ // Quota or disabled storage β€” non-persistent session.
+ }
+ }
+
+ let saveTimer = null;
+ function scheduleSave(delayMs) {
+ if (saveTimer !== null) clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ saveTimer = null;
+ saveLayout();
+ }, delayMs);
}
const K_TOPIC = 0.006;
@@ -313,7 +413,7 @@
}
function renderPanel(n) {
- const root = document.getElementById("details");
+ const root = document.getElementById("details-body");
if (!n) {
root.innerHTML = '<p class="panel-empty">Select a node to inspect.</p>';
return;
@@ -358,6 +458,119 @@
|| n.id.toLowerCase().includes(term);
n.visible = statusOk && textOk;
}
+ rebuildVisibleSorted();
+ scheduleListRender();
+ }
+
+ // ---- Listbox (keyboard-accessible mirror of the canvas) --------------
+ // The visible nodes are also presented as a focusable <ul role="listbox">.
+ // Pointer users keep the canvas; keyboard and screen reader users get
+ // the listbox. Both surfaces call `selectNode(id)` so state stays in
+ // lockstep across input devices.
+ // `visibleSortedCache` is rebuilt by `applyFilters` and consumed by
+ // `renderNodeList` / `moveListboxFocus` β€” saves an O(N log N) sort
+ // on every Arrow key on large vaults.
+ let visibleSortedCache = [];
+ let renderNodeListPending = false;
+
+ function escHtml(s) {
+ return String(s).replace(/[&<>"]/g, (c) => ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ }[c]));
+ }
+
+ function rebuildVisibleSorted() {
+ visibleSortedCache = nodes
+ .filter((n) => n.visible)
+ .slice()
+ .sort((a, b) => {
+ const t = a.topic.localeCompare(b.topic);
+ return t !== 0 ? t : a.id.localeCompare(b.id);
+ });
+ }
+
+ function renderNodeList() {
+ const list = document.getElementById("node-list");
+ const visible = visibleSortedCache;
+ if (visible.length === 0) {
+ list.innerHTML = '<li id="node-list-empty">No matching nodes.</li>';
+ list.setAttribute("aria-activedescendant", "");
+ return;
+ }
+ list.innerHTML = visible
+ .map((n) => {
+ const selected = n.id === selectedId ? ' aria-selected="true"' : ' aria-selected="false"';
+ const title = n.principle.length > 80 ? n.principle.slice(0, 77) + "..." : n.principle;
+ return (
+ '<li role="option" id="node-opt-' + escHtml(n.id) + '"' + selected +
+ ' data-node-id="' + escHtml(n.id) + '">' +
+ '<span class="topic">' + escHtml(n.topic) + '</span>' +
+ escHtml(title) +
+ '</li>'
+ );
+ })
+ .join("");
+ list.setAttribute(
+ "aria-activedescendant",
+ selectedId ? "node-opt-" + selectedId : "",
+ );
+ // Bind per-item click handlers via event delegation (cheap and
+ // survives the full re-render above).
+ list.onclick = (ev) => {
+ const li = ev.target.closest("li[data-node-id]");
+ if (!li) return;
+ selectNode(li.getAttribute("data-node-id"));
+ };
+ }
+
+ // Defer the listbox rebuild to the next animation frame so a held-
+ // down filter key only re-renders the <ul> once per paint instead
+ // of per keystroke. The canvas-side render is on its own rAF loop
+ // and is unaffected.
+ function scheduleListRender() {
+ if (renderNodeListPending) return;
+ renderNodeListPending = true;
+ requestAnimationFrame(() => {
+ renderNodeListPending = false;
+ renderNodeList();
+ });
+ }
+
+ function selectNode(id) {
+ selectedId = id || null;
+ const n = id ? nodeById.get(id) : null;
+ renderPanel(n);
+ // Mirror selection into the listbox without rebuilding the full
+ // DOM (cheaper, preserves scroll position).
+ const list = document.getElementById("node-list");
+ for (const li of list.querySelectorAll('li[data-node-id]')) {
+ li.setAttribute("aria-selected", li.getAttribute("data-node-id") === id ? "true" : "false");
+ }
+ list.setAttribute("aria-activedescendant", id ? "node-opt-" + id : "");
+ if (id) {
+ const focused = list.querySelector('li[data-node-id="' + id + '"]');
+ if (focused && focused.scrollIntoView) {
+ focused.scrollIntoView({ block: "nearest" });
+ }
+ }
+ }
+
+ function moveListboxFocus(delta) {
+ const visible = visibleSortedCache;
+ if (visible.length === 0) return;
+ const cur = selectedId
+ ? visible.findIndex((n) => n.id === selectedId)
+ : -1;
+ let next;
+ if (cur === -1) {
+ next = delta > 0 ? 0 : visible.length - 1;
+ } else {
+ next = (cur + delta + visible.length) % visible.length;
+ }
+ selectNode(visible[next].id);
}
// ---- Wire up DOM events ----------------------------------------------
@@ -380,13 +593,66 @@
const x = e.clientX - r.left;
const y = e.clientY - r.top;
const n = findNode(x, y);
- selectedId = n ? n.id : null;
- renderPanel(n);
+ selectNode(n ? n.id : null);
});
- document.getElementById("search").addEventListener("input", (e) => {
+ // Β§14 polish: keyboard handlers on the listbox. The listbox is
+ // `tabindex="0"`, so it joins the natural tab order after the
+ // search input.
+ const nodeList = document.getElementById("node-list");
+ nodeList.addEventListener("keydown", (e) => {
+ switch (e.key) {
+ case "ArrowDown":
+ e.preventDefault();
+ moveListboxFocus(+1);
+ break;
+ case "ArrowUp":
+ e.preventDefault();
+ moveListboxFocus(-1);
+ break;
+ case "Home":
+ e.preventDefault();
+ if (visibleSortedCache.length > 0) {
+ selectNode(visibleSortedCache[0].id);
+ }
+ break;
+ case "End":
+ e.preventDefault();
+ if (visibleSortedCache.length > 0) {
+ selectNode(visibleSortedCache[visibleSortedCache.length - 1].id);
+ }
+ break;
+ case "Enter":
+ case " ":
+ // Enter / Space commit on the currently focused option. The
+ // visual / panel state already follows focus, so this is a
+ // no-op when something is already selected β€” but we keep the
+ // explicit handler so screen-readers announce the commit.
+ e.preventDefault();
+ if (selectedId) selectNode(selectedId);
+ break;
+ case "Escape":
+ e.preventDefault();
+ selectNode(null);
+ break;
+ default:
+ break;
+ }
+ });
+
+ // Hydrate the search box and status checkboxes from stored filters
+ // before wiring listeners β€” otherwise the first reload still flashes
+ // the unchecked default.
+ const searchInput = document.getElementById("search");
+ searchInput.value = searchTerm;
+ for (const cb of document.querySelectorAll(".status-filter")) {
+ cb.checked = statusFilters.has(cb.value);
+ }
+
+ searchInput.addEventListener("input", (e) => {
searchTerm = e.target.value;
applyFilters();
+ scheduleSave(500);
});
for (const cb of document.querySelectorAll(".status-filter")) {
cb.addEventListener("change", (e) => {
@@ -394,16 +660,56 @@
if (e.target.checked) statusFilters.add(v);
else statusFilters.delete(v);
applyFilters();
+ scheduleSave(500);
});
}
+ // Reset layout button: clears the persisted state and reloads so
+ // physics seeds from `placeInitial` instead of the stored coords.
+ document.getElementById("reset-layout").addEventListener("click", () => {
+ try {
+ localStorage.removeItem(STORAGE_KEY);
+ } catch (e) {
+ // No-op: nothing to clear in non-persistent mode.
+ }
+ location.reload();
+ });
+
+ // Flush on tab close / reload. `pagehide` is the cross-browser
+ // best-effort hook; `beforeunload` is intentionally avoided
+ // because it triggers the browser's "leave site?" prompt under
+ // some configurations.
+ window.addEventListener("pagehide", saveLayout);
+
// ---- Boot ------------------------------------------------------------
resizeCanvas();
placeInitial();
+ applyFilters();
+ // Persist the layout once after each settle. `unsavedMotion`
+ // latches true whenever any visible node has non-trivial velocity
+ // and resets only after `saveLayout` runs; otherwise an idle graph
+ // would JSON.stringify-and-write every 250 ms forever.
+ let settleSavedAt = -Infinity;
+ let unsavedMotion = true;
function frame() {
step();
render();
+ const now = performance.now();
+ if (now - settleSavedAt > 250) {
+ let totalV = 0;
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ const v = Math.abs(n.vx) + Math.abs(n.vy);
+ if (v > 0.05) unsavedMotion = true;
+ totalV += v;
+ }
+ if (totalV < 0.5 && unsavedMotion) {
+ settleSavedAt = now;
+ unsavedMotion = false;
+ saveLayout();
+ }
+ }
requestAnimationFrame(frame);
}
frame();
diff --git a/tests/cli/brain-export.test.ts b/tests/cli/brain-export.test.ts
new file mode 100644
index 00000000..3307e89b
--- /dev/null
+++ b/tests/cli/brain-export.test.ts
@@ -0,0 +1,186 @@
+/**
+ * CLI tests for `o2b brain export` (Β§28).
+ */
+
+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-export-cli-"));
+ 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", "TestExport"], {
+ 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 seedPreference(slug: string): Promise<void> {
+ const r = await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ slug,
+ "--signal",
+ "positive",
+ "--principle",
+ `principle ${slug}`,
+ "--scope",
+ "writing",
+ "--force-confirmed",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+}
+
+describe("brain export", () => {
+ test("missing --format β†’ exit 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "export", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("--format");
+ });
+
+ test("--format json on empty vault β†’ schema envelope, empty list", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "export", "--vault", vault, "--format", "json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ schema: number;
+ generated_at: string;
+ vault_basename: string;
+ preferences: ReadonlyArray<{ id: string }>;
+ };
+ expect(payload.schema).toBe(1);
+ expect(payload.preferences).toEqual([]);
+ expect(payload.vault_basename.length).toBeGreaterThan(0);
+ });
+
+ test("--format json carries seeded preference rows", async () => {
+ await bootstrap();
+ await seedPreference("alpha");
+ await seedPreference("beta");
+ const r = await runCli(
+ ["brain", "export", "--vault", vault, "--format", "json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ preferences: Array<{ id: string; topic: string; principle: string }>;
+ };
+ expect(payload.preferences.map((p) => p.id).sort()).toEqual([
+ "pref-alpha",
+ "pref-beta",
+ ]);
+ });
+
+ test("--format llms-txt emits H1 + section + bullet", async () => {
+ await bootstrap();
+ await seedPreference("alpha");
+ const r = await runCli(
+ ["brain", "export", "--vault", vault, "--format", "llms-txt"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toMatch(/^# .*Brain preferences/);
+ expect(r.stdout).toContain("## Confirmed");
+ expect(r.stdout).toContain(
+ "- pref-alpha (topic: alpha, scope: writing): principle alpha",
+ );
+ });
+
+ test("--out writes a file (and refuses to overwrite without --force)", async () => {
+ await bootstrap();
+ await seedPreference("alpha");
+ const out = join(tmp, "out.json");
+ const r1 = await runCli(
+ [
+ "brain",
+ "export",
+ "--vault",
+ vault,
+ "--format",
+ "json",
+ "--out",
+ out,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r1.returncode).toBe(0);
+ expect(existsSync(out)).toBe(true);
+ const parsed = JSON.parse(readFileSync(out, "utf8")) as {
+ preferences: ReadonlyArray<unknown>;
+ };
+ expect(parsed.preferences.length).toBe(1);
+
+ // Second call without --force should refuse.
+ const r2 = await runCli(
+ [
+ "brain",
+ "export",
+ "--vault",
+ vault,
+ "--format",
+ "json",
+ "--out",
+ out,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r2.returncode).toBe(1);
+ expect(r2.stderr).toContain("--force");
+
+ // With --force the overwrite goes through.
+ writeFileSync(out, "stale");
+ const r3 = await runCli(
+ [
+ "brain",
+ "export",
+ "--vault",
+ vault,
+ "--format",
+ "json",
+ "--out",
+ out,
+ "--force",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r3.returncode).toBe(0);
+ expect(readFileSync(out, "utf8")).not.toBe("stale");
+ });
+
+ test("help text mentions export", async () => {
+ const r = await runCli(["brain", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("export");
+ });
+});
diff --git a/tests/cli/brain-upgrade.test.ts b/tests/cli/brain-upgrade.test.ts
new file mode 100644
index 00000000..f1d4f789
--- /dev/null
+++ b/tests/cli/brain-upgrade.test.ts
@@ -0,0 +1,192 @@
+/**
+ * CLI tests for `o2b brain upgrade`.
+ *
+ * Forks the real `o2b` binary via `runCli`. Each test mutates a
+ * freshly-bootstrapped vault to create a known drift (stale manual or
+ * truncated `_brain.yaml`), then asserts the verb's exit code,
+ * stdout shape, and (for `--apply`) post-state on disk.
+ */
+
+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-upgrade-cli-"));
+ 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);
+}
+
+describe("brain upgrade", () => {
+ test("clean vault β†’ dry-run reports up-to-date, exit 0", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--dry-run"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("up to date");
+ });
+
+ test("--check on clean vault β†’ exit 0", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--check"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ });
+
+ test("--check with pending updates β†’ exit 2", async () => {
+ await bootstrap();
+ // Drift: stale operator copy of _BRAIN.md.
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--check"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stdout).toContain("Brain/_BRAIN.md");
+ });
+
+ test("--dry-run with pending updates β†’ exit 0, shows the diff", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--dry-run"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("update");
+ expect(r.stdout).toContain("--- Brain/_BRAIN.md (live)");
+ expect(r.stdout).toContain("+++ Brain/_BRAIN.md (release)");
+ });
+
+ test("--apply --yes rewrites pending files and creates upgrade-<ts> snapshot", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toMatch(/run_id: upgrade-/);
+ expect(r.stdout).toContain("Brain/_BRAIN.md");
+ // Post-apply: the file is now the canonical template body, not
+ // the stale copy.
+ const body = readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8");
+ expect(body).not.toBe("stale\n");
+ // A snapshot named upgrade-<ts> landed under .snapshots/.
+ const snapEntries = require("node:fs").readdirSync(
+ join(vault, "Brain", ".snapshots"),
+ );
+ expect(
+ snapEntries.some((n: string) => n.startsWith("upgrade-")),
+ ).toBe(true);
+ });
+
+ test("--apply in --json mode requires --yes (non-interactive guard)", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--apply", "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("--yes");
+ });
+
+ test("--apply on clean vault β†’ no snapshot, no log, exit 0", async () => {
+ await bootstrap();
+ const snapsBefore = existsSync(join(vault, "Brain", ".snapshots"))
+ ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots"))
+ .length
+ : 0;
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("nothing to do");
+ const snapsAfter = existsSync(join(vault, "Brain", ".snapshots"))
+ ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots"))
+ .length
+ : 0;
+ expect(snapsAfter).toBe(snapsBefore);
+ });
+
+ test("malformed _brain.yaml reports error in plan and refuses --apply", async () => {
+ await bootstrap();
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "not: a valid: brain yaml\n",
+ );
+ const dry = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--dry-run"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(dry.returncode).toBe(0);
+ expect(dry.stdout).toMatch(/ERROR/);
+
+ const apply = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(apply.returncode).toBe(1);
+ expect(apply.stderr).toContain("upgrade aborted");
+ });
+
+ test("--dry-run and --apply are mutually exclusive", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--dry-run", "--apply"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("mutually exclusive");
+ });
+
+ test("--json --dry-run emits structured plan", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const r = await runCli(
+ ["brain", "upgrade", "--vault", vault, "--dry-run", "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ pending: number;
+ errors: number;
+ files: Array<{ path: string; status: string }>;
+ };
+ expect(payload.pending).toBeGreaterThanOrEqual(1);
+ expect(
+ payload.files.some((f) => f.path === "Brain/_BRAIN.md" && f.status === "update"),
+ ).toBe(true);
+ });
+});
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index dc604d41..f4fcd78b 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -74,6 +74,7 @@ describe("brain --help", () => {
expect(r.stdout).toContain("unpin");
expect(r.stdout).toContain("rollback");
expect(r.stdout).toContain("doctor");
+ expect(r.stdout).toContain("upgrade");
});
test("unknown verb exits 2 and lists known verbs", async () => {
@@ -919,7 +920,9 @@ describe("brain rollback", () => {
n.endsWith(".md"),
).length,
).toBeGreaterThanOrEqual(1);
- // 4. Rollback to the snapshot.
+ // 4. Rollback to the snapshot. State B drifted (a new signal
+ // landed after the snapshot), so v0.10.6 rollback requires
+ // --force-rollback to overwrite the live tree.
const r = await runCli(
[
"brain",
@@ -928,12 +931,192 @@ describe("brain rollback", () => {
vault,
dpayload.run_id,
"--yes",
+ "--force-rollback",
],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("restored:");
});
+
+ test("aborts on drift without --force-rollback (Β§5-tail)", async () => {
+ await bootstrap();
+ // State A: one signal.
+ await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "drift-a",
+ "--signal",
+ "positive",
+ "--principle",
+ "p",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dr = await runCli(
+ ["brain", "dream", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };
+ if (!dpayload.changed) return;
+
+ // Drift: second signal lands after the snapshot.
+ await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "drift-b",
+ "--signal",
+ "positive",
+ "--principle",
+ "p",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const r = await runCli(
+ [
+ "brain",
+ "rollback",
+ "--vault",
+ vault,
+ dpayload.run_id,
+ "--yes",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("Drift detected");
+ expect(r.stderr).toContain("--force-rollback");
+ });
+
+ test("--json drift abort emits structured payload", async () => {
+ await bootstrap();
+ await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "drift-json-a",
+ "--signal",
+ "positive",
+ "--principle",
+ "p",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dr = await runCli(
+ ["brain", "dream", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };
+ if (!dpayload.changed) return;
+
+ await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "drift-json-b",
+ "--signal",
+ "positive",
+ "--principle",
+ "p",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const r = await runCli(
+ [
+ "brain",
+ "rollback",
+ "--vault",
+ vault,
+ dpayload.run_id,
+ "--yes",
+ "--json",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ const payload = JSON.parse(r.stdout) as {
+ run_id: string;
+ drift: boolean;
+ added: string[];
+ removed: string[];
+ changed: string[];
+ };
+ expect(payload.run_id).toBe(dpayload.run_id);
+ expect(payload.drift).toBe(true);
+ });
+
+ test("legacy snapshot without sidecar warns and proceeds", async () => {
+ await bootstrap();
+ await runCli(
+ [
+ "brain",
+ "feedback",
+ "--vault",
+ vault,
+ "--topic",
+ "legacy-a",
+ "--signal",
+ "positive",
+ "--principle",
+ "p",
+ "--agent",
+ "claude",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dr = await runCli(
+ ["brain", "dream", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };
+ if (!dpayload.changed) return;
+
+ // Simulate a pre-v0.10.6 snapshot: archive with no manifest.
+ const sidecar = join(
+ vault,
+ "Brain",
+ ".snapshots",
+ `${dpayload.run_id}.manifest.json`,
+ );
+ rmSync(sidecar, { force: true });
+
+ const r = await runCli(
+ [
+ "brain",
+ "rollback",
+ "--vault",
+ vault,
+ dpayload.run_id,
+ "--yes",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stderr).toContain("no manifest sidecar");
+ expect(r.stderr).toContain("predates v0.10.6");
+ });
});
describe("brain doctor", () => {
diff --git a/tests/core/brain.snapshot.test.ts b/tests/core/brain.snapshot.test.ts
index d2313d1b..89c84a3c 100644
--- a/tests/core/brain.snapshot.test.ts
+++ b/tests/core/brain.snapshot.test.ts
@@ -21,6 +21,11 @@ import {
import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import {
+ BRAIN_MANIFEST_SCHEMA_VERSION,
+ manifestSidecarPath,
+ readManifestSidecar,
+} from "../../src/core/brain/manifest.ts";
let vault: string;
let configHome: string;
@@ -99,6 +104,23 @@ describe("createSnapshot", () => {
test("rejects invalid run_id", () => {
expect(() => createSnapshot(vault, "../escape")).toThrow();
});
+
+ test("writes sidecar manifest alongside the archive (Β§22 + Β§5-tail)", () => {
+ createSnapshot(vault, "dream-with-manifest");
+ const sidecar = manifestSidecarPath(vault, "dream-with-manifest");
+ expect(existsSync(sidecar)).toBe(true);
+ const m = readManifestSidecar(vault, "dream-with-manifest");
+ expect(m).not.toBeNull();
+ expect(m!.schema_version).toBe(BRAIN_MANIFEST_SCHEMA_VERSION);
+ expect(m!.brain_root).toBe("Brain");
+ // The seed tree carries _brain.yaml, _BRAIN.md, the seed signal,
+ // pref, and log entry. All must appear in the manifest.
+ expect(m!.files["_brain.yaml"]).toBeDefined();
+ expect(m!.files["_BRAIN.md"]).toBeDefined();
+ expect(m!.files["inbox/sig-2026-05-14-foo.md"]).toBeDefined();
+ expect(m!.files["preferences/pref-foo.md"]).toBeDefined();
+ expect(m!.files["log/2026-05-14.md"]).toBeDefined();
+ });
});
describe("listSnapshots", () => {
@@ -134,6 +156,22 @@ describe("listSnapshots", () => {
test("returns [] when .snapshots/ is empty", () => {
expect(listSnapshots(vault)).toEqual([]);
});
+
+ test("manifest_path populated when sidecar present, null otherwise", () => {
+ createSnapshot(vault, "dream-with-sidecar");
+ // Simulate a legacy snapshot: drop the sidecar that
+ // createSnapshot just wrote so only the archive remains.
+ const sidecar = manifestSidecarPath(vault, "dream-with-sidecar");
+ expect(existsSync(sidecar)).toBe(true);
+
+ createSnapshot(vault, "dream-legacy");
+ rmSync(manifestSidecarPath(vault, "dream-legacy"), { force: true });
+
+ const list = listSnapshots(vault);
+ const byId = new Map(list.map((s) => [s.run_id, s]));
+ expect(byId.get("dream-with-sidecar")!.manifest_path).toBe(sidecar);
+ expect(byId.get("dream-legacy")!.manifest_path).toBeNull();
+ });
});
describe("pruneSnapshots", () => {
@@ -174,6 +212,46 @@ describe("pruneSnapshots", () => {
expect(res.deleted).toEqual([]);
expect(listSnapshots(vault)).toHaveLength(1);
});
+
+ test("removes sidecar manifest alongside the archive", () => {
+ const labels = ["a", "b", "c"];
+ const ts = [
+ "2026-05-10T00:00:00Z",
+ "2026-05-11T00:00:00Z",
+ "2026-05-12T00:00:00Z",
+ ];
+ for (let i = 0; i < labels.length; i++) {
+ const runId = `dream-prune-${labels[i]}`;
+ createSnapshot(vault, runId);
+ const p = snapshotPath(vault, runId);
+ const t = new Date(ts[i]!);
+ utimesSync(p, t, t);
+ }
+ // Sanity: all three sidecars present pre-prune.
+ for (const l of labels) {
+ expect(existsSync(manifestSidecarPath(vault, `dream-prune-${l}`))).toBe(true);
+ }
+
+ pruneSnapshots(vault, 1);
+ // 'c' is the newest by mtime, so 'a' and 'b' are deleted along with
+ // their sidecars; 'c' and its sidecar survive.
+ expect(existsSync(manifestSidecarPath(vault, "dream-prune-a"))).toBe(false);
+ expect(existsSync(manifestSidecarPath(vault, "dream-prune-b"))).toBe(false);
+ expect(existsSync(manifestSidecarPath(vault, "dream-prune-c"))).toBe(true);
+ });
+
+ test("legacy archive without sidecar still prunes cleanly", () => {
+ createSnapshot(vault, "dream-legacy-prune-old");
+ rmSync(manifestSidecarPath(vault, "dream-legacy-prune-old"), { force: true });
+ const old = snapshotPath(vault, "dream-legacy-prune-old");
+ const t = new Date("2026-05-09T00:00:00Z");
+ utimesSync(old, t, t);
+
+ createSnapshot(vault, "dream-legacy-prune-new");
+ const res = pruneSnapshots(vault, 1);
+ expect(res.deleted).toContain(old);
+ expect(existsSync(old)).toBe(false);
+ });
});
describe("restoreSnapshot β€” round-trip integrity", () => {
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 087b19aa..3a2d29e1 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -76,6 +76,8 @@ describe("BRAIN_* const enums", () => {
"migrate-frontmatter",
// Β§12 merge (v0.10.5)
"merge",
+ // Β§22 upgrade (v0.10.6)
+ "upgrade",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/brain/explorer.test.ts b/tests/core/brain/explorer.test.ts
index 6d0a7603..6601bd4b 100644
--- a/tests/core/brain/explorer.test.ts
+++ b/tests/core/brain/explorer.test.ts
@@ -308,4 +308,43 @@ describe("renderExportedHtml", () => {
const node = parsed.nodes.find((n: { id: string }) => n.id === "pref-script-close");
expect(node.principle).toBe("Never let </script><script>bad()</script> split the data block");
});
+
+ // Β§14 polish (v0.10.6) β€” the keyboard-accessible listbox markup and
+ // localStorage hooks must travel with every exported HTML body.
+ // These tests guard against accidental DOM removal during future
+ // template edits.
+ test("template ships keyboard-accessible listbox markup", () => {
+ writePreference(vault, basePref("a11y"));
+ const html = renderExportedHtml(collectExplorerData(vault));
+ expect(html).toContain('id="node-list"');
+ expect(html).toContain('role="listbox"');
+ expect(html).toContain('aria-activedescendant=""');
+ expect(html).toContain('id="reset-layout"');
+ expect(html).toContain('id="details-body"');
+ });
+
+ test("template wires localStorage layout persistence", () => {
+ writePreference(vault, basePref("store"));
+ const html = renderExportedHtml(collectExplorerData(vault));
+ expect(html).toContain("osb-explorer-layout:");
+ expect(html).toContain("STORAGE_KEY");
+ expect(html).toContain("saveLayout");
+ });
+
+ // Smoke guard against the v0.10.6 regression where the simplify
+ // pass dropped `focusedNodeId` and `visibleNodesSorted()` but left
+ // the keyboard-handler callsites pointing at them (Home / End /
+ // Enter / Space threw ReferenceError at runtime). Without a JS
+ // execution test, this regex check is the cheapest way to keep
+ // the rename honest.
+ test("keyboard handlers reference only live identifiers", () => {
+ writePreference(vault, basePref("kb"));
+ const html = renderExportedHtml(collectExplorerData(vault));
+ expect(html).not.toContain("visibleNodesSorted(");
+ expect(html).not.toContain("focusedNodeId");
+ // The cache + canonical selection variable must both be present
+ // because the handlers consume them.
+ expect(html).toContain("visibleSortedCache");
+ expect(html).toContain("selectedId");
+ });
});
diff --git a/tests/core/brain/export.test.ts b/tests/core/brain/export.test.ts
new file mode 100644
index 00000000..92ef6c0f
--- /dev/null
+++ b/tests/core/brain/export.test.ts
@@ -0,0 +1,227 @@
+/**
+ * Tests for `src/core/brain/export.ts` (Β§28).
+ *
+ * Two surfaces under test:
+ * - `exportPreferencesJson` β€” schema, row count, field set,
+ * deterministic ordering.
+ * - `exportPreferencesLlmsTxt` β€” llmstxt.org H1 + summary + per-
+ * status H2 sections, bullet shape, empty-section omission.
+ */
+
+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 {
+ BRAIN_EXPORT_SCHEMA_VERSION,
+ exportPreferencesJson,
+ exportPreferencesLlmsTxt,
+} from "../../../src/core/brain/export.ts";
+import {
+ moveToRetired,
+ writePreference,
+ type WritePreferenceInput,
+} from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-export-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+function basePref(
+ slug: string,
+ overrides: Partial<WritePreferenceInput> = {},
+): WritePreferenceInput {
+ return {
+ slug,
+ topic: slug,
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-03T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.medium,
+ confidence_value: 0.5,
+ pinned: false,
+ ...overrides,
+ };
+}
+
+describe("exportPreferencesJson", () => {
+ test("empty preferences/ β†’ empty array, valid envelope", () => {
+ const out = exportPreferencesJson(vault);
+ expect(out.schema).toBe(BRAIN_EXPORT_SCHEMA_VERSION);
+ expect(out.vault_basename.length).toBeGreaterThan(0);
+ expect(out.generated_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ expect(out.preferences).toEqual([]);
+ });
+
+ test("mixed-status preferences are all included, retired/signal are excluded", () => {
+ writePreference(
+ vault,
+ basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }),
+ );
+ writePreference(
+ vault,
+ basePref("beta", {
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ confirmed_at: null,
+ }),
+ );
+ writePreference(
+ vault,
+ basePref("gamma", {
+ status: BRAIN_PREFERENCE_STATUS.quarantine,
+ applied_count: 2,
+ violated_count: 3,
+ }),
+ );
+ // A retired pref + a stray signal must not leak into the export.
+ writePreference(vault, basePref("dead"));
+ moveToRetired(
+ vault,
+ join(vault, "Brain", "preferences", "pref-dead.md"),
+ BRAIN_RETIRED_REASON.staleNoEvidence,
+ { now: new Date("2026-05-10T00:00:00Z"), retired_by: "[[Brain/log/2026-05-10]]" },
+ );
+ writeFileSync(
+ join(vault, "Brain", "inbox", "sig-2026-05-04-thing.md"),
+ "---\nkind: brain-signal\n---\nbody\n",
+ );
+
+ const out = exportPreferencesJson(vault);
+ expect(out.preferences.map((p) => p.id)).toEqual([
+ "pref-alpha",
+ "pref-beta",
+ "pref-gamma",
+ ]);
+ });
+
+ test("row carries the canonical field set", () => {
+ writePreference(
+ vault,
+ basePref("alpha", { scope: "writing", pinned: true }),
+ );
+ const out = exportPreferencesJson(vault);
+ const r = out.preferences[0]!;
+ expect(r.id).toBe("pref-alpha");
+ expect(r.topic).toBe("alpha");
+ expect(r.scope).toBe("writing");
+ expect(r.status).toBe("confirmed");
+ expect(r.principle).toBe("Principle for alpha");
+ expect(r.applied_count).toBe(1);
+ expect(r.violated_count).toBe(0);
+ expect(r.confidence).toBe(BRAIN_CONFIDENCE.medium);
+ expect(r.confidence_value).toBe(0.5);
+ expect(r.pinned).toBe(true);
+ expect(r.last_evidence_at).toBe("2026-05-03T00:00:00Z");
+ expect(r.created_at).toBe("2026-05-01T00:00:00Z");
+ expect(r.confirmed_at).toBe("2026-05-02T00:00:00Z");
+ // `writePreference` derives a default tag set; the export
+ // surfaces whatever made it onto disk verbatim.
+ expect(Array.isArray(r.tags)).toBe(true);
+ expect(r.tags).toContain("brain/preference");
+ });
+
+ test("pref without scope β†’ scope: null in the row", () => {
+ writePreference(vault, basePref("no-scope"));
+ const out = exportPreferencesJson(vault);
+ expect(out.preferences[0]!.scope).toBeNull();
+ });
+
+ test("row.body carries the markdown sections after the frontmatter", () => {
+ writePreference(vault, basePref("with-body"));
+ const out = exportPreferencesJson(vault);
+ const r = out.preferences[0]!;
+ expect(typeof r.body).toBe("string");
+ // `writePreference` emits the `## Origin` section listing the
+ // evidenced_by wikilinks as part of the standard skeleton.
+ // The row must surface that body verbatim so a downstream
+ // consumer can re-emit the rule with its origin trail.
+ expect(r.body).toContain("## Origin");
+ expect(r.body).toContain("[[sig-2026-05-01-with-body]]");
+ });
+
+ test("output ordering is stable by id", () => {
+ writePreference(vault, basePref("zeta"));
+ writePreference(vault, basePref("alpha"));
+ writePreference(vault, basePref("mu"));
+ const out = exportPreferencesJson(vault);
+ expect(out.preferences.map((p) => p.id)).toEqual([
+ "pref-alpha",
+ "pref-mu",
+ "pref-zeta",
+ ]);
+ });
+});
+
+describe("exportPreferencesLlmsTxt", () => {
+ test("empty preferences β†’ H1 + summary only, no H2 sections", () => {
+ const txt = exportPreferencesLlmsTxt(vault);
+ expect(txt).toContain("# ");
+ expect(txt).toContain("Brain preferences");
+ expect(txt).toContain("Auto-generated");
+ expect(txt).not.toContain("## Confirmed");
+ expect(txt).not.toContain("## Unconfirmed");
+ expect(txt).not.toContain("## Quarantine");
+ });
+
+ test("mixed statuses render in fixed Confirmed β†’ Unconfirmed β†’ Quarantine order", () => {
+ writePreference(
+ vault,
+ basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }),
+ );
+ writePreference(
+ vault,
+ basePref("beta", {
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ confirmed_at: null,
+ }),
+ );
+ writePreference(
+ vault,
+ basePref("gamma", { status: BRAIN_PREFERENCE_STATUS.quarantine }),
+ );
+ const txt = exportPreferencesLlmsTxt(vault);
+ const idxConfirmed = txt.indexOf("## Confirmed");
+ const idxUnconfirmed = txt.indexOf("## Unconfirmed");
+ const idxQuarantine = txt.indexOf("## Quarantine");
+ expect(idxConfirmed).toBeGreaterThanOrEqual(0);
+ expect(idxUnconfirmed).toBeGreaterThan(idxConfirmed);
+ expect(idxQuarantine).toBeGreaterThan(idxUnconfirmed);
+ });
+
+ test("only-confirmed vault β†’ only the Confirmed section", () => {
+ writePreference(vault, basePref("solo"));
+ const txt = exportPreferencesLlmsTxt(vault);
+ expect(txt).toContain("## Confirmed");
+ expect(txt).not.toContain("## Unconfirmed");
+ expect(txt).not.toContain("## Quarantine");
+ });
+
+ test("bullet shape matches `- <id> (topic: X[, scope: Y]): <principle>`", () => {
+ writePreference(vault, basePref("scoped", { scope: "writing" }));
+ writePreference(vault, basePref("unscoped"));
+ const txt = exportPreferencesLlmsTxt(vault);
+ expect(txt).toContain(
+ "- pref-scoped (topic: scoped, scope: writing): Principle for scoped",
+ );
+ expect(txt).toContain("- pref-unscoped (topic: unscoped): Principle for unscoped");
+ });
+});
diff --git a/tests/core/brain/manifest.test.ts b/tests/core/brain/manifest.test.ts
new file mode 100644
index 00000000..0177c063
--- /dev/null
+++ b/tests/core/brain/manifest.test.ts
@@ -0,0 +1,275 @@
+/**
+ * Tests for `src/core/brain/manifest.ts`.
+ *
+ * Covered:
+ * - empty Brain β†’ empty files map
+ * - regular files hashed; output keys sorted lexicographically
+ * - `.snapshots/` excluded
+ * - symlinks skipped (defense against malicious archive contents)
+ * - byte-stable sha256 across runs on identical inputs
+ * - `diffManifests` classifies added / removed / changed
+ * - sidecar read / write roundtrip; corrupt and missing sidecars
+ * surface as `null` rather than throwing
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ BRAIN_MANIFEST_SCHEMA_VERSION,
+ buildManifest,
+ diffManifests,
+ manifestDiffHasDrift,
+ manifestSidecarPath,
+ readManifestSidecar,
+ writeManifestSidecar,
+ type BrainManifest,
+} from "../../../src/core/brain/manifest.ts";
+
+let vault: string;
+let brain: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-manifest-"));
+ brain = join(vault, "Brain");
+ mkdirSync(brain, { recursive: true });
+ mkdirSync(join(brain, ".snapshots"), { recursive: true });
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+describe("buildManifest", () => {
+ test("empty Brain β†’ empty files map, schema_version 1, brain_root 'Brain'", () => {
+ const m = buildManifest(brain);
+ expect(m.schema_version).toBe(BRAIN_MANIFEST_SCHEMA_VERSION);
+ expect(m.brain_root).toBe("Brain");
+ expect(Object.keys(m.files)).toEqual([]);
+ expect(m.generated_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
+ });
+
+ test("missing brainRoot directory β†’ empty manifest, no throw", () => {
+ rmSync(brain, { recursive: true, force: true });
+ const m = buildManifest(brain);
+ expect(Object.keys(m.files)).toEqual([]);
+ });
+
+ test("two preferences β†’ two entries sorted by relative path", () => {
+ mkdirSync(join(brain, "preferences"), { recursive: true });
+ writeFileSync(join(brain, "preferences", "pref-b.md"), "beta\n");
+ writeFileSync(join(brain, "preferences", "pref-a.md"), "alpha\n");
+ const m = buildManifest(brain);
+ expect(Object.keys(m.files)).toEqual([
+ "preferences/pref-a.md",
+ "preferences/pref-b.md",
+ ]);
+ expect(m.files["preferences/pref-a.md"]!.size).toBe(6);
+ expect(m.files["preferences/pref-a.md"]!.sha256).toMatch(/^[0-9a-f]{64}$/);
+ // sha256("alpha\n") == "31c0c4dee7f8eeeb27ff4f64ff5a7a9d97a6b6f49ad22082f6c12f9f0c5b9d27" β†’ guard via length only.
+ expect(m.files["preferences/pref-a.md"]!.sha256.length).toBe(64);
+ });
+
+ test(".snapshots/ is excluded from the walk", () => {
+ writeFileSync(join(brain, ".snapshots", "phantom.tar.zst"), "binary");
+ writeFileSync(join(brain, ".snapshots", "phantom.manifest.json"), "{}");
+ mkdirSync(join(brain, "preferences"));
+ writeFileSync(join(brain, "preferences", "pref-x.md"), "x");
+ const m = buildManifest(brain);
+ expect(Object.keys(m.files)).toEqual(["preferences/pref-x.md"]);
+ });
+
+ test("symlink under Brain/ is skipped (security)", () => {
+ mkdirSync(join(brain, "preferences"));
+ writeFileSync(join(brain, "preferences", "pref-real.md"), "real");
+ const targetOutside = join(vault, "secret.txt");
+ writeFileSync(targetOutside, "should-not-be-hashed");
+ symlinkSync(targetOutside, join(brain, "preferences", "pref-link.md"));
+ const m = buildManifest(brain);
+ expect(Object.keys(m.files)).toEqual(["preferences/pref-real.md"]);
+ });
+
+ test("identical bytes β†’ identical sha256 across two runs", () => {
+ mkdirSync(join(brain, "preferences"));
+ writeFileSync(join(brain, "preferences", "pref-a.md"), "deterministic");
+ const m1 = buildManifest(brain);
+ const m2 = buildManifest(brain);
+ expect(m1.files["preferences/pref-a.md"]!.sha256).toBe(
+ m2.files["preferences/pref-a.md"]!.sha256,
+ );
+ });
+
+ test("config files at Brain/ root are hashed (e.g. _brain.yaml)", () => {
+ writeFileSync(join(brain, "_brain.yaml"), "schema_version: 1\n");
+ writeFileSync(join(brain, "_BRAIN.md"), "# manual\n");
+ const m = buildManifest(brain);
+ expect(Object.keys(m.files).sort()).toEqual(["_BRAIN.md", "_brain.yaml"]);
+ });
+});
+
+describe("diffManifests", () => {
+ function fakeManifest(
+ files: Record<string, { sha: string; size: number }>,
+ ): BrainManifest {
+ const sortedKeys = Object.keys(files).sort();
+ const out: Record<string, { readonly sha256: string; readonly size: number }> = {};
+ for (const k of sortedKeys) {
+ out[k] = Object.freeze({ sha256: files[k]!.sha, size: files[k]!.size });
+ }
+ return Object.freeze({
+ schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
+ generated_at: "2026-05-18T00:00:00Z",
+ brain_root: "Brain",
+ files: Object.freeze(out),
+ });
+ }
+
+ test("identical manifests β†’ empty diff in all three buckets", () => {
+ const a = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const b = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const d = diffManifests(a, b);
+ expect(d.added).toEqual([]);
+ expect(d.removed).toEqual([]);
+ expect(d.changed).toEqual([]);
+ expect(manifestDiffHasDrift(d)).toBe(false);
+ });
+
+ test("right has extra file β†’ 'added'", () => {
+ const a = fakeManifest({});
+ const b = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const d = diffManifests(a, b);
+ expect(d.added.map((e) => e.path)).toEqual(["preferences/pref-a.md"]);
+ expect(d.added[0]!.before).toBeNull();
+ expect(d.added[0]!.after!.sha256).toBe("x");
+ expect(manifestDiffHasDrift(d)).toBe(true);
+ });
+
+ test("left has extra file β†’ 'removed'", () => {
+ const a = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const b = fakeManifest({});
+ const d = diffManifests(a, b);
+ expect(d.removed.map((e) => e.path)).toEqual(["preferences/pref-a.md"]);
+ expect(d.removed[0]!.after).toBeNull();
+ expect(manifestDiffHasDrift(d)).toBe(true);
+ });
+
+ test("same path different sha256 β†’ 'changed'", () => {
+ const a = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const b = fakeManifest({ "preferences/pref-a.md": { sha: "y", size: 1 } });
+ const d = diffManifests(a, b);
+ expect(d.changed.map((e) => e.path)).toEqual(["preferences/pref-a.md"]);
+ expect(d.changed[0]!.before!.sha256).toBe("x");
+ expect(d.changed[0]!.after!.sha256).toBe("y");
+ });
+
+ test("same path same sha256 different size β†’ 'changed' (defensive)", () => {
+ const a = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 1 } });
+ const b = fakeManifest({ "preferences/pref-a.md": { sha: "x", size: 2 } });
+ const d = diffManifests(a, b);
+ expect(d.changed.length).toBe(1);
+ });
+
+ test("multiple changes β†’ each bucket sorted by path", () => {
+ const a = fakeManifest({
+ "z.md": { sha: "old", size: 1 },
+ "a.md": { sha: "old", size: 1 },
+ });
+ const b = fakeManifest({
+ "z.md": { sha: "new", size: 1 },
+ "b.md": { sha: "new", size: 1 },
+ });
+ const d = diffManifests(a, b);
+ expect(d.added.map((e) => e.path)).toEqual(["b.md"]);
+ expect(d.removed.map((e) => e.path)).toEqual(["a.md"]);
+ expect(d.changed.map((e) => e.path)).toEqual(["z.md"]);
+ });
+});
+
+describe("sidecar I/O", () => {
+ test("manifestSidecarPath lands inside Brain/.snapshots/", () => {
+ expect(manifestSidecarPath(vault, "abc")).toBe(
+ join(brain, ".snapshots", "abc.manifest.json"),
+ );
+ });
+
+ test("read of missing path β†’ null (no throw)", () => {
+ expect(readManifestSidecar(vault, "ghost")).toBeNull();
+ });
+
+ test("read of malformed JSON β†’ null", () => {
+ writeFileSync(manifestSidecarPath(vault, "torn"), "not json {");
+ expect(readManifestSidecar(vault, "torn")).toBeNull();
+ });
+
+ test("read of wrong schema_version β†’ null", () => {
+ writeFileSync(
+ manifestSidecarPath(vault, "old"),
+ JSON.stringify({
+ schema_version: 99,
+ generated_at: "2026-05-18T00:00:00Z",
+ brain_root: "Brain",
+ files: {},
+ }),
+ );
+ expect(readManifestSidecar(vault, "old")).toBeNull();
+ });
+
+ test("read of tampered entry (null) β†’ null, does not crash", () => {
+ writeFileSync(
+ manifestSidecarPath(vault, "tampered-null"),
+ JSON.stringify({
+ schema_version: 1,
+ generated_at: "2026-05-18T00:00:00Z",
+ brain_root: "Brain",
+ files: { "preferences/pref-x.md": null },
+ }),
+ );
+ expect(readManifestSidecar(vault, "tampered-null")).toBeNull();
+ });
+
+ test("read of tampered entry (missing sha256) β†’ null", () => {
+ writeFileSync(
+ manifestSidecarPath(vault, "tampered-shape"),
+ JSON.stringify({
+ schema_version: 1,
+ generated_at: "2026-05-18T00:00:00Z",
+ brain_root: "Brain",
+ files: { "preferences/pref-x.md": { size: 12 } },
+ }),
+ );
+ expect(readManifestSidecar(vault, "tampered-shape")).toBeNull();
+ });
+
+ test("read of tampered entry (wrong sha256 type) β†’ null", () => {
+ writeFileSync(
+ manifestSidecarPath(vault, "tampered-type"),
+ JSON.stringify({
+ schema_version: 1,
+ generated_at: "2026-05-18T00:00:00Z",
+ brain_root: "Brain",
+ files: { "preferences/pref-x.md": { sha256: 42, size: 12 } },
+ }),
+ );
+ expect(readManifestSidecar(vault, "tampered-type")).toBeNull();
+ });
+
+ test("write then read roundtrip yields equal structure", () => {
+ mkdirSync(join(brain, "preferences"));
+ writeFileSync(join(brain, "preferences", "pref-rt.md"), "roundtrip");
+ const original = buildManifest(brain);
+ writeManifestSidecar(vault, "rt", original);
+ const back = readManifestSidecar(vault, "rt");
+ expect(back).not.toBeNull();
+ expect(back!.schema_version).toBe(BRAIN_MANIFEST_SCHEMA_VERSION);
+ expect(back!.brain_root).toBe("Brain");
+ expect(Object.keys(back!.files)).toEqual(Object.keys(original.files));
+ expect(back!.files["preferences/pref-rt.md"]!.sha256).toBe(
+ original.files["preferences/pref-rt.md"]!.sha256,
+ );
+ });
+});
diff --git a/tests/core/brain/templates.test.ts b/tests/core/brain/templates.test.ts
new file mode 100644
index 00000000..7ae8ff76
--- /dev/null
+++ b/tests/core/brain/templates.test.ts
@@ -0,0 +1,82 @@
+/**
+ * Tests for `src/core/brain/templates.ts`.
+ *
+ * Focuses on the rendering primitives β€” the path constants are
+ * implicitly exercised by `init.ts` and `upgrade.ts` tests, but the
+ * substitution path needs its own targeted coverage so CR finding
+ * around `String.prototype.replace` and `$&` / `$1` mangling
+ * (CodeRabbit on PR #21) cannot regress.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ buildSubstitutions,
+ renderTemplate,
+} from "../../../src/core/brain/templates.ts";
+
+describe("renderTemplate", () => {
+ test("replaces a single placeholder verbatim", () => {
+ const subs = new Map([["vault_name", "alpha"]]);
+ expect(renderTemplate("Hello {{vault_name}}!", subs)).toBe("Hello alpha!");
+ });
+
+ test("replaces multiple placeholders independently", () => {
+ const subs = new Map([
+ ["vault_name", "alpha"],
+ ["schema_version", "1"],
+ ]);
+ expect(
+ renderTemplate(
+ "vault {{vault_name}} schema {{schema_version}}",
+ subs,
+ ),
+ ).toBe("vault alpha schema 1");
+ });
+
+ test("preserves literal $& / $1 in substitution values (regression: CR on PR #21)", () => {
+ // String-form `replace` treats `$&`, `$1`, etc. in the
+ // replacement value as backreference syntax. A vault basename
+ // like `pay-$1` (or any future field carrying `$`) must round-
+ // trip verbatim β€” the renderer uses the function form for this.
+ const cases: ReadonlyArray<readonly [string, string]> = [
+ ["pay-$1", "pay-$1"],
+ ["team-$&", "team-$&"],
+ ["double-$$", "double-$$"],
+ ["mixed-$1-and-$&", "mixed-$1-and-$&"],
+ ];
+ for (const [input, expected] of cases) {
+ const subs = new Map([["vault_name", input]]);
+ expect(renderTemplate("name={{vault_name}}", subs)).toBe(
+ `name=${expected}`,
+ );
+ }
+ });
+
+ test("unknown placeholders are left intact (visible typo)", () => {
+ const subs = new Map([["vault_name", "alpha"]]);
+ expect(renderTemplate("Hi {{vault_naem}}", subs)).toBe("Hi {{vault_naem}}");
+ });
+
+ test("placeholder spacing tolerates whitespace inside braces", () => {
+ const subs = new Map([["vault_name", "alpha"]]);
+ expect(renderTemplate("X {{ vault_name }} Y", subs)).toBe("X alpha Y");
+ });
+});
+
+describe("buildSubstitutions", () => {
+ test("derives vault_name from path basename", () => {
+ const subs = buildSubstitutions("/srv/projects/example");
+ expect(subs.get("vault_name")).toBe("example");
+ });
+
+ test("falls back to 'Second Brain' on a vault path without a usable basename", () => {
+ const subs = buildSubstitutions("/");
+ expect(subs.get("vault_name")).toBe("Second Brain");
+ });
+
+ test("schema_version comes from the supplied BrainConfig", () => {
+ const subs = buildSubstitutions("/srv/projects/example");
+ expect(subs.get("schema_version")).toBe("1");
+ });
+});
diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.ts
new file mode 100644
index 00000000..55ffa70b
--- /dev/null
+++ b/tests/core/brain/upgrade.test.ts
@@ -0,0 +1,301 @@
+/**
+ * Tests for `src/core/brain/upgrade.ts`.
+ *
+ * Two layers:
+ * 1. `mergeBrainYaml` β€” pure string transform. Covers missing
+ * sections, missing nested keys, all-present, malformed input
+ * handled at planUpgrade caller (not here).
+ * 2. `planUpgrade` / `applyUpgrade` β€” end-to-end against fixture
+ * vaults bootstrapped via `bootstrapBrain`.
+ */
+
+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 { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import {
+ applyUpgrade,
+ mergeBrainYaml,
+ planUpgrade,
+} from "../../../src/core/brain/upgrade.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { brainConfigPath, brainManualPath } from "../../../src/core/brain/paths.ts";
+import { LEGACY_OVERVIEW_REL_PATH } from "../../../src/core/brain/templates.ts";
+import { listSnapshots } from "../../../src/core/brain/snapshot.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-upgrade-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-upgrade-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("mergeBrainYaml", () => {
+ const FULL = `schema_version: 1
+
+primary_agent: null
+
+dream:
+ candidate_threshold: 3
+ unconfirmed_window_days: 14
+ contradiction_window_days: 14
+
+retire:
+ stale_evidence_days: 90
+
+confidence:
+ 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
+`;
+
+ test("identical input β†’ identical output (no merge needed)", () => {
+ expect(mergeBrainYaml(FULL, FULL)).toBe(FULL);
+ });
+
+ test("missing top-level section is appended at end-of-file", () => {
+ const minimal = `schema_version: 1
+
+primary_agent: null
+
+dream:
+ candidate_threshold: 3
+ unconfirmed_window_days: 14
+ contradiction_window_days: 14
+`;
+ const merged = mergeBrainYaml(minimal, FULL);
+ expect(merged).toContain("retire:");
+ expect(merged).toContain("stale_evidence_days: 90");
+ expect(merged).toContain("snapshots:");
+ expect(merged).toContain("retention_count: 10");
+ // Existing keys must remain at their original spot.
+ expect(merged.indexOf("schema_version: 1")).toBeLessThan(
+ merged.indexOf("retire:"),
+ );
+ expect(merged.indexOf("dream:")).toBeLessThan(merged.indexOf("retire:"));
+ });
+
+ test("missing nested key is inserted at end of its section", () => {
+ const live = `schema_version: 1
+
+primary_agent: null
+
+dream:
+ candidate_threshold: 3
+ unconfirmed_window_days: 14
+ contradiction_window_days: 14
+
+retire:
+ stale_evidence_days: 90
+
+confidence:
+ low_max_applied: 2
+ high_min_applied: 10
+ high_freshness_factor: 0.8
+ medium_min: 0.40
+
+snapshots:
+ retention_count: 10
+`;
+ const merged = mergeBrainYaml(live, FULL);
+ expect(merged).toContain("high_min: 0.75");
+ // Existing `medium_min` line stays where it is.
+ const lines = merged.split("\n");
+ const mediumIdx = lines.findIndex((l) => l.includes("medium_min: 0.40"));
+ const highIdx = lines.findIndex((l) => l.includes("high_min: 0.75"));
+ expect(highIdx).toBeGreaterThan(mediumIdx);
+ });
+
+ test("user-customised value is preserved (never rewritten)", () => {
+ const live = `schema_version: 1
+
+primary_agent: null
+
+dream:
+ candidate_threshold: 5
+ unconfirmed_window_days: 14
+ contradiction_window_days: 14
+
+retire:
+ stale_evidence_days: 90
+
+confidence:
+ 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
+`;
+ const merged = mergeBrainYaml(live, FULL);
+ // The user-tuned candidate_threshold of 5 must survive.
+ expect(merged).toContain("candidate_threshold: 5");
+ expect(merged).not.toContain("candidate_threshold: 3");
+ });
+});
+
+describe("planUpgrade", () => {
+ test("freshly-bootstrapped vault β†’ all files noop", () => {
+ const plan = planUpgrade(vault);
+ expect(plan.pending).toBe(0);
+ expect(plan.errors).toBe(0);
+ for (const f of plan.files) {
+ expect(f.status).toBe("noop");
+ }
+ });
+
+ test("file ordering is _brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md", () => {
+ const plan = planUpgrade(vault);
+ expect(plan.files.map((f) => f.path)).toEqual([
+ "Brain/_brain.yaml",
+ "Brain/_BRAIN.md",
+ LEGACY_OVERVIEW_REL_PATH,
+ ]);
+ });
+
+ test("missing snapshots section in _brain.yaml β†’ update with appended block", () => {
+ const yamlPath = brainConfigPath(vault);
+ const original = readFileSync(yamlPath, "utf8");
+ // Strip the snapshots block.
+ const without = original.replace(/\nsnapshots:[\s\S]*$/, "\n");
+ atomicWriteFileSync(yamlPath, without);
+
+ const plan = planUpgrade(vault);
+ expect(plan.pending).toBe(1);
+ const yamlPlan = plan.files.find((f) => f.path === "Brain/_brain.yaml")!;
+ expect(yamlPlan.status).toBe("update");
+ expect(yamlPlan.before).toBe(without);
+ expect(yamlPlan.after).toContain("snapshots:");
+ expect(yamlPlan.after).toContain("retention_count: 10");
+ });
+
+ test("malformed _brain.yaml surfaces as error (apply must refuse)", () => {
+ atomicWriteFileSync(brainConfigPath(vault), "not: a valid: brain yaml\n");
+ const plan = planUpgrade(vault);
+ expect(plan.errors).toBe(1);
+ const yamlPlan = plan.files.find((f) => f.path === "Brain/_brain.yaml")!;
+ expect(yamlPlan.status).toBe("error");
+ expect(yamlPlan.error.length).toBeGreaterThan(0);
+ });
+
+ test("missing _brain.yaml β†’ status: update with empty before (recoverable)", () => {
+ // ENOENT path: a user (or a bad rsync) deleted _brain.yaml from
+ // an otherwise-bootstrapped vault. Upgrade must restore it from
+ // the canonical default rather than refusing every managed-file
+ // update behind one missing config.
+ rmSync(brainConfigPath(vault), { force: true });
+ const plan = planUpgrade(vault);
+ expect(plan.errors).toBe(0);
+ const yamlPlan = plan.files.find((f) => f.path === "Brain/_brain.yaml")!;
+ expect(yamlPlan.status).toBe("update");
+ expect(yamlPlan.before).toBe("");
+ expect(yamlPlan.after).toContain("schema_version: 1");
+ });
+
+ test("hand-edited _BRAIN.md β†’ status update with full diff", () => {
+ atomicWriteFileSync(brainManualPath(vault), "stale operator copy\n");
+ const plan = planUpgrade(vault);
+ const manualPlan = plan.files.find((f) => f.path === "Brain/_BRAIN.md")!;
+ expect(manualPlan.status).toBe("update");
+ expect(manualPlan.before).toBe("stale operator copy\n");
+ expect(manualPlan.after).toContain("Brain");
+ });
+
+ test("missing _OPEN_SECOND_BRAIN.md β†’ status update with empty before", () => {
+ const overviewPath = join(vault, LEGACY_OVERVIEW_REL_PATH);
+ rmSync(overviewPath, { force: true });
+ const plan = planUpgrade(vault);
+ const ovPlan = plan.files.find((f) => f.path === LEGACY_OVERVIEW_REL_PATH)!;
+ expect(ovPlan.status).toBe("update");
+ expect(ovPlan.before).toBe("");
+ expect(ovPlan.after.length).toBeGreaterThan(0);
+ });
+});
+
+describe("applyUpgrade", () => {
+ test("nothing to do β†’ no snapshot, no log row", () => {
+ const before = listSnapshots(vault).length;
+ const res = applyUpgrade(vault, { agent: "claude-vps-agent" });
+ expect(res.files_updated).toEqual([]);
+ expect(res.run_id).toBe("");
+ expect(listSnapshots(vault).length).toBe(before);
+ });
+
+ test("pending update β†’ snapshot, files rewritten, idempotent re-run", () => {
+ atomicWriteFileSync(brainManualPath(vault), "stale operator copy\n");
+ const res = applyUpgrade(vault, { agent: "claude-vps-agent" });
+ expect(res.run_id.startsWith("upgrade-")).toBe(true);
+ expect(res.files_updated).toContain("Brain/_BRAIN.md");
+ // Snapshot exists with the upgrade prefix.
+ const snaps = listSnapshots(vault);
+ expect(snaps.some((s) => s.run_id === res.run_id)).toBe(true);
+ // The live file is now the canonical template body.
+ expect(readFileSync(brainManualPath(vault), "utf8")).not.toBe(
+ "stale operator copy\n",
+ );
+ // Idempotent re-run: plan is now empty.
+ const res2 = applyUpgrade(vault, { agent: "claude-vps-agent" });
+ expect(res2.files_updated).toEqual([]);
+ });
+
+ test("log row records run id, agent, snapshot, files list", () => {
+ atomicWriteFileSync(brainManualPath(vault), "stale operator copy\n");
+ const res = applyUpgrade(vault, {
+ agent: "claude-vps-agent",
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ const logPath = join(vault, "Brain", "log", "2026-05-18.md");
+ expect(existsSync(logPath)).toBe(true);
+ const logBody = readFileSync(logPath, "utf8");
+ expect(logBody).toContain("upgrade");
+ expect(logBody).toContain(res.run_id);
+ expect(logBody).toContain("claude-vps-agent");
+ expect(logBody).toContain("Brain/_BRAIN.md");
+ });
+
+ test("malformed _brain.yaml refuses to apply (no snapshot taken)", () => {
+ atomicWriteFileSync(brainConfigPath(vault), "not: a valid: brain yaml\n");
+ const before = listSnapshots(vault).length;
+ expect(() => applyUpgrade(vault, { agent: "claude" })).toThrow(
+ /upgrade aborted/,
+ );
+ expect(listSnapshots(vault).length).toBe(before);
+ });
+
+ test("can rollback to upgrade-<ts> snapshot to undo the apply", () => {
+ atomicWriteFileSync(brainManualPath(vault), "stale operator copy\n");
+ const beforeBytes = readFileSync(brainManualPath(vault), "utf8");
+ const res = applyUpgrade(vault, { agent: "claude" });
+ expect(res.files_updated.length).toBeGreaterThan(0);
+ // Smoke: snapshot is restorable. We don't run restoreSnapshot
+ // directly here β€” that path has its own coverage; we just verify
+ // the snapshot exists and the upgrade actually changed bytes.
+ const afterBytes = readFileSync(brainManualPath(vault), "utf8");
+ expect(afterBytes).not.toBe(beforeBytes);
+ expect(listSnapshots(vault).some((s) => s.run_id === res.run_id)).toBe(true);
+ });
+});
diff --git a/tests/e2e/brain-capture-and-fields.test.ts b/tests/e2e/brain-capture-and-fields.test.ts
index 67926dd0..e606f2eb 100644
--- a/tests/e2e/brain-capture-and-fields.test.ts
+++ b/tests/e2e/brain-capture-and-fields.test.ts
@@ -131,13 +131,25 @@ describe("capture + migration end-to-end", () => {
expect(afterMigrate).not.toMatch(/^status: confirmed$/m);
const snapDir = join(vault, "Brain", ".snapshots");
- const snaps = readdirSync(snapDir).filter((n) => n.startsWith("migrate-"));
+ const snaps = readdirSync(snapDir).filter(
+ (n) => n.startsWith("migrate-") && n.endsWith(".tar.zst"),
+ );
expect(snaps.length).toBe(1);
- // Step 6: rollback restores the legacy shape.
+ // Step 6: rollback restores the legacy shape. The migration
+ // intentionally drifted the live tree from the snapshot moment,
+ // so v0.10.6 rollback requires `--force-rollback` to overwrite.
const runId = snaps[0]!.replace(/\.tar\.zst$/, "");
r = await runCli(
- ["brain", "rollback", runId, "--vault", vault, "--yes"],
+ [
+ "brain",
+ "rollback",
+ runId,
+ "--vault",
+ vault,
+ "--yes",
+ "--force-rollback",
+ ],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.ts
index 9639021a..01351e4c 100644
--- a/tests/hooks/detect.test.ts
+++ b/tests/hooks/detect.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test";
import {
detectHookRuntime,
isArtifactToolName,
- isLogToolName,
+ isBrainEventToolName,
summarizeTurn,
} from "../../hooks/lib/detect.ts";
@@ -23,9 +23,9 @@ describe("isArtifactToolName", () => {
);
});
-describe("isLogToolName", () => {
+describe("isBrainEventToolName", () => {
test("recognises the bare name used in Codex transcripts", () => {
- expect(isLogToolName("event_log_append")).toBe(true);
+ expect(isBrainEventToolName("event_log_append")).toBe(true);
});
test("recognises the Claude Code plugin-decorated MCP name", () => {
@@ -33,36 +33,67 @@ describe("isLogToolName", () => {
// Claude prefixes plugin-supplied MCP tools with
// `mcp__plugin_<plugin>_<server>__`.
expect(
- isLogToolName("mcp__plugin_open-second-brain_open-second-brain__event_log_append"),
+ isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain__event_log_append"),
).toBe(true);
});
test("recognises the legacy short MCP name", () => {
// Older Claude builds (and some forks) used a shorter prefix.
- expect(isLogToolName("mcp__open-second-brain__event_log_append")).toBe(true);
+ expect(isBrainEventToolName("mcp__open-second-brain__event_log_append")).toBe(true);
});
test("rejects unrelated names", () => {
- expect(isLogToolName("second_brain_capture")).toBe(false);
- expect(isLogToolName("Write")).toBe(false);
- expect(isLogToolName("event_log_append_other")).toBe(false);
- expect(isLogToolName("not_event_log_append")).toBe(false);
+ expect(isBrainEventToolName("second_brain_capture")).toBe(false);
+ expect(isBrainEventToolName("Write")).toBe(false);
+ expect(isBrainEventToolName("event_log_append_other")).toBe(false);
+ expect(isBrainEventToolName("not_event_log_append")).toBe(false);
});
test("rejects names that contain the suffix but not as a `__`-bounded token", () => {
- expect(isLogToolName("xevent_log_append")).toBe(false);
+ expect(isBrainEventToolName("xevent_log_append")).toBe(false);
+ });
+
+ // Β§30 Β§A (v0.10.6) β€” `brain_feedback` and `brain_apply_evidence`
+ // are now equally valid brain-events from the guardrail's
+ // perspective. The same name-suffix / MCP-prefix coverage applies.
+ test("recognises `brain_feedback` (bare)", () => {
+ expect(isBrainEventToolName("brain_feedback")).toBe(true);
+ });
+
+ test("recognises `brain_feedback` under the Claude Code plugin prefix", () => {
+ expect(
+ isBrainEventToolName(
+ "mcp__plugin_open-second-brain_open-second-brain__brain_feedback",
+ ),
+ ).toBe(true);
+ });
+
+ test("recognises `brain_apply_evidence` (bare and prefixed)", () => {
+ expect(isBrainEventToolName("brain_apply_evidence")).toBe(true);
+ expect(
+ isBrainEventToolName(
+ "mcp__plugin_open-second-brain_open-second-brain__brain_apply_evidence",
+ ),
+ ).toBe(true);
+ });
+
+ test("rejects nearby but non-matching brain_* names", () => {
+ expect(isBrainEventToolName("brain_query")).toBe(false);
+ expect(isBrainEventToolName("brain_doctor")).toBe(false);
+ expect(isBrainEventToolName("brain_digest")).toBe(false);
+ expect(isBrainEventToolName("xbrain_feedback")).toBe(false);
});
});
describe("summarizeTurn", () => {
- test("artifact without log β†’ hadArtifact && !hadLog", () => {
+ test("artifact without log β†’ hadArtifact && !hadBrainEvent", () => {
const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }]);
- expect(s).toEqual({ hadArtifact: true, hadLog: false });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
- test("artifact AND MCP log β†’ hadLog wins", () => {
+ test("artifact AND MCP log β†’ hadBrainEvent wins", () => {
const s = summarizeTurn([{ name: "Write" }, { name: "event_log_append" }]);
- expect(s).toEqual({ hadArtifact: true, hadLog: true });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
});
test("artifact + bash that runs `o2b append-event` counts as log", () => {
@@ -70,7 +101,7 @@ describe("summarizeTurn", () => {
[{ name: "apply_patch" }, { name: "Bash" }],
["o2b append-event 'fixed bug'"],
);
- expect(s).toEqual({ hadArtifact: true, hadLog: true });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
});
test("artifact + bash that runs the legacy `vault-log` wrapper counts as log", () => {
@@ -78,7 +109,7 @@ describe("summarizeTurn", () => {
[{ name: "Write" }, { name: "Bash" }],
["vault-log 'noted finding'"],
);
- expect(s).toEqual({ hadArtifact: true, hadLog: true });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
});
test("the trailing space in the `vault-log ` needle prevents false matches on paths", () => {
@@ -89,7 +120,7 @@ describe("summarizeTurn", () => {
[{ name: "Write" }, { name: "Bash" }],
["cat /srv/audit/vault-log.json"],
);
- expect(s).toEqual({ hadArtifact: true, hadLog: false });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
test("starting the MCP server (`o2b mcp …`) does NOT count as log", () => {
@@ -101,17 +132,58 @@ describe("summarizeTurn", () => {
[{ name: "Write" }, { name: "Bash" }],
["o2b mcp --vault /tmp/vault"],
);
- expect(s).toEqual({ hadArtifact: true, hadLog: false });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
test("bash without an OSB log command does NOT count as log", () => {
const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }], ["echo hello"]);
- expect(s).toEqual({ hadArtifact: true, hadLog: false });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
test("read-only tools yield no artifact", () => {
const s = summarizeTurn([{ name: "Read" }, { name: "Grep" }]);
- expect(s).toEqual({ hadArtifact: false, hadLog: false });
+ expect(s).toEqual({ hadArtifact: false, hadBrainEvent: false });
+ });
+
+ // Β§30 Β§A (v0.10.6) coverage: every brain-event variant counts.
+ test("artifact + `brain_feedback` MCP call clears guardrail", () => {
+ const s = summarizeTurn([
+ { name: "Write" },
+ { name: "mcp__plugin_open-second-brain_open-second-brain__brain_feedback" },
+ ]);
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + `brain_apply_evidence` MCP call clears guardrail", () => {
+ const s = summarizeTurn([
+ { name: "apply_patch" },
+ { name: "brain_apply_evidence" },
+ ]);
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + bash `o2b brain feedback` clears guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "Edit" }, { name: "Bash" }],
+ ["o2b brain feedback --topic foo --signal positive --principle bar"],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + bash `o2b brain apply-evidence` clears guardrail", () => {
+ const s = summarizeTurn(
+ [{ name: "MultiEdit" }, { name: "Bash" }],
+ ["o2b brain apply-evidence --pref pref-foo --artifact '[[a]]' --result applied"],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + `o2b brain query` does NOT clear guardrail (read-only)", () => {
+ const s = summarizeTurn(
+ [{ name: "Write" }, { name: "Bash" }],
+ ["o2b brain query --preference pref-foo"],
+ );
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
});
diff --git a/tests/scripts/macos-sqlite-shim.test.ts b/tests/scripts/macos-sqlite-shim.test.ts
index 72cfc274..32e2457f 100644
--- a/tests/scripts/macos-sqlite-shim.test.ts
+++ b/tests/scripts/macos-sqlite-shim.test.ts
@@ -98,4 +98,19 @@ describe("_macos-sqlite.sh", () => {
});
expect(out).toBe(a);
});
+
+ // Β§31.2 β€” covers the `${VAR+set}` branch added during the v0.10.5
+ // CR fix. A user who deliberately exports an empty
+ // `DYLD_LIBRARY_PATH` (some CI pipelines do this) must keep that
+ // exact value; the shim must not "helpfully" populate it.
+ test("Darwin + explicit empty DYLD_LIBRARY_PATH β†’ preserved verbatim", async () => {
+ const fakePrefix = join(tmp, "homebrew-sqlite-lib");
+ mkdirSync(fakePrefix, { recursive: true });
+ const out = await runShim({
+ O2B_MACOS_FORCE_PLATFORM: "Darwin",
+ O2B_MACOS_SQLITE_PREFIXES_OVERRIDE: fakePrefix,
+ DYLD_LIBRARY_PATH: "",
+ });
+ expect(out).toBe("");
+ });
});