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.5: Brain maturity + embeddings activation β€” explorer, merge, hook cadence, macOS sqlite shim, search hints, cron template

Sol Aitkend0102eb554eb
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index bb8deadc..3dbb0f85 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.4",
+ "version": "0.10.5",
"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 d4ca5b55..16e233e8 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.4",
+ "version": "0.10.5",
"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 9712ee7c..dd8f788a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,105 @@ 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.5] - 2026-05-18
+
+Brings the v0.10.5 "Brain maturity + embeddings activation"
+cluster from `Projects/OpenSecondBrain/Features/_summary` and the
+Hermes onboarding report at
+`Projects/OpenSecondBrain/Features/embedding-provider-activation`:
+Β§14 local HTML/web explorer, Β§12 merge-suggestions plus the
+explicit `o2b brain merge` CLI, Β§4 completion of the deferred D5
+from v0.10.4 (per-runtime cadence in `hooks/lib/messages.ts`), the
+deferred D4 "good vs bad" examples in the `brain-memory` SKILL,
+and a Β§E embeddings-activation cluster (macOS sqlite shim,
+actionable `o2b search check` hints, `--cron-template`,
+`embeddings-setup` SKILL).
+
+No vault migration is required. Existing vaults stay valid:
+`merge` introduces one new retired reason (`merged-into`) and one
+new log event kind (`merge`); both surface only when the operator
+runs `o2b brain merge`.
+
+### Added
+
+- Β§14 β€” `o2b brain explorer` launches a loopback HTTP server (default
+ port `7777`, `--port <n>` to override) that renders preferences and
+ retired entries as a force-directed graph. `o2b brain explorer
+ --export <path>` writes the same view as a single offline HTML file
+ with inlined data; `--force` overwrites an existing file. Live and
+ export modes share one template at `templates/brain-explorer.html`.
+ Zero backend, no LLM, no network. Markdown is parsed in the browser
+ by a vendored ~150-line mini physics engine.
+- Β§12 β€” `o2b brain digest` gains a `## Merge suggestions` section
+ surfacing confirmed/quarantine pairs in the same `(topic, scope)`
+ whose `principle` tokens reach jaccard β‰₯ `0.6`. Pairs β‰₯ doctor's
+ own duplicate threshold continue to trip the
+ `duplicate-preferences` doctor lint. `o2b brain merge <keep>
+ <drop>` is the explicit resolver: `keep` retains its frontmatter,
+ picks up the deduped union of `evidenced_by`, the summed
+ `applied_count` and `violated_count`, and `max(last_evidence_at)`;
+ `drop` retires under reason `merged-into` with a `superseded_by`
+ wikilink to `keep`. The CLI prompts interactively unless `--force`
+ is passed; `--dry-run` reports the plan and writes nothing.
+- Β§4 (completes deferred D5 from v0.10.4) β€” `hooks/lib/messages.ts`
+ emits a per-runtime cadence line above the
+ `brain_feedback`/`brain_apply_evidence` block. Claude Code gets a
+ "many turns ahead, capture now" hint; Codex gets a "one-shot exec,
+ call before return" hint. Unknown runtime renders byte-identical
+ to the v0.10.4 baseline. Detection lives in
+ `hooks/lib/detect.ts:detectHookRuntime`, driven by hook-payload
+ shape (`transcript_path` substring or Claude's
+ `session_id`/`cwd`/`tool_use_id` triple). `stopGuardrailReason`
+ follows the same pattern.
+- Β§15 (completes deferred D4 from v0.10.4) β€” `skills/brain-memory/
+ SKILL.md` gains an `## Examples β€” good vs bad` section: four
+ contrastive pairs covering weak vs strong `principle`,
+ too-general vs precise `topic`, and `note` with versus without
+ the "why" line.
+- Β§E.1 β€” `scripts/_macos-sqlite.sh` shim, sourced from
+ `scripts/o2b` after the Bun precheck. Detects Darwin + Homebrew
+ SQLite and exports `DYLD_LIBRARY_PATH` so `bun:sqlite` picks up
+ a build with `LOAD_EXTENSION` enabled. No-op on Linux and on
+ macOS without `brew install sqlite`. Resolves the v0.10.4
+ blocker where `sqlite-vec` failed to load against Apple's
+ system SQLite (built with `SQLITE_OMIT_LOAD_EXTENSION`).
+- Β§E.2 β€” `o2b search check` gains a `recommendations` field on
+ both the human and JSON outputs. Rules surface concrete next
+ commands when `embedding_key` is missing, when `vec_extension`
+ fails to load (with a macOS-specific `brew install sqlite`
+ hint), and when the install is wired but no embeddings have
+ been computed yet.
+- Β§E.3 β€” `o2b search reindex --cron-template [--interval <N>m|h|d]`
+ prints a watchdog script, a native crontab line, and a
+ `hermes cron create` invocation. Pure stdout β€” writes nothing.
+ Default interval is 30 minutes; `--interval` accepts under
+ 60m / 24h / unlimited days.
+- Β§E.4 β€” `skills/embeddings-setup/SKILL.md` describes the
+ proactive activation flow: when to engage, decision tree based
+ on `o2b search check` output, env-var setup, macOS Homebrew
+ branch, first reindex, and the optional cron template.
+
+### Changed
+
+- `tokenise` and `jaccard` lifted from `src/core/brain/doctor.ts`
+ into `src/core/brain/similarity.ts`. No behavioural change. The
+ doctor lint `duplicate-preferences` and the new merge-candidate
+ detector now share one implementation.
+- `tests/helpers/run-cli.ts` accepts an optional `stdin` string so
+ interactive CLI prompts (`o2b brain merge`) can be exercised
+ end-to-end.
+
+### Internal
+
+- New constant `BRAIN_RETIRED_REASON.mergedInto = "merged-into"`.
+- New log event kind `BRAIN_LOG_EVENT_KIND.merge = "merge"`.
+- New typed error `BrainMergeError` with discriminated `code`
+ values for each invariant guard.
+- New typed error `CronTemplateError` for the `--cron-template`
+ interval parser.
+- `IndexCheckReport` gains an optional `recommendations` array
+ (additive, JSON consumers reading by key are unaffected).
+
## [0.10.4] - 2026-05-17
Brings the v0.10.4 "Brain onboarding quality" cluster from
@@ -1574,6 +1673,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.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
[0.10.2]: https://github.com/itechmeat/open-second-brain/compare/v0.10.1...v0.10.2
diff --git a/README.md b/README.md
index b0312f28..a43b186b 100644
--- a/README.md
+++ b/README.md
@@ -124,12 +124,14 @@ o2b brain apply-evidence Record applied / violated against a preference for
o2b brain digest Render a Markdown or JSON summary of recent Brain transitions
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.
+o2b brain merge (CLI-only) Fold one confirmed/quarantine pref into another (<keep> <drop>); --dry-run / --force; drop retires with reason 'merged-into'
o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)
o2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain/_brain.yaml (--clear)
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 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, …)
@@ -231,9 +233,10 @@ o2b brain digest --vault /path/to/vault --silent-if-empty
```
The Brain verbs in full: `init`, `feedback`, `dream`,
-`apply-evidence`, `digest`, `query`, `reject`, `pin`, `unpin`,
-`set-primary`, `snapshot diff`, `rollback`, `doctor`, `backlinks`,
-`scan-inline`, `import-session`, `migrate-frontmatter`. Seven are
+`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.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index e5afce45..9e368e12 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -354,12 +354,15 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |
| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; six lint rules |
| Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic |
-| Manage search index | `o2b search index \| reindex \| status \| check` | β€” (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite` |
+| Manage search index | `o2b search index \| reindex \| status \| check` | β€” (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) |
+| Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | β€” (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |
| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |
| Retire manually | `o2b brain reject` | β€” (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |
+| 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 |
Operations that change the **protected set** (`pin`, `unpin`,
`reject`, `rollback`) and the **index lifecycle** (`search index`,
diff --git a/docs/plans/2026-05-18-brain-maturity-design.md b/docs/plans/2026-05-18-brain-maturity-design.md
new file mode 100644
index 00000000..5461025a
--- /dev/null
+++ b/docs/plans/2026-05-18-brain-maturity-design.md
@@ -0,0 +1,786 @@
+# v0.10.5 β€” Brain maturity + embeddings activation
+
+Status: draft
+Owners: TBD
+Source: `/root/vault/Projects/OpenSecondBrain/Features/_summary.md` Β§14, Β§12, Β§15-tail, Β§4-tail; `/root/vault/Projects/OpenSecondBrain/Features/embedding-provider-activation.md` (Hermes onboarding report)
+
+## Context
+
+`_summary` groups four items under the theme "Brain maturity, when rules
+grow numerous". They are independent in code surface but share one
+intent: once a vault accumulates tens of preferences, the operator and
+the agents need (a) a way to see the rule set as a graph rather than a
+flat list, (b) a way to recognise and resolve near-duplicate rules
+without LLM help, (c) better calibration of new entries at the moment
+they are written, and (d) per-runtime cadence reminders so the existing
+record-discipline scales to long Claude Code sessions and one-shot Codex
+execs without drifting.
+
+All four ship in one PR under the `v0.10.5` CHANGELOG entry. They share
+no executable surface, but they share the deferred-work block in
+`_summary.md` (two of them retire entries there), the digest renderer
+(Β§12 adds a section), and the `tokenise`/`jaccard` helpers (Β§12 lifts
+them out of `doctor.ts` so both `doctor` and `merge-candidates` reuse
+one implementation β€” DRY).
+
+## Goals
+
+- **G1.** A local browser-based explorer over `Brain/preferences/` and
+ `Brain/retired/`. Two modes: live (loopback HTTP server, re-reads on
+ every `/data.json` request, no watchers) and static export (single
+ HTML file with inlined data, no server). Zero backend, no LLM, no
+ network. Force layout, status / scope / topic filters, full-text
+ search over `principle` and `topic`, right-side detail panel.
+- **G2.** Merge-suggestions in `brain_digest` plus an explicit
+ `o2b brain merge <keep-pref-id> <drop-pref-id>` CLI. The digest
+ surfaces pairs of confirmed/quarantine preferences with same
+ `(topic, scope)` and jaccard-similar `principle` between
+ `JACCARD_MERGE_SUGGEST_THRESHOLD` and `JACCARD_DUPLICATE_THRESHOLD`.
+ The CLI merges keep-first: `keep` stays, `drop` retires with reason
+ `merged-into`. No auto-merge.
+- **G3.** A `## Examples β€” good vs bad` section in
+ `skills/brain-memory/SKILL.md`. Four contrastive pairs covering weak
+ vs strong `principle`, too-general vs precise `topic`, and `note`
+ with and without "why".
+- **G4.** Per-runtime cadence in `hooks/lib/messages.ts:postWriteReminder`
+ and `hooks/lib/messages.ts:stopGuardrailReason`. Runtime is detected
+ from the hook payload shape via a new `detectHookRuntime` helper in
+ `hooks/lib/detect.ts`. Three branches: `claudecode`, `codex`,
+ `unknown`. Unknown is byte-identical to the current text β€” absolute
+ back-compat.
+- **G5.** macOS `sqlite-vec` activation works out of the box. A new
+ `scripts/_macos-sqlite.sh` shim, sourced from `scripts/o2b`,
+ detects Darwin + Homebrew SQLite and exports `DYLD_LIBRARY_PATH`
+ so `bun:sqlite` picks up a build with `LOAD_EXTENSION` enabled.
+ No-op on Linux and on macOS without `brew install sqlite`.
+- **G6.** `o2b search check` becomes actionable: when
+ `vec_extension: unavailable` or `embedding_key: missing`, the
+ output ends with a concrete recipe (env var to set, brew command
+ to run, next command to invoke). JSON output gains a
+ `recommendations` array with the same shape.
+- **G7.** `o2b search reindex --cron-template` prints a ready-to-use
+ watchdog script plus crontab line (and a `hermes cron create`
+ invocation when applicable). Pure stdout, writes nothing β€” agents
+ copy the recipe into the host's cron infrastructure. Preserves
+ the "no daemon in OSB core" invariant.
+- **G8.** New `embeddings-setup` SKILL describing when to engage
+ the proactive setup flow (trigger: user mentions embeddings /
+ semantic search / `o2b search check` warns) and the exact step
+ sequence (check β†’ request key β†’ on macOS suggest `brew install
+ sqlite` β†’ reindex β†’ offer `--cron-template`).
+
+## Non-goals (explicitly deferred)
+
+Each entry below is recorded in `_summary.md β†’ ## Deferred work` in the
+same commit so it survives across planning sessions.
+
+- **D14.1 β€” Obsidian deep-link on double-click in the explorer.** The
+ live mode could open `obsidian://` URIs since it knows the vault
+ path; the export mode runs from anywhere on disk and does not. We
+ keep the surfaces identical: principle visible in the right panel,
+ id button to copy. Trigger to revisit: an operator asking for
+ click-through into Obsidian.
+- **D14.2 β€” Live refresh in the explorer (SSE / WebSocket).** Manual
+ F5 is enough for the first iteration. A push channel breaks the
+ "zero backend" invariant. Trigger: an operator asking for it.
+- **D14.3 β€” Layout-state persistence across runs.** Nodes resettle
+ every load. `localStorage` keyed by `id β†’ {x, y}` is cheap but not
+ critical. Trigger: visible complaint about positions jumping.
+- **D12.1 β€” MCP `brain_merge` tool.** Merge is rare, mutating, and
+ operator-initiated after reviewing the digest. The agent should not
+ call it autonomously. Trigger: a concrete agent use-case that
+ warrants automating the choice.
+- **D12.2 β€” Bulk / interactive merge walkthrough.** Today the CLI
+ takes one `(keep, drop)` pair per invocation. Trigger: β‰₯10 stable
+ suggestions surface in `brain_digest` for at least one operator.
+
+## Β§14 β€” Local explorer
+
+### Surface
+
+```
+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
+o2b brain explorer --export <path> --force # overwrite an existing file
+o2b brain explorer --vault <path> [...] # override the configured vault
+```
+
+Live binds to `127.0.0.1` only. The CLI prints the URL and waits on
+SIGINT. Every GET `/` rebuilds the graph from disk and substitutes the
+JSON into the template; every GET `/data.json` does the same and serves
+the bare JSON. No watchers, no caches, no write endpoints. Bun's
+`Bun.serve` is the HTTP layer (already a project dependency).
+
+Export reads the same template, replaces the data placeholder, writes
+to the given path. Without `--force` an existing file aborts with exit
+1. No partial writes β€” the file is written atomically through the
+existing `fs-atomic` helper.
+
+### Modules
+
+```
+src/core/brain/explorer.ts
+ - collectExplorerData(vault: string): ExplorerGraph // pure read
+ - renderExportedHtml(graph: ExplorerGraph): string // template + inline JSON
+ - buildLiveServer(vault: string, port: number): // Bun.serve
+ { url: string; close: () => Promise<void> }
+
+templates/brain-explorer.html
+ - <style> ~80 lines, system fonts, light/dark via prefers-color-scheme
+ - <body> canvas, left panel (filters + search), right panel (node details)
+ - <script type="application/json" id="brain-data">__GRAPH_JSON__</script>
+ - <script> ~250 lines:
+ parseGraph, miniForceLayout, canvasRenderLoop,
+ hitTest, filterAndSearch, renderRightPanel
+```
+
+The placeholder `__GRAPH_JSON__` is a unique sentinel string that
+appears nowhere else in the template. Both live and export substitute
+the same way.
+
+### Graph schema
+
+```ts
+interface ExplorerGraph {
+ readonly generated_at: string; // ISO-8601
+ readonly schema_version: 1;
+ readonly vault_basename: string; // last segment of vault path, for the page <title>
+ readonly nodes: ReadonlyArray<ExplorerNode>;
+ readonly edges: ReadonlyArray<ExplorerEdge>;
+}
+
+interface ExplorerNode {
+ readonly id: string; // "pref-*" or "ret-*"
+ readonly kind: "preference" | "retired";
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle: string; // full body β€” used for tooltip and search
+ readonly status: "unconfirmed" | "confirmed" | "quarantine" | "retired";
+ readonly confidence: "low" | "medium" | "high" | null;
+ readonly confidence_value: number | null;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly pinned: boolean;
+ readonly retired_reason: string | null;
+ readonly last_evidence_at: string | null;
+ readonly backlink_count: number;
+}
+
+interface ExplorerEdge {
+ readonly source: string; // pref-* or ret-* id
+ readonly target: string; // pref-* or ret-* id
+ readonly kind: "supersedes" | "wikilink";
+}
+```
+
+Signals (`sig-*`) and log days are deliberately excluded from the
+graph β€” they are noise for observability. Edges come from two sources:
+
+1. Frontmatter `supersedes` / `superseded_by` β†’ kind `supersedes`.
+2. Inline `[[...]]` in `principle` and pref/retired body text β†’
+ kind `wikilink`. The existing `buildBacklinkIndex` already enumerates
+ these; the explorer filters its output down to edges where both
+ endpoints are preference or retired ids.
+
+`backlink_count` is the count of inbound edges *of any kind in the
+backlink index* β€” including refs from log entries and signals β€” so it
+matches what `brain_digest` already reports under "Top referenced".
+
+Stable ordering: nodes sorted by `(kind asc, id asc)`, edges by
+`(source asc, target asc, kind asc)`. The same vault state produces
+byte-identical JSON across runs.
+
+### Visual coding (browser-side)
+
+- **Node colour by status:** confirmed = green, unconfirmed = yellow,
+ quarantine = orange, retired = grey. Concrete hex values match the
+ digest section labels for cross-surface consistency (TBD in impl β€”
+ pick once, write once).
+- **Pinned:** gold stroke around the node.
+- **Size:** `8 + sqrt(applied_count) * 6`, clamped to `[8, 40]`.
+- **Edge style:** `supersedes` β€” red dashed; `wikilink` β€” thin grey.
+- **Clustering:** soft attractor per `topic` (virtual centre, weak
+ spring); topic centres weakly repel each other. No layered layout,
+ just charge + spring.
+
+### Mini physics engine
+
+A Verlet-style integrator in plain JS, ~150 lines. State per node:
+`{x, y, vx, vy}`. Per tick: (a) topic-centre attraction with constant
+`K_TOPIC = 0.005`, (b) global charge repulsion `K_CHARGE = 600` against
+all other nodes, (c) edge spring `K_SPRING = 0.05` with rest length
+proportional to size sum, (d) velocity damping 0.85, (e) clamp to
+canvas. `requestAnimationFrame` loop. Layout settles in ~3–5 seconds on
+~200 nodes (back-of-envelope; verify in impl).
+
+Quality is acceptable up to ~300 nodes. For larger vaults a notice
+"layout may be sluggish β€” consider filtering by topic" in the right
+panel; we do not gate.
+
+### Right panel
+
+Selected node renders:
+- id, principle, topic, scope.
+- status badge with confidence band/value.
+- applied_count / violated_count.
+- pinned flag.
+- last_evidence_at.
+- backlink_count.
+- retired_reason and superseded-by link if retired.
+- list of inbound and outbound edges with kind labels.
+
+Empty selection: short legend (colour β†’ status, size β†’ applied_count,
+edge styles) and counts (N preferences, M retired, K edges).
+
+### Error handling
+
+| Condition | Behaviour |
+|---|---|
+| `--vault` not found | `CliError` from existing `resolveBrainVault` |
+| `Brain/preferences/` and `Brain/retired/` both absent | empty graph, HTML shows "No preferences yet" |
+| corrupt frontmatter in a `pref-*.md` | skip the node, stderr warning once (same convention as digest) |
+| live port already in use | exit 1, message "port 7777 already in use; try --port N" |
+| `--export <path>` already exists, no `--force` | exit 1, message "<path> exists; pass --force to overwrite" |
+
+## Β§12 β€” Merge suggestions and `o2b brain merge`
+
+### Surface
+
+```
+o2b brain merge <keep-pref-id> <drop-pref-id> [--dry-run] [--force] [--vault <path>]
+```
+
+- Without flags, the CLI prints the plan (resulting `evidenced_by`,
+ `applied_count`, `violated_count`, retired path for `drop`) and
+ prompts `y/N`. EOF or anything other than `y`/`Y` aborts.
+- `--dry-run` prints the plan and exits 0; no disk writes.
+- `--force` bypasses the interactive prompt. It does **not** bypass
+ invariant guards (mismatched topic/scope, pinned mismatch) β€” those
+ always abort.
+
+### Merge rules
+
+| `keep` field | Result |
+|---|---|
+| `id`, `topic`, `scope`, `principle`, `created_at`, `confirmed_at`, `unconfirmed_until`, `status`, `pinned` | unchanged (keep wins) |
+| `evidenced_by` | sorted dedup of `keep.evidenced_by βˆͺ drop.evidenced_by` |
+| `applied_count` | `keep + drop` |
+| `violated_count` | `keep + drop` |
+| `last_evidence_at` | `max(keep, drop)` by ISO-8601 string comparison |
+| `confidence`, `confidence_value` | unchanged at merge time β€” recomputed by the next `dream` pass from the merged counters |
+
+`drop` lands in `retired/` with:
+- `retired_reason: merged-into` (new constant in `BRAIN_RETIRED_REASON`).
+- `superseded_by: [[<keep-id>|<keep.principle>]]`.
+- `retired_at: now` (UTC, second precision, same as the rest of the
+ Brain writers).
+- `retired_by: [[Brain/log/<today>]]`.
+
+### Guards
+
+Each is a fail-loud abort with exit 1. `--force` does not bypass any of
+them β€” they are data invariants, not UX safety nets.
+
+1. Both ids resolve to files under `preferences/`. If either points
+ into `retired/` (already retired) β†’ abort.
+2. `topic` and `scope` are identical (treating `null === null`). β†’
+ abort with the suggestion "use `o2b brain reject` if `drop` is
+ wrong, not `merge`".
+3. Pin parity: if one is pinned and the other is not, the pinned side
+ must be `keep`. β†’ abort with the suggestion "put the pinned one
+ first as `<keep>`".
+4. `keep.id === drop.id` β†’ abort.
+
+### Atomicity
+
+No snapshot is created for `merge`. The operation is point-precise and
+the existing `o2b brain reject` (the closest analogue) does not snapshot
+either. Roll-back path: copy `retired/<drop-id>.md` back to
+`preferences/<drop-id>.md` and re-run `dream` to recompute counters.
+
+Write order:
+1. `writePreference({ ...mergedKeep, overwrite: true })`.
+2. `moveToRetired(vault, dropPath, "merged-into", { now, retired_by, superseded_by })`.
+3. `appendLogEvent(vault, mergeEvent)` β€” new event kind `merge`.
+4. `regenerateActiveQuiet(vault, { now })` β€” `drop` drops out of
+ `active.md`, `keep` reflects the merged counters.
+
+Step 1 leaves an intermediate state on disk where `keep` is updated but
+`drop` is still in `preferences/`. A crash between (1) and (2) would
+leave the vault with a duplicate-looking pair, which `o2b brain doctor`
+already reports as `duplicate-preferences`. No corruption, no data
+loss β€” the operator re-runs `merge` to finish.
+
+### Log event shape
+
+```markdown
+## 2026-05-18T11:23:45Z merge
+- keep: [[pref-foo|Use imperative voice in commit subjects]]
+- drop: [[pref-bar|Imperative commit messages]] (now [[ret-bar]])
+- signal_union: 8 (was 5, 4)
+- applied_sum: 17 (was 11, 6)
+- violated_sum: 1 (was 1, 0)
+- agent: <agent_name>
+```
+
+`agent` comes from the new `BRAIN_AGENT_NAME` env var that the install
+flow already sets β€” same convention as `o2b brain reject`.
+
+### `merge-candidates` detector
+
+```
+src/core/brain/merge-candidates.ts
+ - findMergeCandidates(vault: string, opts?: { threshold?: number }):
+ ReadonlyArray<MergeCandidate>
+```
+
+```ts
+interface MergeCandidate {
+ readonly a: string; // lexicographically smaller of the two ids
+ readonly b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ readonly jaccard: number; // rounded to 0.01
+}
+```
+
+The function:
+1. Reads `confirmed` and `quarantine` preferences (the same filter as
+ `checkDuplicatePreferences`).
+2. Groups by `(topic, scope ?? "")`.
+3. Pairwise jaccard on `tokenise(principle)`.
+4. Keeps pairs with `jaccard >= threshold`.
+5. Sorts by `(jaccard desc, a asc, b asc)`.
+6. Truncates to `MERGE_SUGGESTION_LIMIT = 10`.
+
+Default threshold: `JACCARD_MERGE_SUGGEST_THRESHOLD = 0.6`. Pairs in
+`[0.6, 0.85)` are merge candidates only (surface in digest). Pairs
+`>= 0.85` continue to be flagged by `doctor` as `duplicate-preferences`
+AND surface in the digest β€” the operator sees them on both surfaces at
+different intensities.
+
+### Similarity helpers (DRY)
+
+`tokenise` and `jaccard` are currently private to `src/core/brain/doctor.ts`.
+Lift them as-is to `src/core/brain/similarity.ts` and update `doctor.ts`
+to import. No functional change; existing doctor tests act as regression
+coverage. The helpers are pure functions, suitable for unit tests
+moved/duplicated under `tests/core/brain/similarity.test.ts`.
+
+### Digest integration
+
+A new optional section in `renderDigest`, between `## Top referenced`
+and `## Confidence shifts`:
+
+```markdown
+## Merge suggestions
+
+- [[pref-foo|Principle one]] β‰ˆ [[pref-bar|Principle two]] β€” topic 'mocking', scope 'testing', jaccard 0.72
+- [[pref-baz|Principle three]] β‰ˆ [[pref-qux|Principle four]] β€” topic 'commits', no scope, jaccard 0.64
+```
+
+JSON form:
+
+```ts
+interface DigestJsonMergeSuggestion {
+ readonly a: string;
+ readonly b: string;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly jaccard: number;
+}
+```
+
+Added to `DigestJson` as `merge_suggestions: ReadonlyArray<…>`. The JSON
+`schema_version` is **not** bumped: additive optional fields are
+non-breaking under the project's current convention (only changes to
+existing field shapes or removed fields would warrant a bump).
+
+Empty list β†’ section omitted in Markdown, empty array in JSON.
+
+The `isEmpty` digest predicate is **not** updated to count merge
+suggestions. `merge_suggestions` reflects current vault state, not
+windowed change β€” including it would turn every digest into "not
+empty", defeating the silent-if-no-changes contract.
+
+`MERGE_SUGGESTION_LIMIT = 10` (defined in `merge-candidates.ts` and
+re-exported, mirroring `HOT_SECTION_LIMIT`).
+
+## Β§15-tail β€” Good vs bad section in `skills/brain-memory/SKILL.md`
+
+Insertion point: after `## Rules`, before `## Fallback capture surfaces`.
+
+```markdown
+## Examples β€” good vs bad
+
+**Bad:** `principle: "Write good commits"`
+**Good:** `principle: "Use imperative voice in commit subjects; describe what the commit does, not what was done"`
+*Why:* the bad form is unenforceable β€” no future signal can reasonably mark an artifact as "applied" or "violated" against it. The good form names a checkable behaviour.
+
+**Bad:** `principle: "Be careful with secrets"`
+**Good:** `principle: "Do not commit `.env`, credentials, or API keys; route them through environment variables"`
+*Why:* the bad form is a vibe. The good form gives the agent a concrete list of patterns to spot in a diff.
+
+**Bad:** `topic: "stuff"`
+**Good:** `topic: "no-internal-abbrev"`
+*Why:* topic is the stable bucket future signals join. A generic slug collects unrelated rules; a precise one keeps the cluster meaningful and lets `brain_query --topic <slug>` return a focused slice.
+
+**Bad:** `note: "fixed it"`
+**Good:** `note: "expanded 'OSB' to 'Open Second Brain' on first use β€” README diff still carried the abbreviation, would have confused a new reader"`
+*Why:* notes survive the artifact. Without the "why" line you cannot tell in three months whether a violation was a regression or a deliberate change.
+```
+
+No code, no config. Hermes picks up the change on next gateway restart;
+Claude Code picks it up on the next `SessionStart` (the
+`sync-claude-skills.sh` hook reads the canonical source).
+
+## Β§4-tail β€” Per-runtime cadence in post-write reminder and stop guardrail
+
+### `detectHookRuntime`
+
+```
+hooks/lib/detect.ts
+ - type HookRuntime = "claudecode" | "codex" | "unknown"
+ - function detectHookRuntime(payload: unknown): HookRuntime
+```
+
+Detection order (first hit wins):
+
+1. `payload.transcript_path` is a string containing `/.claude/projects/`
+ or `/.claude/sessions/` β†’ `claudecode`.
+2. `payload.transcript_path` is a string containing `/.codex/sessions/`
+ β†’ `codex`.
+3. Payload exposes Claude Code's distinctive triple
+ (`session_id`, `cwd`, `tool_use_id` all present as strings) β†’
+ `claudecode`.
+4. Payload exposes Codex's distinctive single field
+ (`function_call_output` present, or `tool_name === "apply_patch"`
+ with `tool_input.input` being a patch string) β†’ `codex`.
+5. Otherwise β†’ `unknown`.
+
+Detection is best-effort and **silent on failure**: malformed payload,
+missing fields, unexpected types all return `unknown`. The hook never
+crashes on detection.
+
+### Reminder text
+
+`postWriteReminder({ toolName, filePath, runtime })`:
+
+```ts
+function cadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return [
+ "_Claude Code session: many turns ahead β€” capture the signal_",
+ "_or evidence now rather than batching to end-of-session; long_",
+ "_sessions risk forgetting the context that distinguishes one_",
+ "_artifact from the next._",
+ ].join("\n");
+ case "codex":
+ return [
+ "_Codex `codex exec` is a one-shot run β€” call `brain_feedback`_",
+ "_or `brain_apply_evidence` before this exec returns; there_",
+ "_is no second turn._",
+ ].join("\n");
+ case "unknown":
+ return "";
+ }
+}
+```
+
+The cadence block is rendered between the opening sentence
+(`Open Second Brain hook: you just ran ...`) and the
+`brain_feedback`/`brain_apply_evidence` paragraphs. When `runtime ===
+"unknown"` the empty string is filtered out, so the rendered text is
+byte-identical to the current v0.10.4 output β€” back-compat is
+unconditional.
+
+`stopGuardrailReason(runtime)` follows the same pattern, with its own
+cadence block:
+- `claudecode`: "_This guardrail fires at most once per turn β€” send_
+ _another reply (with or without `event_log_append`) to clear it._"
+- `codex`: "_This `codex exec` is about to end β€” call_
+ _`event_log_append` now or finish silently; no further guardrail will fire._"
+- `unknown`: empty.
+
+### Call-site updates
+
+```
+hooks/post-write-reminder.ts
+ - import detectHookRuntime
+ - const runtime = detectHookRuntime(payload)
+ - postWriteReminder({ toolName, filePath, runtime })
+
+hooks/stop-log-guardrail.ts
+ - import detectHookRuntime
+ - const runtime = detectHookRuntime(payload)
+ - reason: stopGuardrailReason(runtime)
+```
+
+`hooks.json` matchers stay unchanged.
+
+### What this does NOT touch
+
+- `templates/identity-reminder.<target>.txt` β€” those are the per-turn
+ identity reminders for Hermes / OpenClaw (shipped in v0.10.4),
+ unrelated mechanism.
+- `O2B_TARGET` env var β€” that's the resolver for `buildReminder`, not
+ for hook reminders. No new env var introduced.
+- `hooks/active-inject.ts` β€” different hook, different cadence.
+
+## Β§E β€” Embeddings activation
+
+Folded into v0.10.5 in response to the Hermes onboarding report at
+`/root/vault/Projects/OpenSecondBrain/Features/embedding-provider-activation.md`.
+Three independent slices, all additive, no breaking changes.
+
+### Β§E.1 β€” macOS `sqlite-vec` shim
+
+`scripts/_macos-sqlite.sh` is sourced by `scripts/o2b` immediately
+after the Bun precheck:
+
+```bash
+. "$SCRIPT_DIR/_bun-precheck.sh"
+. "$SCRIPT_DIR/_macos-sqlite.sh"
+exec bun run "$REPO_ROOT/src/cli/main.ts" "$@"
+```
+
+Shim contract:
+
+- Returns early on non-Darwin (Linux ignores the file entirely).
+- Returns early when `DYLD_LIBRARY_PATH` is already set β€” never
+ clobbers a user-configured environment.
+- Probes two Homebrew lib prefixes:
+ - `/opt/homebrew/opt/sqlite/lib` (Apple Silicon)
+ - `/usr/local/opt/sqlite/lib` (Intel)
+- On the first existing directory, exports `DYLD_LIBRARY_PATH=<dir>`.
+- Returns 0 unconditionally β€” the shim never blocks the wrapper.
+
+The shim does **not** install `brew sqlite`. If neither prefix
+exists, `o2b search check` will report `vec_extension: unavailable`
+and the recommendations block (Β§E.2) tells the operator what to
+run.
+
+The Bun:sqlite resolver consults `DYLD_LIBRARY_PATH` before the
+default `/usr/lib/libsqlite3.dylib`, so once the path is set Bun
+picks the Homebrew build that ships without
+`SQLITE_OMIT_LOAD_EXTENSION`. That makes `sqlite-vec`'s
+`db.loadExtension(getLoadablePath())` succeed.
+
+### Β§E.2 β€” Actionable hints in `o2b search check`
+
+`IndexCheckReport` gains an optional `recommendations: string[]`.
+The renderers (human and JSON) surface it as a block after the
+existing warnings/fatals.
+
+Recommendation rules:
+
+| Trigger | Recommendation |
+|---|---|
+| `embedding_key_resolved === false` | `Set OPEN_SECOND_BRAIN_EMBEDDING_KEY in ~/.hermes/.env (or ~/.config/open-second-brain/.env)` followed by `Pick a provider: OpenAI \`text-embedding-3-small\` (~$0.02 / 1M tokens) β€” or any OpenAI-compatible endpoint via OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL.` |
+| `vecExtension === "unavailable"` AND host is Darwin | `Install Homebrew SQLite: \`brew install sqlite\`. The o2b wrapper picks it up automatically on the next invocation.` |
+| `vecExtension === "unavailable"` AND host is Linux | `sqlite-vec did not load. Run \`bun pm ls\` to confirm the optional dependency landed, or rebuild with \`bun install --force\`.` |
+| Both above are OK AND no embeddings yet (`semantic_enabled === false`) | `Run \`o2b search reindex --embeddings\` to compute the first vectors, then optionally \`o2b search reindex --cron-template\` for periodic refresh.` |
+
+Host detection: `process.platform === "darwin"` resolves Darwin;
+no other OS branch is needed because the Linux hint is generic.
+
+JSON shape:
+
+```ts
+interface IndexCheckReport {
+ // existing fields ...
+ readonly recommendations: ReadonlyArray<string>;
+}
+```
+
+The recommendations list is empty when nothing is actionable β€”
+e.g. an already fully wired install. Existing callers that did not
+expect the field are unaffected (additive).
+
+### Β§E.3 β€” `o2b search reindex --cron-template`
+
+New flag on the existing `reindex` verb:
+
+```
+o2b search reindex --cron-template [--interval <duration>] [--vault <path>]
+```
+
+When set, the verb prints the template **to stdout and exits 0
+without indexing**. Side effects: none. The template carries:
+
+1. A bash watchdog script body (commented header explains how to
+ save it) that:
+ - Sources `~/.hermes/.env` if present, otherwise the same file
+ resolution as the rest of the CLI.
+ - Runs `o2b search reindex --embeddings --json`.
+ - Parses the JSON, suppresses output when `stats.added +
+ stats.updated + stats.deleted === 0` (no changes), prints a
+ one-line summary otherwise.
+ - Exits non-zero only on real reindex failure.
+2. A native crontab line for the chosen interval (default 30
+ minutes; `--interval 6h` / `--interval 10m` accepted with the
+ same parser used by `hermes cron`).
+3. A `hermes cron create` invocation as the recommended path on a
+ Hermes-bearing host. (Detection of Hermes is best-effort β€” the
+ line prints unconditionally with a "if Hermes is available"
+ header note. Pure stdout, no filesystem probe.)
+
+The template is rendered from a fixed string with three
+substitutions: the script's exec path (resolved through the same
+process used by `install-cli`), the chosen interval expression,
+and the Hermes job id placeholder (`<your-job-id>`). No external
+template engine.
+
+`--interval` parser shares logic with the existing duration
+parser used elsewhere in the search CLI; if the project has no
+single helper today, a new one lands in
+`src/cli/search.ts` (private) and is reused only inside that
+file.
+
+### Β§E.4 β€” `embeddings-setup` SKILL
+
+New skill at `skills/embeddings-setup/SKILL.md`. Shipped alongside
+the existing `brain-memory` SKILL so Hermes / Claude Code / Codex
+all see it in their tool list.
+
+Skill body lays out:
+
+- **When to invoke.** Triggers: user mentions "embedding",
+ "semantic search", "vector index"; OR an agent runs
+ `o2b search check` whose output contains `vec_extension:
+ unavailable` or `embedding_key: missing` or any
+ recommendation line.
+- **Decision flow.** Always start with `o2b search check`;
+ branch on what it reports. The branches mirror the
+ recommendations table from Β§E.2 so the SKILL stays in sync if
+ recommendations evolve.
+- **macOS branch.** Install `brew sqlite`, no script patching β€”
+ the OSB wrapper handles `DYLD_LIBRARY_PATH` automatically.
+- **Key handling.** Never echo or commit the key. Prompt the
+ user, then write to `~/.hermes/.env` or the configured env
+ file. Use a placeholder when the user hasn't supplied a value
+ yet so the agent never invents a fake one.
+- **Periodic indexation.** After the first successful
+ reindex, offer `o2b search reindex --cron-template` and
+ explain the interval trade-off (30 min if the vault changes
+ actively; 6 h if it's mostly read-only).
+- **Multi-agent note.** Only the agent designated as the
+ reindex owner (typically Hermes) needs
+ `OPEN_SECOND_BRAIN_EMBEDDING_KEY` β€” read-only consumers
+ (Claude Code, Codex) operate on the already-computed vectors
+ and do not need credentials.
+
+The SKILL is the proactive surface; the CLI hints in Β§E.2 are
+the reactive one. Both call the same recipes β€” the SKILL has
+narrative, the hints are one-liners with the same commands.
+
+### Β§E.5 β€” Non-goals (added to the deferred list)
+
+- **D-E.1 β€” Automatic `brew install` invocation.** The SKILL
+ tells the user / agent to run it; OSB itself never calls
+ `brew`. Adding package-manager side effects to a CLI wrapper
+ invites privilege questions and platform-specific edge cases
+ out of proportion to the win.
+- **D-E.2 β€” `o2b search reindex --watch` long-running daemon.**
+ The OSB invariant "no daemon" stands. `--cron-template` is the
+ endorsed path; `--watch` would force a process-lifecycle story
+ (systemd / launchctl / supervisor) that the project deliberately
+ avoids.
+- **D-E.3 β€” Auto-write of crontab entries.** The CLI prints the
+ template; the operator (or the agent in the user's name)
+ decides where it lands. Direct `crontab -e` invocation is
+ invasive and platform-specific.
+
+## Tests
+
+| File | Coverage |
+|---|---|
+| `tests/core/brain/explorer.test.ts` | `collectExplorerData` against a fixture vault: node and edge counts, filtering signals/log out of edges, statuses, `confidence_value === null` legacy prefs, deterministic byte-identical JSON across two runs. `renderExportedHtml` substitutes the placeholder exactly once and the resulting `<script type="application/json">` block round-trips through `JSON.parse`. |
+| `tests/cli/brain-explorer.test.ts` | `o2b brain explorer --export <tmp>` creates the file; second run without `--force` exits 1; with `--force` overwrites. Live mode β€” spawn subprocess, GET `/`, GET `/data.json`, assert Content-Type, assert `127.0.0.1` binding, SIGINT shuts down. Port already in use exits 1 with the documented message. |
+| `tests/core/brain/similarity.test.ts` | `tokenise` over utf-8, punctuation, multilingual input; `jaccard` for empty, identical, disjoint, partial. Mirrors the coverage formerly inside `doctor.test.ts` so the lift-out has explicit regression. |
+| `tests/core/brain/merge-candidates.test.ts` | Fixture-driven: pairs in `[0.6, 0.85)` surface; pairs `>= 0.85` also surface (and `doctor` still flags them); pairs across different `(topic, scope)` do not; unconfirmed and retired prefs do not; stable `(jaccard desc, a asc, b asc)` ordering; `MERGE_SUGGESTION_LIMIT` truncates. |
+| `tests/core/brain/digest.test.ts` (extended) | New fixture with a merge-candidate pair β†’ Markdown `## Merge suggestions` section and JSON `merge_suggestions` array present. Existing fixtures without candidates β†’ section absent, JSON field empty. `isEmpty` predicate not affected by merge suggestions. |
+| `tests/core/brain/merge.test.ts` | Full merge against a fixture: `evidenced_by` deduped union, summed counters, `last_evidence_at = max`, retired file with `merged-into` and `superseded_by`, `merge` log event, `active.md` regenerated, `keep.pinned` preserved. Guard cases: mismatched topic, mismatched scope, pinned mismatch (drop pinned, keep unpinned), `keep === drop`, drop already retired. `--dry-run` performs no writes. |
+| `tests/cli/brain-merge.test.ts` | CLI shape: positional parsing, error exits with documented wording, interactive `y/N` through the existing `readSingleLine` pump, `--force` skips the prompt but not the guards. |
+| `tests/hooks/detect.test.ts` (extended) | `detectHookRuntime` against fixtures of each runtime's known payload shape; malformed payloads (missing fields, wrong types) return `unknown` without throwing. |
+| `tests/hooks/post-write-reminder.test.ts` (extended) | Existing cases stay green. New: Claude Code payload produces the `Claude Code session` cadence line; Codex payload produces the `Codex exec` cadence line; unknown produces no cadence line β€” and the resulting `additionalContext` matches the pre-change v0.10.4 string byte-for-byte. |
+| `tests/hooks/stop-log-guardrail.test.ts` (extended) | Symmetric coverage for `stopGuardrailReason`. |
+| `tests/scripts/macos-sqlite-shim.test.ts` | Spawn the shim under bash with `uname` stubbed via `PATH` overrides; assert `DYLD_LIBRARY_PATH` exported only on Darwin + when a Homebrew prefix exists; assert no-op when `DYLD_LIBRARY_PATH` is preset; assert no-op on Linux (`uname` says `Linux`). |
+| `tests/core/search/check-recommendations.test.ts` | Drive `indexCheck` against curated fixtures: missing key β†’ recommendation referencing `OPEN_SECOND_BRAIN_EMBEDDING_KEY`; vec unavailable on Darwin (mock `process.platform`) β†’ `brew install sqlite`; both OK and no embeddings β†’ reindex recipe; fully healthy install β†’ empty recommendations array. |
+| `tests/cli/search-cron-template.test.ts` | `o2b search reindex --cron-template` prints a non-empty body containing the keywords `crontab`, `o2b search reindex`, and (when `--interval 6h`) `0 */6 * * *`. Verb writes nothing to disk under `tmp`; `--cron-template` without `--vault` still resolves through the existing machine config; `--cron-template --interval garbage` exits 1 with a parser error. |
+
+SKILL.md (Β§15-tail) carries no test surface β€” it is documentation. The
+`embeddings-setup` SKILL (Β§E.4) likewise: prose-only, the test surface
+is the live agent flow.
+
+## Migration
+
+None.
+
+- Β§14 is pure-read against existing Brain state, no schema change.
+- Β§12 introduces one new constant (`BRAIN_RETIRED_REASON.merged-into`)
+ and one new log event kind (`merge`). Existing vaults remain valid
+ β€” the new reason and event are only emitted when an operator runs
+ `o2b brain merge`. `brain_doctor` accepts unknown retired-reason
+ strings already (treats them as opaque).
+- Β§15-tail is text inside a SKILL file; no schema and no parser.
+- Β§4-tail is back-compat by construction: `unknown` runtime renders the
+ pre-change text byte-for-byte. The new `runtime` field on
+ `PostWriteReminderInput` is required at the type level (TypeScript
+ catches missed call-sites at compile time), but production has only
+ two call-sites (the two hook scripts) and they are updated in the
+ same PR.
+- Β§E.1 macOS shim is additive: a missing `_macos-sqlite.sh` would
+ trip the `source` line in `scripts/o2b`. Pre-existing installs
+ carry the new file via plugin update. Hosts where Bun never
+ needed the shim (Linux, macOS without brew sqlite) see no
+ behaviour change.
+- Β§E.2 `recommendations` is an additive optional field on
+ `IndexCheckReport`. Old JSON consumers that read by-key keep
+ working; new ones can opt in.
+- Β§E.3 `--cron-template` is a new flag on an existing verb; no
+ existing flag changes shape.
+- Β§E.4 SKILL is a new file under `skills/` β€” Hermes / Claude Code
+ / Codex pick it up through the normal mirror flow (no manual
+ registration needed).
+
+## Risk and known-unknowns
+
+- **Explorer layout quality on large vaults.** The Verlet mini-engine
+ is tuned for ≀300 nodes. Larger vaults (~500+) may settle slowly
+ or chaotically. Mitigation: the right panel surfaces a "consider
+ filtering by topic" hint past a node-count threshold; the operator
+ can also fall back to `o2b brain doctor` for the same information
+ in list form. Trigger to revisit: an operator reporting unusable
+ layout β€” at that point we either tune constants, swap in a smarter
+ algorithm, or take D14.x out of deferred.
+- **Force-merge of mismatched scope.** A user-friendly error message
+ must spell out *why* the merge was refused; otherwise an operator
+ may keep retrying with `--force` and miss that `--force` does not
+ bypass invariants. The impl-plan should include a fixture test on
+ the exact error wording.
+- **Hook runtime detection on future Claude Code releases.** The
+ detection relies on `transcript_path` substrings and the
+ `session_id` / `cwd` / `tool_use_id` triple. Both have changed once
+ in the project's history (the prefix on MCP tool names changed
+ twice in two months β€” see comment in `hooks/lib/detect.ts`). The
+ detector falls back to `unknown` cleanly when both signals miss,
+ so the failure mode is "the cadence hint disappears", not "the
+ hook crashes". Acceptable.
+- **Static export size.** With ~200 preferences and a Verlet engine
+ inline, the exported HTML lands around 200–300 KB. Acceptable for
+ attaching to retros and Drive backups. If it ever creeps past 1 MB
+ for a single vault, revisit (likely cause: long `principle` bodies;
+ truncate for `tooltip`, keep full in panel).
+
+## Out-of-scope
+
+See *Non-goals (explicitly deferred)* above. These items are recorded
+in `_summary.md β†’ ## Deferred work` in the same commit to survive
+across planning sessions.
diff --git a/docs/plans/2026-05-18-brain-maturity-impl.md b/docs/plans/2026-05-18-brain-maturity-impl.md
new file mode 100644
index 00000000..bbac40ab
--- /dev/null
+++ b/docs/plans/2026-05-18-brain-maturity-impl.md
@@ -0,0 +1,2149 @@
+# v0.10.5 Brain maturity β€” Implementation Plan
+
+> **For agentic workers:** Use `superpowers:executing-plans` (or
+> `superpowers:subagent-driven-development` for fresh-context-per-task
+> dispatch) to walk this plan task-by-task. Steps use checkbox
+> (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship Β§14 (local explorer), Β§12 (merge-suggestions plus
+`o2b brain merge`), Β§15-tail (good-vs-bad SKILL section), and Β§4-tail
+(per-runtime cadence for `hooks/lib/messages.ts`) from
+`Projects/OpenSecondBrain/Features/_summary` in one PR.
+
+**Architecture:** Four independent slices land in dependency order.
+Β§12 lands first because lifting `tokenise`/`jaccard` out of
+`doctor.ts` into `src/core/brain/similarity.ts` is a refactor that
+should settle before any new consumer (the new
+`merge-candidates.ts`) is wired up. Β§14 lands second β€” large slice,
+isolated module, no cross-coupling with Β§12 beyond the digest staying
+green. Β§4-tail lands third because the hook surface is small and
+back-compat by construction. Β§15-tail lands last β€” text-only, no
+test surface.
+
+- **Β§12** lifts `tokenise`/`jaccard` into `src/core/brain/similarity.ts`,
+ adds `src/core/brain/merge-candidates.ts` (read-only detector),
+ `src/core/brain/merge.ts` (mutating writer), one CLI verb `merge`,
+ a new `BRAIN_RETIRED_REASON.mergedInto` constant, a new
+ `BRAIN_LOG_EVENT_KIND.merge` constant, and a new digest section.
+- **Β§14** ships entirely under `src/core/brain/explorer.ts` plus
+ `templates/brain-explorer.html` plus one CLI verb `explorer`. No
+ cross-module dependency outside the existing `buildBacklinkIndex`
+ and `parsePreference` / `parseRetired` readers.
+- **Β§4-tail** is two-file change: `hooks/lib/detect.ts` gains
+ `detectHookRuntime`, `hooks/lib/messages.ts` gains a `runtime`
+ parameter and a `cadenceLine` helper, the two hook entry points
+ thread the value.
+- **Β§15-tail** is one inline edit in `skills/brain-memory/SKILL.md`.
+
+**Tech Stack:** TypeScript on Bun. No new external dependencies.
+Re-uses `fs-atomic.ts`, `proper-lockfile` (already in deps),
+`bun:test`, `tsc --noEmit`, `Bun.serve` for the live explorer.
+
+**Source of truth for behaviour:**
+[`docs/plans/2026-05-18-brain-maturity-design.md`](./2026-05-18-brain-maturity-design.md).
+Every task below implements a slice of that spec β€” on conflict the
+spec wins and this plan is amended.
+
+---
+
+## Plan-wide conventions
+
+These apply to every task; do not re-state per step.
+
+- **Imports.** Production code uses `node:`-prefixed builtins
+ (`node:fs`, `node:os`, `node:path`). Tests use
+ `import { test, expect, describe, beforeEach, afterEach } from "bun:test"`.
+ Always `.ts` extensions in cross-module imports.
+- **Result shape.** New public-API return values are `Object.freeze`-d
+ at the producing call site (project convention).
+- **Errors.** Reuse existing typed errors when the failure mode
+ matches. Create one new typed error `BrainMergeError` for Β§12
+ because its failure shape (mismatched topic/scope, pin parity,
+ same-id) is distinct enough to warrant a separate catch handler in
+ the CLI verb.
+- **No git from this plan.** Each task ends with **Pause for review
+ (no commit).** Active git is reserved for the user β€” see vault
+ memory `project_o2b_no_active_git`.
+- **No misleading fallbacks.** New CLI flags exit 2 with an explicit
+ message rather than silently fall through. The explorer detects
+ unknown runtime in the hook by returning the literal `"unknown"`
+ β€” that branch then renders no cadence line, which is
+ byte-identical to the pre-change reminder.
+- **Atomic writes** via `src/core/fs-atomic.ts:atomicWriteFileSync`.
+ Single-file export (Β§14 `--export`) writes through the atomic
+ helper.
+- **Style preferences (Brain active):**
+ - `pref-no-exclamation-marks-in-docs` β€” no exclamation marks in
+ prose strings (rendered text, error messages, comments).
+ - `pref-no-simply-word` β€” the word "simply" is forbidden in any
+ written artifact (docs, comments, log strings, tests).
+- **Verification.** Every task ends with a targeted `bun test
+ tests/path/to/file.test.ts` and an expected pass count. End of
+ every Phase: full `bun test` + `bun run typecheck` green.
+- **CHANGELOG.** Touched exactly once, in Phase 5. Do not bump
+ mid-PR β€” per vault memory `feedback_one_pr_one_version`.
+- **`_summary.md` (vault).** Touched exactly once, in Phase 5, in
+ the same step that bumps the CHANGELOG. Two deferred entries are
+ retired (Β§4 per-runtime hook text, Β§15 good-vs-bad SKILL section)
+ and three new entries are added (D14.1, D14.2, D14.3, D12.1,
+ D12.2). The vault is at `/root/vault/` β€” this is a VAULT edit, not
+ a repo edit, and lives outside the git tree.
+
+---
+
+## File map
+
+New files (count: 12):
+
+```
+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
+src/core/brain/merge.ts # Β§12 writer
+src/core/brain/explorer.ts # Β§14 module
+templates/brain-explorer.html # Β§14 template
+tests/core/brain/similarity.test.ts # Β§12
+tests/core/brain/merge-candidates.test.ts # Β§12
+tests/core/brain/merge.test.ts # Β§12
+tests/cli/brain-merge.test.ts # Β§12
+tests/core/brain/explorer.test.ts # Β§14
+tests/cli/brain-explorer.test.ts # Β§14
+```
+
+Modified files (count: 15):
+
+```
+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
+src/cli/brain.ts # Β§12 + Β§14 wiring
+hooks/lib/detect.ts # Β§4-tail runtime detector
+hooks/lib/messages.ts # Β§4-tail cadence
+hooks/post-write-reminder.ts # Β§4-tail call site
+hooks/stop-log-guardrail.ts # Β§4-tail call site
+skills/brain-memory/SKILL.md # Β§15-tail section
+tests/hooks/detect.test.ts # Β§4-tail
+tests/hooks/post-write-reminder.test.ts # Β§4-tail
+tests/hooks/stop-log-guardrail.test.ts # Β§4-tail
+tests/core/brain/digest.test.ts # Β§12 digest section
+CHANGELOG.md # Phase 5 only
+package.json # Phase 5 only (version bump)
+```
+
+Version-mirror files (touched once in Phase 5 via `bun run sync-version`):
+
+```
+.claude-plugin/plugin.json
+.codex-plugin/plugin.json
+plugins/codex/.codex-plugin/plugin.json
+plugins/hermes/plugin.yaml
+plugin.yaml
+openclaw.plugin.json
+__init__.py
+```
+
+`bun run sync-version` rewrites these from `package.json`; do not
+hand-edit.
+
+---
+
+## Phase 1 β€” Β§12 Merge
+
+Smallest blast radius first: lift the shared helpers, then write the
+read-only detector, then the mutating writer, then the digest section,
+then the CLI verb.
+
+### Task 1.1: Lift `tokenise` and `jaccard` into `src/core/brain/similarity.ts`
+
+**Objective:** Create the shared similarity module with the current
+helpers, byte-identical behaviour. `doctor.ts` becomes the first
+consumer.
+
+**Files:**
+- Create: `src/core/brain/similarity.ts`
+- Modify: `src/core/brain/doctor.ts` (remove the two local functions, add import)
+- Create: `tests/core/brain/similarity.test.ts`
+
+**Step 1: Write failing test**
+
+```ts
+// tests/core/brain/similarity.test.ts
+import { describe, expect, test } from "bun:test";
+import { jaccard, tokenise } from "../../../src/core/brain/similarity.ts";
+
+describe("tokenise", () => {
+ test("lowercases and splits on punctuation", () => {
+ const tokens = tokenise("Use imperative voice; describe what the commit DOES");
+ expect(tokens.has("use")).toBe(true);
+ expect(tokens.has("imperative")).toBe(true);
+ expect(tokens.has("does")).toBe(true);
+ expect(tokens.has(";")).toBe(false);
+ });
+
+ test("keeps multi-byte tokens", () => {
+ const tokens = tokenise("Π˜ΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠΉ ΠΈΠΌΠΏΠ΅Ρ€Π°Ρ‚ΠΈΠ²");
+ expect(tokens.has("ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠΉ")).toBe(true);
+ expect(tokens.has("ΠΈΠΌΠΏΠ΅Ρ€Π°Ρ‚ΠΈΠ²")).toBe(true);
+ });
+
+ test("filters tokens of length 1", () => {
+ const tokens = tokenise("a b cd");
+ expect(tokens.has("a")).toBe(false);
+ expect(tokens.has("cd")).toBe(true);
+ });
+});
+
+describe("jaccard", () => {
+ test("identical sets β†’ 1", () => {
+ expect(jaccard(new Set(["a", "b"]), new Set(["a", "b"]))).toBe(1);
+ });
+ test("disjoint sets β†’ 0", () => {
+ expect(jaccard(new Set(["a"]), new Set(["b"]))).toBe(0);
+ });
+ test("both empty β†’ 0", () => {
+ expect(jaccard(new Set(), new Set())).toBe(0);
+ });
+ test("partial overlap β†’ intersection / union", () => {
+ expect(jaccard(new Set(["a", "b", "c"]), new Set(["b", "c", "d"]))).toBeCloseTo(2 / 4, 5);
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+```
+bun test tests/core/brain/similarity.test.ts
+```
+Expected: FAIL β€” module not found.
+
+**Step 3: Write minimal implementation**
+
+Lift the two functions byte-for-byte from `src/core/brain/doctor.ts`
+into the new module. Re-export.
+
+```ts
+// src/core/brain/similarity.ts
+/**
+ * Shared similarity helpers β€” `tokenise` + `jaccard`. Lifted out of
+ * `doctor.ts` so both `duplicate-preferences` lint and the
+ * `merge-candidates` detector use one implementation (DRY).
+ *
+ * No language-specific stopword list: Brain principles are routinely
+ * multilingual and an English-only list would either under-filter or
+ * skew similarity on non-English text.
+ */
+
+const TOKEN_STOPWORDS: ReadonlySet<string> = new Set();
+
+export function tokenise(text: string): ReadonlySet<string> {
+ return new Set(
+ text
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}_-]+/u)
+ .filter((t) => t.length > 1 && !TOKEN_STOPWORDS.has(t)),
+ );
+}
+
+export function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
+ if (a.size === 0 && b.size === 0) return 0;
+ let intersection = 0;
+ for (const t of a) if (b.has(t)) intersection++;
+ const union = a.size + b.size - intersection;
+ if (union === 0) return 0;
+ return intersection / union;
+}
+```
+
+**Step 4: Update `doctor.ts` to import from the new module**
+
+- Remove the local `TOKEN_STOPWORDS`, `tokenise`, `jaccard`.
+- Add `import { jaccard, tokenise } from "./similarity.ts";` near the
+ top of `doctor.ts`.
+
+**Step 5: Run tests to verify pass and no doctor regression**
+
+```
+bun test tests/core/brain/similarity.test.ts
+bun test tests/core/brain/doctor.test.ts
+```
+Expected: both green; existing doctor tests unchanged.
+
+**Step 6: Pause for review (no commit).**
+
+---
+
+### Task 1.2: Add `BRAIN_RETIRED_REASON.mergedInto` and `BRAIN_LOG_EVENT_KIND.merge`
+
+**Objective:** New constants in `types.ts`, no other changes.
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+
+**Step 1: Add to `BRAIN_RETIRED_REASON`**
+
+In the existing const block (after `supersededByContext`):
+
+```ts
+ // Preference retired through `o2b brain merge` β€” counters and
+ // evidence were folded into the retained pref pointed at by
+ // `superseded_by`. Distinct from `rebutted` (signals) and
+ // `superseded-by-context` (outdated evidence) because no
+ // contradiction is implied β€” the rules said the same thing.
+ mergedInto: "merged-into",
+```
+
+**Step 2: Add to `BRAIN_LOG_EVENT_KIND`**
+
+In the existing const block (after `migrateFrontmatter`):
+
+```ts
+ /**
+ * `merge` β€” operator ran `o2b brain merge <keep> <drop>`. Payload
+ * carries both wikilinks, the union-size of `evidenced_by`, and
+ * the summed counters as raw integers for audit grepping.
+ */
+ merge: "merge",
+```
+
+**Step 3: Typecheck**
+
+```
+bun run typecheck
+```
+Expected: PASS.
+
+**Step 4: Pause for review (no commit).**
+
+---
+
+### Task 1.3: Implement `findMergeCandidates`
+
+**Objective:** Read-only detector returning the pairs that the digest
+will render.
+
+**Files:**
+- Create: `src/core/brain/merge-candidates.ts`
+- Create: `tests/core/brain/merge-candidates.test.ts`
+
+**Step 1: Write failing test**
+
+```ts
+// tests/core/brain/merge-candidates.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { findMergeCandidates } from "../../../src/core/brain/merge-candidates.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-merge-cand-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+function writePref(slug: string, body: Record<string, string | number | boolean>): void {
+ const fm = Object.entries(body)
+ .map(([k, v]) => `${k}: ${typeof v === "string" ? JSON.stringify(v) : String(v)}`)
+ .join("\n");
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ `---\n${fm}\n---\n\nPrinciple body.\n`,
+ );
+}
+
+describe("findMergeCandidates", () => {
+ test("pair in [0.6, 0.85) surfaces", () => {
+ writePref("imperative-commits", {
+ id: "pref-imperative-commits",
+ topic: "commits",
+ principle: "Use imperative voice in commit subjects",
+ status: "confirmed",
+ confidence: "high",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 3,
+ violated_count: 0,
+ });
+ writePref("imperative-subjects", {
+ id: "pref-imperative-subjects",
+ topic: "commits",
+ principle: "Write commit subjects in imperative voice and keep them short",
+ status: "confirmed",
+ confidence: "high",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 2,
+ violated_count: 0,
+ });
+ const out = findMergeCandidates(vault);
+ expect(out.length).toBeGreaterThanOrEqual(1);
+ expect(out[0].topic).toBe("commits");
+ expect(out[0].jaccard).toBeGreaterThanOrEqual(0.6);
+ });
+
+ test("pairs across different topic or scope do not surface", () => {
+ writePref("a", {
+ id: "pref-a", topic: "x", principle: "Same words here",
+ status: "confirmed", confidence: "high",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 1, violated_count: 0,
+ });
+ writePref("b", {
+ id: "pref-b", topic: "y", principle: "Same words here",
+ status: "confirmed", confidence: "high",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 1, violated_count: 0,
+ });
+ expect(findMergeCandidates(vault).length).toBe(0);
+ });
+
+ test("stable ordering by (jaccard desc, a asc, b asc)", () => {
+ // Three prefs forming three pairs with descending jaccard.
+ // Verify deterministic order.
+ writePref("a", { id: "pref-a", topic: "t", principle: "alpha beta gamma delta",
+ status: "confirmed", confidence: "high",
+ created_at: "2026-05-01T00:00:00Z", unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 1, violated_count: 0 });
+ writePref("b", { id: "pref-b", topic: "t", principle: "alpha beta gamma epsilon",
+ status: "confirmed", confidence: "high",
+ created_at: "2026-05-01T00:00:00Z", unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 1, violated_count: 0 });
+ writePref("c", { id: "pref-c", topic: "t", principle: "alpha beta zeta eta",
+ status: "confirmed", confidence: "high",
+ created_at: "2026-05-01T00:00:00Z", unconfirmed_until: "2026-05-08T00:00:00Z",
+ applied_count: 1, violated_count: 0 });
+ const out = findMergeCandidates(vault);
+ // First pair should be (a, b) with highest jaccard.
+ expect(out[0].a < out[0].b).toBe(true);
+ for (let i = 1; i < out.length; i++) {
+ expect(out[i].jaccard).toBeLessThanOrEqual(out[i - 1].jaccard);
+ }
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+```
+bun test tests/core/brain/merge-candidates.test.ts
+```
+Expected: FAIL β€” module not found.
+
+**Step 3: Implement**
+
+```ts
+// src/core/brain/merge-candidates.ts
+/**
+ * `findMergeCandidates` β€” pure-read detector for the `## Merge
+ * suggestions` digest section and the upcoming `o2b brain merge`
+ * CLI. Pairs of confirmed/quarantine preferences in the same
+ * `(topic, scope)` bucket whose `principle` tokens share jaccard
+ * similarity at or above `JACCARD_MERGE_SUGGEST_THRESHOLD`.
+ *
+ * Pairs at or above `JACCARD_DUPLICATE_THRESHOLD` are also flagged
+ * by `doctor` as `duplicate-preferences`; the digest surface is the
+ * lighter signal, the doctor surface is the heavier one.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parsePreference } from "./preference.ts";
+import { jaccard, tokenise } from "./similarity.ts";
+import { BRAIN_PREFERENCE_STATUS } from "./types.ts";
+
+export const JACCARD_MERGE_SUGGEST_THRESHOLD = 0.6;
+export const MERGE_SUGGESTION_LIMIT = 10;
+
+export interface MergeCandidate {
+ readonly a: string;
+ readonly b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ readonly jaccard: number;
+}
+
+export function findMergeCandidates(
+ vault: string,
+ opts: { threshold?: number; limit?: number } = {},
+): ReadonlyArray<MergeCandidate> {
+ const threshold = opts.threshold ?? JACCARD_MERGE_SUGGEST_THRESHOLD;
+ const limit = opts.limit ?? MERGE_SUGGESTION_LIMIT;
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.preferences)) return Object.freeze([]);
+
+ interface Entry {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle: string;
+ readonly tokens: ReadonlySet<string>;
+ }
+ const entries: Entry[] = [];
+ for (const f of readdirSync(dirs.preferences, { withFileTypes: true })) {
+ if (!f.isFile() || !f.name.endsWith(".md") || !f.name.startsWith("pref-")) continue;
+ try {
+ const p = parsePreference(join(dirs.preferences, f.name));
+ if (
+ p.status !== BRAIN_PREFERENCE_STATUS.confirmed
+ && p.status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) continue;
+ entries.push({
+ id: p.id,
+ topic: p.topic,
+ scope: p.scope ?? null,
+ principle: p.principle,
+ tokens: tokenise(p.principle),
+ });
+ } catch {
+ // Doctor reports corruption; the detector skips silently.
+ }
+ }
+
+ const buckets = new Map<string, Entry[]>();
+ for (const e of entries) {
+ const key = `${e.topic}\x00${e.scope ?? ""}`;
+ const bucket = buckets.get(key) ?? [];
+ bucket.push(e);
+ buckets.set(key, bucket);
+ }
+
+ const candidates: MergeCandidate[] = [];
+ for (const bucket of buckets.values()) {
+ if (bucket.length < 2) continue;
+ bucket.sort((a, b) => a.id.localeCompare(b.id));
+ for (let i = 0; i < bucket.length; i++) {
+ for (let j = i + 1; j < bucket.length; j++) {
+ const a = bucket[i]!;
+ const b = bucket[j]!;
+ const sim = jaccard(a.tokens, b.tokens);
+ if (sim < threshold) continue;
+ candidates.push({
+ a: a.id,
+ b: b.id,
+ topic: a.topic,
+ scope: a.scope,
+ principle_a: a.principle,
+ principle_b: b.principle,
+ jaccard: Math.round(sim * 100) / 100,
+ });
+ }
+ }
+ }
+
+ candidates.sort((x, y) => {
+ const diff = y.jaccard - x.jaccard;
+ if (diff !== 0) return diff;
+ const da = x.a.localeCompare(y.a);
+ if (da !== 0) return da;
+ return x.b.localeCompare(y.b);
+ });
+
+ return Object.freeze(candidates.slice(0, limit));
+}
+```
+
+**Step 4: Run tests to verify pass**
+
+```
+bun test tests/core/brain/merge-candidates.test.ts
+```
+Expected: 3 passed.
+
+**Step 5: Pause for review (no commit).**
+
+---
+
+### Task 1.4: Wire merge-candidates into `brain_digest`
+
+**Objective:** Render the `## Merge suggestions` Markdown section and
+the `merge_suggestions` JSON array. Existing fixtures without any
+candidates β†’ section absent, JSON empty array.
+
+**Files:**
+- Modify: `src/core/brain/digest.ts`
+- Modify: `tests/core/brain/digest.test.ts`
+
+**Step 1: Add JSON type and update `DigestJson`**
+
+In `src/core/brain/digest.ts`, after `DigestJsonTopReferenced`:
+
+```ts
+export interface DigestJsonMergeSuggestion {
+ readonly a: string;
+ readonly b: string;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly jaccard: number;
+}
+```
+
+Add `readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;`
+to `DigestJson`.
+
+**Step 2: Add to `DigestData` and `collectDigestData`**
+
+```ts
+interface DigestData {
+ // ... existing fields ...
+ readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;
+}
+```
+
+In `collectDigestData`, before the `return`:
+
+```ts
+const merge_suggestions = findMergeCandidates(vault).map((c) => ({
+ a: c.a,
+ b: c.b,
+ principle_a: c.principle_a,
+ principle_b: c.principle_b,
+ topic: c.topic,
+ scope: c.scope,
+ jaccard: c.jaccard,
+}));
+```
+
+Add `merge_suggestions` to the returned object.
+
+**Import:** add at top of file:
+
+```ts
+import { findMergeCandidates } from "./merge-candidates.ts";
+```
+
+**Step 3: Render in JSON and Markdown**
+
+JSON path: add `merge_suggestions: data.merge_suggestions` to the
+`payload` object inside the `format === "json"` branch.
+
+Markdown path: in `renderMarkdown`, after the `top_referenced` block
+and before the `confidence_shifts` block:
+
+```ts
+if (data.merge_suggestions.length > 0) {
+ lines.push(`## Merge suggestions (${data.merge_suggestions.length})`, "");
+ for (const item of data.merge_suggestions) {
+ const scope = item.scope ?? "β€”";
+ lines.push(
+ `- ${renderPrefLink({ id: item.a, principle: item.principle_a })}`
+ + ` β‰ˆ ${renderPrefLink({ id: item.b, principle: item.principle_b })}`
+ + ` β€” topic '${item.topic}', scope ${scope}, jaccard ${item.jaccard.toFixed(2)}`,
+ );
+ }
+ lines.push("");
+}
+```
+
+**Step 4: `isEmpty` predicate**
+
+Do **NOT** add `merge_suggestions` to `isEmpty`. The predicate gates
+the silent-if-no-changes behaviour; suggestions reflect current
+state, not windowed change. Existing tests assert empty-window
+collapses to one line β€” keep that contract.
+
+**Step 5: Add digest tests**
+
+Append two test cases in `tests/core/brain/digest.test.ts`:
+
+- One fixture with two near-duplicate confirmed prefs β†’ assert
+ Markdown contains `## Merge suggestions` and JSON
+ `merge_suggestions.length >= 1`.
+- One fixture with zero candidates (existing fixtures) β†’ assert
+ Markdown does NOT contain `## Merge suggestions` and JSON
+ `merge_suggestions === []`.
+
+**Step 6: Run tests**
+
+```
+bun test tests/core/brain/digest.test.ts
+```
+Expected: all previous tests still green plus the two new ones.
+
+**Step 7: Pause for review (no commit).**
+
+---
+
+### Task 1.5: Implement `merge` writer module
+
+**Objective:** Pure mutating writer that the CLI verb wraps. All
+guards in one place, all writes via existing atomic helpers.
+
+**Files:**
+- Create: `src/core/brain/merge.ts`
+- Create: `tests/core/brain/merge.test.ts`
+
+**Step 1: Define the surface**
+
+```ts
+// src/core/brain/merge.ts
+import type { BrainPreference } from "./types.ts";
+
+export class BrainMergeError extends Error {
+ constructor(readonly code: string, message: string) {
+ super(message);
+ this.name = "BrainMergeError";
+ }
+}
+
+export interface MergeOptions {
+ readonly now?: Date;
+ readonly agentName?: string;
+ readonly dryRun?: boolean;
+}
+
+export interface MergePlan {
+ readonly keep_id: string;
+ readonly drop_id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly merged_evidenced_by: ReadonlyArray<string>;
+ readonly applied_sum: number;
+ readonly violated_sum: number;
+ readonly last_evidence_at: string | null;
+ readonly retired_path: string;
+}
+
+/**
+ * Build the merge plan and (unless dryRun) execute it. Throws
+ * `BrainMergeError` on any guard failure.
+ */
+export function mergePreferences(
+ vault: string,
+ keepId: string,
+ dropId: string,
+ opts?: MergeOptions,
+): MergePlan;
+```
+
+**Step 2: Write failing tests**
+
+```ts
+// tests/core/brain/merge.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { BrainMergeError, mergePreferences } from "../../../src/core/brain/merge.ts";
+
+let vault: string;
+const NOW = new Date("2026-05-18T10:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-merge-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+// Helpers: writePref, writeRetired β€” copy from explorer test once written.
+
+describe("mergePreferences β€” guards", () => {
+ test("rejects mismatched topic", () => {
+ // ... writePref keep with topic=x, drop with topic=y ...
+ expect(() => mergePreferences(vault, "pref-keep", "pref-drop", { now: NOW }))
+ .toThrow(BrainMergeError);
+ });
+
+ test("rejects mismatched scope (string vs null)", () => { /* ... */ });
+ test("rejects keep_id === drop_id", () => { /* ... */ });
+ test("rejects drop already in retired/", () => { /* ... */ });
+ test("rejects keep=unpinned, drop=pinned", () => { /* ... */ });
+ test("accepts both pinned", () => { /* ... */ });
+});
+
+describe("mergePreferences β€” happy path", () => {
+ test("merges counters, evidenced_by, last_evidence_at; retires drop with merged-into", () => {
+ // ... writePref keep + drop ...
+ const plan = mergePreferences(vault, "pref-keep", "pref-drop", { now: NOW, agentName: "test" });
+ expect(plan.applied_sum).toBe(/* k.applied + d.applied */);
+ // Read keep file, assert applied_count, violated_count, last_evidence_at, evidenced_by union.
+ // Read retired file, assert retired_reason: merged-into, superseded_by: [[pref-keep|...]].
+ // Read log/today, assert one `## ... merge` block.
+ // Assert active.md regenerated (does not contain drop, does contain keep with new counters).
+ });
+
+ test("dryRun returns plan but writes nothing", () => { /* ... */ });
+});
+```
+
+Fill in the `writePref` / `writeRetired` helpers using the same
+frontmatter shapes as in `merge-candidates.test.ts` plus the fields
+required for `BrainPreference` parsing (`evidenced_by` array,
+`applied_count`, `violated_count`, `last_evidence_at`, `pinned`,
+`confidence_value`).
+
+**Step 3: Verify failure**
+
+```
+bun test tests/core/brain/merge.test.ts
+```
+Expected: FAIL β€” module not found.
+
+**Step 4: Implement**
+
+Implementation outline (translate to TS, ~180 lines):
+
+1. Resolve paths via `preferencePath(vault, slug)` / `retiredPath`.
+2. Parse both prefs via `parsePreference`. Throw `BrainMergeError`
+ with codes `keep-not-found`, `drop-not-found` if missing.
+3. Guards (each throws with a distinct code):
+ - `same-id` if `keepId === dropId`.
+ - `drop-already-retired` if `dropId` resolves under `retired/`.
+ - `topic-mismatch` if `keep.topic !== drop.topic`.
+ - `scope-mismatch` if `keep.scope !== drop.scope` (treating
+ undefined as `null` consistently).
+ - `pin-parity` if exactly one of the two is pinned and the
+ pinned one is `drop`.
+4. Compute `mergedKeep`:
+ - `evidenced_by`: sorted dedup union.
+ - `applied_count`: sum.
+ - `violated_count`: sum.
+ - `last_evidence_at`: max by ISO-8601 lexical compare; null when
+ both null.
+ - All other fields = `keep` as-is.
+5. Compute the `MergePlan` object. Return early if `dryRun`.
+6. Write: `writePreference(mergedKeep, { overwrite: true })`.
+7. Move drop: `moveToRetired(vault, dropPath, "merged-into", { now,
+ retired_by: "[[Brain/log/<today>]]", superseded_by: renderPrefLink({
+ id: keep.id, principle: keep.principle }) })`.
+8. Append log event of kind `merge` via `appendLogEvent` with body:
+ - `keep`, `drop` (titled wikilinks)
+ - `signal_union: <N> (was <K>, <D>)`
+ - `applied_sum: <N> (was <K>, <D>)`
+ - `violated_sum: <N> (was <K>, <D>)`
+ - `agent: <agentName ?? "unknown">`
+9. `regenerateActiveQuiet(vault, { now })`.
+
+**Step 5: Run tests**
+
+```
+bun test tests/core/brain/merge.test.ts
+```
+Expected: 8 passed (6 guards + 2 happy-path).
+
+**Step 6: Pause for review (no commit).**
+
+---
+
+### Task 1.6: Add `o2b brain merge` CLI verb
+
+**Objective:** CLI wrapper around `mergePreferences` with interactive
+confirmation and `--dry-run` / `--force`.
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Create: `tests/cli/brain-merge.test.ts`
+
+**Step 1: Add verb dispatch**
+
+In `src/cli/brain.ts`:
+
+- Add `case "merge": return await cmdBrainMerge(rest);` to the
+ switch in `handleBrainSubcommand`.
+- Add `merge` entry to `BRAIN_HELP` and a `VERB_HELP["merge"]` block.
+
+**Step 2: Implement `cmdBrainMerge`**
+
+Reuse `parse` (CLI flag parser), `resolveBrainVault`, `readSingleLine`
+(for interactive y/N β€” same pattern as rollback).
+
+Behaviour:
+- Args: two positional ids (keep, drop). `parse` rejects fewer/more
+ than 2.
+- Flags: `--dry-run`, `--force`, `--vault <path>`.
+- Compute plan via `mergePreferences(vault, keep, drop, { dryRun:
+ true, now, agentName })`.
+- Print plan summary on stdout: 4 lines (keep / drop / counters /
+ retired_path).
+- If `--dry-run`: print "dry-run; no changes" and return 0.
+- If `--force`: skip prompt.
+- Else: prompt `Proceed? [y/N] ` via `readSingleLine`. Anything not
+ `y`/`Y` β†’ return 0 with "merge cancelled".
+- Call `mergePreferences` again with `dryRun: false` to commit.
+- Print one-line confirmation and return 0.
+
+**Step 3: Tests**
+
+```ts
+// tests/cli/brain-merge.test.ts
+describe("o2b brain merge", () => {
+ test("dry-run prints plan and writes nothing", async () => { /* ... */ });
+ test("--force commits without prompt", async () => { /* ... */ });
+ test("interactive 'y' commits", async () => { /* ... */ });
+ test("interactive 'N' (default) does not commit", async () => { /* ... */ });
+ test("topic mismatch exits 1 with documented message", async () => { /* ... */ });
+ test("missing keep exits 1", async () => { /* ... */ });
+ test("same id exits 1", async () => { /* ... */ });
+});
+```
+
+Each test spawns `bun run src/cli/main.ts brain merge <args>` against a
+fixture vault, asserts exit code, stdout/stderr, and on-disk effect
+(or non-effect).
+
+**Step 4: Verify**
+
+```
+bun test tests/cli/brain-merge.test.ts
+```
+Expected: 7 passed.
+
+**Step 5: Phase 1 typecheck and full test**
+
+```
+bun run typecheck
+bun test
+```
+Expected: both green. Existing `digest.test.ts` and `doctor.test.ts`
+included.
+
+**Step 6: Pause for review (no commit).**
+
+---
+
+## Phase 2 β€” Β§14 Local explorer
+
+### Task 2.1: Implement `collectExplorerData`
+
+**Objective:** Pure-read data collector returning the
+`ExplorerGraph` shape from the design doc.
+
+**Files:**
+- Create: `src/core/brain/explorer.ts` (data side only β€” rendering in 2.2)
+- Create: `tests/core/brain/explorer.test.ts`
+
+**Step 1: Write failing test**
+
+```ts
+// tests/core/brain/explorer.test.ts
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+// ... usual mkdtemp boilerplate ...
+import { collectExplorerData } from "../../../src/core/brain/explorer.ts";
+
+describe("collectExplorerData", () => {
+ test("empty Brain β†’ 0 nodes, 0 edges", () => {
+ const g = collectExplorerData(vault);
+ expect(g.nodes).toEqual([]);
+ expect(g.edges).toEqual([]);
+ expect(g.schema_version).toBe(1);
+ });
+
+ test("includes confirmed, unconfirmed, quarantine, retired", () => { /* ... */ });
+
+ test("supersedes edge from retired.superseded_by", () => { /* ... */ });
+
+ test("wikilink edge from principle body, deduped", () => { /* ... */ });
+
+ test("excludes edges to signals or log files", () => { /* ... */ });
+
+ test("byte-identical output across runs on the same vault", () => {
+ const g1 = JSON.stringify(collectExplorerData(vault));
+ const g2 = JSON.stringify(collectExplorerData(vault));
+ expect(g1).toBe(g2);
+ });
+
+ test("legacy pref with confidence_value=null surfaces as null", () => { /* ... */ });
+
+ test("backlink_count matches buildBacklinkIndex", () => { /* ... */ });
+});
+```
+
+**Step 2: Verify failure**
+
+```
+bun test tests/core/brain/explorer.test.ts
+```
+Expected: FAIL.
+
+**Step 3: Implement `collectExplorerData`**
+
+Source code outline:
+
+```ts
+import { existsSync, readdirSync } from "node:fs";
+import { basename, join } from "node:path";
+import { buildBacklinkIndex } from "./backlinks.ts";
+import { brainDirs } from "./paths.ts";
+import { parsePreference, parseRetired } from "./preference.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+import { extractWikilinks } from "../vault.ts";
+
+export interface ExplorerNode { /* per spec */ }
+export interface ExplorerEdge { /* per spec */ }
+export interface ExplorerGraph { /* per spec */ }
+
+export function collectExplorerData(vault: string): ExplorerGraph {
+ const dirs = brainDirs(vault);
+ const nodes: ExplorerNode[] = [];
+ const knownIds = new Set<string>();
+
+ // 1. Walk preferences/.
+ // 2. Walk retired/.
+ // 3. Build backlink index, copy `backlink_count` per node.
+
+ // 4. Build edges:
+ // - frontmatter `supersedes` / `superseded_by` (one edge per ref).
+ // - inline wikilinks in principle body AND retired body, filtered
+ // to refs that land in `knownIds`.
+ // - dedup keyed by (source, target, kind).
+
+ // 5. Sort nodes by (kind, id). Sort edges by (source, target, kind).
+
+ return Object.freeze({
+ generated_at: new Date().toISOString(),
+ schema_version: 1,
+ vault_basename: basename(vault),
+ nodes: Object.freeze(nodes),
+ edges: Object.freeze(edges),
+ });
+}
+```
+
+Use the existing `buildBacklinkIndex` for `backlink_count` (the
+function returns `Map<targetId, refs[]>` β€” count = `refs.length`).
+
+**Step 4: Verify**
+
+```
+bun test tests/core/brain/explorer.test.ts
+```
+Expected: 8 passed.
+
+**Step 5: Pause for review (no commit).**
+
+---
+
+### Task 2.2: Implement `renderExportedHtml` plus the HTML template
+
+**Objective:** Substitute the JSON placeholder, write the template to
+disk with mini physics engine + canvas renderer.
+
+**Files:**
+- Create: `templates/brain-explorer.html`
+- Modify: `src/core/brain/explorer.ts` (add `renderExportedHtml`)
+- Modify: `tests/core/brain/explorer.test.ts` (template tests)
+
+**Step 1: Skeleton template**
+
+Create `templates/brain-explorer.html` with:
+
+```html
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Open Second Brain β€” Explorer</title>
+ <style>/* ~80 lines, system-ui font, light/dark via prefers-color-scheme */</style>
+</head>
+<body>
+ <header>...</header>
+ <aside id="filters">
+ <input id="search" type="search" placeholder="Search principle or topic" />
+ <fieldset id="status-filters">...</fieldset>
+ <fieldset id="kind-filters">...</fieldset>
+ </aside>
+ <main>
+ <canvas id="canvas"></canvas>
+ </main>
+ <aside id="details">
+ <p class="empty">Select a node to inspect.</p>
+ </aside>
+
+ <script type="application/json" id="brain-data">__GRAPH_JSON__</script>
+ <script>
+ // ~250 lines:
+ // 1. Parse JSON.
+ // 2. Build internal state (id β†’ node, edges as adj list).
+ // 3. miniForceLayout: Verlet with topic-center attraction,
+ // global charge repulsion, edge spring, damping. Tick on rAF.
+ // 4. canvasRender: clear, draw edges, draw nodes (colour by status,
+ // size by sqrt(applied_count), gold stroke if pinned).
+ // 5. hitTest: nearest node within radius on mousemove / click.
+ // 6. filterAndSearch: hide non-matching nodes; their edges hide too.
+ // 7. renderRightPanel: id, principle, topic, scope, status,
+ // confidence band/value, applied/violated, pinned, last_evidence_at,
+ // backlink_count, retired_reason if retired, edges list.
+ </script>
+</body>
+</html>
+```
+
+Tune constants: `K_TOPIC = 0.005`, `K_CHARGE = 600`, `K_SPRING =
+0.05`, damping `0.85`, max-velocity clamp.
+
+**Step 2: `renderExportedHtml` in `explorer.ts`**
+
+```ts
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const TEMPLATE_PATH = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "..",
+ "templates",
+ "brain-explorer.html",
+);
+
+const PLACEHOLDER = "__GRAPH_JSON__";
+
+let templateCache: string | undefined;
+
+function loadTemplate(): string {
+ if (templateCache !== undefined) return templateCache;
+ templateCache = readFileSync(TEMPLATE_PATH, "utf8");
+ if (!templateCache.includes(PLACEHOLDER)) {
+ throw new Error(
+ `brain-explorer.html template missing the ${PLACEHOLDER} marker`,
+ );
+ }
+ return templateCache;
+}
+
+export function renderExportedHtml(graph: ExplorerGraph): string {
+ // JSON.stringify with `2` would bloat the file β€” single-line.
+ const json = JSON.stringify(graph);
+ return loadTemplate().replace(PLACEHOLDER, () => json);
+}
+```
+
+`String.replace(_, fn)` form avoids `$&`/`$1` injection if the JSON
+ever contains the `$` sigil (it might β€” `principle` is free text).
+
+**Step 3: Add template tests**
+
+```ts
+test("renderExportedHtml replaces the placeholder exactly once", () => {
+ const html = renderExportedHtml(collectExplorerData(vault));
+ expect(html.includes("__GRAPH_JSON__")).toBe(false);
+ const match = html.match(/<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/);
+ expect(match).not.toBeNull();
+ const parsed = JSON.parse(match![1]!);
+ expect(parsed.schema_version).toBe(1);
+});
+
+test("template carries the placeholder before substitution", () => {
+ const raw = readFileSync(TEMPLATE_PATH, "utf8");
+ expect(raw.includes("__GRAPH_JSON__")).toBe(true);
+});
+```
+
+**Step 4: Verify**
+
+```
+bun test tests/core/brain/explorer.test.ts
+```
+Expected: all previous tests still green plus the two new ones.
+
+**Step 5: Manual smoke (optional, no test)**
+
+Render against the local vault, open the file in a browser, verify:
+- Nodes render and settle.
+- Hover shows tooltip.
+- Click populates the right panel.
+- Search box filters live.
+- Status filter checkboxes work.
+
+Document in the PR description; this is not gated in CI.
+
+**Step 6: Pause for review (no commit).**
+
+---
+
+### Task 2.3: Implement `buildLiveServer`
+
+**Objective:** Tiny HTTP server on loopback that re-reads vault per
+request and serves the same template + JSON.
+
+**Files:**
+- Modify: `src/core/brain/explorer.ts`
+
+**Step 1: Write the function**
+
+```ts
+import { Server } from "bun";
+
+export interface LiveServerHandle {
+ readonly url: string;
+ close(): Promise<void>;
+}
+
+export function buildLiveServer(
+ vault: string,
+ port: number,
+): LiveServerHandle {
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port,
+ fetch(req) {
+ const url = new URL(req.url);
+ if (url.pathname === "/" || url.pathname === "/index.html") {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ return new Response(html, {
+ headers: { "content-type": "text/html; charset=utf-8" },
+ });
+ }
+ if (url.pathname === "/data.json") {
+ const graph = collectExplorerData(vault);
+ return new Response(JSON.stringify(graph), {
+ headers: { "content-type": "application/json; charset=utf-8" },
+ });
+ }
+ return new Response("not found", { status: 404 });
+ },
+ });
+ return {
+ url: `http://127.0.0.1:${server.port}/`,
+ close: async () => { server.stop(); },
+ };
+}
+```
+
+**Step 2: Test**
+
+In `tests/cli/brain-explorer.test.ts` (created next task), add the
+live-server smoke. Server-only tests live there because they spawn a
+subprocess via the CLI.
+
+**Step 3: Pause for review (no commit).**
+
+---
+
+### Task 2.4: Add `o2b brain explorer` CLI verb
+
+**Objective:** Thread CLI flags into the explorer module and ship the
+binary entry.
+
+**Files:**
+- Modify: `src/cli/brain.ts`
+- Create: `tests/cli/brain-explorer.test.ts`
+
+**Step 1: Verb dispatch**
+
+```ts
+case "explorer":
+ return await cmdBrainExplorer(rest);
+```
+
+Add `explorer` to `BRAIN_HELP` and a `VERB_HELP["explorer"]` block.
+
+**Step 2: Implement `cmdBrainExplorer`**
+
+```ts
+async function cmdBrainExplorer(argv: ReadonlyArray<string>): Promise<number> {
+ const args = parse(argv, {
+ flags: { force: false },
+ options: { port: "7777", export: null, vault: null },
+ });
+ const vault = resolveBrainVault(args.options.vault);
+ const exportPath = args.options.export;
+
+ if (exportPath !== null) {
+ if (existsSync(exportPath) && !args.flags.force) {
+ fail(`${exportPath} exists; pass --force to overwrite`);
+ return 1;
+ }
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ atomicWriteFileSync(exportPath, html);
+ ok(`Exported ${graph.nodes.length} nodes to ${exportPath}`);
+ return 0;
+ }
+
+ const port = parseInt(args.options.port, 10);
+ if (!Number.isFinite(port) || port < 1 || port > 65535) {
+ fail(`invalid --port value: ${args.options.port}`);
+ return 1;
+ }
+ let server: LiveServerHandle;
+ try {
+ server = buildLiveServer(vault, port);
+ } catch (err) {
+ const msg = (err as Error).message;
+ if (/EADDRINUSE/.test(msg)) {
+ fail(`port ${port} already in use; try --port <other>`);
+ return 1;
+ }
+ throw err;
+ }
+ ok(`Live explorer at ${server.url}`);
+ info("Press Ctrl+C to stop.");
+
+ await new Promise<void>((resolve) => {
+ const onSignal = (): void => { server.close().then(() => resolve()); };
+ process.once("SIGINT", onSignal);
+ process.once("SIGTERM", onSignal);
+ });
+ return 0;
+}
+```
+
+**Step 3: Tests**
+
+```ts
+// tests/cli/brain-explorer.test.ts
+describe("o2b brain explorer --export", () => {
+ test("creates the file, exit 0", async () => { /* ... */ });
+ test("refuses overwrite without --force", async () => { /* ... */ });
+ test("overwrites with --force", async () => { /* ... */ });
+ test("contains parseable JSON in the data script tag", async () => { /* ... */ });
+});
+
+describe("o2b brain explorer (live)", () => {
+ test("binds to 127.0.0.1 and serves / + /data.json", async () => {
+ // Bun.spawn the CLI, poll http://127.0.0.1:<port>/, parse the
+ // <script type=application/json>, assert schema_version. SIGINT.
+ });
+ test("port in use exits 1 with documented message", async () => { /* ... */ });
+});
+```
+
+For the live test, use a high random port (e.g. `30000 + Math.floor(Math.random() * 30000)`) to avoid collisions on the build host. The single-user VPS does not multiplex tests but CI might.
+
+**Step 4: Verify**
+
+```
+bun test tests/cli/brain-explorer.test.ts
+```
+Expected: 6 passed.
+
+**Step 5: Phase 2 typecheck and full test**
+
+```
+bun run typecheck
+bun test
+```
+Expected: green.
+
+**Step 6: Pause for review (no commit).**
+
+---
+
+## Phase 3 β€” Β§4-tail Per-runtime hook cadence
+
+### Task 3.1: Add `detectHookRuntime` and `HookRuntime`
+
+**Objective:** Extend `hooks/lib/detect.ts` with the runtime detector.
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Modify: `tests/hooks/detect.test.ts`
+
+**Step 1: Write failing tests**
+
+```ts
+// in tests/hooks/detect.test.ts β€” append to existing describe
+import { detectHookRuntime } from "../../hooks/lib/detect.ts";
+
+describe("detectHookRuntime", () => {
+ test("Claude Code transcript path β†’ claudecode", () => {
+ expect(detectHookRuntime({
+ transcript_path: "/Users/x/.claude/projects/-srv/projects/foo/abc.jsonl",
+ })).toBe("claudecode");
+ });
+ test("Codex transcript path β†’ codex", () => {
+ expect(detectHookRuntime({
+ transcript_path: "/root/.codex/sessions/2026-05-18T10-00-00Z.json",
+ })).toBe("codex");
+ });
+ test("Claude Code triple β†’ claudecode (no transcript_path)", () => {
+ expect(detectHookRuntime({
+ session_id: "x", cwd: "/srv", tool_use_id: "y",
+ })).toBe("claudecode");
+ });
+ test("Codex apply_patch shape β†’ codex", () => {
+ expect(detectHookRuntime({
+ tool_name: "apply_patch",
+ tool_input: { input: "*** Begin Patch\n...\n*** End Patch" },
+ })).toBe("codex");
+ });
+ test("malformed payload β†’ unknown without throw", () => {
+ expect(detectHookRuntime(null)).toBe("unknown");
+ expect(detectHookRuntime(undefined)).toBe("unknown");
+ expect(detectHookRuntime("string")).toBe("unknown");
+ expect(detectHookRuntime({})).toBe("unknown");
+ });
+});
+```
+
+**Step 2: Implement**
+
+```ts
+// hooks/lib/detect.ts (add at end)
+export type HookRuntime = "claudecode" | "codex" | "unknown";
+
+const CLAUDE_TRANSCRIPT_NEEDLES = ["/.claude/projects/", "/.claude/sessions/"];
+const CODEX_TRANSCRIPT_NEEDLE = "/.codex/sessions/";
+
+export function detectHookRuntime(payload: unknown): HookRuntime {
+ if (payload === null || typeof payload !== "object") return "unknown";
+ const p = payload as Record<string, unknown>;
+
+ const tp = p["transcript_path"];
+ if (typeof tp === "string") {
+ if (CLAUDE_TRANSCRIPT_NEEDLES.some((n) => tp.includes(n))) return "claudecode";
+ if (tp.includes(CODEX_TRANSCRIPT_NEEDLE)) return "codex";
+ }
+
+ // Claude Code's hook payload distinctively carries all three.
+ if (
+ typeof p["session_id"] === "string"
+ && typeof p["cwd"] === "string"
+ && typeof p["tool_use_id"] === "string"
+ ) {
+ return "claudecode";
+ }
+
+ // Codex's PostToolUse payload for apply_patch carries the patch
+ // body in `tool_input.input` as a string.
+ if (p["tool_name"] === "apply_patch") {
+ const ti = p["tool_input"];
+ if (ti !== null && typeof ti === "object") {
+ const input = (ti as Record<string, unknown>)["input"];
+ if (typeof input === "string" && input.includes("*** Begin Patch")) {
+ return "codex";
+ }
+ }
+ }
+
+ return "unknown";
+}
+```
+
+**Step 3: Verify**
+
+```
+bun test tests/hooks/detect.test.ts
+```
+Expected: existing tests still green plus 5 new.
+
+**Step 4: Pause for review (no commit).**
+
+---
+
+### Task 3.2: Thread `runtime` through `postWriteReminder` and `stopGuardrailReason`
+
+**Objective:** Add the parameter, render the cadence line, keep
+`unknown` byte-identical to current output.
+
+**Files:**
+- Modify: `hooks/lib/messages.ts`
+- Modify: `hooks/post-write-reminder.ts`
+- Modify: `hooks/stop-log-guardrail.ts`
+- Modify: `tests/hooks/post-write-reminder.test.ts`
+- Modify: `tests/hooks/stop-log-guardrail.test.ts`
+
+**Step 1: Update `hooks/lib/messages.ts`**
+
+```ts
+import type { HookRuntime } from "./detect.ts";
+
+export interface PostWriteReminderInput {
+ readonly toolName: string;
+ readonly filePath: string | null;
+ readonly runtime: HookRuntime;
+}
+
+function postWriteCadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return [
+ "_Claude Code session: many turns ahead β€” capture the signal_",
+ "_or evidence now rather than batching to end-of-session; long_",
+ "_sessions risk forgetting the context that distinguishes one_",
+ "_artifact from the next._",
+ ].join("\n");
+ case "codex":
+ return [
+ "_Codex `codex exec` is a one-shot run β€” call `brain_feedback`_",
+ "_or `brain_apply_evidence` before this exec returns; there_",
+ "_is no second turn._",
+ ].join("\n");
+ case "unknown":
+ return "";
+ }
+}
+
+export function postWriteReminder({
+ toolName, filePath, runtime,
+}: PostWriteReminderInput): string {
+ const target = filePath ? `\`${filePath}\`` : "a file";
+ const cadence = postWriteCadenceLine(runtime);
+ const parts: string[] = [
+ `Open Second Brain hook: you just ran \`${toolName}\` against ${target}.`,
+ "",
+ ];
+ if (cadence) {
+ parts.push(cadence, "");
+ }
+ parts.push(
+ "If this turn contained a user preference, correction, or rule that",
+ "should outlast the current task (\"don't do X\", \"prefer Y\", \"use",
+ "A instead of B\"), call `brain_feedback` once per signal to record",
+ "it into `Brain/inbox/`.",
+ "",
+ "If a confirmed or unconfirmed preference in `Brain/preferences/`",
+ "scopes to the artifact you just produced, call",
+ "`brain_apply_evidence` with `result: applied | violated` so the",
+ "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.",
+ );
+ return parts.join("\n");
+}
+
+function stopGuardrailCadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return "_This guardrail fires at most once per turn β€” send another reply (with or without `event_log_append`) to clear it._";
+ case "codex":
+ return "_This `codex exec` is about to end β€” call `event_log_append` now or finish silently; no further guardrail will fire._";
+ case "unknown":
+ return "";
+ }
+}
+
+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`.",
+ "",
+ ];
+ 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.",
+ "",
+ "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.",
+ );
+ return parts.join("\n");
+}
+```
+
+`stopGuardrailReason` has a default `runtime = "unknown"` so callers
+that haven't been updated yet keep working β€” back-compat for any
+third-party hook or test that calls the function with no argument.
+
+**Step 2: Update call sites**
+
+`hooks/post-write-reminder.ts` β€” between `const toolName` and the call
+to `postWriteReminder`:
+
+```ts
+import { detectHookRuntime } from "./lib/detect.ts";
+// ...
+const runtime = detectHookRuntime(payload);
+const text = postWriteReminder({ toolName, filePath, runtime });
+```
+
+`hooks/stop-log-guardrail.ts` β€” analogous:
+
+```ts
+import { detectHookRuntime } from "./lib/detect.ts";
+// ...
+const runtime = detectHookRuntime(payload);
+const out = {
+ decision: "block",
+ reason: stopGuardrailReason(runtime),
+};
+```
+
+**Step 3: Update tests**
+
+In `tests/hooks/post-write-reminder.test.ts`:
+
+```ts
+test("Claude Code payload includes the claudecode cadence line", async () => {
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "Write",
+ tool_input: { file_path: "/tmp/foo.md", content: "hello" },
+ session_id: "abc", cwd: "/srv", tool_use_id: "xyz",
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.additionalContext).toContain("Claude Code session");
+});
+
+test("Codex payload includes the codex cadence line", async () => {
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "apply_patch",
+ tool_input: { input: "*** Begin Patch\n*** Update File: /tmp/foo.md\n*** End Patch" },
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.additionalContext).toContain("codex exec");
+});
+
+test("unknown runtime renders byte-identical to v0.10.4 baseline", async () => {
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "Write",
+ tool_input: { file_path: "/tmp/foo.md", content: "hello" },
+ // No transcript_path, no triple, no apply_patch shape.
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.additionalContext).not.toContain("Claude Code session");
+ expect(out.hookSpecificOutput.additionalContext).not.toContain("codex exec");
+ // Spot-check the original lines are present in order.
+ expect(out.hookSpecificOutput.additionalContext).toContain("brain_feedback");
+ expect(out.hookSpecificOutput.additionalContext).toContain("brain_apply_evidence");
+});
+```
+
+Symmetric three tests in `tests/hooks/stop-log-guardrail.test.ts`.
+
+**Step 4: Verify**
+
+```
+bun test tests/hooks/
+bun run typecheck
+```
+Expected: green.
+
+**Step 5: Pause for review (no commit).**
+
+---
+
+## Phase 6 β€” Β§E Embeddings activation
+
+Folded in mid-PR after the Hermes onboarding report
+`/root/vault/Projects/OpenSecondBrain/Features/embedding-provider-activation.md`.
+Three independent slices plus one SKILL; design lives under
+`Β§E.1–§E.4` in the design doc.
+
+### Task 6.1: macOS sqlite shim β€” `scripts/_macos-sqlite.sh`
+
+**Objective:** A sourced bash file that exports
+`DYLD_LIBRARY_PATH` to Homebrew sqlite on Darwin, no-op
+elsewhere; `scripts/o2b` sources it after the Bun precheck.
+
+**Files:**
+- Create: `scripts/_macos-sqlite.sh`
+- Modify: `scripts/o2b`
+- Create: `tests/scripts/macos-sqlite-shim.test.ts`
+
+**Step 1: Write failing test** β€” see design Β§E.1 / Tests row.
+The test spawns the shim under `bash -c '...'` with a stub
+`uname` shadowing the real one through a tmp `PATH` entry, then
+asserts the exported env. Three cases:
+- `uname` says `Linux` β†’ `DYLD_LIBRARY_PATH` unset on exit.
+- `uname` says `Darwin`, brew prefix `/opt/homebrew/opt/sqlite/lib`
+ exists (mkdir under tmp + alias prefix into the shim via env
+ override) β†’ `DYLD_LIBRARY_PATH` set to that path.
+- `uname` says `Darwin`, `DYLD_LIBRARY_PATH=/preset` β†’ preserved
+ verbatim (shim must not clobber).
+
+To stay portable, expose two env overrides in the shim:
+`O2B_MACOS_SQLITE_PREFIXES_OVERRIDE` (colon-separated test
+inputs) and `O2B_MACOS_FORCE_PLATFORM` (`Darwin` / `Linux`).
+Both undocumented in user-facing help; comment in the script
+explains they exist for the test harness.
+
+**Step 2: Implement.** See design Β§E.1 contract. The full body
+fits in ~25 lines. Comment header describes WHY (Apple's
+`OMIT_LOAD_EXTENSION`).
+
+**Step 3: Wire into `scripts/o2b`.** Add one source line after
+`_bun-precheck.sh`. `shellcheck source=` directive ditto.
+
+**Step 4: Run tests.**
+
+```
+bun test tests/scripts/macos-sqlite-shim.test.ts
+```
+
+Expected: 3 passed.
+
+**Step 5: Pause for review (no commit).**
+
+### Task 6.2: `recommendations` field on `IndexCheckReport`
+
+**Objective:** Add an optional `recommendations: string[]` to
+`IndexCheckReport`; populate it from rule table in design Β§E.2;
+render in human + JSON.
+
+**Files:**
+- Modify: `src/core/search/types.ts` (extend report shape)
+- Modify: `src/core/search/indexer.ts` (build the list)
+- Modify: `src/cli/search.ts` (render in JSON + human)
+- Create: `tests/core/search/check-recommendations.test.ts`
+
+**Step 1: Write failing tests.** Drive `indexCheck` via the
+public API with custom config; for the Darwin branch, monkey-
+patch `process.platform` for the duration of the test (using
+`Object.defineProperty(process, "platform", { value: "darwin" })`
+and restore in `afterEach`). Coverage as listed in design.
+
+**Step 2: Type change.**
+
+```ts
+// src/core/search/types.ts
+export interface IndexCheckReport {
+ // existing fields
+ readonly recommendations: ReadonlyArray<string>;
+}
+```
+
+**Step 3: Builder.** Inside `indexCheck` (`src/core/search/indexer.ts`),
+after the existing warning aggregation:
+
+```ts
+const recommendations: string[] = [];
+if (!embeddingKeyResolved) {
+ recommendations.push(
+ "Set OPEN_SECOND_BRAIN_EMBEDDING_KEY in ~/.hermes/.env (or the configured env file).",
+ );
+ recommendations.push(
+ "Provider: OpenAI `text-embedding-3-small` is the default; any OpenAI-compatible endpoint works via OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL.",
+ );
+}
+if (vecExtension === "unavailable") {
+ if (process.platform === "darwin") {
+ recommendations.push(
+ "Install Homebrew SQLite: `brew install sqlite`. The o2b wrapper picks it up on the next invocation via DYLD_LIBRARY_PATH.",
+ );
+ } else {
+ recommendations.push(
+ "sqlite-vec did not load. Confirm the optional dependency with `bun pm ls`, or rebuild with `bun install --force`.",
+ );
+ }
+}
+if (embeddingKeyResolved && vecExtension === "loaded" /* and no embeddings yet */) {
+ recommendations.push(
+ "Run `o2b search reindex --embeddings` to compute the first vectors, then optionally `o2b search reindex --cron-template` for periodic refresh.",
+ );
+}
+return Object.freeze({
+ ...,
+ recommendations: Object.freeze(recommendations),
+});
+```
+
+The "no embeddings yet" branch needs a fact from the status
+side; the simplest path is to consult `embeddings === 0` via
+the same store, which the function already has open. Detail
+in the impl.
+
+**Step 4: Render.** In `src/cli/search.ts`:
+
+```ts
+function jsonForCheck(r: IndexCheckReport): unknown {
+ return {
+ // existing fields ...
+ recommendations: r.recommendations,
+ };
+}
+function renderCheckHuman(r: IndexCheckReport): string {
+ // existing block ...
+ if (r.recommendations.length > 0) {
+ lines.push("");
+ lines.push("recommendations:");
+ for (const rec of r.recommendations) lines.push(` - ${rec}`);
+ }
+ return lines.join("\n") + "\n";
+}
+```
+
+**Step 5: Verify.**
+
+```
+bun test tests/core/search/check-recommendations.test.ts
+bun test tests/cli/search.test.ts # may surface a renderer regression
+```
+
+**Step 6: Pause for review (no commit).**
+
+### Task 6.3: `o2b search reindex --cron-template`
+
+**Objective:** Pure stdout template printer; writes nothing.
+
+**Files:**
+- Modify: `src/cli/search.ts` (extend `cmdSearchReindex`)
+- Create: `src/cli/search-cron-template.ts` (template body)
+- Create: `tests/cli/search-cron-template.test.ts`
+
+**Step 1: Tests.** See design Β§E.3 / Tests row.
+
+**Step 2: Implement `renderCronTemplate(interval: string)`.**
+Returns a single string. Substitutions:
+- `__O2B_BIN__` resolves to `process.argv0`-style absolute path
+ (use the same resolution as `install-cli`).
+- `__INTERVAL_CRON__` is the cron expression (e.g. `*/30 * * *
+ *` for 30 minutes).
+- `__INTERVAL_HUMAN__` is the human form (`30 minutes`).
+
+Duration parser accepts `s`/`m`/`h`/`d` suffixes; rejects
+zero / negative; rejects unrecognised units with a clear
+message.
+
+**Step 3: Wire into the verb.**
+
+```ts
+async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ // existing flags ...
+ "cron-template": { type: "boolean" },
+ interval: { type: "string" },
+ });
+ if (flags["cron-template"] === true) {
+ const intervalRaw = (flags["interval"] as string | undefined) ?? "30m";
+ let body: string;
+ try {
+ body = renderCronTemplate(intervalRaw);
+ } catch (err) {
+ process.stderr.write(`error: ${(err as Error).message}\n`);
+ return 1;
+ }
+ process.stdout.write(body);
+ return 0;
+ }
+ // existing reindex flow ...
+}
+```
+
+**Step 4: Verify.**
+
+```
+bun test tests/cli/search-cron-template.test.ts
+```
+
+**Step 5: Pause for review (no commit).**
+
+### Task 6.4: `embeddings-setup` SKILL
+
+**Objective:** New SKILL file under `skills/embeddings-setup/SKILL.md`.
+
+**Files:**
+- Create: `skills/embeddings-setup/SKILL.md`
+
+**Step 1: Author the file.** See design Β§E.4 for the content
+outline. Front matter `name: embeddings-setup`, description
+with explicit triggers (verbatim phrases the agent watches for).
+
+**Step 2: No test surface** β€” prose only.
+
+**Step 3: Pause for review (no commit).**
+
+### Phase 6 close-out
+
+After Tasks 6.1–6.4:
+
+```
+bun run typecheck
+bun test
+```
+
+Expected: both green; new test counts:
+- `tests/scripts/macos-sqlite-shim.test.ts` β€” 3
+- `tests/core/search/check-recommendations.test.ts` β€” ~4
+- `tests/cli/search-cron-template.test.ts` β€” ~4
+
+CHANGELOG and `_summary.md` deferred-block updates land in
+Phase 5 (Task 5.1 and Task 5.3) β€” expand those entries with
+`Β§E` lines covering the activation slices and the new D-E.x
+deferred items.
+
+---
+
+## Phase 4 β€” Β§15-tail Good vs bad SKILL section
+
+### Task 4.1: Insert the examples section
+
+**Objective:** One inline edit in `skills/brain-memory/SKILL.md`.
+
+**Files:**
+- Modify: `skills/brain-memory/SKILL.md`
+
+**Step 1: Locate insertion point**
+
+After the `## Rules` block, before the `## Fallback capture surfaces`
+heading.
+
+**Step 2: Insert content**
+
+```markdown
+## Examples β€” good vs bad
+
+**Bad:** `principle: "Write good commits"`
+**Good:** `principle: "Use imperative voice in commit subjects; describe what the commit does, not what was done"`
+*Why:* the bad form is unenforceable β€” no future signal can reasonably mark an artifact as "applied" or "violated" against it. The good form names a checkable behaviour.
+
+**Bad:** `principle: "Be careful with secrets"`
+**Good:** `principle: "Do not commit \`.env\`, credentials, or API keys; route them through environment variables"`
+*Why:* the bad form is a vibe. The good form gives the agent a concrete list of patterns to spot in a diff.
+
+**Bad:** `topic: "stuff"`
+**Good:** `topic: "no-internal-abbrev"`
+*Why:* topic is the stable bucket future signals join. A generic slug collects unrelated rules; a precise one keeps the cluster meaningful and lets `brain_query --topic <slug>` return a focused slice.
+
+**Bad:** `note: "fixed it"`
+**Good:** `note: "expanded 'OSB' to 'Open Second Brain' on first use β€” README diff still carried the abbreviation, would have confused a new reader"`
+*Why:* notes survive the artifact. Without the "why" line you cannot tell in three months whether a violation was a regression or a deliberate change.
+```
+
+**Step 3: Verify there is no SKILL parser to satisfy**
+
+`grep -rn "Examples β€” good vs bad" src/ tests/` returns zero β€” the
+section is documentation only. The skill scanner already accepts
+arbitrary headings.
+
+**Step 4: Pause for review (no commit).**
+
+---
+
+## Phase 5 β€” Wrap-up
+
+### Task 5.1: CHANGELOG entry
+
+**Objective:** One `## [0.10.5]` block.
+
+**Files:**
+- Modify: `CHANGELOG.md`
+
+**Step 1: Insert at the top of the file, under the front-matter intro**
+
+```markdown
+## [0.10.5]
+
+Brings the v0.10.5 "Brain maturity" cluster from
+`Projects/OpenSecondBrain/Features/_summary`: Β§14 local
+HTML/web explorer, Β§12 merge-suggestions plus `o2b brain merge`,
+Β§4 (partial β€” completes the deferred D5 from v0.10.4) per-runtime
+cadence in `hooks/lib/messages.ts`, and Β§15-tail "good vs bad"
+examples in the brain-memory SKILL.
+
+No vault migration is required.
+
+### Added
+
+- Β§14 β€” `o2b brain explorer` launches a loopback HTTP server
+ rendering preferences and retired entries as a force-directed
+ graph; `o2b brain explorer --export <path>` writes the same view
+ as a single offline HTML file with inlined data. Both modes share
+ one template under `templates/brain-explorer.html`. Bun.serve
+ handles the live mode; no backend, no LLM, no network. Markdown is
+ parsed in the browser.
+- Β§12 β€” `o2b brain digest` gains a `## Merge suggestions` section
+ surfacing confirmed/quarantine pairs in the same `(topic, scope)`
+ whose `principle` tokens jaccard β‰₯ 0.6. Pairs β‰₯ 0.85 continue to
+ trip the `duplicate-preferences` doctor lint. `o2b brain merge
+ <keep> <drop>` is the explicit slice for resolving them: `keep`
+ retains its frontmatter, picks up the deduped union of
+ `evidenced_by`, the summed `applied_count` and `violated_count`,
+ and `max(last_evidence_at)`; `drop` lands in `retired/` with
+ reason `merged-into` and a `superseded_by` wikilink to `keep`. The
+ CLI prompts interactively unless `--force` is passed; `--dry-run`
+ reports the plan and writes nothing.
+- Β§4 (completes deferred D5 from v0.10.4) β€” `hooks/lib/messages.ts`
+ emits a per-runtime cadence line above the
+ `brain_feedback`/`brain_apply_evidence` block. Claude Code gets a
+ "many turns ahead, capture now" hint; Codex gets a "one-shot exec,
+ call before return" hint. Unknown runtime renders byte-identical
+ to the v0.10.4 baseline. Detection lives in
+ `hooks/lib/detect.ts:detectHookRuntime`, driven by hook-payload
+ shape (`transcript_path` substring or Claude's
+ `session_id`/`cwd`/`tool_use_id` triple). `stopGuardrailReason`
+ follows the same pattern.
+- Β§15 (completes deferred D4 from v0.10.4) β€” `skills/brain-memory/
+ SKILL.md` gains an `## Examples β€” good vs bad` section: four
+ contrastive pairs for weak/strong `principle`, too-general/
+ precise `topic`, and `note` with/without the "why" line.
+
+### Changed
+
+- `tokenise` and `jaccard` lifted from `src/core/brain/doctor.ts`
+ into `src/core/brain/similarity.ts`. No behavioural change. The
+ doctor lint `duplicate-preferences` and the new merge-candidate
+ detector now share one implementation.
+
+### Internal
+
+- New constant `BRAIN_RETIRED_REASON.mergedInto = "merged-into"`.
+- New log event kind `BRAIN_LOG_EVENT_KIND.merge = "merge"`.
+- New typed error `BrainMergeError`.
+```
+
+`[Unreleased]` is never added β€” per vault memory
+`feedback_no_unreleased_section`.
+
+**Step 2: Pause for review (no commit).**
+
+---
+
+### Task 5.2: Bump version
+
+**Objective:** `package.json` from `0.10.4` to `0.10.5`. Mirror via
+the existing script.
+
+**Files:**
+- Modify: `package.json`
+- Auto-modified by `bun run sync-version`: the seven mirror files.
+
+**Step 1: Edit `package.json`**
+
+```diff
+- "version": "0.10.4",
++ "version": "0.10.5",
+```
+
+**Step 2: Run sync**
+
+```
+bun run sync-version
+```
+
+**Step 3: Verify drift gone**
+
+```
+bun run sync-version:check
+```
+Expected: exit 0.
+
+**Step 4: Pause for review (no commit).**
+
+---
+
+### Task 5.3: Vault edit β€” retire deferred items, add new ones
+
+**Objective:** Update `_summary.md` deferred-work block. This is a
+**vault edit** (`/root/vault/`), not a repo edit.
+
+**Files:**
+- Modify: `/root/vault/Projects/OpenSecondBrain/Features/_summary.md`
+
+**Step 1: Replace the two deferred entries that this PR retires**
+
+Find the deferred-work section, locate the two entries:
+- `Β§4 β€” per-runtime steering text для Claude Code ΠΈ Codex.`
+- `Β§15 Β«good vs badΒ» SKILL-сСкция.`
+
+Replace them with one consolidated line:
+
+```markdown
+- **Β§4 per-runtime hook cadence + Β§15 good-vs-bad SKILL section β€” shipped in v0.10.5.**
+```
+
+(Project memory `feedback_no_legacy_framing` says retired-deferred
+entries should disappear from `_summary` for new readers; keeping a
+one-line "shipped in" pointer is acceptable for cross-reference.)
+
+**Step 2: Add new deferred entries (Β§14, Β§12 sub-features)**
+
+Append, in the same deferred-work block:
+
+```markdown
+- **Β§14 Obsidian deep-link from explorer.** Live mode could open
+ `obsidian://` URIs; export mode cannot. We keep both surfaces
+ identical. Trigger to revisit: explicit operator request.
+- **Β§14 Live-refresh in explorer (SSE / WebSocket).** Manual F5 is
+ enough for the first iteration; push channel would break the
+ zero-backend invariant. Trigger: explicit operator request.
+- **Β§14 Layout-state persistence across runs.** Nodes resettle every
+ load. `localStorage` keyed by id is cheap, not critical. Trigger:
+ complaint about position jumps.
+- **Β§12 MCP `brain_merge` tool.** Merge is rare, mutating, and
+ operator-initiated after digest review. Not suitable for agent
+ autonomy. Trigger: a concrete agent use-case.
+- **Β§12 Bulk / interactive merge walkthrough.** Today the CLI takes
+ one `(keep, drop)` pair per invocation. Trigger: β‰₯10 stable
+ suggestions surface for at least one operator.
+```
+
+**Step 3: Pause for review (no commit).**
+
+The vault is synced via Syncthing and backed up nightly; the user
+notices changes through Obsidian or the daily backup. No git for the
+vault.
+
+---
+
+### Task 5.4: Final full test pass
+
+**Objective:** Repo green end-to-end before handoff.
+
+**Step 1: Typecheck**
+
+```
+bun run typecheck
+```
+Expected: PASS.
+
+**Step 2: Test**
+
+```
+bun test
+```
+Expected: all green. Note the new test counts:
+- `tests/core/brain/similarity.test.ts` β€” 7 cases
+- `tests/core/brain/merge-candidates.test.ts` β€” 3 cases
+- `tests/core/brain/merge.test.ts` β€” 8 cases (6 guards + 2 happy-path)
+- `tests/cli/brain-merge.test.ts` β€” 7 cases
+- `tests/core/brain/explorer.test.ts` β€” 10 cases
+- `tests/cli/brain-explorer.test.ts` β€” 6 cases
+- `tests/hooks/detect.test.ts` (extended) β€” +5 cases
+- `tests/hooks/post-write-reminder.test.ts` (extended) β€” +3 cases
+- `tests/hooks/stop-log-guardrail.test.ts` (extended) β€” +3 cases
+- `tests/core/brain/digest.test.ts` (extended) β€” +2 cases
+
+**Step 3: Lint / format if the project has hooks**
+
+`bun run lint` if defined. Otherwise skip.
+
+**Step 4: Manual sanity**
+
+- `bun run src/cli/main.ts brain explorer --export /tmp/brain-test.html --vault /root/vault`
+- Open the file in a browser, sanity-check the graph.
+- `bun run src/cli/main.ts brain digest --vault /root/vault`
+- Verify either an empty `## Merge suggestions` (clean vault) or the
+ section appears (vault with at least one near-duplicate pair).
+- `bun run src/cli/main.ts brain merge --help`
+- Verify the help output is clean.
+
+**Step 5: Pause for review (no commit).**
+
+End of plan. Hand back to the user β€” they decide commits, PR, and
+release.
+
+---
+
+## Risks and known-unknowns (cross-reference design doc)
+
+The design doc has the canonical list. Quick pointer:
+- Explorer layout quality on large vaults (mitigation: hint past a
+ node-count threshold).
+- Force-merge error wording β€” the impl tests assert exact strings.
+- Hook runtime detection on future runtime releases β€” unknown branch
+ preserves the v0.10.4 reminder verbatim, so the failure mode is
+ "cadence hint disappears", not a crash.
+- Static export size β€” grows with vault size; acceptable up to ~1 MB
+ for the typical 100-200 preference vault.
+
+## Out-of-scope
+
+Listed in the design doc under *Non-goals (explicitly deferred)* and
+mirrored into `_summary.md β†’ ## Deferred work` in Task 5.3.
diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.ts
index 6b5de4d3..b159485e 100644
--- a/hooks/lib/detect.ts
+++ b/hooks/lib/detect.ts
@@ -87,3 +87,66 @@ export function summarizeTurn(
}
return { hadArtifact, hadLog };
}
+
+// ---- Runtime detection (Β§4-tail) ---------------------------------------
+
+/**
+ * Which runtime is invoking the hook. `unknown` is the fail-safe and
+ * renders byte-identical reminder text to the v0.10.4 baseline, so
+ * a future runtime that breaks both signals never crashes the hook.
+ */
+export type HookRuntime = "claudecode" | "codex" | "unknown";
+
+const CLAUDE_TRANSCRIPT_NEEDLES = [
+ "/.claude/projects/",
+ "/.claude/sessions/",
+] as const;
+const CODEX_TRANSCRIPT_NEEDLE = "/.codex/sessions/";
+
+/**
+ * Infer the runtime from a hook payload by shape. First-hit wins,
+ * order matches the design doc:
+ *
+ * 1. `transcript_path` substring (`/.claude/projects/`, `/.claude/sessions/`).
+ * 2. `transcript_path` substring (`/.codex/sessions/`).
+ * 3. Claude Code distinctive triple (`session_id` + `cwd` + `tool_use_id`).
+ * 4. Codex apply_patch shape (`tool_name === "apply_patch"` with
+ * a patch body in `tool_input.input`).
+ * 5. `"unknown"`.
+ *
+ * Malformed payloads (`null`, primitives, missing fields, wrong types)
+ * resolve to `"unknown"` without throwing β€” the hook never crashes on
+ * detection.
+ */
+export function detectHookRuntime(payload: unknown): HookRuntime {
+ if (payload === null || typeof payload !== "object") return "unknown";
+ const p = payload as Record<string, unknown>;
+
+ const tp = p["transcript_path"];
+ if (typeof tp === "string") {
+ if (CLAUDE_TRANSCRIPT_NEEDLES.some((n) => tp.includes(n))) {
+ return "claudecode";
+ }
+ if (tp.includes(CODEX_TRANSCRIPT_NEEDLE)) return "codex";
+ }
+
+ if (
+ typeof p["session_id"] === "string"
+ && typeof p["cwd"] === "string"
+ && typeof p["tool_use_id"] === "string"
+ ) {
+ return "claudecode";
+ }
+
+ if (p["tool_name"] === "apply_patch") {
+ const ti = p["tool_input"];
+ if (ti !== null && typeof ti === "object") {
+ const input = (ti as Record<string, unknown>)["input"];
+ if (typeof input === "string" && input.includes("*** Begin Patch")) {
+ return "codex";
+ }
+ }
+ }
+
+ return "unknown";
+}
diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.ts
index 0c30627f..397a9c51 100644
--- a/hooks/lib/messages.ts
+++ b/hooks/lib/messages.ts
@@ -11,18 +11,55 @@
* agent's runtime, not in a conversation context β€” the language
* choice for the *event log entry itself* still follows the
* conversation locale per the `agent-event-log` skill.
+ *
+ * Β§4-tail (v0.10.5): a per-runtime cadence line is interpolated
+ * between the opening sentence and the rest of the reminder when the
+ * payload-shape detector resolves to `claudecode` or `codex`. The
+ * `unknown` branch renders byte-identical to the v0.10.4 baseline so
+ * old hook installs and unfamiliar runtimes are not affected.
*/
+import type { HookRuntime } from "./detect.ts";
+
export interface PostWriteReminderInput {
readonly toolName: string;
readonly filePath: string | null;
+ readonly runtime: HookRuntime;
+}
+
+function postWriteCadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return [
+ "_Claude Code session: many turns ahead β€” capture the signal_",
+ "_or evidence now rather than batching to end-of-session; long_",
+ "_sessions risk forgetting the context that distinguishes one_",
+ "_artifact from the next._",
+ ].join("\n");
+ case "codex":
+ return [
+ "_Codex `codex exec` is a one-shot run β€” call `brain_feedback`_",
+ "_or `brain_apply_evidence` before this exec returns; there is_",
+ "_no second turn._",
+ ].join("\n");
+ case "unknown":
+ return "";
+ }
}
-export function postWriteReminder({ toolName, filePath }: PostWriteReminderInput): string {
+export function postWriteReminder({
+ toolName,
+ filePath,
+ runtime,
+}: PostWriteReminderInput): string {
const target = filePath ? `\`${filePath}\`` : "a file";
- return [
+ const cadence = postWriteCadenceLine(runtime);
+ const parts: string[] = [
`Open Second Brain hook: you just ran \`${toolName}\` against ${target}.`,
"",
+ ];
+ if (cadence !== "") parts.push(cadence, "");
+ parts.push(
"If this turn contained a user preference, correction, or rule that",
"should outlast the current task (\"don't do X\", \"prefer Y\", \"use",
"A instead of B\"), call `brain_feedback` once per signal to record",
@@ -36,15 +73,31 @@ export function postWriteReminder({ toolName, filePath }: PostWriteReminderInput
"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.",
- ].join("\n");
+ );
+ return parts.join("\n");
+}
+
+function stopGuardrailCadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return "_This guardrail fires at most once per turn β€” send another reply (with or without `event_log_append`) to clear it._";
+ case "codex":
+ return "_This `codex exec` is about to end β€” call `event_log_append` now or finish silently; no further guardrail will fire._";
+ case "unknown":
+ return "";
+ }
}
-export function stopGuardrailReason(): string {
- return [
+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`.",
"",
+ ];
+ 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.",
@@ -52,5 +105,6 @@ export function stopGuardrailReason(): string {
"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.",
- ].join("\n");
+ );
+ return parts.join("\n");
}
diff --git a/hooks/post-write-reminder.ts b/hooks/post-write-reminder.ts
index 86955d56..2d489d37 100755
--- a/hooks/post-write-reminder.ts
+++ b/hooks/post-write-reminder.ts
@@ -25,7 +25,7 @@
*/
import { asHookPayload, readHookInput } from "./lib/stdin.ts";
-import { isArtifactToolName } from "./lib/detect.ts";
+import { detectHookRuntime, isArtifactToolName } from "./lib/detect.ts";
import { postWriteReminder } from "./lib/messages.ts";
async function main(): Promise<void> {
@@ -47,7 +47,8 @@ async function main(): Promise<void> {
if (isToolResponseError(payload.tool_response)) return;
const filePath = extractFilePath(payload.tool_input);
- const text = postWriteReminder({ toolName, filePath });
+ const runtime = detectHookRuntime(payload);
+ const text = postWriteReminder({ toolName, filePath, runtime });
const out = {
hookSpecificOutput: {
diff --git a/hooks/stop-log-guardrail.ts b/hooks/stop-log-guardrail.ts
index bbdd3971..2d6f3505 100755
--- a/hooks/stop-log-guardrail.ts
+++ b/hooks/stop-log-guardrail.ts
@@ -27,7 +27,7 @@
import { asHookPayload, readHookInput } from "./lib/stdin.ts";
import { readTranscript } from "./lib/transcript.ts";
-import { summarizeTurn } from "./lib/detect.ts";
+import { detectHookRuntime, summarizeTurn } from "./lib/detect.ts";
import { stopGuardrailReason } from "./lib/messages.ts";
async function main(): Promise<void> {
@@ -53,9 +53,10 @@ async function main(): Promise<void> {
const summary = summarizeTurn(signal.toolCalls, signal.bashCommands);
if (!summary.hadArtifact || summary.hadLog) return;
+ const runtime = detectHookRuntime(payload);
const out = {
decision: "block",
- reason: stopGuardrailReason(),
+ reason: stopGuardrailReason(runtime),
};
process.stdout.write(JSON.stringify(out) + "\n");
}
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index befe76bd..59b971c2 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.4",
+ "version": "0.10.5",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 44d83301..858e90fd 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.4",
+ "version": "0.10.5",
"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 853c6587..78f3991b 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.4"
+version: "0.10.5"
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 45655561..b17d5caf 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.4",
+ "version": "0.10.5",
"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 4f56b8d2..f01828ee 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.4"
+version: "0.10.5"
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 9f78c996..35101f1b 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.4"
+version = "0.10.5"
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/scripts/_macos-sqlite.sh b/scripts/_macos-sqlite.sh
new file mode 100644
index 00000000..cafba4ba
--- /dev/null
+++ b/scripts/_macos-sqlite.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+# Sourced by scripts/o2b after _bun-precheck.sh.
+#
+# Apple ships /usr/lib/libsqlite3.dylib with the build flag
+# SQLITE_OMIT_LOAD_EXTENSION enabled. bun:sqlite resolves the
+# system library by default, so `db.loadExtension(...)` β€” which
+# the sqlite-vec optional dependency uses for semantic search β€”
+# fails with "This build of sqlite3 does not support dynamic
+# extension loading".
+#
+# Homebrew's sqlite formula is built WITH extension loading.
+# Setting DYLD_LIBRARY_PATH to the Homebrew lib dir makes the
+# dynamic loader pick that build before the system one.
+#
+# Side effects: exports DYLD_LIBRARY_PATH when (and only when):
+# 1. uname -s is Darwin
+# 2. DYLD_LIBRARY_PATH is not already set by the caller
+# 3. one of the known Homebrew lib prefixes exists on disk
+#
+# Otherwise no-op. The wrapper continues regardless. Hosts
+# without `brew install sqlite` see `o2b search check` report
+# `vec_extension: unavailable`, plus the actionable
+# recommendation block added in v0.10.5.
+#
+# Test seams (undocumented in user-facing help):
+# O2B_MACOS_FORCE_PLATFORM β€” override `uname -s` ("Darwin" | "Linux")
+# O2B_MACOS_SQLITE_PREFIXES_OVERRIDE β€” colon-separated prefix list
+
+# shellcheck shell=bash
+
+_o2b_macos_platform=""
+if [[ -n "${O2B_MACOS_FORCE_PLATFORM-}" ]]; then
+ _o2b_macos_platform="${O2B_MACOS_FORCE_PLATFORM}"
+else
+ _o2b_macos_platform="$(uname -s 2>/dev/null || echo "")"
+fi
+
+if [[ "${_o2b_macos_platform}" != "Darwin" ]]; then
+ unset _o2b_macos_platform
+ return 0 2>/dev/null || true
+fi
+
+# Honour caller-configured DYLD_LIBRARY_PATH verbatim β€” including
+# an explicit empty string (the caller is signalling "leave the
+# loader at its defaults, do not prepend anything"). Use `+set`
+# so we distinguish "unset" from "set, possibly empty".
+if [[ -n "${DYLD_LIBRARY_PATH+set}" ]]; then
+ unset _o2b_macos_platform
+ return 0 2>/dev/null || true
+fi
+
+if [[ -n "${O2B_MACOS_SQLITE_PREFIXES_OVERRIDE-}" ]]; then
+ IFS=':' read -r -a _o2b_macos_prefixes <<< "${O2B_MACOS_SQLITE_PREFIXES_OVERRIDE}"
+else
+ _o2b_macos_prefixes=(
+ "/opt/homebrew/opt/sqlite/lib" # Apple Silicon
+ "/usr/local/opt/sqlite/lib" # Intel
+ )
+fi
+
+for _o2b_macos_prefix in "${_o2b_macos_prefixes[@]}"; do
+ if [[ -d "${_o2b_macos_prefix}" ]]; then
+ export DYLD_LIBRARY_PATH="${_o2b_macos_prefix}"
+ break
+ fi
+done
+
+unset _o2b_macos_platform _o2b_macos_prefixes _o2b_macos_prefix
diff --git a/scripts/o2b b/scripts/o2b
index 6702a972..5ef6b956 100755
--- a/scripts/o2b
+++ b/scripts/o2b
@@ -10,4 +10,7 @@ REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
# shellcheck source=./_bun-precheck.sh
. "$SCRIPT_DIR/_bun-precheck.sh"
+# shellcheck source=./_macos-sqlite.sh
+. "$SCRIPT_DIR/_macos-sqlite.sh"
+
exec bun run "$REPO_ROOT/src/cli/main.ts" "$@"
diff --git a/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.md
index d3efe3c6..94942676 100644
--- a/skills/brain-memory/SKILL.md
+++ b/skills/brain-memory/SKILL.md
@@ -113,6 +113,28 @@ o2b brain apply-evidence \
- Do not write into `Brain/.snapshots/` or `Brain/retired/` directly β€” those are managed by `dream` and `o2b brain reject` only.
- `o2b brain reject` requires `--reason <text>` from v0.10.1 onward. The reason is persisted on the retired file as `user_rejected_reason`. The next dream pass will mark any future signal on the same `(topic, scope)` as `signal-suppressed` and move it straight to `processed/` β€” do not re-record the same signal hoping it will re-grow into a preference. If you genuinely disagree with a past reject, raise it with the user; do not route around it via `brain_feedback`.
+## Examples β€” good vs bad
+
+These four pairs calibrate what makes a recorded signal useful versus
+noise. The form of the entry matters as much as the timing β€” a vague
+`principle` clogs the dream pass; a precise one trains it.
+
+**Bad:** `principle: "Write good commits"`
+**Good:** `principle: "Use imperative voice in commit subjects; describe what the commit does, not what was done"`
+*Why:* the bad form is unenforceable β€” no future signal can reasonably mark an artifact as "applied" or "violated" against it. The good form names a checkable behaviour.
+
+**Bad:** `principle: "Be careful with secrets"`
+**Good:** `principle: "Do not commit .env, credentials, or API keys; route them through environment variables"`
+*Why:* the bad form is a vibe. The good form gives the agent a concrete list of patterns to spot in a diff.
+
+**Bad:** `topic: "stuff"`
+**Good:** `topic: "no-internal-abbrev"`
+*Why:* topic is the stable bucket future signals join. A generic slug collects unrelated rules; a precise one keeps the cluster meaningful and lets `brain_query --topic <slug>` return a focused slice.
+
+**Bad:** `note: "fixed it"`
+**Good:** `note: "expanded 'OSB' to 'Open Second Brain' on first use β€” README diff still carried the abbreviation, would have confused a new reader"`
+*Why:* notes survive the artifact. Without the "why" line you cannot tell in three months whether a violation was a regression or a deliberate change.
+
## Fallback capture surfaces
When no agent is in the loop at the moment the rule is formed, the
diff --git a/skills/embeddings-setup/SKILL.md b/skills/embeddings-setup/SKILL.md
new file mode 100644
index 00000000..50f150f4
--- /dev/null
+++ b/skills/embeddings-setup/SKILL.md
@@ -0,0 +1,153 @@
+---
+name: embeddings-setup
+description: Bring Open Second Brain semantic search online β€” embedding API key, sqlite-vec extension, first reindex, optional periodic refresh. INVOKE when the user mentions "embeddings", "semantic search", "vector index", or after `o2b search check` reports `vec_extension: unavailable`, `embedding_key: missing`, or any line in its `recommendations:` block. SKIP when the user is asking conceptual questions about embeddings or comparing providers without intent to set up β€” answer those directly.
+---
+
+# Embeddings setup
+
+Open Second Brain ships with two search paths: keyword-only (always
+on, no credentials) and semantic via embedded vectors (opt-in). This
+SKILL walks the activation flow for the semantic path. The flow is
+proactive β€” when the user mentions semantic search or `o2b search
+check` surfaces missing pieces, take the user through this list
+rather than waiting for explicit instruction.
+
+## Step 1 β€” Always start with `o2b search check`
+
+```
+o2b search check
+```
+
+The output names every missing piece and ends with a
+`recommendations:` block listing the exact commands to fix each.
+Read both before suggesting next steps. The `recommendations` field
+is also present in the `--json` output for headless callers.
+
+Branch on what the report shows:
+
+- `embedding_key: MISSING` β†’ go to step 2.
+- `vec_extension: unavailable` on macOS β†’ go to step 3.
+- `vec_extension: unavailable` on Linux β†’ go to step 4.
+- Everything OK but `semantic_enabled: false` (no embeddings yet) β†’
+ go to step 5.
+
+## Step 2 β€” Provider and API key
+
+Ask the user which provider they want. The default is
+`text-embedding-3-small` from OpenAI (about $0.02 per 1M tokens,
+which covers tens of thousands of vault pages). Any OpenAI-compatible
+endpoint works β€” Groq, Together, a local LM Studio server, etc.
+
+Required env vars (write to `~/.hermes/.env` or the configured env
+file, never to a tracked file):
+
+```bash
+OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER=openai-compat
+OPEN_SECOND_BRAIN_EMBEDDING_MODEL=text-embedding-3-small
+OPEN_SECOND_BRAIN_EMBEDDING_KEY=<placeholder; user pastes the key>
+# Optional β€” only when not using OpenAI:
+# OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL=https://api.together.xyz/v1
+```
+
+**Never invent or echo the key.** Write a placeholder, then ask the
+user to paste their key in place of it. Recheck with `o2b search
+check` after the user confirms.
+
+## Step 3 β€” macOS: install Homebrew SQLite
+
+Apple ships `/usr/lib/libsqlite3.dylib` with
+`SQLITE_OMIT_LOAD_EXTENSION`, so the optional `sqlite-vec` extension
+cannot load against the system SQLite. Homebrew's `sqlite` formula
+is built with extension loading enabled.
+
+```bash
+brew install sqlite
+```
+
+The `o2b` wrapper auto-detects Homebrew SQLite on Darwin and exports
+`DYLD_LIBRARY_PATH` for `bun:sqlite` on the next invocation. No
+manual patching of the wrapper script is needed (the v0.10.5 shim
+`scripts/_macos-sqlite.sh` handles it). Verify with:
+
+```
+o2b search check
+```
+
+Expect `vec_extension: loaded`.
+
+## Step 4 β€” Linux: reconfirm the optional dependency
+
+`sqlite-vec` ships as an optional dependency. If the install path
+missed it, force a rebuild:
+
+```bash
+bun pm ls | grep sqlite-vec
+bun install --force
+```
+
+If the package is present but still does not load, the Linux build
+of `libsqlite3` may have been compiled without `LOAD_EXTENSION`.
+Capture `sqlite3 :memory: "PRAGMA compile_options;"` and surface it
+to the user β€” they will know whether their distro's SQLite is
+unusual.
+
+## Step 5 β€” Compute the first vectors
+
+```
+o2b search reindex --embeddings
+```
+
+This walks the vault, chunks every Markdown file, and computes
+embeddings. Cost scales linearly with vault size β€” a 150-file vault
+typically lands in a few seconds.
+
+Verify semantic search works:
+
+```
+o2b search "preferences for code review"
+```
+
+The output rows carry `(semantic)` in the source column when the
+match came from the vector index.
+
+## Step 6 β€” Offer periodic reindex
+
+The vault keeps changing β€” other agents add notes, the user edits
+existing ones. Without periodic refresh the embeddings drift behind
+the keyword index.
+
+```
+o2b search reindex --cron-template
+```
+
+Prints a watchdog script (a heredoc that, when the operator runs
+the printed block, lands at `~/.local/bin/osb-reindex.sh`), a
+native crontab line, and a `hermes cron create` command. Pure
+stdout β€” the verb writes nothing on its own; pick the path that
+matches the host and paste the relevant section into your
+shell / crontab. Recommended cadence:
+
+- 30 minutes when the vault sees active multi-agent work.
+- 6 hours when changes are sporadic.
+
+Override with `--interval 6h` (or any `<N>m|h|d` value below 60m / 24h
+/ unlimited days).
+
+## Multi-agent note
+
+Only the agent that runs `reindex` needs
+`OPEN_SECOND_BRAIN_EMBEDDING_KEY`. Read-only consumers (sibling
+Claude Code / Codex / OpenClaw sessions on the same vault) query
+the already-computed vectors and never see the key. When designating
+the reindex owner, the canonical choice is Hermes (it carries the
+cron infrastructure); the others stay credential-free.
+
+## What this SKILL does NOT do
+
+- Does not invoke `brew install` on the user's behalf. The SKILL
+ prints the command; the user runs it.
+- Does not paste an API key into the env file silently. Always use
+ a placeholder, then ask the user to substitute.
+- Does not commit env files. They live outside the tracked tree.
+- Does not launch a long-running watcher inside OSB β€” the
+ `--cron-template` recipe is the endorsed automation path.
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 7690b6c8..dd10226f 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -25,6 +25,8 @@
import { existsSync, readFileSync, readdirSync, statSync, type Dirent } from "node:fs";
import { resolve } from "node:path";
+import { atomicWriteFileSync } from "../core/fs-atomic.ts";
+
import {
defaultConfigPath,
resolveAgentName,
@@ -49,6 +51,17 @@ import {
importSessionPath,
} from "../core/brain/sessions/import.ts";
import { SessionImportError } from "../core/brain/sessions/types.ts";
+import {
+ buildLiveServer,
+ collectExplorerData,
+ renderExportedHtml,
+ type LiveServerHandle,
+} from "../core/brain/explorer.ts";
+import {
+ BrainMergeError,
+ mergePreferences,
+ type MergePlan,
+} from "../core/brain/merge.ts";
import { moveToRetired, parsePreference, writePreference } from "../core/brain/preference.ts";
import { brainDirs, preferencePath } from "../core/brain/paths.ts";
import { isoDate, isoSecond } from "../core/brain/time.ts";
@@ -767,6 +780,178 @@ async function cmdBrainReject(argv: string[]): Promise<number> {
return 0;
}
+async function cmdBrainMerge(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ force: { type: "boolean" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ if (positional.length !== 2) {
+ return fail(
+ "brain merge requires exactly two positional ids: <keep-pref-id> <drop-pref-id>",
+ );
+ }
+ const [keepId, dropId] = positional as [string, string];
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent =
+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const dryRun = flags["dry-run"] === true;
+ const force = flags["force"] === true;
+ const wantJson = flags["json"] === true;
+
+ // Plan first via dryRun so the prompt shows real numbers without
+ // touching disk. A second call commits when the operator agrees.
+ // Each `mergePreferences` invocation takes its own fresh timestamp
+ // so the commit reflects when it ran (the operator may take a
+ // long time to confirm at the prompt below).
+ let plan: MergePlan;
+ try {
+ plan = mergePreferences(vault, keepId, dropId, {
+ now: new Date(),
+ agentName: agent,
+ dryRun: true,
+ });
+ } catch (exc) {
+ if (exc instanceof BrainMergeError) {
+ return fail(`brain merge: ${exc.message}`);
+ }
+ return fail(
+ `brain merge: failed to plan merge: ${(exc as Error).message ?? exc}`,
+ );
+ }
+
+ const planLines = [
+ `merge plan:`,
+ ` keep: ${plan.keep_id}`,
+ ` drop: ${plan.drop_id} β†’ ${plan.retired_path}`,
+ ` topic: ${plan.topic}${plan.scope ? `, scope: ${plan.scope}` : ""}`,
+ ` evidenced_by union: ${plan.merged_evidenced_by.length}`,
+ ` applied_sum: ${plan.applied_sum}`,
+ ` violated_sum: ${plan.violated_sum}`,
+ ` last_evidence_at: ${plan.last_evidence_at ?? "β€”"}`,
+ ];
+
+ if (dryRun) {
+ if (wantJson) {
+ okJson({ dry_run: true, plan });
+ } else {
+ for (const line of planLines) ok(line);
+ ok("dry-run; no changes written");
+ }
+ return 0;
+ }
+
+ if (!force) {
+ if (wantJson) {
+ return fail(
+ "brain merge: --json without --force is not supported (interactive prompt cannot render)",
+ );
+ }
+ // Non-TTY stdin can only "answer" the prompt with EOF, which we
+ // would interpret as N β†’ exit 0 "merge cancelled". For
+ // automation that path is misleading (looks like an intentional
+ // no-op). Require `--force` instead, same shape as rollback /
+ // migrate-frontmatter guards.
+ if (!process.stdin.isTTY) {
+ return fail(
+ "brain merge: --force required when stdin is not a TTY (cannot prompt for confirmation)",
+ );
+ }
+ for (const line of planLines) process.stderr.write(line + "\n");
+ process.stderr.write("Proceed? [y/N] ");
+ const ans = (await readSingleLine()).toLowerCase();
+ if (ans !== "y" && ans !== "yes") {
+ ok("merge cancelled");
+ return 0;
+ }
+ }
+
+ try {
+ mergePreferences(vault, keepId, dropId, {
+ now: new Date(),
+ agentName: agent,
+ });
+ } catch (exc) {
+ if (exc instanceof BrainMergeError) {
+ return fail(`brain merge: ${exc.message}`);
+ }
+ return fail(
+ `brain merge: failed to commit merge: ${(exc as Error).message ?? exc}`,
+ );
+ }
+
+ if (wantJson) {
+ okJson({ merged: true, plan });
+ } else {
+ ok(`merged: ${plan.drop_id} β†’ ${plan.keep_id} (retired as merged-into)`);
+ }
+ return 0;
+}
+
+async function cmdBrainExplorer(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ port: { type: "string" },
+ export: { type: "string" },
+ force: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const exportPath = flags["export"] as string | undefined;
+ const force = flags["force"] === true;
+
+ if (exportPath !== undefined) {
+ if (existsSync(exportPath) && !force) {
+ return fail(
+ `${exportPath} exists; pass --force to overwrite`,
+ );
+ }
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ try {
+ atomicWriteFileSync(exportPath, html);
+ } catch (err) {
+ return fail(
+ `failed to write ${exportPath}: ${(err as Error).message ?? err}`,
+ );
+ }
+ ok(`exported ${graph.nodes.length} nodes to ${exportPath}`);
+ return 0;
+ }
+
+ const portRaw = (flags["port"] as string | undefined) ?? "7777";
+ const port = Number.parseInt(portRaw, 10);
+ if (!/^\d+$/.test(portRaw) || !Number.isFinite(port) || port < 1 || port > 65535) {
+ return fail(`invalid --port value: ${portRaw}`);
+ }
+
+ let server: LiveServerHandle;
+ try {
+ server = buildLiveServer(vault, port);
+ } catch (err) {
+ const msg = (err as Error).message ?? String(err);
+ if (/EADDRINUSE|address already in use/i.test(msg)) {
+ return fail(`port ${port} already in use; try --port <other>`);
+ }
+ return fail(`failed to start explorer: ${msg}`);
+ }
+
+ ok(`Live explorer at ${server.url}`);
+ info("Press Ctrl+C to stop.");
+
+ await new Promise<void>((resolveStop) => {
+ const stop = (): void => {
+ void server.close().then(() => resolveStop());
+ };
+ process.once("SIGINT", stop);
+ process.once("SIGTERM", stop);
+ });
+ return 0;
+}
+
async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
vault: { type: "string" },
@@ -1619,6 +1804,8 @@ Brain verbs (observing memory):
set-primary Declare or clear primary_agent in _brain.yaml (--clear)
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)
+ 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;
--dry-run previews via the same diff renderer)
@@ -1714,6 +1901,29 @@ const VERB_HELP: Record<string, string> = {
"@osb markers in user/assistant messages, and replay of brain_feedback\n" +
"tool_use calls. Dedup against the inbox by normalised payload hash.\n" +
"Autodetect failure exits 2 β€” pass --format to override.\n",
+ merge:
+ "usage: o2b brain merge <keep-pref-id> <drop-pref-id>\n" +
+ " [--dry-run] [--force] [--vault <path>] [--json]\n" +
+ " [--agent <name>]\n" +
+ "Merge two near-duplicate preferences. <keep> retains identity and\n" +
+ "principle; <drop> retires with reason 'merged-into' and a\n" +
+ "superseded_by wikilink to <keep>. <keep> picks up the sorted-dedup\n" +
+ "union of evidenced_by, the summed applied_count / violated_count,\n" +
+ "and max(last_evidence_at). Confidence is recomputed by the next\n" +
+ "dream pass β€” not by merge itself.\n" +
+ "--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",
+ explorer:
+ "usage: o2b brain explorer [--port <n>] [--vault <path>]\n" +
+ " o2b brain explorer --export <path> [--force] [--vault <path>]\n" +
+ "Live mode: bind a loopback HTTP server on 127.0.0.1:<port> (default\n" +
+ "7777) that renders preferences and retired entries as a force-directed\n" +
+ "graph. Press Ctrl+C to stop.\n" +
+ "Export mode: write the same view as a single offline HTML file at\n" +
+ "<path>. Without --force, refuses to overwrite an existing file.\n" +
+ "Zero backend, no LLM, no network access. The page consumes a\n" +
+ "prebuilt JSON graph; it does not parse vault Markdown client-side.\n",
};
// ── Public entry point ──────────────────────────────────────────────────────
@@ -1787,6 +1997,10 @@ export async function handleBrainSubcommand(
return await cmdBrainScanInline(rest);
case "import-session":
return await cmdBrainImportSession(rest);
+ case "merge":
+ return await cmdBrainMerge(rest);
+ case "explorer":
+ return await cmdBrainExplorer(rest);
default:
process.stderr.write(`error: unknown brain verb: ${verb}\n`);
process.stdout.write(BRAIN_HELP);
diff --git a/src/cli/search-cron-template.ts b/src/cli/search-cron-template.ts
new file mode 100644
index 00000000..f5ce60a3
--- /dev/null
+++ b/src/cli/search-cron-template.ts
@@ -0,0 +1,164 @@
+/**
+ * Β§E.3 -- 'o2b search reindex --cron-template' renderer.
+ *
+ * Prints a watchdog script body, a native crontab line, and an
+ * optional 'hermes cron create' invocation. Pure stdout, writes
+ * nothing. The operator (or agent in the user's name) copies what
+ * fits their host into the cron infrastructure of choice.
+ *
+ * Duration parser accepts <N>s|m|h|d. Mapping to a cron expression
+ * covers the common cadences:
+ * - minutes: every N (N less than 60) maps to N-step minutes
+ * - hours: every N hours maps to N-step hours
+ * - days: every N days maps to N-step days
+ * - seconds: rejected (cron's finest grain is one minute)
+ *
+ * Inputs outside those bounds raise a CronTemplateError with a
+ * concrete suggestion (use the next unit up).
+ */
+
+export class CronTemplateError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "CronTemplateError";
+ }
+}
+
+interface ParsedInterval {
+ /** Cron expression for the chosen interval. */
+ readonly cron: string;
+ /** Human-readable label (e.g. "30 minutes"). */
+ readonly human: string;
+ /** Schedule string for 'hermes cron create --schedule ...'. */
+ readonly hermesSchedule: string;
+}
+
+export function parseInterval(raw: string): ParsedInterval {
+ const trimmed = raw.trim();
+ const m = /^(\d+)\s*(s|m|h|d)$/.exec(trimmed);
+ if (!m) {
+ throw new CronTemplateError(
+ "cannot parse interval " + JSON.stringify(raw) +
+ ": expected <N>s|m|h|d (e.g. 30m, 6h, 1d)",
+ );
+ }
+ const n = parseInt(m[1]!, 10);
+ const unit = m[2]!;
+ if (n <= 0) {
+ throw new CronTemplateError(
+ "interval must be positive; got " + JSON.stringify(raw),
+ );
+ }
+ if (unit === "s") {
+ throw new CronTemplateError(
+ "cron grain is one minute -- second-level intervals are not supported",
+ );
+ }
+ if (unit === "m") {
+ if (n >= 60) {
+ const hours = Math.round(n / 60);
+ throw new CronTemplateError(
+ "intervals of 60 minutes or more must use the h unit (e.g. " +
+ hours + "h)",
+ );
+ }
+ const cron = "*/" + n + " * * * *";
+ return { cron, human: n + " minutes", hermesSchedule: cron };
+ }
+ if (unit === "h") {
+ if (n >= 24) {
+ const days = Math.round(n / 24);
+ throw new CronTemplateError(
+ "intervals of 24 hours or more must use the d unit (e.g. " +
+ days + "d)",
+ );
+ }
+ const cron = "0 */" + n + " * * *";
+ return { cron, human: n + " hours", hermesSchedule: cron };
+ }
+ // unit === "d"
+ const cron = "0 0 */" + n + " * *";
+ return { cron, human: n + " days", hermesSchedule: cron };
+}
+
+export interface RenderCronTemplateOptions {
+ /** Override the resolved o2b binary path (test seam). */
+ readonly o2bBin?: string;
+}
+
+export function renderCronTemplate(
+ interval: string,
+ opts: RenderCronTemplateOptions = {},
+): string {
+ const parsed = parseInterval(interval);
+ const o2bBin = opts.o2bBin ?? "o2b";
+ const watchdogBody = renderWatchdogBody(o2bBin);
+ const header =
+ "# ----------------------------------------------------------------------\n" +
+ "# Open Second Brain - periodic reindex template\n" +
+ "# interval: " + parsed.human + "\n" +
+ "#\n" +
+ "# Pick ONE of the three paths below. The watchdog script is the\n" +
+ "# common piece; both crontab and Hermes-cron rely on it.\n" +
+ "# ----------------------------------------------------------------------\n";
+ const watchdog =
+ "## 1. Watchdog script - save to ~/.local/bin/osb-reindex.sh\n" +
+ "## (then chmod +x). Sources ~/.hermes/.env if present so the\n" +
+ "## embedding API key lands in the environment.\n" +
+ "\n" +
+ "cat >~/.local/bin/osb-reindex.sh <<'OSBEOF'\n" +
+ watchdogBody +
+ "OSBEOF\n" +
+ "chmod +x ~/.local/bin/osb-reindex.sh\n";
+ const nativeCron =
+ "## 2. Native crontab - open 'crontab -e' and append:\n" +
+ "\n" +
+ parsed.cron + " ~/.local/bin/osb-reindex.sh\n";
+ const hermesCron =
+ "## 3. Hermes cron (preferred when Hermes is the embedding owner):\n" +
+ "\n" +
+ "hermes cron create \\\n" +
+ " --name osb-reindex \\\n" +
+ " --schedule '" + parsed.hermesSchedule + "' \\\n" +
+ ' --command "$HOME/.local/bin/osb-reindex.sh" \\\n' +
+ " --no-agent\n";
+ const footer =
+ "# ----------------------------------------------------------------------\n" +
+ "# After install, verify with: " + o2bBin + " search status\n" +
+ "# ----------------------------------------------------------------------\n";
+ return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer]
+ .join("\n");
+}
+
+function renderWatchdogBody(o2bBin: string): string {
+ // The bash body lives in a heredoc on the operator's host. JS-side
+ // strings are plain text -- no JS-level interpolation of shell
+ // variables. The watchdog prints the JSON line verbatim when
+ // something changed; the operator pipes it through jq, Slack, or
+ // keeps the raw line.
+ const lines = [
+ "#!/usr/bin/env bash",
+ "set -euo pipefail",
+ "",
+ "# Pick up OPEN_SECOND_BRAIN_EMBEDDING_* from the Hermes env file",
+ "# if it exists. Other env files can be appended below.",
+ 'if [[ -f "$HOME/.hermes/.env" ]]; then',
+ ' set -a; . "$HOME/.hermes/.env"; set +a',
+ "fi",
+ "",
+ "out=$(" + o2bBin + " search reindex --embeddings --json)",
+ "# Emit the JSON line only when the reindex actually changed",
+ "# something. jq is preferred; fall back to grep when missing.",
+ "if command -v jq >/dev/null 2>&1; then",
+ ' changed=$(printf "%s" "$out" | jq -r ".stats.added + .stats.updated + .stats.deleted")',
+ ' if [ "$changed" != "0" ] && [ -n "$changed" ]; then',
+ ' printf "%s\\n" "$out"',
+ " fi",
+ "else",
+ ' if printf "%s" "$out" | grep -Eq \'"(added|updated|deleted)"[[:space:]]*:[[:space:]]*[1-9]\'; then',
+ ' printf "%s\\n" "$out"',
+ " fi",
+ "fi",
+ ];
+ return lines.join("\n") + "\n";
+}
diff --git a/src/cli/search.ts b/src/cli/search.ts
index 0f5b3ffa..e8e43dc6 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -32,6 +32,10 @@ import type {
SearchOutcome,
} from "../core/search/index.ts";
import { CliError, parseFlags } from "./argparse.ts";
+import {
+ CronTemplateError,
+ renderCronTemplate,
+} from "./search-cron-template.ts";
const KNOWN_VERBS = new Set(["query", "index", "reindex", "status", "check"]);
@@ -293,7 +297,23 @@ async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {
concurrency: { type: "string" },
json: { type: "boolean" },
verbose: { type: "boolean" },
+ "cron-template": { type: "boolean" },
+ interval: { type: "string" },
});
+ if (flags["cron-template"] === true) {
+ const intervalRaw = (flags["interval"] as string | undefined) ?? "30m";
+ try {
+ const body = renderCronTemplate(intervalRaw);
+ process.stdout.write(body);
+ return 0;
+ } catch (err) {
+ if (err instanceof CronTemplateError) {
+ process.stderr.write(`error: ${err.message}\n`);
+ return 1;
+ }
+ throw err;
+ }
+ }
const cfg = resolveConfig(flags);
const stats = await reindexVault(cfg, {
embeddings: flags["embeddings"] === true,
@@ -400,6 +420,7 @@ function jsonForCheck(r: IndexCheckReport): unknown {
provider_reason: r.providerReason,
warnings: r.warnings,
fatal: r.fatal,
+ recommendations: r.recommendations,
};
}
@@ -418,5 +439,10 @@ function renderCheckHuman(r: IndexCheckReport): string {
}
for (const w of r.warnings) lines.push(`warning: ${w}`);
for (const f of r.fatal) lines.push(`fatal: ${f}`);
+ if (r.recommendations.length > 0) {
+ lines.push("");
+ lines.push("recommendations:");
+ for (const rec of r.recommendations) lines.push(` - ${rec}`);
+ }
return lines.join("\n") + "\n";
}
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index 33762a53..ab9bcb0d 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -39,6 +39,7 @@ import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";
+import { findMergeCandidates } from "./merge-candidates.ts";
import { brainDirs, vaultRelative } from "./paths.ts";
import { normaliseWikilinkTarget, renderPrefLink } from "./wikilink.ts";
import { parsePreference, parseRetired } from "./preference.ts";
@@ -164,6 +165,21 @@ export interface DigestJsonTopReferenced {
readonly backlink_count: number;
}
+/**
+ * Near-duplicate pair surfaced for operator review. Detected by
+ * `findMergeCandidates`. Reflects current vault state, not windowed
+ * change β€” does not gate the `isEmpty` predicate.
+ */
+export interface DigestJsonMergeSuggestion {
+ readonly a: string;
+ readonly b: string;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly jaccard: number;
+}
+
export interface DigestJson {
readonly schema_version: 1;
readonly generated_at: string;
@@ -183,6 +199,7 @@ export interface DigestJson {
readonly contradictions: ReadonlyArray<DigestJsonContradiction>;
readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
+ readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;
}
/**
@@ -235,6 +252,7 @@ export function renderDigest(
contradictions: data.contradictions,
top_applied: data.top_applied,
top_referenced: data.top_referenced,
+ merge_suggestions: data.merge_suggestions,
};
return Object.freeze({
content: JSON.stringify(payload, null, 2) + "\n",
@@ -259,6 +277,7 @@ interface DigestData {
readonly contradictions: ReadonlyArray<DigestJsonContradiction>;
readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
+ readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;
}
function collectDigestData(
@@ -344,6 +363,25 @@ function collectDigestData(
const top_applied = pickTopApplied(preferences);
const top_referenced = pickTopReferenced(vault, preferences);
+ // `merge_suggestions` reflects current vault state, not windowed
+ // change. It is independent of `since`/`until` on purpose β€”
+ // operators should see pending duplicates regardless of the digest
+ // window. Excluded from `isEmpty` for the same reason.
+ // Reuse the already-parsed preferences from the digest scan
+ // instead of asking the detector to walk `Brain/preferences/`
+ // a second time. Same on-disk state, single read.
+ const preferenceObjects = preferences.map(({ pref }) => pref);
+ const merge_suggestions = findMergeCandidates(vault, {
+ preferences: preferenceObjects,
+ }).map((c) => ({
+ a: c.a,
+ b: c.b,
+ principle_a: c.principle_a,
+ principle_b: c.principle_b,
+ topic: c.topic,
+ scope: c.scope,
+ jaccard: c.jaccard,
+ }));
return {
new_unconfirmed,
@@ -353,6 +391,7 @@ function collectDigestData(
contradictions,
top_applied,
top_referenced,
+ merge_suggestions,
};
}
@@ -746,6 +785,18 @@ function renderMarkdown(
}
lines.push("");
}
+ if (data.merge_suggestions.length > 0) {
+ lines.push(`## Merge suggestions (${data.merge_suggestions.length})`, "");
+ for (const item of data.merge_suggestions) {
+ const scope = item.scope ?? "β€”";
+ lines.push(
+ `- ${renderPrefLink({ id: item.a, principle: item.principle_a })}`
+ + ` β‰ˆ ${renderPrefLink({ id: item.b, principle: item.principle_b })}`
+ + ` β€” topic '${item.topic}', scope ${scope}, jaccard ${item.jaccard.toFixed(2)}`,
+ );
+ }
+ lines.push("");
+ }
if (data.confidence_shifts.length > 0) {
lines.push("## Confidence shifts", "");
for (const item of data.confidence_shifts) {
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index c2de0091..df777b8c 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -55,6 +55,7 @@ import {
parseRetired,
} from "./preference.ts";
import { parseSignal } from "./signal.ts";
+import { findSimilarPairs, tokenise } from "./similarity.ts";
import {
BRAIN_LOG_EVENT_KIND,
BRAIN_PREFERENCE_STATUS,
@@ -647,8 +648,6 @@ function readAllLogRecords(vault: string): ReadonlyArray<LogRecord> {
return out;
}
-const TOKEN_STOPWORDS: ReadonlySet<string> = new Set();
-
/**
* `duplicate-preferences`: pairwise jaccard similarity of `principle`
* tokens within each `(topic, scope)` bucket of confirmed/quarantine
@@ -660,13 +659,7 @@ function checkDuplicatePreferences(
records: ReadonlyArray<PreferenceRecord>,
issues: DoctorIssue[],
): void {
- interface PrefEntry {
- readonly id: string;
- readonly topic: string;
- readonly scope: string | undefined;
- readonly tokens: ReadonlySet<string>;
- }
- const entries: PrefEntry[] = [];
+ const entries = [];
for (const { pref } of records) {
if (
pref.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
@@ -674,39 +667,26 @@ function checkDuplicatePreferences(
) continue;
entries.push({
id: pref.id,
- topic: pref.topic,
- scope: pref.scope,
+ // Same-scope-undefined falls in its own bucket. Mirrors the
+ // Β§12 merge-candidate detector exactly β€” both surfaces stay
+ // in sync via the shared walker.
+ bucketKey: `${pref.topic}\x00${pref.scope ?? ""}`,
tokens: tokenise(pref.principle),
+ source: pref,
});
}
- // Group by (topic, scope). Same scope-undefined falls in its own bucket.
- const buckets = new Map<string, PrefEntry[]>();
- for (const e of entries) {
- const key = `${e.topic}\x00${e.scope ?? ""}`;
- const arr = buckets.get(key) ?? [];
- arr.push(e);
- buckets.set(key, arr);
- }
- for (const [, bucket] of buckets) {
- if (bucket.length < 2) continue;
- for (let i = 0; i < bucket.length; i++) {
- for (let j = i + 1; j < bucket.length; j++) {
- const a = bucket[i]!;
- const b = bucket[j]!;
- const sim = jaccard(a.tokens, b.tokens);
- if (sim >= JACCARD_DUPLICATE_THRESHOLD) {
- issues.push({
- severity: "warning",
- code: "duplicate-preferences",
- message:
- `[[${a.id}]] and [[${b.id}]] in topic '${a.topic}'` +
- `${a.scope ? ` (scope: ${a.scope})` : ""}` +
- ` look like duplicates (jaccard ${sim.toFixed(2)} of principle tokens).` +
- " Consider merging.",
- });
- }
- }
- }
+ const pairs = findSimilarPairs(entries, { threshold: JACCARD_DUPLICATE_THRESHOLD });
+ for (const pair of pairs) {
+ const a = pair.a.source;
+ issues.push({
+ severity: "warning",
+ code: "duplicate-preferences",
+ message:
+ `[[${pair.a.id}]] and [[${pair.b.id}]] in topic '${a.topic}'` +
+ `${a.scope ? ` (scope: ${a.scope})` : ""}` +
+ ` look like duplicates (jaccard ${pair.jaccard.toFixed(2)} of principle tokens).` +
+ " Consider merging.",
+ });
}
}
@@ -848,28 +828,6 @@ function checkOrphanEvidence(
}
}
-function tokenise(text: string): ReadonlySet<string> {
- // Lowercase + split on whitespace + punctuation; no language-
- // specific stopwords (Brain principles in this project are
- // routinely multilingual and an English-only list would either
- // under-filter or skew the similarity score on non-English text).
- return new Set(
- text
- .toLowerCase()
- .split(/[^\p{L}\p{N}_-]+/u)
- .filter((t) => t.length > 1 && !TOKEN_STOPWORDS.has(t)),
- );
-}
-
-function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
- if (a.size === 0 && b.size === 0) return 0;
- let intersection = 0;
- for (const t of a) if (b.has(t)) intersection++;
- const union = a.size + b.size - intersection;
- if (union === 0) return 0;
- return intersection / union;
-}
-
function collectAllBasenames(vault: string): ReadonlySet<string> {
const out = new Set<string>();
const dirs = brainDirs(vault);
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 09685b33..b9dbfe86 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -1156,12 +1156,24 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
const dirs = brainDirs(vault);
if (!existsSync(dirs.log)) return [];
const out: ApplyEvidenceEntry[] = [];
+ const mergeAliases = new Map<string, string>();
for (const name of readdirSync(dirs.log)) {
if (!name.endsWith(".md")) continue;
const date = name.slice(0, -3);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
const { entries } = parseLogDay(vault, date);
for (const e of entries) {
+ if (e.eventType === BRAIN_LOG_EVENT_KIND.merge) {
+ const keep = parseWikilinkFromBodyValue(e.body["keep"]);
+ const drop = parseWikilinkFromBodyValue(e.body["drop"]);
+ if (keep?.startsWith("pref-") && drop?.startsWith("pref-")) {
+ mergeAliases.set(
+ drop.slice("pref-".length),
+ resolveMergeAlias(keep.slice("pref-".length), mergeAliases),
+ );
+ }
+ continue;
+ }
if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
const prefRaw = e.body["preference"];
const result = e.body["result"];
@@ -1181,10 +1193,33 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
});
}
}
+ const resolved = out.map((entry) => ({
+ ...entry,
+ pref_slug: resolveMergeAlias(entry.pref_slug, mergeAliases),
+ }));
// Stable order: by timestamp ascending. Multiple entries at the same
// second keep their parse order (parseLogDay returns insertion order).
- out.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
- return out;
+ resolved.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
+ return resolved;
+}
+
+function parseWikilinkFromBodyValue(value: unknown): string | null {
+ return typeof value === "string" ? parseWikilink(value) : null;
+}
+
+function resolveMergeAlias(
+ slug: string,
+ aliases: ReadonlyMap<string, string>,
+): string {
+ let current = slug;
+ const seen = new Set<string>();
+ while (!seen.has(current)) {
+ seen.add(current);
+ const next = aliases.get(current);
+ if (!next) return current;
+ current = next;
+ }
+ return current;
}
function planRefresh(
diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.ts
new file mode 100644
index 00000000..fdbdc13d
--- /dev/null
+++ b/src/core/brain/explorer.ts
@@ -0,0 +1,378 @@
+/**
+ * Β§14 Brain explorer β€” data collector.
+ *
+ * Pure read. Walks `Brain/preferences/` and `Brain/retired/`, builds
+ * a node list plus an edge list derived from:
+ *
+ * 1. Frontmatter `supersedes` / `superseded_by` (kind `supersedes`).
+ * 2. Inline `[[wikilinks]]` anywhere in the file's frontmatter
+ * values and body, filtered to refs landing on another node
+ * (kind `wikilink`).
+ *
+ * Signal (`sig-*`) and log refs never appear in `edges` β€” the
+ * explorer view is about the rule graph, not the audit trail.
+ *
+ * Output is deterministic: nodes sorted by `(kind, id)`, edges by
+ * `(source, target, kind)`. The collector emits a frozen object so
+ * the live HTTP handler and the static export branch cannot
+ * accidentally mutate it.
+ */
+
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { basename, dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";
+import { brainDirs } from "./paths.ts";
+import { parsePreference, parseRetired } from "./preference.ts";
+import {
+ BRAIN_PREFERENCE_STATUS,
+ type BrainConfidence,
+ type BrainPreference,
+ type BrainRetired,
+} from "./types.ts";
+
+export const EXPLORER_SCHEMA_VERSION = 1 as const;
+
+export type ExplorerNodeKind = "preference" | "retired";
+export type ExplorerNodeStatus =
+ | "unconfirmed"
+ | "confirmed"
+ | "quarantine"
+ | "retired";
+export type ExplorerEdgeKind = "supersedes" | "wikilink";
+
+export interface ExplorerNode {
+ readonly id: string;
+ readonly kind: ExplorerNodeKind;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle: string;
+ readonly status: ExplorerNodeStatus;
+ readonly confidence: BrainConfidence | null;
+ readonly confidence_value: number | null;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly pinned: boolean;
+ readonly retired_reason: string | null;
+ readonly last_evidence_at: string | null;
+ readonly backlink_count: number;
+}
+
+export interface ExplorerEdge {
+ readonly source: string;
+ readonly target: string;
+ readonly kind: ExplorerEdgeKind;
+}
+
+export interface ExplorerGraph {
+ readonly generated_at: string;
+ readonly schema_version: typeof EXPLORER_SCHEMA_VERSION;
+ readonly vault_basename: string;
+ readonly nodes: ReadonlyArray<ExplorerNode>;
+ readonly edges: ReadonlyArray<ExplorerEdge>;
+}
+
+export interface CollectExplorerDataOptions {
+ /** Wall clock for `generated_at`. Defaults to `new Date()`. */
+ readonly now?: Date;
+}
+
+export function collectExplorerData(
+ vault: string,
+ opts: CollectExplorerDataOptions = {},
+): ExplorerGraph {
+ const dirs = brainDirs(vault);
+ // Build the backlink index first so node factories can stamp the
+ // final count in one pass β€” avoids the prior write-then-overwrite
+ // shape that left a transient `backlink_count: 0` on every node.
+ const backlinkIndex = buildBacklinkIndex(vault);
+ const countFor = (id: string): number =>
+ (backlinkIndex.get(id) ?? []).length;
+
+ const nodes: ExplorerNode[] = [];
+ const knownIds = new Set<string>();
+
+ if (existsSync(dirs.preferences)) {
+ for (const entry of readdirSync(dirs.preferences, { withFileTypes: true })) {
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
+ if (!entry.name.startsWith("pref-")) continue;
+ const path = join(dirs.preferences, entry.name);
+ try {
+ const pref = parsePreference(path);
+ nodes.push(nodeFromPreference(pref, countFor(pref.id)));
+ knownIds.add(pref.id);
+ } catch {
+ // Doctor reports parse-level corruption; the explorer skips
+ // silently so one bad file does not blank the whole graph.
+ }
+ }
+ }
+
+ if (existsSync(dirs.retired)) {
+ for (const entry of readdirSync(dirs.retired, { withFileTypes: true })) {
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
+ if (!entry.name.startsWith("ret-")) continue;
+ const path = join(dirs.retired, entry.name);
+ try {
+ const ret = parseRetired(path);
+ nodes.push(nodeFromRetired(ret, countFor(ret.id)));
+ knownIds.add(ret.id);
+ } catch {
+ // ditto
+ }
+ }
+ }
+
+ // Edges derived from the backlink index. The index maps
+ // `target β†’ ref[]` where each ref carries `source` + `field`.
+ // Field name `supersedes` / `superseded_by` β†’ kind `supersedes`;
+ // anything else (`evidenced_by`, `body`, …) β†’ kind `wikilink`.
+ // Self-references and refs whose source is not a node (log
+ // files, signals) are filtered out.
+ const edges = deriveEdges(backlinkIndex, knownIds);
+
+ // 5. Stable order.
+ nodes.sort((a, b) => {
+ if (a.kind !== b.kind) return a.kind.localeCompare(b.kind);
+ return a.id.localeCompare(b.id);
+ });
+ edges.sort((a, b) => {
+ const s = a.source.localeCompare(b.source);
+ if (s !== 0) return s;
+ const t = a.target.localeCompare(b.target);
+ if (t !== 0) return t;
+ return a.kind.localeCompare(b.kind);
+ });
+
+ const now = opts.now ?? new Date();
+ return Object.freeze({
+ generated_at: now.toISOString(),
+ schema_version: EXPLORER_SCHEMA_VERSION,
+ vault_basename: basename(vault),
+ nodes: Object.freeze(nodes),
+ edges: Object.freeze(edges),
+ });
+}
+
+function nodeFromPreference(
+ pref: BrainPreference,
+ backlinkCount: number,
+): ExplorerNode {
+ return {
+ id: pref.id,
+ kind: "preference",
+ topic: pref.topic,
+ scope: pref.scope ?? null,
+ principle: pref.principle,
+ status: statusOf(pref.status),
+ confidence: pref.confidence,
+ confidence_value: pref.confidence_value,
+ applied_count: pref.applied_count,
+ violated_count: pref.violated_count,
+ pinned: pref.pinned,
+ retired_reason: null,
+ last_evidence_at: pref.last_evidence_at,
+ backlink_count: backlinkCount,
+ };
+}
+
+function nodeFromRetired(
+ ret: BrainRetired,
+ backlinkCount: number,
+): ExplorerNode {
+ return {
+ id: ret.id,
+ kind: "retired",
+ topic: ret.topic,
+ scope: ret.scope ?? null,
+ principle: ret.principle,
+ status: "retired",
+ confidence: ret.confidence ?? null,
+ confidence_value: ret.confidence_value ?? null,
+ applied_count: ret.applied_count,
+ violated_count: ret.violated_count,
+ pinned: ret.pinned ?? false,
+ retired_reason: ret.retired_reason,
+ last_evidence_at: ret.last_evidence_at,
+ backlink_count: backlinkCount,
+ };
+}
+
+function statusOf(s: BrainPreference["status"]): ExplorerNodeStatus {
+ switch (s) {
+ case BRAIN_PREFERENCE_STATUS.unconfirmed:
+ return "unconfirmed";
+ case BRAIN_PREFERENCE_STATUS.confirmed:
+ return "confirmed";
+ case BRAIN_PREFERENCE_STATUS.quarantine:
+ return "quarantine";
+ default:
+ // Forward-compat: future statuses fall back to the closest
+ // visual category (unconfirmed) rather than crashing.
+ return "unconfirmed";
+ }
+}
+
+// ---- Template rendering -------------------------------------------------
+
+const TEMPLATE_PATH = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "..",
+ "templates",
+ "brain-explorer.html",
+);
+
+/**
+ * Unique sentinel string substituted with the graph JSON. Must appear
+ * exactly once in the template; the renderer fails loudly otherwise so
+ * a stale template (missing or accidentally double-substituted marker)
+ * surfaces immediately instead of producing a half-rendered HTML file.
+ */
+const PLACEHOLDER = "__GRAPH_JSON__";
+
+let templateCache: string | undefined;
+
+function loadTemplate(): string {
+ if (templateCache !== undefined) return templateCache;
+ let raw: string;
+ try {
+ raw = readFileSync(TEMPLATE_PATH, "utf8");
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ throw new Error(
+ `Failed to load brain-explorer template from ${TEMPLATE_PATH}: ${msg}`,
+ );
+ }
+ const first = raw.indexOf(PLACEHOLDER);
+ const last = raw.lastIndexOf(PLACEHOLDER);
+ if (first === -1) {
+ throw new Error(
+ `brain-explorer.html template is missing the ${PLACEHOLDER} marker`,
+ );
+ }
+ if (first !== last) {
+ throw new Error(
+ `brain-explorer.html template carries ${PLACEHOLDER} more than once;`
+ + ` substitution must be unique to keep the output deterministic`,
+ );
+ }
+ templateCache = raw;
+ return templateCache;
+}
+
+/**
+ * Substitute the placeholder with a single-line JSON serialisation of
+ * `graph`. Single-line keeps the export size lean β€” the rendered file
+ * routinely lands in a Drive backup or PR comment.
+ *
+ * Uses the function-form of `String.prototype.replace` to avoid `$&`
+ * / `$1` injection through the JSON body (principle bodies are free
+ * text and may contain `$`).
+ */
+export function renderExportedHtml(graph: ExplorerGraph): string {
+ const json = JSON.stringify(graph).replace(/[<>&]/g, (c) => {
+ switch (c) {
+ case "<":
+ return "\\u003c";
+ case ">":
+ return "\\u003e";
+ case "&":
+ return "\\u0026";
+ default:
+ return c;
+ }
+ });
+ return loadTemplate().replace(PLACEHOLDER, () => json);
+}
+
+/** Test-only escape hatch: forget the cached template body. */
+export function __resetExplorerTemplateCacheForTests(): void {
+ templateCache = undefined;
+}
+
+// ---- Live server -------------------------------------------------------
+
+export interface LiveServerHandle {
+ readonly url: string;
+ readonly port: number;
+ close(): Promise<void>;
+}
+
+/**
+ * Boot a loopback-only HTTP server that serves the explorer template
+ * and a JSON endpoint. Each GET re-reads the vault β€” no caches, no
+ * watchers, no write endpoints. Binding to `127.0.0.1` is non-optional;
+ * the explorer is single-user observability and should not be
+ * reachable across the network.
+ *
+ * Throws when the port is unavailable; the CLI catches `EADDRINUSE`
+ * and turns it into a friendly exit message.
+ */
+export function buildLiveServer(vault: string, port: number): LiveServerHandle {
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port,
+ fetch(req) {
+ const url = new URL(req.url);
+ if (url.pathname === "/" || url.pathname === "/index.html") {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ return new Response(html, {
+ headers: { "content-type": "text/html; charset=utf-8" },
+ });
+ }
+ if (url.pathname === "/data.json") {
+ const graph = collectExplorerData(vault);
+ return new Response(JSON.stringify(graph), {
+ headers: { "content-type": "application/json; charset=utf-8" },
+ });
+ }
+ return new Response("not found", { status: 404 });
+ },
+ });
+ // Bun's `Server.port` is typed as `number | undefined` because the
+ // server might bind to a Unix socket. The HTTP path above always
+ // resolves to a TCP port, so a missing value is a runtime
+ // contradiction worth surfacing explicitly.
+ const actualPort = server.port;
+ if (typeof actualPort !== "number") {
+ server.stop();
+ throw new Error("buildLiveServer: server bound without a TCP port");
+ }
+ return {
+ url: `http://127.0.0.1:${actualPort}/`,
+ port: actualPort,
+ close: async () => {
+ server.stop();
+ },
+ };
+}
+
+// ---- Helpers ------------------------------------------------------------
+
+function deriveEdges(
+ index: BacklinkIndex,
+ knownIds: ReadonlySet<string>,
+): ExplorerEdge[] {
+ const edges: ExplorerEdge[] = [];
+ const seen = new Set<string>();
+ for (const [target, refs] of index) {
+ if (!knownIds.has(target)) continue;
+ for (const ref of refs) {
+ if (!knownIds.has(ref.source)) continue; // logs / signals
+ if (ref.source === target) continue;
+ const kind: ExplorerEdgeKind =
+ ref.field === "supersedes" || ref.field === "superseded_by"
+ ? "supersedes"
+ : "wikilink";
+ const key = `${ref.source}\x00${target}\x00${kind}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ edges.push({ source: ref.source, target, kind });
+ }
+ }
+ return edges;
+}
diff --git a/src/core/brain/merge-candidates.ts b/src/core/brain/merge-candidates.ts
new file mode 100644
index 00000000..5217330b
--- /dev/null
+++ b/src/core/brain/merge-candidates.ts
@@ -0,0 +1,131 @@
+/**
+ * `findMergeCandidates` β€” pure-read detector for the `## Merge
+ * suggestions` digest section and the upcoming `o2b brain merge`
+ * CLI. Pairs of confirmed/quarantine preferences in the same
+ * `(topic, scope)` bucket whose `principle` tokens reach jaccard
+ * similarity at or above `JACCARD_MERGE_SUGGEST_THRESHOLD`.
+ *
+ * The bucket-and-pair walk lives in `similarity.ts:findSimilarPairs`
+ * and is shared with the `duplicate-preferences` doctor lint β€”
+ * different threshold, same detector body.
+ *
+ * Callers that already parsed the preferences (digest, doctor)
+ * pass them in via `opts.preferences` to avoid a second pass over
+ * `Brain/preferences/`.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parsePreference } from "./preference.ts";
+import { findSimilarPairs, tokenise } from "./similarity.ts";
+import {
+ BRAIN_PREFERENCE_STATUS,
+ type BrainPreference,
+} from "./types.ts";
+
+/** Inclusive lower bound for surfacing a pair to the digest. */
+export const JACCARD_MERGE_SUGGEST_THRESHOLD = 0.6;
+
+/**
+ * Cap on the size of the rendered list β€” keeps the digest skimmable.
+ * Operators wanting the full picture can call `o2b brain doctor` or
+ * the explorer.
+ */
+export const MERGE_SUGGESTION_LIMIT = 10;
+
+export interface MergeCandidate {
+ /** Lexicographically smaller of the two preference ids. */
+ readonly a: string;
+ readonly b: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle_a: string;
+ readonly principle_b: string;
+ /** Jaccard similarity in `[0, 1]`, rounded to two decimal places. */
+ readonly jaccard: number;
+}
+
+export interface FindMergeCandidatesOptions {
+ readonly threshold?: number;
+ readonly limit?: number;
+ /**
+ * Pre-parsed preferences to scan. When set, the detector does not
+ * touch the filesystem β€” useful for callers (digest, doctor) that
+ * already walked `Brain/preferences/` for other reasons.
+ */
+ readonly preferences?: ReadonlyArray<BrainPreference>;
+}
+
+export function findMergeCandidates(
+ vault: string,
+ opts: FindMergeCandidatesOptions = {},
+): ReadonlyArray<MergeCandidate> {
+ const threshold = opts.threshold ?? JACCARD_MERGE_SUGGEST_THRESHOLD;
+ const limit = opts.limit ?? MERGE_SUGGESTION_LIMIT;
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
+ throw new RangeError(
+ `findMergeCandidates: threshold must be a finite number in [0, 1]; got ${String(threshold)}`,
+ );
+ }
+ if (!Number.isInteger(limit) || limit < 0) {
+ throw new RangeError(
+ `findMergeCandidates: limit must be a non-negative integer; got ${String(limit)}`,
+ );
+ }
+ const prefs = opts.preferences ?? readPreferences(vault);
+
+ const entries = [];
+ for (const p of prefs) {
+ if (
+ p.status !== BRAIN_PREFERENCE_STATUS.confirmed
+ && p.status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) {
+ continue;
+ }
+ entries.push({
+ id: p.id,
+ bucketKey: `${p.topic}\x00${p.scope ?? ""}`,
+ tokens: tokenise(p.principle),
+ source: p,
+ });
+ }
+
+ const pairs = findSimilarPairs(entries, { threshold });
+
+ const candidates: MergeCandidate[] = pairs.map((pair) => ({
+ a: pair.a.id,
+ b: pair.b.id,
+ topic: pair.a.source.topic,
+ scope: pair.a.source.scope ?? null,
+ principle_a: pair.a.source.principle,
+ principle_b: pair.b.source.principle,
+ jaccard: Math.round(pair.jaccard * 100) / 100,
+ }));
+
+ candidates.sort((x, y) => {
+ const diff = y.jaccard - x.jaccard;
+ if (diff !== 0) return diff;
+ const da = x.a.localeCompare(y.a);
+ if (da !== 0) return da;
+ return x.b.localeCompare(y.b);
+ });
+
+ return Object.freeze(candidates.slice(0, limit));
+}
+
+function readPreferences(vault: string): BrainPreference[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.preferences)) return [];
+ const out: BrainPreference[] = [];
+ for (const f of readdirSync(dirs.preferences, { withFileTypes: true })) {
+ if (!f.isFile() || !f.name.endsWith(".md") || !f.name.startsWith("pref-")) continue;
+ try {
+ out.push(parsePreference(join(dirs.preferences, f.name)));
+ } catch {
+ // doctor reports corruption; the detector skips silently.
+ }
+ }
+ return out;
+}
diff --git a/src/core/brain/merge.ts b/src/core/brain/merge.ts
new file mode 100644
index 00000000..5b3c73fc
--- /dev/null
+++ b/src/core/brain/merge.ts
@@ -0,0 +1,286 @@
+/**
+ * `mergePreferences` β€” explicit operator-initiated merge of two
+ * confirmed/quarantine preferences (Β§12).
+ *
+ * Contract: `keep` retains identity. `drop` retires under
+ * `BRAIN_RETIRED_REASON.mergedInto` with a `superseded_by` pointing
+ * at `keep`. `keep` picks up the sorted-dedup union of
+ * `evidenced_by`, the sum of `applied_count` / `violated_count`, and
+ * `max(last_evidence_at)`. `confidence` and `confidence_value` are
+ * NOT recomputed here β€” the next `dream` pass owns that derivation;
+ * recomputing in-place would split the source of truth.
+ *
+ * All guards (`same-id`, `keep-not-found`, `drop-not-found`,
+ * `topic-mismatch`, `scope-mismatch`, `pin-parity`) are data
+ * invariants and throw `BrainMergeError`. `--force` at the CLI
+ * level does NOT bypass them β€” it only skips the interactive
+ * confirmation prompt.
+ *
+ * No snapshot is created. Merge is point-precise (one keep, one
+ * drop). Roll-back: copy `Brain/retired/ret-<drop>.md` back to
+ * `Brain/preferences/pref-<drop>.md`, rerun `o2b brain dream` to
+ * recompute counters.
+ */
+
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import { regenerateActiveQuiet } from "./active.ts";
+import { appendLogEvent } from "./log.ts";
+import { brainDirs, preferencePath } from "./paths.ts";
+import {
+ moveToRetired,
+ parsePreference,
+ writePreference,
+} from "./preference.ts";
+import { isoDate, isoSecond } from "./time.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_RETIRED_REASON,
+} from "./types.ts";
+import { renderPrefLink } from "./wikilink.ts";
+
+export type BrainMergeErrorCode =
+ | "same-id"
+ | "keep-not-found"
+ | "drop-not-found"
+ | "drop-already-retired"
+ | "topic-mismatch"
+ | "scope-mismatch"
+ | "pin-parity"
+ | "unsupported-status";
+
+export class BrainMergeError extends Error {
+ readonly code: BrainMergeErrorCode;
+ constructor(code: BrainMergeErrorCode, message: string) {
+ super(message);
+ this.name = "BrainMergeError";
+ this.code = code;
+ }
+}
+
+export interface MergeOptions {
+ /** Wall clock for the run. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** Agent identity stamped into the log event. */
+ readonly agentName?: string;
+ /** When true, return the plan but make no writes. */
+ readonly dryRun?: boolean;
+}
+
+export interface MergePlan {
+ readonly keep_id: string;
+ readonly drop_id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly merged_evidenced_by: ReadonlyArray<string>;
+ readonly applied_sum: number;
+ readonly violated_sum: number;
+ readonly last_evidence_at: string | null;
+ readonly retired_path: string;
+}
+
+export function mergePreferences(
+ vault: string,
+ keepId: string,
+ dropId: string,
+ opts: MergeOptions = {},
+): MergePlan {
+ if (keepId === dropId) {
+ throw new BrainMergeError(
+ "same-id",
+ `keep and drop refer to the same preference '${keepId}'`,
+ );
+ }
+ const now = opts.now ?? new Date();
+ const dryRun = opts.dryRun === true;
+
+ const keepSlug = stripPrefPrefix(keepId);
+ const dropSlug = stripPrefPrefix(dropId);
+ const keepPath = preferencePath(vault, keepSlug);
+ const dropPath = preferencePath(vault, dropSlug);
+
+ if (!existsSync(keepPath)) {
+ if (existsSync(join(brainDirs(vault).retired, `ret-${keepSlug}.md`))) {
+ throw new BrainMergeError(
+ "keep-not-found",
+ `keep '${keepId}' is already retired; cannot merge into a retired pref`,
+ );
+ }
+ throw new BrainMergeError(
+ "keep-not-found",
+ `keep '${keepId}' not found under Brain/preferences/`,
+ );
+ }
+ if (!existsSync(dropPath)) {
+ if (existsSync(join(brainDirs(vault).retired, `ret-${dropSlug}.md`))) {
+ throw new BrainMergeError(
+ "drop-already-retired",
+ `drop '${dropId}' is already in Brain/retired/`,
+ );
+ }
+ throw new BrainMergeError(
+ "drop-not-found",
+ `drop '${dropId}' not found under Brain/preferences/`,
+ );
+ }
+
+ const keep = parsePreference(keepPath);
+ const drop = parsePreference(dropPath);
+
+ if (!isMergeableStatus(keep.status)) {
+ throw new BrainMergeError(
+ "unsupported-status",
+ `keep '${keepId}' has status '${keep.status}'; merge only supports confirmed or quarantine preferences`,
+ );
+ }
+ if (!isMergeableStatus(drop.status)) {
+ throw new BrainMergeError(
+ "unsupported-status",
+ `drop '${dropId}' has status '${drop.status}'; merge only supports confirmed or quarantine preferences`,
+ );
+ }
+
+ if (keep.topic !== drop.topic) {
+ throw new BrainMergeError(
+ "topic-mismatch",
+ `topic mismatch: keep='${keep.topic}', drop='${drop.topic}'.`
+ + " Merge is for near-duplicate rules in the same bucket;"
+ + " use `o2b brain reject` if drop is wrong rather than redundant.",
+ );
+ }
+ const keepScope = keep.scope ?? null;
+ const dropScope = drop.scope ?? null;
+ if (keepScope !== dropScope) {
+ throw new BrainMergeError(
+ "scope-mismatch",
+ `scope mismatch: keep='${keepScope ?? "(none)"}', drop='${dropScope ?? "(none)"}'.`
+ + " Use `o2b brain reject` instead.",
+ );
+ }
+ if (keep.pinned !== drop.pinned && drop.pinned) {
+ throw new BrainMergeError(
+ "pin-parity",
+ `drop '${dropId}' is pinned but keep '${keepId}' is not;`
+ + " put the pinned pref first as <keep> if you want to merge.",
+ );
+ }
+
+ const merged_evidenced_by = mergeEvidencedBy(
+ keep.evidenced_by,
+ drop.evidenced_by,
+ );
+ const applied_sum = keep.applied_count + drop.applied_count;
+ const violated_sum = keep.violated_count + drop.violated_count;
+ const last_evidence_at = maxIso(keep.last_evidence_at, drop.last_evidence_at);
+
+ const plan: MergePlan = Object.freeze({
+ keep_id: keepId,
+ drop_id: dropId,
+ topic: keep.topic,
+ scope: keepScope,
+ merged_evidenced_by,
+ applied_sum,
+ violated_sum,
+ last_evidence_at,
+ retired_path: join(brainDirs(vault).retired, `ret-${dropSlug}.md`),
+ });
+
+ if (dryRun) return plan;
+
+ // 1. Rewrite keep with the merged fields. Confidence band/value
+ // are NOT recomputed here β€” dream owns that derivation. We
+ // pass the existing values through so the file is consistent.
+ writePreference(
+ vault,
+ {
+ slug: keepSlug,
+ topic: keep.topic,
+ principle: keep.principle,
+ created_at: keep.created_at,
+ unconfirmed_until: keep.unconfirmed_until,
+ status: keep.status,
+ evidenced_by: merged_evidenced_by,
+ confirmed_at: keep.confirmed_at,
+ applied_count: applied_sum,
+ violated_count: violated_sum,
+ last_evidence_at,
+ confidence: keep.confidence,
+ confidence_value: keep.confidence_value,
+ pinned: keep.pinned,
+ ...(keep.scope ? { scope: keep.scope } : {}),
+ ...(keep.supersedes ? { supersedes: keep.supersedes } : {}),
+ ...(keep.aliases ? { aliases: keep.aliases } : {}),
+ },
+ { overwrite: true },
+ );
+
+ // 2. Move drop to retired/ with merged-into reason. moveToRetired
+ // re-reads the source file, so the latest on-disk state is
+ // what lands in the snapshot β€” including drop's own counters,
+ // which we want preserved as audit trail.
+ const supersededBy = renderPrefLink({
+ id: keep.id,
+ principle: keep.principle,
+ });
+ moveToRetired(vault, dropPath, BRAIN_RETIRED_REASON.mergedInto, {
+ now,
+ retired_by: `[[Brain/log/${isoDate(now)}]]`,
+ superseded_by: supersededBy,
+ });
+
+ // 3. Append a `merge` log event with audit-grade payload.
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.merge,
+ body: {
+ keep: renderPrefLink({ id: keep.id, principle: keep.principle }),
+ drop: renderPrefLink({ id: drop.id, principle: drop.principle }),
+ signal_union: `${merged_evidenced_by.length} (was ${keep.evidenced_by.length}, ${drop.evidenced_by.length})`,
+ applied_sum: `${applied_sum} (was ${keep.applied_count}, ${drop.applied_count})`,
+ violated_sum: `${violated_sum} (was ${keep.violated_count}, ${drop.violated_count})`,
+ agent: opts.agentName ?? "unknown",
+ },
+ });
+
+ // 4. Regenerate active.md so the operator sees the new state on
+ // their next session start.
+ regenerateActiveQuiet(vault, { now });
+
+ return plan;
+}
+
+function stripPrefPrefix(id: string): string {
+ if (!id.startsWith("pref-") || id.length <= "pref-".length) {
+ throw new BrainMergeError(
+ "keep-not-found",
+ `expected a 'pref-…' id; got '${id}'`,
+ );
+ }
+ return id.slice("pref-".length);
+}
+
+function mergeEvidencedBy(
+ a: ReadonlyArray<string>,
+ b: ReadonlyArray<string>,
+): ReadonlyArray<string> {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const v of [...a, ...b]) {
+ if (seen.has(v)) continue;
+ seen.add(v);
+ out.push(v);
+ }
+ out.sort();
+ return Object.freeze(out);
+}
+
+function maxIso(a: string | null, b: string | null): string | null {
+ if (a === null) return b;
+ if (b === null) return a;
+ return a >= b ? a : b;
+}
+
+function isMergeableStatus(status: string): boolean {
+ return status === "confirmed" || status === "quarantine";
+}
diff --git a/src/core/brain/similarity.ts b/src/core/brain/similarity.ts
new file mode 100644
index 00000000..254f0260
--- /dev/null
+++ b/src/core/brain/similarity.ts
@@ -0,0 +1,84 @@
+/**
+ * Shared similarity helpers β€” `tokenise`, `jaccard`, and the
+ * bucket-and-pair walk used by both the `duplicate-preferences`
+ * doctor lint and the `merge-candidates` digest detector.
+ *
+ * No language-specific stopword list: Brain principles are routinely
+ * multilingual and an English-only list would either under-filter on
+ * non-English text or skew the score against valid pairs.
+ */
+
+const TOKEN_STOPWORDS: ReadonlySet<string> = new Set();
+
+export function tokenise(text: string): ReadonlySet<string> {
+ return new Set(
+ text
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}_-]+/u)
+ .filter((t) => t.length > 1 && !TOKEN_STOPWORDS.has(t)),
+ );
+}
+
+export function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
+ if (a.size === 0 && b.size === 0) return 0;
+ let intersection = 0;
+ for (const t of a) if (b.has(t)) intersection++;
+ const union = a.size + b.size - intersection;
+ if (union === 0) return 0;
+ return intersection / union;
+}
+
+/**
+ * Entry shape consumed by {@link findSimilarPairs}. Callers project
+ * their domain object (preference, retired, signal) into this shape
+ * before invoking the walker.
+ */
+export interface SimilarityEntry<T> {
+ readonly id: string;
+ readonly bucketKey: string;
+ readonly tokens: ReadonlySet<string>;
+ readonly source: T;
+}
+
+export interface SimilarPair<T> {
+ readonly a: SimilarityEntry<T>;
+ readonly b: SimilarityEntry<T>;
+ readonly jaccard: number;
+}
+
+export interface FindSimilarPairsOptions {
+ readonly threshold: number;
+}
+
+/**
+ * Group `entries` by `bucketKey`, then return every intra-bucket
+ * pair whose jaccard similarity is at or above `threshold`. Pairs
+ * are emitted with `a.id < b.id`. Buckets of size 1 are skipped.
+ * No upper limit on output β€” callers truncate when needed.
+ */
+export function findSimilarPairs<T>(
+ entries: ReadonlyArray<SimilarityEntry<T>>,
+ opts: FindSimilarPairsOptions,
+): SimilarPair<T>[] {
+ const out: SimilarPair<T>[] = [];
+ const buckets = new Map<string, SimilarityEntry<T>[]>();
+ for (const e of entries) {
+ const bucket = buckets.get(e.bucketKey) ?? [];
+ bucket.push(e);
+ buckets.set(e.bucketKey, bucket);
+ }
+ for (const bucket of buckets.values()) {
+ if (bucket.length < 2) continue;
+ bucket.sort((x, y) => x.id.localeCompare(y.id));
+ for (let i = 0; i < bucket.length; i++) {
+ for (let j = i + 1; j < bucket.length; j++) {
+ const a = bucket[i]!;
+ const b = bucket[j]!;
+ const sim = jaccard(a.tokens, b.tokens);
+ if (sim < opts.threshold) continue;
+ out.push({ a, b, jaccard: sim });
+ }
+ }
+ }
+ return out;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index be2bf4e1..66a51636 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -93,6 +93,12 @@ export const BRAIN_RETIRED_REASON = {
// convention change). Single `outdated` event is enough; the
// evidence is interpreted as a definitive contextual rebuttal.
supersededByContext: "superseded-by-context",
+ // Preference retired through `o2b brain merge` β€” counters and
+ // evidence were folded into the retained pref pointed at by
+ // `superseded_by`. Distinct from `rebutted` (opposing signals)
+ // and `superseded-by-context` (outdated evidence): merge implies
+ // no contradiction, the two rules said the same thing.
+ mergedInto: "merged-into",
} as const;
export type BrainRetiredReason =
(typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];
@@ -161,6 +167,12 @@ export const BRAIN_LOG_EVENT_KIND = {
* id, snapshot path, and counters.
*/
migrateFrontmatter: "migrate-frontmatter",
+ /**
+ * `merge` (Β§12) β€” operator ran `o2b brain merge <keep> <drop>`.
+ * Payload carries both wikilinks plus union-size of `evidenced_by`
+ * and the summed counters as raw integers for audit grepping.
+ */
+ merge: "merge",
} as const;
export type BrainLogEventKind =
(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -483,6 +495,19 @@ export interface BrainMigrateFrontmatterLogEvent extends BrainLogEventBase {
readonly run_id: string;
}
+/**
+ * `merge` entry β€” operator ran `o2b brain merge <keep> <drop>`.
+ * Payload carries the titled wikilinks to both prefs plus the
+ * union-size of `evidenced_by` and the summed counters as raw
+ * integers for audit grepping.
+ */
+export interface BrainMergeLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.merge;
+ readonly keep: string;
+ readonly drop: string;
+ readonly agent: string;
+}
+
/** Discriminated union of every concrete log event type. */
export type BrainLogEvent =
| BrainDreamLogEvent
@@ -499,7 +524,8 @@ export type BrainLogEvent =
| BrainRollbackLogEvent
| BrainScanInlineLogEvent
| BrainImportSessionLogEvent
- | BrainMigrateFrontmatterLogEvent;
+ | BrainMigrateFrontmatterLogEvent
+ | BrainMergeLogEvent;
// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index 59b43354..1c568807 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -509,6 +509,17 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
}
}
+ // Β§E.2 β€” Actionable hints derived from the check state.
+ // Rules match the design doc table; agents and operators read the
+ // list to know what command to run next without learning the
+ // internals of OSB.
+ const recommendations = buildRecommendations({
+ config,
+ embeddingKeyResolved,
+ vecExtension,
+ providerReachable,
+ });
+
return Object.freeze({
vaultReadable,
indexDirWritable,
@@ -520,6 +531,51 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
providerReason,
warnings: Object.freeze(warnings),
fatal: Object.freeze(fatal),
+ recommendations: Object.freeze(recommendations),
});
}
+interface BuildRecommendationsInput {
+ readonly config: ResolvedSearchConfig;
+ readonly embeddingKeyResolved: boolean;
+ readonly vecExtension: "loaded" | "unavailable" | "not-attempted";
+ readonly providerReachable: boolean | null;
+}
+
+function buildRecommendations(input: BuildRecommendationsInput): string[] {
+ const recs: string[] = [];
+
+ if (input.config.semantic.enabled && !input.embeddingKeyResolved) {
+ recs.push(
+ "Set OPEN_SECOND_BRAIN_EMBEDDING_KEY in ~/.hermes/.env (or the configured env file).",
+ );
+ recs.push(
+ "Provider: OpenAI `text-embedding-3-small` is the default; any OpenAI-compatible endpoint works via OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL.",
+ );
+ }
+
+ if (input.vecExtension === "unavailable") {
+ if (process.platform === "darwin") {
+ recs.push(
+ "Install Homebrew SQLite: `brew install sqlite`. The o2b wrapper picks it up automatically on the next invocation via DYLD_LIBRARY_PATH.",
+ );
+ } else {
+ recs.push(
+ "sqlite-vec did not load. Confirm the optional dependency with `bun pm ls`, or rebuild with `bun install --force`.",
+ );
+ }
+ }
+
+ // "Everything wired, no embeddings yet" β†’ suggest the first
+ // reindex plus the optional cron template. providerReachable is
+ // `true` only after both key and vec are present, so it is the
+ // tightest proxy for "ready to compute but never did".
+ if (input.providerReachable === true && input.vecExtension === "loaded") {
+ recs.push(
+ "Run `o2b search reindex --embeddings` to compute the first vectors, then optionally `o2b search reindex --cron-template` for periodic refresh.",
+ );
+ }
+
+ return recs;
+}
+
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 44da1b67..83e76f8b 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -93,6 +93,13 @@ export interface IndexCheckReport {
readonly providerReason: string | null;
readonly warnings: ReadonlyArray<string>;
readonly fatal: ReadonlyArray<string>;
+ /**
+ * Actionable hints derived from the check state β€” empty when
+ * nothing needs operator attention. The CLI renders these under a
+ * `recommendations:` block; the JSON exposes them under the same
+ * key so headless callers (Hermes cron, CI) can act on them.
+ */
+ readonly recommendations: ReadonlyArray<string>;
}
export interface SearchOptions {
diff --git a/templates/brain-explorer.html b/templates/brain-explorer.html
new file mode 100644
index 00000000..d6b405a6
--- /dev/null
+++ b/templates/brain-explorer.html
@@ -0,0 +1,413 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<title>Open Second Brain β€” Explorer</title>
+<style>
+ :root {
+ color-scheme: light dark;
+ --bg: #fafafa;
+ --panel: #ffffff;
+ --border: #e0e0e0;
+ --text: #1a1a1a;
+ --muted: #666;
+ --accent: #4263eb;
+ --confirmed: #2f9e44;
+ --unconfirmed: #f59f00;
+ --quarantine: #e8590c;
+ --retired: #868e96;
+ --pinned: #f9c74f;
+ --edge: #cfcfcf;
+ --edge-supersedes: #c92a2a;
+ }
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #1a1a1a;
+ --panel: #242424;
+ --border: #383838;
+ --text: #f0f0f0;
+ --muted: #999;
+ --edge: #444;
+ }
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
+ body { display: grid; grid-template-columns: 240px 1fr 320px; grid-template-rows: 36px 1fr; }
+ header { grid-column: 1 / -1; padding: 0 12px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; background: var(--panel); }
+ header .title { font-weight: 600; }
+ header .meta { color: var(--muted); font-size: 12px; }
+ aside { background: var(--panel); border-right: 1px solid var(--border); padding: 10px 12px; overflow: auto; }
+ aside.right { border-right: none; border-left: 1px solid var(--border); }
+ aside h3 { margin: 12px 0 6px 0; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); }
+ aside h3:first-child { margin-top: 0; }
+ aside label { display: block; padding: 2px 0; cursor: pointer; }
+ aside input[type="search"] { width: 100%; padding: 6px 8px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--text); }
+ main { position: relative; overflow: hidden; background: var(--bg); }
+ canvas { display: block; width: 100%; height: 100%; cursor: grab; }
+ canvas:active { cursor: grabbing; }
+ .legend { display: flex; gap: 8px; flex-wrap: wrap; font-size: 11px; color: var(--muted); }
+ .legend .dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; vertical-align: middle; margin-right: 4px; }
+ .stats { color: var(--muted); font-size: 12px; }
+ .panel-empty { color: var(--muted); font-style: italic; }
+ .field { display: flex; gap: 6px; margin: 3px 0; }
+ .field .k { color: var(--muted); min-width: 100px; }
+ .field .v { word-break: break-word; }
+ .principle { padding: 6px 8px; background: var(--bg); border-left: 3px solid var(--accent); margin: 6px 0; }
+ .pill { display: inline-block; padding: 1px 6px; border-radius: 10px; font-size: 11px; background: var(--bg); border: 1px solid var(--border); }
+ .pill.confirmed { border-color: var(--confirmed); color: var(--confirmed); }
+ .pill.unconfirmed { border-color: var(--unconfirmed); color: var(--unconfirmed); }
+ .pill.quarantine { border-color: var(--quarantine); color: var(--quarantine); }
+ .pill.retired { border-color: var(--retired); color: var(--retired); }
+ ul.edge-list { list-style: none; padding-left: 0; margin: 4px 0; }
+ 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; }
+</style>
+</head>
+<body>
+<header>
+ <span class="title">Brain Explorer</span>
+ <span id="vault-name" class="meta"></span>
+ <span id="stats" class="stats"></span>
+</header>
+<aside class="left">
+ <h3>Search</h3>
+ <input id="search" type="search" placeholder="topic or principle..." />
+ <h3>Status</h3>
+ <label><input type="checkbox" class="status-filter" value="confirmed" checked /> <span class="legend"><span class="dot" style="background: var(--confirmed)"></span>confirmed</span></label>
+ <label><input type="checkbox" class="status-filter" value="unconfirmed" checked /> <span class="legend"><span class="dot" style="background: var(--unconfirmed)"></span>unconfirmed</span></label>
+ <label><input type="checkbox" class="status-filter" value="quarantine" checked /> <span class="legend"><span class="dot" style="background: var(--quarantine)"></span>quarantine</span></label>
+ <label><input type="checkbox" class="status-filter" value="retired" checked /> <span class="legend"><span class="dot" style="background: var(--retired)"></span>retired</span></label>
+ <h3>Legend</h3>
+ <div class="stats">
+ Node size grows with applied_count.<br />
+ Gold ring = pinned.<br />
+ Red dashed edge = supersedes.<br />
+ Grey edge = wikilink.
+ </div>
+</aside>
+<main>
+ <canvas id="canvas"></canvas>
+</main>
+<aside id="details" class="right">
+ <p class="panel-empty">Select a node to inspect.</p>
+</aside>
+
+<script type="application/json" id="brain-data">__GRAPH_JSON__</script>
+<script>
+"use strict";
+
+(function () {
+ const dataEl = document.getElementById("brain-data");
+ let graph;
+ try {
+ graph = JSON.parse(dataEl.textContent);
+ } catch (e) {
+ document.getElementById("details").textContent = "Failed to parse graph data: " + e.message;
+ return;
+ }
+
+ document.getElementById("vault-name").textContent = graph.vault_basename || "(unnamed vault)";
+ document.getElementById("stats").textContent =
+ graph.nodes.length + " nodes, " + graph.edges.length + " edges";
+
+ const canvas = document.getElementById("canvas");
+ const ctx = canvas.getContext("2d");
+ const COLORS = {
+ confirmed: "#2f9e44",
+ unconfirmed: "#f59f00",
+ quarantine: "#e8590c",
+ retired: "#868e96",
+ pinned: "#f9c74f",
+ edge: "#cfcfcf",
+ "edge-supersedes": "#c92a2a",
+ };
+
+ // ---- State -------------------------------------------------------------
+ const nodes = graph.nodes.map((n) => ({
+ ...n,
+ x: 0,
+ y: 0,
+ vx: 0,
+ vy: 0,
+ radius: Math.max(8, Math.min(40, 8 + Math.sqrt(n.applied_count) * 6)),
+ visible: true,
+ }));
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
+ const edges = graph.edges
+ .map((e) => ({ ...e, sNode: nodeById.get(e.source), tNode: nodeById.get(e.target) }))
+ .filter((e) => e.sNode && e.tNode);
+
+ // Topic centres for soft clustering.
+ const topics = new Map();
+ for (const n of nodes) {
+ if (!topics.has(n.topic)) {
+ topics.set(n.topic, { x: 0, y: 0, count: 0 });
+ }
+ topics.get(n.topic).count++;
+ }
+
+ // Filter state.
+ const statusFilters = new Set(["confirmed", "unconfirmed", "quarantine", "retired"]);
+ let searchTerm = "";
+
+ // ---- Layout -----------------------------------------------------------
+ function placeInitial() {
+ const w = canvas.width;
+ const h = canvas.height;
+ const cx = w / 2;
+ const cy = h / 2;
+ // Place topic centres on a circle.
+ const topicNames = Array.from(topics.keys());
+ topicNames.forEach((name, i) => {
+ const angle = (i / Math.max(1, topicNames.length)) * Math.PI * 2;
+ const r = Math.min(w, h) * 0.25;
+ const t = topics.get(name);
+ t.x = cx + Math.cos(angle) * r;
+ t.y = cy + Math.sin(angle) * r;
+ });
+ // Place each node near its topic centre with jitter.
+ for (const n of nodes) {
+ const t = topics.get(n.topic);
+ n.x = t.x + (Math.random() - 0.5) * 80;
+ n.y = t.y + (Math.random() - 0.5) * 80;
+ }
+ }
+
+ const K_TOPIC = 0.006;
+ const K_CHARGE = 700;
+ const K_SPRING = 0.04;
+ const DAMPING = 0.85;
+ const MAX_V = 12;
+
+ function step() {
+ const w = canvas.width;
+ const h = canvas.height;
+ // Topic attraction.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ const t = topics.get(n.topic);
+ n.vx += (t.x - n.x) * K_TOPIC;
+ n.vy += (t.y - n.y) * K_TOPIC;
+ }
+ // Charge repulsion (pairwise β€” fine for O(N^2) at N ≀ 300).
+ for (let i = 0; i < nodes.length; i++) {
+ const a = nodes[i];
+ if (!a.visible) continue;
+ for (let j = i + 1; j < nodes.length; j++) {
+ const b = nodes[j];
+ if (!b.visible) continue;
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ const d2 = dx * dx + dy * dy + 0.01;
+ const f = K_CHARGE / d2;
+ const d = Math.sqrt(d2);
+ const fx = (dx / d) * f;
+ const fy = (dy / d) * f;
+ a.vx += fx; a.vy += fy;
+ b.vx -= fx; b.vy -= fy;
+ }
+ }
+ // Edge springs.
+ for (const e of edges) {
+ if (!e.sNode.visible || !e.tNode.visible) continue;
+ const dx = e.tNode.x - e.sNode.x;
+ const dy = e.tNode.y - e.sNode.y;
+ const d = Math.sqrt(dx * dx + dy * dy) + 0.01;
+ const rest = e.sNode.radius + e.tNode.radius + 40;
+ const f = (d - rest) * K_SPRING;
+ const fx = (dx / d) * f;
+ const fy = (dy / d) * f;
+ e.sNode.vx += fx; e.sNode.vy += fy;
+ e.tNode.vx -= fx; e.tNode.vy -= fy;
+ }
+ // Damping + integrate + clamp.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ n.vx *= DAMPING;
+ n.vy *= DAMPING;
+ if (n.vx > MAX_V) n.vx = MAX_V; else if (n.vx < -MAX_V) n.vx = -MAX_V;
+ if (n.vy > MAX_V) n.vy = MAX_V; else if (n.vy < -MAX_V) n.vy = -MAX_V;
+ n.x += n.vx;
+ n.y += n.vy;
+ // Soft wall.
+ const pad = 30;
+ if (n.x < pad) { n.x = pad; n.vx *= -0.3; }
+ if (n.x > w - pad) { n.x = w - pad; n.vx *= -0.3; }
+ if (n.y < pad) { n.y = pad; n.vy *= -0.3; }
+ if (n.y > h - pad) { n.y = h - pad; n.vy *= -0.3; }
+ }
+ }
+
+ // ---- Render -----------------------------------------------------------
+ let selectedId = null;
+ let hoverId = null;
+
+ function render() {
+ const w = canvas.width;
+ const h = canvas.height;
+ ctx.clearRect(0, 0, w, h);
+ // Edges.
+ ctx.lineWidth = 1;
+ for (const e of edges) {
+ if (!e.sNode.visible || !e.tNode.visible) continue;
+ ctx.beginPath();
+ ctx.moveTo(e.sNode.x, e.sNode.y);
+ ctx.lineTo(e.tNode.x, e.tNode.y);
+ if (e.kind === "supersedes") {
+ ctx.strokeStyle = COLORS["edge-supersedes"];
+ ctx.setLineDash([4, 4]);
+ } else {
+ ctx.strokeStyle = COLORS.edge;
+ ctx.setLineDash([]);
+ }
+ ctx.stroke();
+ }
+ ctx.setLineDash([]);
+ // Nodes.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ ctx.beginPath();
+ ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
+ ctx.fillStyle = COLORS[n.status] || COLORS.unconfirmed;
+ ctx.fill();
+ if (n.pinned) {
+ ctx.lineWidth = 3;
+ ctx.strokeStyle = COLORS.pinned;
+ ctx.stroke();
+ }
+ if (n.id === selectedId || n.id === hoverId) {
+ ctx.lineWidth = 2;
+ ctx.strokeStyle = "#1a1a1a";
+ ctx.stroke();
+ }
+ }
+ // Hover tooltip.
+ if (hoverId) {
+ const h = nodeById.get(hoverId);
+ if (h && h.visible) {
+ const label = h.principle.length > 80 ? h.principle.slice(0, 77) + "..." : h.principle;
+ ctx.font = "12px system-ui";
+ const metrics = ctx.measureText(label);
+ const padX = 6, padY = 4;
+ const x = h.x + h.radius + 6;
+ const y = h.y - h.radius;
+ ctx.fillStyle = "rgba(0, 0, 0, 0.78)";
+ ctx.fillRect(x, y, metrics.width + padX * 2, 18 + padY);
+ ctx.fillStyle = "#fff";
+ ctx.fillText(label, x + padX, y + 14);
+ }
+ }
+ }
+
+ // ---- Hit test, panel render ------------------------------------------
+ function findNode(px, py) {
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ const n = nodes[i];
+ if (!n.visible) continue;
+ const dx = px - n.x;
+ const dy = py - n.y;
+ if (dx * dx + dy * dy <= n.radius * n.radius) return n;
+ }
+ return null;
+ }
+
+ function renderPanel(n) {
+ const root = document.getElementById("details");
+ if (!n) {
+ root.innerHTML = '<p class="panel-empty">Select a node to inspect.</p>';
+ return;
+ }
+ const inbound = edges.filter((e) => e.target === n.id);
+ const outbound = edges.filter((e) => e.source === n.id);
+ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c]));
+ const html = [
+ '<div class="field"><span class="k">id</span><span class="v"><code>' + esc(n.id) + '</code></span></div>',
+ '<div class="principle">' + esc(n.principle) + '</div>',
+ '<div class="field"><span class="k">topic</span><span class="v">' + esc(n.topic) + '</span></div>',
+ n.scope ? '<div class="field"><span class="k">scope</span><span class="v">' + esc(n.scope) + '</span></div>' : "",
+ '<div class="field"><span class="k">status</span><span class="v"><span class="pill ' + n.status + '">' + n.status + '</span>'
+ + (n.confidence ? ' <span class="pill">' + n.confidence + (n.confidence_value !== null ? ' (' + n.confidence_value.toFixed(2) + ')' : '') + '</span>' : '')
+ + '</span></div>',
+ '<div class="field"><span class="k">applied</span><span class="v">' + n.applied_count + '</span></div>',
+ '<div class="field"><span class="k">violated</span><span class="v">' + n.violated_count + '</span></div>',
+ n.pinned ? '<div class="field"><span class="k">pinned</span><span class="v">yes</span></div>' : "",
+ n.last_evidence_at ? '<div class="field"><span class="k">last evidence</span><span class="v">' + esc(n.last_evidence_at) + '</span></div>' : "",
+ '<div class="field"><span class="k">backlinks</span><span class="v">' + n.backlink_count + ' inbound</span></div>',
+ n.retired_reason ? '<div class="field"><span class="k">retired reason</span><span class="v">' + esc(n.retired_reason) + '</span></div>' : "",
+ "<h3>Outbound</h3>",
+ outbound.length === 0
+ ? '<p class="panel-empty">none</p>'
+ : '<ul class="edge-list">' + outbound.map((e) => '<li>' + esc(e.target) + ' <span class="kind">[' + e.kind + ']</span></li>').join("") + '</ul>',
+ "<h3>Inbound</h3>",
+ inbound.length === 0
+ ? '<p class="panel-empty">none</p>'
+ : '<ul class="edge-list">' + inbound.map((e) => '<li>' + esc(e.source) + ' <span class="kind">[' + e.kind + ']</span></li>').join("") + '</ul>',
+ ].join("");
+ root.innerHTML = html;
+ }
+
+ // ---- Filtering -------------------------------------------------------
+ function applyFilters() {
+ const term = searchTerm.toLowerCase();
+ for (const n of nodes) {
+ const statusOk = statusFilters.has(n.status);
+ const textOk = !term
+ || n.principle.toLowerCase().includes(term)
+ || n.topic.toLowerCase().includes(term)
+ || n.id.toLowerCase().includes(term);
+ n.visible = statusOk && textOk;
+ }
+ }
+
+ // ---- Wire up DOM events ----------------------------------------------
+ function resizeCanvas() {
+ const r = canvas.getBoundingClientRect();
+ canvas.width = Math.max(100, Math.floor(r.width));
+ canvas.height = Math.max(100, Math.floor(r.height));
+ }
+ window.addEventListener("resize", resizeCanvas);
+
+ canvas.addEventListener("mousemove", (e) => {
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ hoverId = n ? n.id : null;
+ });
+ canvas.addEventListener("click", (e) => {
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ selectedId = n ? n.id : null;
+ renderPanel(n);
+ });
+
+ document.getElementById("search").addEventListener("input", (e) => {
+ searchTerm = e.target.value;
+ applyFilters();
+ });
+ for (const cb of document.querySelectorAll(".status-filter")) {
+ cb.addEventListener("change", (e) => {
+ const v = e.target.value;
+ if (e.target.checked) statusFilters.add(v);
+ else statusFilters.delete(v);
+ applyFilters();
+ });
+ }
+
+ // ---- Boot ------------------------------------------------------------
+ resizeCanvas();
+ placeInitial();
+
+ function frame() {
+ step();
+ render();
+ requestAnimationFrame(frame);
+ }
+ frame();
+})();
+</script>
+</body>
+</html>
diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.ts
new file mode 100644
index 00000000..4cb76c40
--- /dev/null
+++ b/tests/cli/brain-explorer.test.ts
@@ -0,0 +1,236 @@
+/**
+ * CLI tests for `o2b brain explorer`.
+ *
+ * Covers the two surfaces (live HTTP + static export) plus the
+ * documented error paths. The live server is exercised via subprocess
+ * spawn so the SIGINT shutdown path is verified end-to-end.
+ */
+
+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 { writePreference } from "../../src/core/brain/preference.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-explorer-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);
+}
+
+function seedOnePref(): void {
+ writePreference(vault, {
+ slug: "explorer-seed",
+ topic: "explorer-seed",
+ principle: "Explorer seed principle",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: ["[[sig-2026-05-01-explorer-seed]]"],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 2,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: "high",
+ confidence_value: 0.8,
+ pinned: false,
+ });
+}
+
+/** Pick a random high port to dodge collisions on shared build hosts. */
+function pickPort(): number {
+ return 30000 + Math.floor(Math.random() * 25000);
+}
+
+describe("o2b brain explorer --help", () => {
+ test("prints both modes", async () => {
+ const r = await runCli(["brain", "explorer", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("brain explorer");
+ expect(r.stdout).toContain("--export");
+ expect(r.stdout).toContain("--port");
+ });
+});
+
+describe("o2b brain explorer --export", () => {
+ test("creates the file and prints the node count", async () => {
+ await bootstrap();
+ seedOnePref();
+ const out = join(tmp, "brain.html");
+ const r = await runCli(
+ ["brain", "explorer", "--vault", vault, "--export", out],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("exported");
+ expect(existsSync(out)).toBe(true);
+ const body = readFileSync(out, "utf8");
+ expect(body.includes("__GRAPH_JSON__")).toBe(false);
+ const match = body.match(
+ /<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/,
+ );
+ const parsed = JSON.parse(match![1]!);
+ expect(parsed.nodes.length).toBe(1);
+ expect(parsed.nodes[0].id).toBe("pref-explorer-seed");
+ });
+
+ test("refuses to overwrite without --force", async () => {
+ await bootstrap();
+ seedOnePref();
+ const out = join(tmp, "brain.html");
+ writeFileSync(out, "pre-existing");
+ const r = await runCli(
+ ["brain", "explorer", "--vault", vault, "--export", out],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("exists");
+ expect(readFileSync(out, "utf8")).toBe("pre-existing");
+ });
+
+ test("overwrites with --force", async () => {
+ await bootstrap();
+ seedOnePref();
+ const out = join(tmp, "brain.html");
+ writeFileSync(out, "pre-existing");
+ const r = await runCli(
+ [
+ "brain", "explorer", "--vault", vault,
+ "--export", out, "--force",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(readFileSync(out, "utf8").startsWith("<!doctype html>")).toBe(true);
+ });
+
+ test("invalid --port value exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "explorer", "--vault", vault, "--port", "garbage"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("invalid --port");
+ });
+
+ test("partially numeric --port value exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "explorer", "--vault", vault, "--port", "123abc"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("invalid --port");
+ });
+});
+
+describe("o2b brain explorer (live)", () => {
+ test("binds to 127.0.0.1, serves / and /data.json, shuts down on SIGINT", async () => {
+ await bootstrap();
+ seedOnePref();
+ const port = pickPort();
+ // Spawn the CLI manually so we can poll the server and send SIGINT.
+ // `cwd: process.cwd()` instead of a hard-coded path so the test
+ // works from any checkout (CI, local clone, contributor laptop).
+ const isolatedConfig = config;
+ const proc = Bun.spawn(
+ [
+ "bun", "run", "src/cli/main.ts",
+ "brain", "explorer",
+ "--vault", vault,
+ "--port", String(port),
+ ],
+ {
+ cwd: process.cwd(),
+ env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: isolatedConfig },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ try {
+ // Wait up to ~3s for the server to come up.
+ let up = false;
+ let mainBody = "";
+ let dataBody = "";
+ for (let i = 0; i < 30; i++) {
+ await new Promise((res) => setTimeout(res, 100));
+ try {
+ const r = await fetch(`http://127.0.0.1:${port}/`);
+ if (r.ok) {
+ mainBody = await r.text();
+ const d = await fetch(`http://127.0.0.1:${port}/data.json`);
+ dataBody = await d.text();
+ up = true;
+ break;
+ }
+ } catch {
+ // ECONNREFUSED while booting β€” keep waiting.
+ }
+ }
+ expect(up).toBe(true);
+ expect(mainBody).toContain("Brain Explorer");
+ expect(mainBody.includes("__GRAPH_JSON__")).toBe(false);
+ const parsed = JSON.parse(dataBody);
+ expect(parsed.nodes.length).toBe(1);
+ } finally {
+ // Always tear the spawned CLI down so a failing assertion does
+ // not leak the port into the next test on the same worker.
+ try {
+ proc.kill("SIGINT");
+ await proc.exited;
+ } catch {
+ // process may have already exited or be in a weird state;
+ // either way nothing else for us to do here.
+ }
+ }
+ });
+
+ test("port in use exits 1 with a friendly message", async () => {
+ await bootstrap();
+ const port = pickPort();
+ // Hold the port from inside the test process so the CLI hits
+ // EADDRINUSE.
+ const blocker = Bun.serve({
+ hostname: "127.0.0.1",
+ port,
+ fetch: () => new Response("blocker"),
+ });
+ try {
+ const r = await runCli(
+ ["brain", "explorer", "--vault", vault, "--port", String(port)],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toMatch(/already in use|in use/);
+ } finally {
+ blocker.stop();
+ }
+ });
+});
diff --git a/tests/cli/brain-merge.test.ts b/tests/cli/brain-merge.test.ts
new file mode 100644
index 00000000..5bf14b35
--- /dev/null
+++ b/tests/cli/brain-merge.test.ts
@@ -0,0 +1,227 @@
+/**
+ * CLI tests for `o2b brain merge`.
+ *
+ * The verb wraps `mergePreferences` from `src/core/brain/merge.ts`,
+ * which has its own end-to-end unit coverage. Here we lock the CLI
+ * surface: argument shape, interactive prompt, `--force` / `--dry-run`,
+ * `--json`, and the exact exit codes for the most-common guard
+ * failures.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdtempSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-merge-cli-test-"));
+ 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);
+}
+
+function makePref(slug: string, overrides: Record<string, unknown> = {}): void {
+ writePreference(vault, {
+ slug,
+ topic: "commits",
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ 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-02T00:00:00Z",
+ confidence: "high",
+ confidence_value: 0.8,
+ pinned: false,
+ ...overrides,
+ });
+}
+
+describe("o2b brain merge β€” surface", () => {
+ test("--help prints the verb usage block", async () => {
+ const r = await runCli(["brain", "merge", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("brain merge");
+ expect(r.stdout).toContain("<keep-pref-id>");
+ expect(r.stdout).toContain("<drop-pref-id>");
+ });
+
+ test("missing positional args exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "merge"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("two positional ids");
+ });
+
+ test("only one positional exits 1", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "merge", "pref-a"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(1);
+ });
+});
+
+describe("o2b brain merge β€” guards", () => {
+ test("same id exits 1 with explanatory message", async () => {
+ await bootstrap();
+ makePref("a");
+ const r = await runCli(
+ ["brain", "merge", "pref-a", "pref-a", "--vault", vault, "--force"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("same preference");
+ });
+
+ test("keep missing exits 1", async () => {
+ await bootstrap();
+ makePref("b");
+ const r = await runCli(
+ ["brain", "merge", "pref-missing", "pref-b", "--vault", vault, "--force"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("not found");
+ });
+
+ test("topic mismatch exits 1 even with --force", async () => {
+ await bootstrap();
+ makePref("a", { topic: "x" });
+ makePref("b", { topic: "y" });
+ const r = await runCli(
+ ["brain", "merge", "pref-a", "pref-b", "--vault", vault, "--force"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("topic mismatch");
+ // Drop is still present in preferences/ β€” guard refused the write.
+ expect(
+ existsSync(join(vault, "Brain", "preferences", "pref-b.md")),
+ ).toBe(true);
+ });
+});
+
+describe("o2b brain merge β€” happy paths", () => {
+ test("--dry-run prints plan and writes nothing", async () => {
+ await bootstrap();
+ makePref("keep", { applied_count: 3 });
+ makePref("drop", { applied_count: 2 });
+ const r = await runCli(
+ [
+ "brain", "merge", "pref-keep", "pref-drop",
+ "--vault", vault, "--dry-run",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("merge plan:");
+ expect(r.stdout).toContain("applied_sum: 5");
+ expect(r.stdout).toContain("dry-run; no changes written");
+ // Drop is still in preferences/.
+ expect(
+ existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),
+ ).toBe(true);
+ expect(
+ existsSync(join(vault, "Brain", "retired", "ret-drop.md")),
+ ).toBe(false);
+ });
+
+ test("--force commits without prompt", async () => {
+ await bootstrap();
+ makePref("keep");
+ makePref("drop");
+ const r = await runCli(
+ [
+ "brain", "merge", "pref-keep", "pref-drop",
+ "--vault", vault, "--force",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("merged:");
+ expect(
+ existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),
+ ).toBe(false);
+ expect(
+ existsSync(join(vault, "Brain", "retired", "ret-drop.md")),
+ ).toBe(true);
+ });
+
+ test("non-TTY without --force exits 1 with the TTY guard message", async () => {
+ // Subprocess stdin (pipe or stdin: undefined) is never a TTY,
+ // so the interactive prompt cannot be answered. The verb
+ // refuses to fall through to a silent "merge cancelled" β€” that
+ // would let automation misread the no-op as success. Same
+ // shape as `brain rollback` / `brain migrate-frontmatter`.
+ await bootstrap();
+ makePref("keep");
+ makePref("drop");
+ const r = await runCli(
+ ["brain", "merge", "pref-keep", "pref-drop", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("--force required when stdin is not a TTY");
+ // No mutation: drop still in preferences/, no retired/ entry.
+ expect(
+ existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),
+ ).toBe(true);
+ expect(
+ existsSync(join(vault, "Brain", "retired", "ret-drop.md")),
+ ).toBe(false);
+ expect(
+ existsSync(join(vault, "Brain", "retired", "ret-drop.md")),
+ ).toBe(false);
+ });
+
+ test("--json --dry-run emits parseable payload", async () => {
+ await bootstrap();
+ makePref("keep", { applied_count: 3, violated_count: 1 });
+ makePref("drop", { applied_count: 2, violated_count: 0 });
+ const r = await runCli(
+ [
+ "brain", "merge", "pref-keep", "pref-drop",
+ "--vault", vault, "--dry-run", "--json",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ dry_run: boolean;
+ plan: { applied_sum: number; violated_sum: number };
+ };
+ expect(payload.dry_run).toBe(true);
+ expect(payload.plan.applied_sum).toBe(5);
+ expect(payload.plan.violated_sum).toBe(1);
+ });
+});
diff --git a/tests/cli/search-cron-template.test.ts b/tests/cli/search-cron-template.test.ts
new file mode 100644
index 00000000..3976f74f
--- /dev/null
+++ b/tests/cli/search-cron-template.test.ts
@@ -0,0 +1,161 @@
+/**
+ * Tests for the `--cron-template` flag on `o2b search reindex`.
+ *
+ * The verb writes nothing to disk; we exercise it by spawning the
+ * CLI with `runCli`. The renderer itself has unit-level coverage
+ * for the duration parser via direct calls β€” that protects the
+ * subtler edge cases (invalid units, large values).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ CronTemplateError,
+ parseInterval,
+ renderCronTemplate,
+} from "../../src/cli/search-cron-template.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+describe("parseInterval", () => {
+ test("30m β†’ */30 * * * *", () => {
+ const r = parseInterval("30m");
+ expect(r.cron).toBe("*/30 * * * *");
+ expect(r.human).toBe("30 minutes");
+ expect(r.hermesSchedule).toBe(r.cron);
+ });
+
+ test("6h β†’ 0 */6 * * *", () => {
+ expect(parseInterval("6h").cron).toBe("0 */6 * * *");
+ });
+
+ test("1d β†’ 0 0 */1 * *", () => {
+ expect(parseInterval("1d").cron).toBe("0 0 */1 * *");
+ });
+
+ test("60m rejected with hint about the h unit", () => {
+ expect(() => parseInterval("60m")).toThrow(CronTemplateError);
+ try {
+ parseInterval("60m");
+ } catch (e) {
+ expect((e as Error).message).toContain("h unit");
+ }
+ });
+
+ test("24h rejected with hint about the d unit", () => {
+ expect(() => parseInterval("24h")).toThrow(CronTemplateError);
+ });
+
+ test("seconds rejected", () => {
+ expect(() => parseInterval("30s")).toThrow(CronTemplateError);
+ });
+
+ test("zero rejected", () => {
+ expect(() => parseInterval("0m")).toThrow(CronTemplateError);
+ });
+
+ test("garbage rejected with explanatory message", () => {
+ try {
+ parseInterval("garbage");
+ } catch (e) {
+ expect((e as Error).message).toContain("expected <N>s|m|h|d");
+ }
+ });
+});
+
+describe("renderCronTemplate", () => {
+ test("body contains every expected anchor", () => {
+ const body = renderCronTemplate("30m");
+ expect(body).toContain("Open Second Brain");
+ expect(body).toContain("30 minutes");
+ expect(body).toContain("*/30 * * * *");
+ expect(body).toContain("osb-reindex.sh");
+ expect(body).toContain("hermes cron create");
+ expect(body).toContain("search reindex --embeddings");
+ });
+
+ test("grep fallback emits when added, updated, or deleted are non-zero", () => {
+ const body = renderCronTemplate("30m");
+ expect(body).toContain(
+ '"(added|updated|deleted)"[[:space:]]*:[[:space:]]*[1-9]',
+ );
+ expect(body).not.toContain('"added": [^0]');
+ });
+
+ test("--o2bBin override flows into every command line", () => {
+ const body = renderCronTemplate("1h", { o2bBin: "/usr/local/bin/o2b-x" });
+ expect(body).toContain("/usr/local/bin/o2b-x search reindex");
+ expect(body).toContain("/usr/local/bin/o2b-x search status");
+ });
+
+ test("6h interval renders the 0 */6 cron expression", () => {
+ const body = renderCronTemplate("6h");
+ expect(body).toContain("0 */6 * * *");
+ });
+});
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cron-template-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("o2b search reindex --cron-template (CLI)", () => {
+ async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ }
+
+ test("default 30m prints the template and writes nothing under tmp", async () => {
+ await bootstrap();
+ const before = readdirSync(tmp);
+ const r = await runCli(
+ ["search", "reindex", "--cron-template", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("*/30 * * * *");
+ expect(r.stdout).toContain("osb-reindex.sh");
+ // No new entries in tmp from the CLI itself.
+ expect(readdirSync(tmp).sort()).toEqual(before.sort());
+ });
+
+ test("--interval 6h renders the 0 */6 cron expression", async () => {
+ await bootstrap();
+ const r = await runCli(
+ [
+ "search", "reindex", "--cron-template",
+ "--interval", "6h",
+ "--vault", vault,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("0 */6 * * *");
+ });
+
+ test("--interval garbage exits 1 with the parser error", async () => {
+ await bootstrap();
+ const r = await runCli(
+ [
+ "search", "reindex", "--cron-template",
+ "--interval", "garbage",
+ "--vault", vault,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("expected <N>s|m|h|d");
+ });
+});
diff --git a/tests/core/brain.digest.test.ts b/tests/core/brain.digest.test.ts
index b9b9d5c1..6287a267 100644
--- a/tests/core/brain.digest.test.ts
+++ b/tests/core/brain.digest.test.ts
@@ -472,3 +472,109 @@ describe("top_applied / top_referenced sections", () => {
expect(targetEntry!.backlink_count).toBeGreaterThanOrEqual(2);
});
});
+
+describe("merge_suggestions section (Β§12)", () => {
+ test("surfaces a near-duplicate pair in markdown and JSON", () => {
+ // Both prefs are confirmed in the SAME (topic, scope) bucket and
+ // share most of their `principle` tokens. The detector should
+ // pick them up at the default 0.6 threshold.
+ writePreference(
+ tmp,
+ basePref("imperative-a", {
+ topic: "commits",
+ principle: "Use imperative voice in commit subjects",
+ status: "confirmed",
+ confirmed_at: "2026-05-10T00:00:00Z",
+ applied_count: 3,
+ confidence: "high",
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("imperative-b", {
+ topic: "commits",
+ principle: "Write commit subjects in imperative voice",
+ status: "confirmed",
+ confirmed_at: "2026-05-10T00:00:00Z",
+ applied_count: 2,
+ confidence: "high",
+ }),
+ );
+
+ // Drive a confirmed event inside the window so the markdown path
+ // renders (the digest collapses to a one-liner when nothing in
+ // the window changed). Confirmation date inside [SINCE, UNTIL).
+ writePreference(
+ tmp,
+ basePref("noop-window", {
+ topic: "noop-window",
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 1,
+ }),
+ );
+
+ const md = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "markdown" });
+ expect(md.content).toContain("## Merge suggestions");
+ expect(md.content).toContain("[[pref-imperative-a|");
+ expect(md.content).toContain("[[pref-imperative-b|");
+ expect(md.content).toContain("topic 'commits'");
+
+ const json = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "json" });
+ const parsed = JSON.parse(json.content) as DigestJson;
+ expect(parsed.merge_suggestions.length).toBeGreaterThanOrEqual(1);
+ const pair = parsed.merge_suggestions[0]!;
+ expect(pair.a < pair.b).toBe(true);
+ expect(pair.topic).toBe("commits");
+ expect(pair.jaccard).toBeGreaterThanOrEqual(0.6);
+ });
+
+ test("no candidates β†’ section absent in markdown, empty array in JSON", () => {
+ // Single confirmed pref β†’ no pair β†’ no suggestions.
+ writePreference(
+ tmp,
+ basePref("solo", {
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 1,
+ }),
+ );
+ const md = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "markdown" });
+ expect(md.content).not.toContain("## Merge suggestions");
+ const json = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "json" });
+ const parsed = JSON.parse(json.content) as DigestJson;
+ expect(parsed.merge_suggestions).toEqual([]);
+ });
+
+ test("merge_suggestions does not flip the empty-window collapse", () => {
+ // Build two near-duplicate prefs but place them OUTSIDE the
+ // window. The window itself contains nothing β†’ digest should
+ // still collapse to the empty-window one-liner and report
+ // `empty: true`, even though merge_suggestions has entries.
+ writePreference(
+ tmp,
+ basePref("dup-a", {
+ topic: "outside",
+ principle: "alpha beta gamma delta",
+ status: "confirmed",
+ confirmed_at: "2026-04-01T00:00:00Z",
+ applied_count: 1,
+ confidence: "high",
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("dup-b", {
+ topic: "outside",
+ principle: "alpha beta gamma epsilon",
+ status: "confirmed",
+ confirmed_at: "2026-04-01T00:00:00Z",
+ applied_count: 1,
+ confidence: "high",
+ }),
+ );
+ const r = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "markdown" });
+ expect(r.empty).toBe(true);
+ expect(r.content).toMatch(/^Brain digest β€” \d{4}-\d{2}-\d{2}: no changes\n$/);
+ });
+});
diff --git a/tests/core/brain.dream.test.ts b/tests/core/brain.dream.test.ts
index 28f02bb1..9076580f 100644
--- a/tests/core/brain.dream.test.ts
+++ b/tests/core/brain.dream.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { appendApplyEvidence } from "../../src/core/brain/apply-evidence.ts";
import { dream } from "../../src/core/brain/dream.ts";
import { parseLogDay } from "../../src/core/brain/log.ts";
+import { mergePreferences } from "../../src/core/brain/merge.ts";
import {
brainConfigPath,
brainDirs,
@@ -328,6 +329,61 @@ describe("dream β€” unconfirmed β†’ confirmed promotion on first applied evidenc
expect(pref.violated_count).toBe(0);
expect(pref.last_evidence_at).toBe("2026-05-05T10:00:00Z");
});
+
+ test("preserves evidence counts folded by brain merge", () => {
+ writePreference(vault, {
+ slug: "keep",
+ topic: "merge-evidence",
+ principle: "Keep this merged preference",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: ["[[sig-keep]]"],
+ });
+ writePreference(vault, {
+ slug: "drop",
+ topic: "merge-evidence",
+ principle: "Drop this merged preference",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: ["[[sig-drop]]"],
+ });
+ appendApplyEvidence(
+ vault,
+ { pref_id: "keep", artifact: "[[k1]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-03T10:00:00Z") },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "keep", artifact: "[[k2]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-03T11:00:00Z") },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "drop", artifact: "[[d1]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-04T10:00:00Z") },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "drop", artifact: "[[d2]]", result: "violated", agent: "claude" },
+ { now: new Date("2026-05-05T10:00:00Z") },
+ );
+
+ dream(vault, { now: new Date("2026-05-06T00:00:00Z") });
+ mergePreferences(vault, "pref-keep", "pref-drop", {
+ now: new Date("2026-05-07T00:00:00Z"),
+ agentName: "test-agent",
+ });
+
+ dream(vault, { now: new Date("2026-05-08T00:00:00Z") });
+ const pref = parsePreference(preferencePath(vault, "keep"));
+ expect(pref.applied_count).toBe(3);
+ expect(pref.violated_count).toBe(1);
+ expect(pref.last_evidence_at).toBe("2026-05-05T10:00:00Z");
+ });
});
// ----- Confidence formula -------------------------------------------------
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 0fcb44ff..087b19aa 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -46,6 +46,7 @@ describe("BRAIN_* const enums", () => {
expect(BRAIN_RETIRED_REASON.userRejected).toBe("user-rejected");
expect(BRAIN_RETIRED_REASON.quarantineViolated).toBe("quarantine-violated");
expect(BRAIN_RETIRED_REASON.supersededByContext).toBe("superseded-by-context");
+ expect(BRAIN_RETIRED_REASON.mergedInto).toBe("merged-into");
});
test("BRAIN_APPLY_RESULT values", () => {
@@ -73,6 +74,8 @@ describe("BRAIN_* const enums", () => {
"scan-inline",
"import-session",
"migrate-frontmatter",
+ // Β§12 merge (v0.10.5)
+ "merge",
]);
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
new file mode 100644
index 00000000..6d0a7603
--- /dev/null
+++ b/tests/core/brain/explorer.test.ts
@@ -0,0 +1,311 @@
+/**
+ * Tests for the Β§14 explorer data collector. We exercise:
+ * - empty Brain β†’ empty graph
+ * - mixed preferences (unconfirmed, confirmed, quarantine) plus
+ * retired entries appear as nodes with the expected status
+ * - supersedes edges from `superseded_by`
+ * - inline wikilink edges from body / frontmatter dedup
+ * - signal / log refs are filtered out of the edge list
+ * - byte-identical JSON across two runs on the same vault
+ * - legacy `confidence_value: null` surfaces as `null` (not zero)
+ * - `backlink_count` matches the index in `backlinks.ts`
+ *
+ * The render side (template + JSON inlining) gets its own task.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+
+import {
+ buildBacklinkIndex,
+ backlinkCount,
+} from "../../../src/core/brain/backlinks.ts";
+import {
+ collectExplorerData,
+ EXPLORER_SCHEMA_VERSION,
+ renderExportedHtml,
+} from "../../../src/core/brain/explorer.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-explorer-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { 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: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: BRAIN_CONFIDENCE.low,
+ confidence_value: 0,
+ pinned: false,
+ ...overrides,
+ };
+}
+
+describe("collectExplorerData", () => {
+ test("empty Brain β†’ 0 nodes, 0 edges, schema_version 1", () => {
+ const g = collectExplorerData(vault);
+ expect(g.nodes).toEqual([]);
+ expect(g.edges).toEqual([]);
+ expect(g.schema_version).toBe(1);
+ expect(EXPLORER_SCHEMA_VERSION).toBe(1);
+ expect(typeof g.generated_at).toBe("string");
+ });
+
+ test("nodes include confirmed, unconfirmed, quarantine, retired", () => {
+ writePreference(
+ vault,
+ basePref("conf", { status: BRAIN_PREFERENCE_STATUS.confirmed, applied_count: 5, confidence: BRAIN_CONFIDENCE.high }),
+ );
+ writePreference(
+ vault,
+ basePref("trial", {
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ confirmed_at: null,
+ }),
+ );
+ writePreference(
+ vault,
+ basePref("quar", {
+ status: BRAIN_PREFERENCE_STATUS.quarantine,
+ applied_count: 2,
+ violated_count: 3,
+ }),
+ );
+ // Create a fourth pref and retire it.
+ writePreference(vault, basePref("dead"));
+ const deadPath = join(vault, "Brain", "preferences", "pref-dead.md");
+ moveToRetired(vault, deadPath, BRAIN_RETIRED_REASON.staleNoEvidence, {
+ now: new Date("2026-05-10T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-10]]",
+ });
+
+ const g = collectExplorerData(vault);
+ const ids = g.nodes.map((n) => n.id).sort();
+ expect(ids).toEqual(["pref-conf", "pref-quar", "pref-trial", "ret-dead"]);
+ const byId = new Map(g.nodes.map((n) => [n.id, n]));
+ expect(byId.get("pref-conf")!.status).toBe("confirmed");
+ expect(byId.get("pref-trial")!.status).toBe("unconfirmed");
+ expect(byId.get("pref-quar")!.status).toBe("quarantine");
+ expect(byId.get("ret-dead")!.status).toBe("retired");
+ expect(byId.get("ret-dead")!.kind).toBe("retired");
+ expect(byId.get("pref-conf")!.kind).toBe("preference");
+ });
+
+ test("supersedes edge: from a pref pointing at a retired", () => {
+ // First, write a base pref and retire it.
+ writePreference(vault, basePref("old", { topic: "shared" }));
+ moveToRetired(
+ vault,
+ join(vault, "Brain", "preferences", "pref-old.md"),
+ BRAIN_RETIRED_REASON.rebutted,
+ {
+ now: new Date("2026-05-05T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-05]]",
+ },
+ );
+ // Then write a successor that names the retired pref via `supersedes`.
+ writePreference(
+ vault,
+ basePref("new", {
+ topic: "shared",
+ supersedes: "[[ret-old]]",
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ confirmed_at: null,
+ }),
+ );
+ const g = collectExplorerData(vault);
+ const supersedesEdges = g.edges.filter((e) => e.kind === "supersedes");
+ expect(supersedesEdges.length).toBeGreaterThanOrEqual(1);
+ const e = supersedesEdges.find(
+ (x) => x.source === "pref-new" && x.target === "ret-old",
+ );
+ expect(e).toBeDefined();
+ });
+
+ test("wikilink edges between preferences land as kind 'wikilink'; signal refs excluded", () => {
+ writePreference(vault, basePref("a"));
+ // Cross-pref wikilink via `evidenced_by` β€” `principle` is a
+ // frontmatter field, not body content, so wikilinks inside it
+ // do not feed the backlink index. Real cross-pref refs in this
+ // project flow through `evidenced_by`, `supersedes`, or body
+ // sections.
+ writePreference(
+ vault,
+ basePref("b", {
+ evidenced_by: ["[[pref-a]]", "[[sig-foo]]"],
+ }),
+ );
+ const g = collectExplorerData(vault);
+ const wlEdges = g.edges.filter((e) => e.kind === "wikilink");
+ const bToA = wlEdges.find(
+ (e) => e.source === "pref-b" && e.target === "pref-a",
+ );
+ expect(bToA).toBeDefined();
+ // No edge to the signal β€” sig-foo is not in the node set.
+ expect(g.edges.find((e) => e.target === "sig-foo")).toBeUndefined();
+ // No edge to a non-existent target.
+ expect(g.edges.find((e) => e.target === "pref-nope")).toBeUndefined();
+ });
+
+ test("output is byte-identical across two runs (modulo generated_at)", () => {
+ writePreference(vault, basePref("alpha", { applied_count: 2 }));
+ writePreference(vault, basePref("beta"));
+ const g1 = collectExplorerData(vault);
+ const g2 = collectExplorerData(vault);
+ // Strip the timestamp before comparing.
+ const stripped = (g: { generated_at: string }): string =>
+ JSON.stringify({ ...g, generated_at: "" });
+ expect(stripped(g1)).toBe(stripped(g2));
+ });
+
+ test("legacy null confidence_value surfaces as null, not zero", () => {
+ // `writePreference` with `confidence_value: null` writes the
+ // legacy on-disk shape that pre-v0.10.3 dream passes left behind.
+ writePreference(
+ vault,
+ basePref("legacy", {
+ applied_count: 1,
+ last_evidence_at: null,
+ confidence: BRAIN_CONFIDENCE.low,
+ confidence_value: null,
+ }),
+ );
+ const g = collectExplorerData(vault);
+ const node = g.nodes.find((n) => n.id === "pref-legacy");
+ expect(node).toBeDefined();
+ expect(node!.confidence_value).toBeNull();
+ });
+
+ test("backlink_count matches buildBacklinkIndex output", () => {
+ writePreference(vault, basePref("target"));
+ // Two sources, both reaching target via `evidenced_by` (the
+ // canonical inter-pref reference field).
+ writePreference(
+ vault,
+ basePref("source1", { evidenced_by: ["[[pref-target]]"] }),
+ );
+ writePreference(
+ vault,
+ basePref("source2", { evidenced_by: ["[[pref-target]]"] }),
+ );
+ const g = collectExplorerData(vault);
+ const node = g.nodes.find((n) => n.id === "pref-target");
+ const expected = backlinkCount(buildBacklinkIndex(vault), "pref-target");
+ expect(node!.backlink_count).toBe(expected);
+ expect(node!.backlink_count).toBeGreaterThanOrEqual(2);
+ });
+
+ test("vault_basename equals the last path segment", () => {
+ const g = collectExplorerData(vault);
+ expect(g.vault_basename).toBe(basename(vault));
+ });
+
+ test("stable ordering: nodes by (kind, id); edges by (source, target, kind)", () => {
+ writePreference(vault, basePref("b-pref"));
+ writePreference(vault, basePref("a-pref"));
+ writePreference(vault, basePref("c-pref"));
+ moveToRetired(
+ vault,
+ join(vault, "Brain", "preferences", "pref-c-pref.md"),
+ BRAIN_RETIRED_REASON.rebutted,
+ {
+ now: new Date("2026-05-10T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-10]]",
+ },
+ );
+ const g = collectExplorerData(vault);
+ // Preferences come first (kind 'preference' < 'retired' lexically),
+ // then retired. Within each kind, ids ascend.
+ const kinds = g.nodes.map((n) => n.kind);
+ expect(kinds).toEqual(["preference", "preference", "retired"]);
+ const prefIds = g.nodes.filter((n) => n.kind === "preference").map((n) => n.id);
+ expect(prefIds).toEqual([...prefIds].sort());
+ });
+});
+
+describe("renderExportedHtml", () => {
+ test("substitutes the placeholder exactly once with parseable JSON", () => {
+ writePreference(vault, basePref("foo"));
+ const g = collectExplorerData(vault);
+ const html = renderExportedHtml(g);
+ expect(html.includes("__GRAPH_JSON__")).toBe(false);
+ const match = html.match(
+ /<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/,
+ );
+ expect(match).not.toBeNull();
+ const parsed = JSON.parse(match![1]!);
+ expect(parsed.schema_version).toBe(1);
+ expect(Array.isArray(parsed.nodes)).toBe(true);
+ expect(parsed.nodes.length).toBe(1);
+ expect(parsed.nodes[0].id).toBe("pref-foo");
+ });
+
+ test("survives `$` in principle bodies (no $&/$1 injection)", () => {
+ writePreference(
+ vault,
+ basePref("dollars", {
+ principle: "Money is $100 or $$abc β€” keep this exact",
+ }),
+ );
+ const g = collectExplorerData(vault);
+ const html = renderExportedHtml(g);
+ const match = html.match(
+ /<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/,
+ );
+ const parsed = JSON.parse(match![1]!);
+ const node = parsed.nodes.find((n: { id: string }) => n.id === "pref-dollars");
+ expect(node.principle).toBe("Money is $100 or $$abc β€” keep this exact");
+ });
+
+ test("escapes script-closing text in inline JSON", () => {
+ writePreference(
+ vault,
+ basePref("script-close", {
+ principle: "Never let </script><script>bad()</script> split the data block",
+ }),
+ );
+ const g = collectExplorerData(vault);
+ const html = renderExportedHtml(g);
+ expect(html).not.toContain("</script><script>bad()");
+ const match = html.match(
+ /<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/,
+ );
+ expect(match).not.toBeNull();
+ const parsed = JSON.parse(match![1]!);
+ 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");
+ });
+});
diff --git a/tests/core/brain/merge-candidates.test.ts b/tests/core/brain/merge-candidates.test.ts
new file mode 100644
index 00000000..8a450d3f
--- /dev/null
+++ b/tests/core/brain/merge-candidates.test.ts
@@ -0,0 +1,208 @@
+/**
+ * Tests for the read-only `findMergeCandidates` detector that feeds
+ * the `## Merge suggestions` digest section and the `o2b brain merge`
+ * CLI. Fixtures are built via the canonical `writePreference` writer
+ * so the on-disk shape stays in lockstep with production output.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ findMergeCandidates,
+ JACCARD_MERGE_SUGGEST_THRESHOLD,
+ MERGE_SUGGESTION_LIMIT,
+} from "../../../src/core/brain/merge-candidates.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-merge-cand-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+interface MakePrefOpts {
+ readonly slug: string;
+ readonly topic: string;
+ readonly principle: string;
+ readonly scope?: string;
+ readonly status?:
+ | typeof BRAIN_PREFERENCE_STATUS.unconfirmed
+ | typeof BRAIN_PREFERENCE_STATUS.confirmed
+ | typeof BRAIN_PREFERENCE_STATUS.quarantine;
+}
+
+function makePref(opts: MakePrefOpts): void {
+ const status = opts.status ?? BRAIN_PREFERENCE_STATUS.confirmed;
+ writePreference(vault, {
+ slug: opts.slug,
+ topic: opts.topic,
+ principle: opts.principle,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status,
+ evidenced_by: [`[[sig-2026-05-01-${opts.slug}]]`],
+ confirmed_at:
+ status === BRAIN_PREFERENCE_STATUS.unconfirmed ? null : "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ ...(opts.scope ? { scope: opts.scope } : {}),
+ });
+}
+
+describe("findMergeCandidates", () => {
+ test("empty Brain β†’ empty result", () => {
+ expect(findMergeCandidates(vault)).toEqual([]);
+ });
+
+ test("pair in [threshold, 1) within same (topic, scope) surfaces", () => {
+ makePref({
+ slug: "imperative-commits",
+ topic: "commits",
+ principle: "Use imperative voice in commit subjects",
+ });
+ makePref({
+ slug: "imperative-subjects",
+ topic: "commits",
+ principle: "Write commit subjects in imperative voice",
+ });
+ const out = findMergeCandidates(vault);
+ expect(out.length).toBe(1);
+ expect(out[0]!.topic).toBe("commits");
+ expect(out[0]!.scope).toBeNull();
+ expect(out[0]!.jaccard).toBeGreaterThanOrEqual(
+ JACCARD_MERGE_SUGGEST_THRESHOLD,
+ );
+ // Ids stored as lexicographically smaller / larger.
+ expect(out[0]!.a < out[0]!.b).toBe(true);
+ });
+
+ test("pair below threshold does not surface", () => {
+ makePref({
+ slug: "imperative-commits",
+ topic: "commits",
+ principle: "Use imperative voice in commit subjects",
+ });
+ makePref({
+ slug: "long-bodies",
+ topic: "commits",
+ principle: "Wrap message body at seventy two columns please",
+ });
+ expect(findMergeCandidates(vault).length).toBe(0);
+ });
+
+ test("pairs across different topics do not surface", () => {
+ makePref({
+ slug: "a",
+ topic: "x",
+ principle: "alpha beta gamma delta",
+ });
+ makePref({
+ slug: "b",
+ topic: "y",
+ principle: "alpha beta gamma delta",
+ });
+ expect(findMergeCandidates(vault).length).toBe(0);
+ });
+
+ test("pairs across different scopes do not surface", () => {
+ makePref({
+ slug: "a",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ scope: "writing",
+ });
+ makePref({
+ slug: "b",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ scope: "coding",
+ });
+ expect(findMergeCandidates(vault).length).toBe(0);
+ });
+
+ test("unconfirmed prefs are excluded", () => {
+ makePref({
+ slug: "a",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ });
+ makePref({
+ slug: "b",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ });
+ expect(findMergeCandidates(vault).length).toBe(0);
+ });
+
+ test("quarantine prefs surface", () => {
+ makePref({
+ slug: "a",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ status: BRAIN_PREFERENCE_STATUS.quarantine,
+ });
+ makePref({
+ slug: "b",
+ topic: "t",
+ principle: "alpha beta gamma delta",
+ });
+ const out = findMergeCandidates(vault);
+ expect(out.length).toBe(1);
+ });
+
+ test("stable ordering by (jaccard desc, a asc, b asc)", () => {
+ // Three prefs in the same bucket. Pair (a, b) is closest; pair
+ // (a, c) and (b, c) share lower similarity. Verify ordering.
+ makePref({ slug: "a", topic: "t", principle: "alpha beta gamma delta" });
+ makePref({ slug: "b", topic: "t", principle: "alpha beta gamma epsilon" });
+ makePref({ slug: "c", topic: "t", principle: "alpha beta zeta eta" });
+ const out = findMergeCandidates(vault);
+ expect(out.length).toBeGreaterThan(0);
+ // First pair must have highest jaccard.
+ for (let i = 1; i < out.length; i++) {
+ expect(out[i]!.jaccard).toBeLessThanOrEqual(out[i - 1]!.jaccard);
+ }
+ // Tie-break: a-id then b-id ascending. Verify by checking the
+ // smaller a comes first when jaccards are equal.
+ for (let i = 1; i < out.length; i++) {
+ if (out[i]!.jaccard === out[i - 1]!.jaccard) {
+ if (out[i]!.a !== out[i - 1]!.a) {
+ expect(out[i - 1]!.a.localeCompare(out[i]!.a)).toBeLessThan(0);
+ } else {
+ expect(out[i - 1]!.b.localeCompare(out[i]!.b)).toBeLessThan(0);
+ }
+ }
+ }
+ });
+
+ test("limit truncates at MERGE_SUGGESTION_LIMIT", () => {
+ // Build 6 near-identical confirmed prefs in one bucket β€” yields
+ // 15 pairs, well above the default limit of 10.
+ for (let i = 0; i < 6; i++) {
+ makePref({
+ slug: `dup-${i}`,
+ topic: "t",
+ principle: "alpha beta gamma delta epsilon zeta eta theta",
+ });
+ }
+ const out = findMergeCandidates(vault);
+ expect(out.length).toBe(MERGE_SUGGESTION_LIMIT);
+ });
+});
diff --git a/tests/core/brain/merge.test.ts b/tests/core/brain/merge.test.ts
new file mode 100644
index 00000000..10869c72
--- /dev/null
+++ b/tests/core/brain/merge.test.ts
@@ -0,0 +1,287 @@
+/**
+ * Tests for `mergePreferences` β€” the Β§12 mutating writer.
+ *
+ * Fixtures are built via the canonical `writePreference` so the
+ * on-disk shape stays in lockstep with production output. Guards
+ * are tested by `expect.toThrow(BrainMergeError)` plus a `code`
+ * check; the happy path is verified by reading the resulting files
+ * back through `parsePreference`/`parseRetired`/`parseLogDay`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { regenerateActiveQuiet } from "../../../src/core/brain/active.ts";
+import { parseLogDay } from "../../../src/core/brain/log.ts";
+import {
+ BrainMergeError,
+ mergePreferences,
+} from "../../../src/core/brain/merge.ts";
+import {
+ parsePreference,
+ parseRetired,
+ writePreference,
+ type WritePreferenceInput,
+} from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+const NOW = new Date("2026-05-18T10:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-merge-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { 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: "commits",
+ 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-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ pinned: false,
+ ...overrides,
+ };
+}
+
+describe("mergePreferences β€” guards", () => {
+ test("rejects when keep id equals drop id", () => {
+ writePreference(vault, basePref("a"));
+ expect(() =>
+ mergePreferences(vault, "pref-a", "pref-a", { now: NOW }),
+ ).toThrow(BrainMergeError);
+ });
+
+ test("rejects when keep is missing", () => {
+ writePreference(vault, basePref("b"));
+ try {
+ mergePreferences(vault, "pref-missing", "pref-b", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("keep-not-found");
+ }
+ });
+
+ test("rejects when drop is missing", () => {
+ writePreference(vault, basePref("a"));
+ try {
+ mergePreferences(vault, "pref-a", "pref-missing", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("drop-not-found");
+ }
+ });
+
+ test("rejects mismatched topic", () => {
+ writePreference(vault, basePref("a", { topic: "x" }));
+ writePreference(vault, basePref("b", { topic: "y" }));
+ try {
+ mergePreferences(vault, "pref-a", "pref-b", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("topic-mismatch");
+ }
+ });
+
+ test("rejects mismatched scope (string vs null)", () => {
+ writePreference(vault, basePref("a", { scope: "writing" }));
+ writePreference(vault, basePref("b"));
+ try {
+ mergePreferences(vault, "pref-a", "pref-b", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("scope-mismatch");
+ }
+ });
+
+ test("rejects when drop is pinned and keep is not", () => {
+ writePreference(vault, basePref("a"));
+ writePreference(vault, basePref("b", { pinned: true }));
+ try {
+ mergePreferences(vault, "pref-a", "pref-b", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("pin-parity");
+ }
+ });
+
+ test("rejects unconfirmed preferences", () => {
+ writePreference(
+ vault,
+ basePref("a", {
+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,
+ confirmed_at: null,
+ }),
+ );
+ writePreference(vault, basePref("b"));
+ try {
+ mergePreferences(vault, "pref-a", "pref-b", { now: NOW });
+ throw new Error("expected throw");
+ } catch (e) {
+ expect(e).toBeInstanceOf(BrainMergeError);
+ expect((e as BrainMergeError).code).toBe("unsupported-status");
+ }
+ });
+
+ test("accepts when both are pinned", () => {
+ writePreference(vault, basePref("a", { pinned: true }));
+ writePreference(vault, basePref("b", { pinned: true }));
+ expect(() =>
+ mergePreferences(vault, "pref-a", "pref-b", { now: NOW }),
+ ).not.toThrow();
+ });
+});
+
+describe("mergePreferences β€” happy path", () => {
+ test("merges counters, evidenced_by, last_evidence_at; retires drop with merged-into", () => {
+ writePreference(
+ vault,
+ basePref("keep", {
+ evidenced_by: ["[[sig-2026-05-01-keep]]", "[[sig-2026-05-02-shared]]"],
+ applied_count: 5,
+ violated_count: 1,
+ last_evidence_at: "2026-05-10T00:00:00Z",
+ principle: "Use imperative voice in commit subjects",
+ }),
+ );
+ writePreference(
+ vault,
+ basePref("drop", {
+ evidenced_by: ["[[sig-2026-05-02-shared]]", "[[sig-2026-05-03-drop]]"],
+ applied_count: 4,
+ violated_count: 0,
+ last_evidence_at: "2026-05-12T00:00:00Z",
+ principle: "Write commit subjects in imperative voice",
+ }),
+ );
+ regenerateActiveQuiet(vault, { now: NOW });
+
+ const plan = mergePreferences(vault, "pref-keep", "pref-drop", {
+ now: NOW,
+ agentName: "test-agent",
+ });
+
+ expect(plan.keep_id).toBe("pref-keep");
+ expect(plan.drop_id).toBe("pref-drop");
+ expect(plan.applied_sum).toBe(9);
+ expect(plan.violated_sum).toBe(1);
+ expect(plan.last_evidence_at).toBe("2026-05-12T00:00:00Z");
+ expect(plan.merged_evidenced_by).toEqual([
+ "[[sig-2026-05-01-keep]]",
+ "[[sig-2026-05-02-shared]]",
+ "[[sig-2026-05-03-drop]]",
+ ]);
+
+ // Keep is updated on disk.
+ const keepPath = join(vault, "Brain", "preferences", "pref-keep.md");
+ const keep = parsePreference(keepPath);
+ expect(keep.applied_count).toBe(9);
+ expect(keep.violated_count).toBe(1);
+ expect(keep.last_evidence_at).toBe("2026-05-12T00:00:00Z");
+ expect(keep.evidenced_by).toEqual([
+ "[[sig-2026-05-01-keep]]",
+ "[[sig-2026-05-02-shared]]",
+ "[[sig-2026-05-03-drop]]",
+ ]);
+ // Principle and other identity fields stay on keep.
+ expect(keep.principle).toBe("Use imperative voice in commit subjects");
+
+ // Drop is gone from preferences/ and present in retired/ with the
+ // merged-into reason and a superseded_by pointing at keep.
+ const dropPrefPath = join(vault, "Brain", "preferences", "pref-drop.md");
+ expect(existsSync(dropPrefPath)).toBe(false);
+ const retiredPath = join(vault, "Brain", "retired", "ret-drop.md");
+ const retired = parseRetired(retiredPath);
+ expect(retired.retired_reason).toBe(BRAIN_RETIRED_REASON.mergedInto);
+ expect(retired.superseded_by).toBeTruthy();
+ expect(retired.superseded_by!).toContain("pref-keep");
+
+ // Log carries a `merge` event with both wikilinks plus the
+ // summary counters.
+ const day = NOW.toISOString().slice(0, 10);
+ const { entries } = parseLogDay(vault, day);
+ const merges = entries.filter(
+ (e) => e.eventType === BRAIN_LOG_EVENT_KIND.merge,
+ );
+ expect(merges.length).toBe(1);
+ const body = merges[0]!.body;
+ expect(String(body["keep"])).toContain("pref-keep");
+ expect(String(body["drop"])).toContain("pref-drop");
+ expect(String(body["applied_sum"])).toContain("9");
+ expect(String(body["agent"])).toBe("test-agent");
+
+ // active.md regenerated β€” drop is gone, keep is there.
+ const activeContent = readFileSync(join(vault, "Brain", "active.md"), "utf8");
+ expect(activeContent).toContain("pref-keep");
+ expect(activeContent).not.toContain("pref-drop");
+ });
+
+ test("dryRun returns plan but writes nothing", () => {
+ writePreference(vault, basePref("keep"));
+ writePreference(vault, basePref("drop"));
+ const before = readFileSync(
+ join(vault, "Brain", "preferences", "pref-keep.md"),
+ "utf8",
+ );
+ const plan = mergePreferences(vault, "pref-keep", "pref-drop", {
+ now: NOW,
+ dryRun: true,
+ });
+ expect(plan.applied_sum).toBe(2);
+ // Disk unchanged.
+ expect(
+ readFileSync(join(vault, "Brain", "preferences", "pref-keep.md"), "utf8"),
+ ).toBe(before);
+ expect(
+ existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),
+ ).toBe(true);
+ expect(
+ existsSync(join(vault, "Brain", "retired", "ret-drop.md")),
+ ).toBe(false);
+ });
+
+ test("preserves keep.pinned across merge", () => {
+ writePreference(vault, basePref("keep", { pinned: true }));
+ writePreference(vault, basePref("drop", { pinned: true }));
+ mergePreferences(vault, "pref-keep", "pref-drop", { now: NOW });
+ const keep = parsePreference(
+ join(vault, "Brain", "preferences", "pref-keep.md"),
+ );
+ expect(keep.pinned).toBe(true);
+ });
+});
diff --git a/tests/core/brain/similarity.test.ts b/tests/core/brain/similarity.test.ts
new file mode 100644
index 00000000..82466166
--- /dev/null
+++ b/tests/core/brain/similarity.test.ts
@@ -0,0 +1,63 @@
+/**
+ * Tests for the lifted similarity helpers (`tokenise`, `jaccard`).
+ * The implementations are byte-for-byte the ones that lived inside
+ * `doctor.ts` until v0.10.5 β€” these cases are the regression coverage
+ * for the lift-out, plus a few sanity checks on multi-byte input that
+ * the doctor lint already relies on implicitly.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { jaccard, tokenise } from "../../../src/core/brain/similarity.ts";
+
+describe("tokenise", () => {
+ test("lowercases and splits on punctuation", () => {
+ const tokens = tokenise(
+ "Use imperative voice; describe what the commit DOES",
+ );
+ expect(tokens.has("use")).toBe(true);
+ expect(tokens.has("imperative")).toBe(true);
+ expect(tokens.has("does")).toBe(true);
+ expect(tokens.has(";")).toBe(false);
+ });
+
+ test("keeps multi-byte (Cyrillic) tokens", () => {
+ const tokens = tokenise("Π˜ΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠΉ ΠΈΠΌΠΏΠ΅Ρ€Π°Ρ‚ΠΈΠ²");
+ expect(tokens.has("ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠΉ")).toBe(true);
+ expect(tokens.has("ΠΈΠΌΠΏΠ΅Ρ€Π°Ρ‚ΠΈΠ²")).toBe(true);
+ });
+
+ test("filters single-character tokens", () => {
+ const tokens = tokenise("a b cd");
+ expect(tokens.has("a")).toBe(false);
+ expect(tokens.has("b")).toBe(false);
+ expect(tokens.has("cd")).toBe(true);
+ });
+
+ test("retains digits as tokens", () => {
+ const tokens = tokenise("commit-42 ships v10");
+ expect(tokens.has("commit-42")).toBe(true);
+ expect(tokens.has("ships")).toBe(true);
+ expect(tokens.has("v10")).toBe(true);
+ });
+});
+
+describe("jaccard", () => {
+ test("identical sets β†’ 1", () => {
+ expect(jaccard(new Set(["a", "b"]), new Set(["a", "b"]))).toBe(1);
+ });
+
+ test("disjoint sets β†’ 0", () => {
+ expect(jaccard(new Set(["a"]), new Set(["b"]))).toBe(0);
+ });
+
+ test("both empty β†’ 0", () => {
+ expect(jaccard(new Set(), new Set())).toBe(0);
+ });
+
+ test("partial overlap β†’ |intersection| / |union|", () => {
+ expect(
+ jaccard(new Set(["a", "b", "c"]), new Set(["b", "c", "d"])),
+ ).toBeCloseTo(2 / 4, 5);
+ });
+});
diff --git a/tests/core/search/check-recommendations.test.ts b/tests/core/search/check-recommendations.test.ts
new file mode 100644
index 00000000..7cf40d25
--- /dev/null
+++ b/tests/core/search/check-recommendations.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Tests for Β§E.2 β€” `indexCheck` populates the `recommendations`
+ * array per the design doc table. Driven through `makeConfig` so
+ * the test never mutates real CLI state.
+ *
+ * Platform-specific branches (`process.platform === "darwin"`) are
+ * exercised by re-defining `process.platform` for the duration of
+ * the test and restoring after. The override is local and
+ * synchronous so it cannot leak between tests on the same worker.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+
+import { indexCheck } from "../../../src/core/search/indexer.ts";
+import { createTempVault, makeConfig } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+const ORIGINAL_PLATFORM = process.platform;
+
+function setPlatform(p: NodeJS.Platform): void {
+ Object.defineProperty(process, "platform", {
+ value: p,
+ writable: true,
+ configurable: true,
+ });
+}
+
+beforeEach(() => {
+ const v = createTempVault("indexer-recs");
+ vault = v.vault;
+ dbPath = v.dbPath;
+ cleanup = v.cleanup;
+});
+
+afterEach(() => {
+ setPlatform(ORIGINAL_PLATFORM);
+ cleanup();
+});
+
+test("semantic disabled β†’ no recommendations", async () => {
+ const cfg = makeConfig({ vault, dbPath });
+ const r = await indexCheck(cfg);
+ expect(r.recommendations).toEqual([]);
+});
+
+test("semantic enabled, no key β†’ recipe mentions the env var and the provider", async () => {
+ const cfg = makeConfig({
+ vault,
+ dbPath,
+ semantic: { enabled: true, apiKey: null, model: "text-embedding-3-small" },
+ });
+ const r = await indexCheck(cfg);
+ expect(
+ r.recommendations.some((s) => s.includes("OPEN_SECOND_BRAIN_EMBEDDING_KEY")),
+ ).toBe(true);
+ expect(
+ r.recommendations.some((s) => s.includes("text-embedding-3-small")),
+ ).toBe(true);
+});
+
+test("vec unavailable on Darwin β†’ brew sqlite recipe", async () => {
+ setPlatform("darwin");
+ // Force the vec branch by enabling semantic without a key β€” `vec`
+ // load is attempted regardless of the key.
+ const cfg = makeConfig({
+ vault,
+ dbPath,
+ semantic: { enabled: true, apiKey: null },
+ });
+ const r = await indexCheck(cfg);
+ // Vec may load if sqlite-vec is genuinely installed on the test
+ // host. The Darwin recommendation only appears when vec didn't
+ // load β€” assert conditional on the report's own field.
+ if (r.vecExtension === "unavailable") {
+ expect(
+ r.recommendations.some((s) => s.includes("brew install sqlite")),
+ ).toBe(true);
+ }
+});
+
+test("vec unavailable on Linux β†’ bun pm hint, no brew mention", async () => {
+ setPlatform("linux");
+ const cfg = makeConfig({
+ vault,
+ dbPath,
+ semantic: { enabled: true, apiKey: null },
+ });
+ const r = await indexCheck(cfg);
+ if (r.vecExtension === "unavailable") {
+ expect(
+ r.recommendations.some((s) => s.includes("bun pm ls")),
+ ).toBe(true);
+ expect(
+ r.recommendations.every((s) => !s.includes("brew install")),
+ ).toBe(true);
+ }
+});
+
+test("Recommendations array is frozen at the top level", async () => {
+ const cfg = makeConfig({ vault, dbPath });
+ const r = await indexCheck(cfg);
+ expect(Object.isFrozen(r.recommendations)).toBe(true);
+});
diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.ts
index 22367eea..a0d6c7fb 100644
--- a/tests/helpers/run-cli.ts
+++ b/tests/helpers/run-cli.ts
@@ -40,7 +40,7 @@ const RUNTIME_OVERRIDABLE_ENV = [
export async function runCli(
args: ReadonlyArray<string>,
- opts: { env?: Record<string, string> } = {},
+ opts: { env?: Record<string, string>; stdin?: string } = {},
): Promise<RunResult> {
const callerEnv = opts.env ?? {};
// Build the child env from process.env, then strip any runtime-resolution
@@ -60,9 +60,14 @@ export async function runCli(
const proc = Bun.spawn(["bun", "run", CLI_ENTRY, ...args], {
cwd: ROOT,
env,
+ stdin: opts.stdin === undefined ? "ignore" : "pipe",
stdout: "pipe",
stderr: "pipe",
});
+ if (opts.stdin !== undefined && proc.stdin !== undefined) {
+ proc.stdin.write(opts.stdin);
+ await proc.stdin.end();
+ }
const [stdout, stderr] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.ts
index de8f9b09..9639021a 100644
--- a/tests/hooks/detect.test.ts
+++ b/tests/hooks/detect.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import {
+ detectHookRuntime,
isArtifactToolName,
isLogToolName,
summarizeTurn,
@@ -113,3 +114,64 @@ describe("summarizeTurn", () => {
expect(s).toEqual({ hadArtifact: false, hadLog: false });
});
});
+
+describe("detectHookRuntime", () => {
+ test("Claude Code transcript path β†’ claudecode", () => {
+ expect(
+ detectHookRuntime({
+ transcript_path:
+ "/Users/x/.claude/projects/-srv/projects/foo/abc.jsonl",
+ }),
+ ).toBe("claudecode");
+ });
+
+ test("Codex transcript path β†’ codex", () => {
+ expect(
+ detectHookRuntime({
+ transcript_path: "/root/.codex/sessions/2026-05-18.json",
+ }),
+ ).toBe("codex");
+ });
+
+ test("Claude Code triple without transcript_path β†’ claudecode", () => {
+ expect(
+ detectHookRuntime({
+ session_id: "x",
+ cwd: "/srv",
+ tool_use_id: "y",
+ }),
+ ).toBe("claudecode");
+ });
+
+ test("Codex apply_patch shape β†’ codex", () => {
+ expect(
+ detectHookRuntime({
+ tool_name: "apply_patch",
+ tool_input: {
+ input:
+ "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch",
+ },
+ }),
+ ).toBe("codex");
+ });
+
+ test("apply_patch without a recognisable body β†’ unknown", () => {
+ // The tool name alone is not enough β€” runtime detection requires
+ // the patch body so we never label hand-rolled payloads.
+ expect(
+ detectHookRuntime({
+ tool_name: "apply_patch",
+ tool_input: { input: "not a patch" },
+ }),
+ ).toBe("unknown");
+ });
+
+ test("malformed payloads β†’ unknown without throwing", () => {
+ expect(detectHookRuntime(null)).toBe("unknown");
+ expect(detectHookRuntime(undefined)).toBe("unknown");
+ expect(detectHookRuntime("string")).toBe("unknown");
+ expect(detectHookRuntime(42)).toBe("unknown");
+ expect(detectHookRuntime({})).toBe("unknown");
+ expect(detectHookRuntime({ transcript_path: 42 })).toBe("unknown");
+ });
+});
diff --git a/tests/hooks/post-write-reminder.test.ts b/tests/hooks/post-write-reminder.test.ts
index 17e45a1d..5803e301 100644
--- a/tests/hooks/post-write-reminder.test.ts
+++ b/tests/hooks/post-write-reminder.test.ts
@@ -118,4 +118,48 @@ describe("post-write-reminder hook", () => {
expect(exit).toBe(0);
expect(stdout).toBe("");
});
+
+ test("Claude Code transcript path triggers the claudecode cadence line", async () => {
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "Write",
+ tool_input: { file_path: "/tmp/foo.md", content: "hi" },
+ transcript_path: "/Users/x/.claude/projects/-srv/foo.jsonl",
+ });
+ expect(r.exit).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.additionalContext).toContain(
+ "Claude Code session",
+ );
+ });
+
+ test("Codex apply_patch shape triggers the codex cadence line", async () => {
+ const patch =
+ "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch\n";
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "apply_patch",
+ tool_input: { input: patch },
+ });
+ expect(r.exit).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.additionalContext).toContain("codex exec");
+ });
+
+ test("unknown runtime renders without either cadence line (v0.10.4 baseline)", async () => {
+ const r = await runHook({
+ hook_event_name: "PostToolUse",
+ tool_name: "Write",
+ tool_input: { file_path: "/tmp/foo.md", content: "hi" },
+ // No transcript_path, no Claude triple, no apply_patch shape.
+ });
+ expect(r.exit).toBe(0);
+ const out = JSON.parse(r.stdout);
+ const text = out.hookSpecificOutput.additionalContext as string;
+ expect(text).not.toContain("Claude Code session");
+ expect(text).not.toContain("codex exec");
+ // Spot-check the original body is intact.
+ expect(text).toContain("brain_feedback");
+ expect(text).toContain("brain_apply_evidence");
+ });
});
diff --git a/tests/hooks/stop-log-guardrail.test.ts b/tests/hooks/stop-log-guardrail.test.ts
index ac8efc94..cd8ff7bc 100644
--- a/tests/hooks/stop-log-guardrail.test.ts
+++ b/tests/hooks/stop-log-guardrail.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -209,4 +209,89 @@ describe("stop-log-guardrail hook", () => {
const out = JSON.parse(r.stdout);
expect(out.decision).toBe("block");
});
+
+ test("Claude Code transcript path adds the claudecode cadence line", async () => {
+ // Reuse the per-test `tmp` so afterEach cleans this up too.
+ const transcript_path = join(
+ tmp,
+ ".claude",
+ "projects",
+ "session.jsonl",
+ );
+ mkdirSync(dirname(transcript_path), { recursive: true });
+ writeFileSync(
+ transcript_path,
+ [
+ ccUser("write something"),
+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
+ ].join("\n") + "\n",
+ );
+ const r = await runHook({
+ hook_event_name: "Stop",
+ transcript_path,
+ stop_hook_active: false,
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.decision).toBe("block");
+ expect(out.reason as string).toContain("This guardrail fires");
+ });
+
+ test("Codex transcript path adds the codex cadence line", async () => {
+ // Reuse the per-test `tmp` so afterEach cleans this up too.
+ const transcript_path = join(
+ tmp,
+ ".codex",
+ "sessions",
+ "session.jsonl",
+ );
+ mkdirSync(dirname(transcript_path), { recursive: true });
+ writeFileSync(
+ transcript_path,
+ [
+ JSON.stringify({
+ type: "response_item",
+ payload: {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: "patch the file" }],
+ },
+ }),
+ JSON.stringify({
+ type: "response_item",
+ payload: {
+ type: "custom_tool_call",
+ name: "apply_patch",
+ call_id: "c1",
+ input: "",
+ },
+ }),
+ ].join("\n") + "\n",
+ );
+ const r = await runHook({
+ hook_event_name: "Stop",
+ transcript_path,
+ stop_hook_active: false,
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.decision).toBe("block");
+ expect(out.reason as string).toContain("codex exec");
+ });
+
+ test("unknown runtime omits the cadence line (v0.10.4 baseline)", async () => {
+ const transcript_path = writeTranscript([
+ ccUser("please add a file"),
+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
+ ]);
+ const r = await runHook({
+ hook_event_name: "Stop",
+ transcript_path,
+ stop_hook_active: false,
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.decision).toBe("block");
+ const reason = out.reason as string;
+ expect(reason).not.toContain("This guardrail fires");
+ expect(reason).not.toContain("codex exec");
+ expect(reason).toContain("event_log_append");
+ });
});
diff --git a/tests/scripts/macos-sqlite-shim.test.ts b/tests/scripts/macos-sqlite-shim.test.ts
new file mode 100644
index 00000000..72cfc274
--- /dev/null
+++ b/tests/scripts/macos-sqlite-shim.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Tests for `scripts/_macos-sqlite.sh`.
+ *
+ * The shim is sourced by `scripts/o2b`; we test it in isolation by
+ * sourcing it from a one-liner shell and probing the resulting
+ * `DYLD_LIBRARY_PATH`. Platform is faked via `O2B_MACOS_FORCE_PLATFORM`,
+ * Homebrew prefixes via `O2B_MACOS_SQLITE_PREFIXES_OVERRIDE` β€” both
+ * are intentional test seams baked into the shim.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const SHIM = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "scripts",
+ "_macos-sqlite.sh",
+);
+
+let tmp: string;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-macos-shim-"));
+});
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+async function runShim(env: Record<string, string>): Promise<string> {
+ // Source the shim, then echo DYLD_LIBRARY_PATH. The shim returns 0
+ // even on no-op, so we always read the echoed value (possibly empty).
+ const proc = Bun.spawn(
+ [
+ "bash",
+ "-c",
+ `. "${SHIM}"; echo "DYLD=\${DYLD_LIBRARY_PATH-}"`,
+ ],
+ {
+ env: { ...env, PATH: process.env.PATH ?? "/usr/bin:/bin" },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ const stdout = await new Response(proc.stdout).text();
+ await proc.exited;
+ const match = stdout.match(/^DYLD=(.*)$/m);
+ return match ? match[1]! : "";
+}
+
+describe("_macos-sqlite.sh", () => {
+ test("Linux platform β†’ no DYLD_LIBRARY_PATH export", async () => {
+ const out = await runShim({ O2B_MACOS_FORCE_PLATFORM: "Linux" });
+ expect(out).toBe("");
+ });
+
+ test("Darwin + brew prefix present β†’ DYLD_LIBRARY_PATH set", 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,
+ });
+ expect(out).toBe(fakePrefix);
+ });
+
+ test("Darwin + DYLD_LIBRARY_PATH preset β†’ 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: "/user/configured/lib",
+ });
+ expect(out).toBe("/user/configured/lib");
+ });
+
+ test("Darwin + no prefix exists β†’ no DYLD_LIBRARY_PATH export", async () => {
+ const missing = join(tmp, "does-not-exist");
+ const out = await runShim({
+ O2B_MACOS_FORCE_PLATFORM: "Darwin",
+ O2B_MACOS_SQLITE_PREFIXES_OVERRIDE: missing,
+ });
+ expect(out).toBe("");
+ });
+
+ test("Darwin + first prefix exists, second too β†’ first wins", async () => {
+ const a = join(tmp, "a");
+ const b = join(tmp, "b");
+ mkdirSync(a, { recursive: true });
+ mkdirSync(b, { recursive: true });
+ const out = await runShim({
+ O2B_MACOS_FORCE_PLATFORM: "Darwin",
+ O2B_MACOS_SQLITE_PREFIXES_OVERRIDE: `${a}:${b}`,
+ });
+ expect(out).toBe(a);
+ });
+});