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.11.0 - Brain-centric vault layout: one agent-owned root, opt-in user notes (#35)

Sol Aitkenc0022687fa1b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 998ee741..add6018a 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.18",
+ "version": "0.11.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index cfc1505e..6c9a653e 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.18",
+ "version": "0.11.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edaf1af1..56d27a66 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,109 @@ 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.11.0] - 2026-05-26
+
+Brain-centric vault layout. The agent now owns one top-level
+directory in the vault: `Brain/`. The legacy `AI Wiki/` subtree is
+gone; Pay Memory writes nest under `Brain/payments/`. User-authored
+notes (daily journals, weekly notes, etc.) live wherever the
+operator names them and become read-only inputs to the agent only
+when listed under a new `notes.read_paths` config block. The
+`appendEvent` / `o2b append-event` writer that previously touched
+`Daily/<date>.md` is removed entirely; agents record narrative
+milestones through `brain_note` into `Brain/log/<today>.md`.
+
+This release also clears every pre-1.0 backward-compat shim from
+the codebase. Open Second Brain has no public users yet — keeping
+dual-shape parsers, legacy migration verbs, or "lift-only" band
+overlays just to honour an unpublished contract was pure dead
+weight.
+
+### Added
+
+- `_brain.yaml` gains a `notes:` block with `read_paths` - the
+ vault-relative folders the agent may READ user-authored notes
+ from. Empty (or absent) means no scanning; the agent never writes
+ to those paths.
+- Path constants module (`src/core/brain/paths.ts`,
+ `src/core/pay-memory/paths.ts`): every vault-relative path used
+ by Brain or Pay Memory now lives behind a named constant
+ (`BRAIN_ROOT_REL`, `PAY_MEMORY_*_REL`, etc.). Future renames are
+ a one-line edit.
+- README poster at `docs/images/readme-poster.jpg`, rendered under
+ the H1.
+
+### Changed
+
+- `o2b init` no longer scaffolds vault content. Vault bootstrap is
+ `o2b brain init`'s job; `o2b init` now only persists machine-local
+ config (vault path, agent name, timezone).
+- `o2b brain init` no longer writes `AI Wiki/_OPEN_SECOND_BRAIN.md`.
+ The operating manual lives at `Brain/_BRAIN.md` only.
+- `o2b index` writes to `<vault>/Brain/_INDEX.md` instead of
+ `<vault>/AI Wiki/index.md`.
+- `o2b brain scan-inline` walks only folders listed under
+ `notes.read_paths` (or `--path` overrides). Default is "no folders
+ to scan"; the agent never crawls the vault without an operator
+ opt-in.
+- Pay Memory writes under `Brain/payments/` (receipts go directly
+ into `Brain/payments/<YYYY-MM-DD>/<slug>.md`, no nested
+ `payments/` subdir).
+- Brain upgrade plan: only `Brain/_brain.yaml` and `Brain/_BRAIN.md`
+ (the legacy overview file is gone from the plan and from the
+ release entirely).
+- `computeConfidence` (the `dream` band derivation) uses only the
+ numeric Wilson-lower-bound × freshness thresholds. The
+ step-function band and the max-with-numeric overlay are deleted;
+ the bands now move strictly with the numeric value.
+- README quick start leads with the agent-delegated path: paste a
+ one-liner into your agent, the agent reads `install/hermes.md`
+ and runs every command. The hand-run command sequence stays as a
+ fallback.
+- README top-features table re-curated around human impact: each
+ row is "what this means for you", not "what this does in code".
+
+### Removed
+
+- `o2b append-event` CLI verb, the `appendEvent` core function,
+ and `src/core/event-log.ts`. Use `o2b brain note` or the
+ `brain_note` MCP tool instead.
+- `o2b brain migrate-frontmatter` CLI verb and its core module.
+ Files with the legacy un-prefixed Group C frontmatter (`status:`,
+ `applied_count:`, ...) no longer parse — the only shape on disk
+ is `_status:`, `_applied_count:`, ... `BrainDoubleShapeError` and
+ the dual-shape detection in `normalizeDerivedKeys` are gone.
+- `src/core/init.ts` (the legacy `bootstrapVault` scaffolder).
+- `src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl` and the
+ `LEGACY_OVERVIEW_*` exports.
+- Legacy step-function band derivation in `computeConfidence`. The
+ `legacyBand` / `max(legacy, numeric)` "lift-only" overlay is
+ gone; numeric thresholds win outright. The dead config fields
+ `confidence.high_min_applied` and `confidence.high_freshness_factor`
+ that fed the step-function are removed from the schema, validator,
+ default YAML, and type declarations.
+- Historical inline comments referencing the retired
+ `second_brain_capture` / `event_log_append` / `appendEvent` /
+ AI Wiki/ / Daily/ surfaces, and the pre-v0.10.3 / pre-v0.10.6
+ fallback notes that documented them.
+
+### Breaking changes
+
+- Shell scripts and cron jobs that piped messages into
+ `Daily/<date>.md` via `o2b append-event` must migrate to
+ `o2b brain note` (writes into `Brain/log/<today>.md` + JSONL
+ sidecar).
+- Operators who relied on scan-inline's old "scan everything"
+ default must add the desired folders under `notes.read_paths` in
+ `_brain.yaml`, or pass `--path` explicitly on every invocation.
+- Preference / retired files using the legacy un-prefixed
+ frontmatter keys (`status:`, `applied_count:`, ...) no longer
+ parse. Rename them to the `_`-prefixed shape (`_status:`, ...).
+- Confidence bands move stricter on stale prefs and on prefs with
+ fewer than ~15 applied events. Anyone tuning thresholds may want
+ to revisit `confidence.high_min` / `medium_min` against the new
+ numeric semantics.
+
## [0.10.18] - 2026-05-25
Temporal + synthesis layer: seven related features that add time as
@@ -542,8 +645,8 @@ Operational friction reduction: one-command update across all
runtimes, weekly brain digest with agent quality summary, Cursor
SQLite deep parsing for accurate transcript activity, and Obsidian
deep-links in the live explorer. Companion design and impl plan at
-`docs/superpowers/specs/2026-05-20-v0.10.12-design.md` and
-`docs/plans/2026-05-20-v0.10.12-impl.md`.
+`docs/brainstorm/operational-friction-reduction/{design.md,plan.md}`
+and `docs/plans/2026-05-20-v0.10.12-impl.md`.
### Added
@@ -2793,6 +2896,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0
[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1
[0.9.0]: https://github.com/itechmeat/open-second-brain/compare/v0.8.1...v0.9.0
+[0.11.0]: https://github.com/itechmeat/open-second-brain/compare/v0.10.18...v0.11.0
[0.10.18]: https://github.com/itechmeat/open-second-brain/compare/v0.10.17...v0.10.18
[0.10.17]: https://github.com/itechmeat/open-second-brain/compare/v0.10.16...v0.10.17
[0.10.16]: https://github.com/itechmeat/open-second-brain/compare/v0.10.15...v0.10.16
diff --git a/README.md b/README.md
index 9c5e11d8..2dfb1fa8 100644
--- a/README.md
+++ b/README.md
@@ -1,672 +1,172 @@
# Open Second Brain
-A filesystem-first, agent-owned second brain for Obsidian-compatible
-Markdown vaults. Plugs into the agent runtime you already use — Hermes
-Agent, Claude Code, OpenAI Codex, OpenClaw, or any MCP-aware client —
-and gives it deterministic CLI / MCP / hook surfaces for observing
-memory (preference accretion via the `Brain/` layer), wiki indexing,
-paid-action audit, and health checks. The model never has to guess at
-any of that.
-
-Open Second Brain is **not** a daemon, **not** a vault replacement,
-and **not** an LLM-driven knowledge store — the `dream` consolidation
-pass is pure deterministic counters. The plugin never writes hidden
-state outside the configured vault and config directory.
-
-## How it works
-
-Three loops cooperate over plain Markdown:
-
-- **Capture.** Agents call `brain_feedback` to drop taste signals into
- `Brain/inbox/`.
-- **Accretion.** A deterministic `dream` pass clusters repeat signals
- into rules — counters and atomic file moves, no LLM.
-- **Application.** Agents log whether each rule was `applied` /
- `violated` / `outdated`, or record a narrative milestone via
- `brain_note` for events that fit neither category. `Brain/active.md`
- is auto-regenerated and injected at session start; `brain_search`
- exposes full-text search across the whole vault.
-
-Every event lands in `Brain/log/<date>.md` (human-facing) plus a
-structured `Brain/log/<date>.jsonl` sidecar (machine-facing), written
-atomically by one writer so the two stay in lockstep.
+![Open Second Brain - your knowledge, amplified by AI](docs/images/readme-poster.jpg)
+
+> An [Obsidian](https://obsidian.md)-native memory layer for your AI agent. Plain Markdown you own, in the same vault you already use.
+
+Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/hermes-agent) and turns your Obsidian vault into a memory layer the agent reads and writes through deterministic CLI / MCP tools. Preferences, signals, evidence, and audit trails are real `.md` files under `Brain/` in the vault you already open in Obsidian every day. You can grep them, version them with git, search them in Obsidian, edit them by hand. No daemon, no vector black box, no hidden state outside the vault.
+
+## Why
+
+- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.
+- **You own the data.** Plain Markdown on your filesystem. No service to cancel, no cloud account, no schema migration when a vendor pivots. Syncthing to your other machines if you want.
+- **Memory that learns deterministically.** A `dream` pass turns repeat signals into rules and retires the ones nothing applies any more. Counters and atomic file moves - no LLM inside the algorithm, no surprise hallucinations in your memory.
+- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.
+
+## One vault, many runtimes
```mermaid
flowchart LR
- Agent[Agent / human]
- Agent -- brain_feedback --> Inbox[(Brain/inbox/)]
- Inbox -. dream .-> Pref[(Brain/preferences/)]
- Agent -- brain_apply_evidence --> Log[(Brain/log/)]
- Agent -- brain_note --> Log
- Log -. dream .-> Pref
- Pref -. regenerate .-> Active[Brain/active.md]
- Active -- SessionStart hook --> Agent
- Vault[Vault Markdown] -- o2b search index --> FTS[(SQLite + FTS5<br/>brain_search)]
- FTS --> Agent
+ Vault[("Your vault<br/>Brain/ - plain Markdown")]
+ Hermes["**Hermes Agent**<br/>(primary)"]
+ CC[Claude Code]
+ Codex[OpenAI Codex]
+ Others["Cursor · Aider · OpenClaw<br/>opencode · kiro · Copilot CLI<br/>Gemini CLI · Pi · any MCP host"]
+
+ Hermes <==> Vault
+ CC <--> Vault
+ Codex <--> Vault
+ Others <--> Vault
+
+ style Hermes fill:#1e3a5f,stroke:#90caf9,color:#fff
+ style Vault fill:#5d3a9b,stroke:#ce93d8,color:#fff
```
-Mechanics, dream pipeline, state diagram, snapshot model, hygiene
-lints, MCP resources, the v0.10.0 search layer, and the full set of
-safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).
-
-## Supported runtimes
-
-| Runtime | Integration | Notes |
-| --------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
-| Hermes Agent | Hermes plugin (`plugin.yaml`) + MCP server | Adds a per-turn identity reminder via the `pre_llm_call` hook. |
-| Claude Code | Marketplace plugin + bundled `.mcp.json` + lifecycle hooks | `hooks/hooks.json` registers a `PostToolUse` reminder that points the agent at `brain_feedback` / `brain_apply_evidence` after every Write/Edit. See [`hooks/`](hooks/). |
-| OpenAI Codex | Marketplace plugin + MCP server + lifecycle hooks | Same hook bundle as Claude Code. |
-| OpenClaw | Native JS plugin (`openclaw.extensions`) — no MCP needed | Core query/status/health tools are registered directly inside OpenClaw's Node.js process. Native parity with the `brain_*` tools is tracked separately in the post-v0.9 roadmap. |
-| Cursor / Aider / opencode / kiro / Copilot CLI / Gemini CLI / Pi | One-shot `o2b install --target <name> --apply` | v0.10.11 multi-runtime orchestrator with idempotent managed block and sidecar manifest. See `install/<name>.md` and `install.md`. |
-| Other MCP hosts | Generic adapter (stdio MCP server, persisted plugin config) | `o2b install --target generic --apply --out -` prints the payload; see `install/generic.md`. |
-
-## What it does
-
-- Bootstraps `Brain/` — the observing-memory layer where the agent
- records taste signals, accreted preferences, evidence, and
- pre-run snapshots.
-- Runs a deterministic `dream` pass that turns repeat signals into
- confirmed rules, retires stale ones, and surfaces contradictions
- — no LLM inside the algorithm, only counters, thresholds, and
- atomic file operations. See [Brain section](#brain-observing-memory).
-- Regenerates a Markdown page index from frontmatter and wikilinks
- (`o2b index`).
-- Exports config snapshots with secret-like values redacted
- (`o2b export-config`).
-- Runs vault + adapter health checks (`o2b doctor`, plus
- `o2b brain doctor` for Brain-specific invariants).
-- Surfaces vault care signals as one ranked next-step list
- (`o2b brain actions`): page-level duplicates
- (`o2b brain page-dedup`), self-healing structural drift
- (`o2b brain lint --consolidate`), token-budget monitoring
- (`o2b brain token-footprint`), and a bounded-token vault slice
- for priming an agent's context window
- (`o2b brain context-pack --max-tokens N`). Per-page metadata
- (`_lifecycle`, `tier`, `merged_into`) feeds the ranker and the
- search relevance signal.
-- Aggregates an operator dashboard from trust verdict, doctor /
- dream counts, verification delta, instruction-file ceiling
- warnings, and top maintenance actions
- (`o2b brain summary` / `brain_operator_summary`). The verdict
- band (`clean | watch | investigate`) is computed from
- structural signals only - no LLM, no per-language vocabulary.
-- Exposes the vault as a connected link graph: frontmatter
- `aliases:` resolve transparently into the backlink index;
- every `BacklinkRef` keeps `#heading` / `#^block-id` anchors so
- consumers see paragraph-level intent; raw-text mentions outside
- `[[...]]` surface via `o2b brain unlinked` /
- `brain_unlinked_mentions`; a concept-scoped cluster (target +
- linkers, optionally + unlinked mentions) lands as a
- deterministic JSON envelope via `o2b brain synthesise` /
- `brain_concept_synthesis`; per-MOC coverage audit classifies
- cluster members into well-covered / fragile / candidate-missing
- via `o2b brain moc-audit` / `brain_moc_audit`. Match boundaries
- are Unicode-aware (codepoint class) and the MOC heuristic uses
- link density only - no per-language vocabulary anywhere.
-- Layers structured property filters on top of full-text search
- (`o2b search "<query>" --property type=decision --property
- status=open`). The filter applies to frontmatter scalars as a
- post-FTS phase; `additionalProperties` extension on
- `brain_search` mirrors it at the MCP boundary.
-- Surfaces a user-authored vault-root instruction file
- (`VAULT.md` by default, configurable via
- `link_graph.vault_instruction_file`) through the `brain_context`
- envelope. Absent file = field omitted; existing hosts stay
- byte-identical.
-- Treats time as a first-class axis. The `temporal:` config block
- drives a new `src/core/brain/temporal/` subsystem that
- materializes one `TimelineIndex` per invocation from
- `Brain/log/<date>.jsonl` plus retired/ frontmatter and feeds
- five operator surfaces over the same deterministic projection:
- a chronological event list (`o2b brain timeline` /
- `brain_timeline`), per-preference or per-topic belief evolution
- (`o2b brain evolution` / `brain_belief_evolution`) with running
- evidence counts and retire-chain walking, structural staleness
- reports (`o2b brain stale` / `brain_stale_scan`) using
- configurable per-kind thresholds, a daily brief
- (`o2b brain daily` / `brain_daily_brief`), and a 7-day synthesis
- with contradictions list (`o2b brain weekly` /
- `brain_weekly_synthesis`). All helpers ship deterministic data
- shapes - no LLM call inside. Preference, signal, and retired
- frontmatter grow additive optional `valid_from` / `valid_until`
- / `recorded_at` slots so future write paths can populate the
- bi-temporal axis without breaking existing files.
-- (Optional) Records paid agent actions through **Pay Memory**:
- receipts, generated assets, spending policy decisions, human
- approval state, and per-day reports — all as plain Markdown
- inside the vault.
-
-## Install
-
-`install.md` is a short router. Pick the matching per-runtime page
-under [`install/`](install/) and follow it end-to-end. The
-MCP-aware runtimes share one CLI orchestrator:
+Hermes Agent owns the schedule (dream cron, daily digests, Telegram delivery). Other runtimes participate as readers and writers of the same Brain through MCP - no per-runtime fork of the memory.
-```bash
-o2b install --target <name> --apply
-o2b install --check
-```
+## Quick start with Hermes Agent
-Supported `--target` values: `cursor`, `aider`, `opencode`, `kiro`,
-`copilot-cli`, `gemini-cli`, `pi`, `generic`. Each writes a sidecar
-manifest at `<vault>/.open-second-brain/install.lock.json` so
-`o2b uninstall --target <name> --apply` removes exactly what was
-added.
+**The simplest path - let your agent set it up.** Paste this into Hermes (or whichever AI agent already has shell access on the target machine):
-For runtimes that ship their own plugin/MCP install pipeline
-(Hermes, Claude Code, Codex, OpenClaw) the corresponding
-`install/<runtime>.md` walks through the runtime-native flow.
+> Install Open Second Brain for me by following the steps at <https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md>. My vault is at `/path/to/your-vault`.
-First-time-setup users can also run a guided wizard:
+The agent reads the install doc, runs every command, and verifies the result. That's it.
+
+If you prefer running the steps yourself:
```bash
-o2b init --interactive
-```
+# 1. Install the plugin
+hermes plugins install itechmeat/open-second-brain --enable
+hermes gateway restart
-The wizard composes `o2b init`, optional `o2b brain init`, and
-per-target `o2b install` behind a single linear question/answer
-flow with an explicit confirmation gate.
+# 2. Put `o2b` on PATH
+~/.hermes/plugins/open-second-brain/scripts/o2b install-cli
-## CLI
+# 3. Bootstrap the vault
+o2b init --vault /path/to/your-vault --name "My Second Brain"
+o2b brain init --vault /path/to/your-vault --primary-agent <agent-name>
-After `o2b install-cli` the following commands are on PATH:
-
-```text
-o2b status Show config / vault status
-o2b init Bootstrap the vault profile (idempotent)
-o2b install-cli Symlink o2b and o2b-hook into ~/.local/bin
-o2b doctor Run vault + adapter checks
-o2b index Rebuild the Markdown page index
-o2b export-config Write a redacted config snapshot
-o2b mcp Run the MCP tool server (stdio)
-o2b tool-call Invoke an MCP tool handler from the CLI
-o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks
-o2b update Update OSB installation across all detected runtimes; --target <name> / --dry-run / --force / --json
-
-# Brain (observing memory)
-o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set
-o2b brain feedback Record one taste signal (--topic, --signal, --principle, ...)
-o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
-o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
-o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
-o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback
-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; drift abort vs --force-rollback)
-o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes
-o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])
-o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode).
-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, …)
-o2b brain import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)
-o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
-o2b brain migrate-frontmatter (CLI-only) Rewrite legacy `status:` keys to `_status:`
-
-# Vault scope (single exclusion policy for every vault walker)
-o2b vault status Walks the vault under the active policy; reports include / exclude counts and which rules fired
-o2b vault inspect <relpath> Point-check one vault-relative path; reports matched rule, source, and whether the path exists on disk
-
-# Discipline (daily logging-discipline cron)
-o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime activity); status ok | info | alert
-o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digest
-o2b discipline uninstall Remove the cron job; --weekly removes only the weekly digest, without flag removes both
-
-# Pay Memory
-o2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/
-o2b append-payment-receipt Save a Markdown receipt for a paid API call
-o2b capture-asset Save a Markdown note for a generated asset
-o2b payment-report Aggregate a date's receipts into a Markdown report
-o2b check-payment-policy Evaluate a paid call against policies/spending.json
-o2b request-payment-approval Create a pending payment request (human must approve)
-o2b approve-payment-request Mark a pending request as approved
-o2b reject-payment-request Mark a pending request as rejected
-o2b consume-payment-request Link an approved request to its resulting receipt
-o2b list-pending-payments List pending / approved / etc. requests
-o2b payment-digest Render a 4-line digest for a date
-
-# Helpers
-o2b-hook Internal launcher invoked by hooks/hooks.json (Claude Code & Codex)
+# 4. Verify
+o2b doctor --vault /path/to/your-vault
```
-The local checkout can also be used without installing the symlinks
-— run commands through `scripts/o2b` and `scripts/vault-log`.
-
-## MCP tool server
-
-The plugin ships an optional stdio MCP server (`o2b mcp`) that
-exposes the same deterministic operations as MCP tools:
-
-- **Core (3):** `second_brain_status`, `second_brain_query`,
- `vault_health`.
-- **Brain (19):** `brain_feedback`, `brain_dream`,
- `brain_apply_evidence`, `brain_note`, `brain_context`,
- `brain_digest`, `brain_query`, `brain_doctor`, `brain_backlinks`,
- `brain_context_pack`, `brain_unlinked_mentions`,
- `brain_concept_synthesis`, `brain_moc_audit`, `brain_timeline`,
- `brain_belief_evolution`, `brain_stale_scan`,
- `brain_daily_brief`, `brain_weekly_synthesis`,
- `brain_operator_summary`. See the
- [Brain section](#brain-observing-memory) below.
-- **Pay Memory (8):** `payment_memory_init`,
- `payment_receipt_append`, `asset_capture`,
- `payment_report_generate`, `payment_policy_check`,
- `payment_request_approval`, `payment_request_status`,
- `payment_request_consume`.
-
-Each runtime registers the server differently — Hermes via
-`mcp_servers:` in `~/.hermes/config.yaml`, Codex via `codex mcp add`
-(written to `~/.codex/config.toml`), Claude Code automatically through
-the plugin-bundled `.mcp.json`, OpenClaw not at all (tools registered
-natively). The exact wiring is in `install.md`; the protocol,
-schemas, and lifecycle details are in [`docs/mcp.md`](docs/mcp.md).
-
-### Writer split (Claude Code 2.1.121+)
-
-The plugin's `.mcp.json` ships **two** MCP-server entries:
-
-- `open-second-brain` — the full surface (21 tools); subject to
- Claude Code's `MCPSearch` tool-search deferral when MCP
- definitions push the system prompt past 10% of the context window.
-- `open-second-brain-writer` — a minimal always-loaded surface of
- four tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`
- (writers) and `brain_context` (read-only pull-bootstrap of
- `Brain/active.md`, v0.10.10). The agent records taste signals,
- evidence events, and milestone notes — and fetches the active
- rule digest at session start in runtimes without a SessionStart
- hook — without a ToolSearch round-trip on every session boot.
-
-Both servers reuse the same backing CLI (`o2b mcp --scope writer`
-vs the default `--scope full`). Handlers are byte-identical; the
-writer-mode instructions text explicitly tells the agent to prefer
-the writer copy over any duplicate the full server still exposes
-(both call the same code path).
-
-## Lifecycle hooks (Claude Code & Codex)
-
-The plugin bundles a `hooks/hooks.json` that both runtimes auto-load.
-One hook fires per turn:
-
-- **PostToolUse** (matcher `Write|Edit|MultiEdit|apply_patch`) —
- after a file-mutating tool succeeds, injects a short reminder
- pointing the agent at `brain_feedback` (when the turn contained a
- user preference or correction) and `brain_apply_evidence` (when an
- active preference in `Brain/preferences/` scopes to the artifact
- just produced).
-
-Hermes and OpenClaw don't load these hooks — they have their own
-per-turn channels. Full design notes:
-[`hooks/README.md`](hooks/README.md).
-
-## Brain (observing memory)
-
-Brain is the agent-writable observing-memory layer. Agents record
-user preferences as raw taste signals; a deterministic `dream` pass
-accretes repeat signals into rules with confidence that grows from
-real applications and decays when nothing applies the rule any more.
-There is no LLM inside the algorithm — only counters, thresholds,
-and `mv` operations.
+Register the MCP server in `~/.hermes/config.yaml` and restart the gateway one more time - the agent now reads `Brain/active.md` on every session start and writes signals through `brain_feedback`. Full step-by-step including MCP wiring: [`install/hermes.md`](install/hermes.md).
-```bash
-o2b brain init --vault /path/to/vault
-# → Brain/{inbox,preferences,retired,log,.snapshots}/ plus _brain.yaml and _BRAIN.md
-
-# Record a taste signal (agent or human, mid-conversation):
-o2b brain feedback \
- --vault /path/to/vault \
- --topic no-internal-abbrev --signal negative \
- --principle "Do not use internal abbreviations in user-facing copy unless explained first" \
- --agent claude
-
-# After producing a durable artifact, record evidence:
-o2b brain apply-evidence \
- --vault /path/to/vault \
- --pref pref-no-internal-abbrev \
- --artifact "[[Daily/2026.05.14#section-blog-post]]" \
- --result applied --agent claude
-
-# Run a dream pass (cron or manual): promotes candidates, retires stale rules:
-o2b brain dream --vault /path/to/vault
-
-# Short daily summary (markdown or JSON), suitable for Hermes cron → Telegram:
-o2b brain digest --vault /path/to/vault --silent-if-empty
-```
+## Other runtimes
-The Brain verbs in full: `init`, `feedback`, `dream`,
-`apply-evidence`, `digest`, `query`, `reject`, `merge`, `pin`,
-`unpin`, `set-primary`, `protect`, `unprotect`, `snapshot diff`,
-`rollback`, `upgrade`, `export`, `doctor`, `backlinks`,
-`scan-inline`, `import-session`, `import-claude-memory`,
-`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.
-
-### Discipline (daily logging sanity-check)
-
-`o2b discipline report` renders a deterministic Telegram MarkdownV2
-block comparing brain-event counts per agent (parsed from
-`Brain/log/<yesterday>.md`) against runtime-agnostic activity proxies
-(git on watched repos + mtime walk on watched non-repo paths + vault
-delta on `Brain/inbox|preferences|retired/`). Status is binary —
-`alert` if taste events (`feedback`+`apply_evidence`) are zero while
-activity is non-zero, `info` for a quiet day, `ok` otherwise. No LLM
-in the report path.
-
-`o2b discipline install --vault <v> --telegram-target <target>`
-writes one cron entry into the Hermes scheduler (job id derived from
-`sha256(vault)` so multiple vaults on one host do not collide). The
-configuration block lives in `Brain/_brain.yaml`:
-
-```yaml
-discipline_report:
- enabled: true
- timezone: "Europe/Belgrade"
- watched_paths:
- - "/srv/projects/open-second-brain"
- - "/root/.hermes/plugins"
- known_agents:
- - "@claude-vps-agent"
- - "@codex-vps-agent"
-```
+| Runtime | Install |
+| --- | --- |
+| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |
+| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |
+| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |
+| Cursor · Aider · opencode · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |
+| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |
-When the section is absent or `enabled: false`, the report exits 0
-with a stderr note and the cron job stays silent.
-
-### Cross-project setup
-
-When your coding work happens in a project directory that is not the
-vault itself, add a pointer snippet to your project's `CLAUDE.md` or
-`AGENTS.md` so the agent knows where to read preferences from. The
-canonical snippet, the rules for multi-device Syncthing setups, and
-the `o2b brain set-primary` invocation are in
-[`docs/cross-project-pointer.md`](docs/cross-project-pointer.md).
-
-A vault shared across hosts should declare a single
-`primary_agent` in `Brain/_brain.yaml` — the runtime that owns the
-dream cron. Dream runs from a different agent emit a non-fatal
-warning (stderr for CLI, `warnings` array for MCP) and tag the dream
-summary log with `non_primary_agent: <caller>`.
-
-### Capture surfaces
-
-Three independent paths land a signal in `Brain/inbox/`:
-
-- **Live** — the agent calls `brain_feedback` (MCP) or `o2b brain
- feedback` (CLI) the moment the rule is formulated.
-- **Inline** — the user (or agent) writes an `@osb` marker into any
- vault markdown file. `o2b brain scan-inline` finds every marker,
- creates the corresponding signal, and annotates the source file
- with `@osb✓ [[sig-...]]` so a re-run is a no-op. Two marker
- shapes: a single line `@osb feedback negative topic=... principle="..."`
- or a fenced ` ```osb` block with YAML inside.
-- **Session import** — `o2b brain import-session <path>` reads a
- Claude Code / Codex CLI / Hermes session JSONL and extracts both
- `@osb` markers from message text and replays of `brain_feedback`
- tool-use calls. Useful when MCP wasn't available at recording time
- or the agent didn't make the call live.
-
-All three paths share a normalised payload hash so the same rule
-captured twice from different surfaces dedups automatically. Pre-run snapshots of `Brain/` go to `Brain/.snapshots/` and
-support `o2b brain rollback <run_id>`. Pinned preferences are exempt
-from automatic retire (`stale-no-evidence`, `expired-unconfirmed`,
-`rebutted`); only `o2b brain reject` can retire them.
-
-Full design and implementation plan:
-[`docs/plans/2026-05-15-brain-observing-memory.md`](docs/plans/2026-05-15-brain-observing-memory.md).
-Post-v0.9 trigger-based roadmap:
-[`docs/plans/2026-05-15-brain-roadmap.md`](docs/plans/2026-05-15-brain-roadmap.md).
-The `brain-memory` skill (loaded automatically) instructs agents when
-to call `brain_feedback` and `brain_apply_evidence`.
-
-## Pay Memory
-
-Pay Memory is an audit layer for paid agent actions. The agent makes
-the paid API call itself (typically through `pay` from
-[solana-foundation/pay](https://github.com/solana-foundation/pay));
-Open Second Brain records the reason, the policy check, the receipt,
-and any generated asset as plain Markdown inside the vault. It never
-executes payments and never holds wallet keys.
+Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.
-```bash
-o2b init-pay-memory --vault /path/to/vault
-# → AI Wiki/{policies,payments,assets,drafts,reports}/ and policies/spending.md
-
-# After running `pay --sandbox curl …` and capturing the output:
-o2b append-payment-receipt \
- --vault /path/to/vault \
- --service paysponge/fal \
- --status success \
- --reason "Generate one original blog header image" \
- --actual-amount 0.05 --currency USDC \
- --result-ref https://fal-cdn.example/img.png \
- --result-note "AI Wiki/assets/blog-header.md" \
- --raw-output-file /tmp/pay-output.txt
-
-o2b capture-asset \
- --vault /path/to/vault \
- --title "Blog Header: Pay Memory" \
- --service paysponge/fal \
- --result-url https://fal-cdn.example/img.png \
- --source-receipt "AI Wiki/payments/2026-05-10/<receipt-slug>.md"
-
-o2b payment-report --vault /path/to/vault --date 2026-05-10
-```
+## How rules accrete
-The spending policy at `AI Wiki/policies/spending.md` is read by the
-agent before each paid call; this MVP does not enforce policy at
-runtime. The `--raw-output-file` of a receipt is run through a
-redactor that masks values for `api_key` / `token` / `secret` /
-`bearer` / `authorization` / `private_key` / `password` / `passwd` /
-`pwd` / `credential` / `session_token` in env, YAML, JSON, and
-HTTP-header shapes. Best-effort only — verify the saved receipt
-before sharing it externally.
-
-### Optional: machine-readable spending policy
-
-To enable runtime enforcement, drop a JSON companion at
-`AI Wiki/policies/spending.json`:
-
-```json
-{
- "schema_version": 1,
- "currency": "USDC",
- "max_total_per_day": 0.10,
- "max_single_call": 0.07,
- "allowed_services": ["paysponge/fal"],
- "max_per_category": { "media_generation": 1 },
- "require_approval_above": 0.05
-}
+```mermaid
+sequenceDiagram
+ actor You
+ participant Agent as Hermes Agent
+ participant Inbox as Brain/inbox
+ participant Pref as Brain/preferences
+ participant Log as Brain/log
+
+ You->>Agent: "no, write full names instead of abbreviations"
+ Agent->>Inbox: brain_feedback (signal)
+ Note over Inbox: ... repeats over days ...
+ Inbox->>Pref: dream pass (counters + mv, no LLM)
+ Agent->>Log: brain_apply_evidence (applied | violated)
+ Note over Pref,Log: confidence grows from evidence,<br/>decays when nothing applies the rule
+ Pref-->>Agent: Brain/active.md injected at session start
```
-Then have the agent (or the user) run:
+Three repeat signals on the same topic graduate to a confirmed rule. Evidence shifts confidence up or down. Rules with zero recent evidence retire automatically. You can pin, merge, retire, or roll back with `o2b brain {pin,merge,reject,rollback}` - see [`docs/cli-reference.md`](docs/cli-reference.md).
-```bash
-o2b check-payment-policy --service paysponge/fal --expected-amount 0.05
-```
+## Top features
-Exit codes are `0` (allowed), `1` (denied), `3` (approval required)
-so a shell script can branch. The MCP tool `payment_policy_check`
-returns the same structured decision. If `spending.json` is absent,
-the check fails open (`has_policy: false`) — existing flows that
-rely on the Markdown-only policy keep working.
+The capabilities you actually feel day to day:
-### Optional: approval workflow
+| # | Feature | What it means for you |
+|---|---|---|
+| 1 | Your memory, in your Obsidian vault | Every rule the agent learns about you is a Markdown file you can open, read, and edit. Wikilinks, backlinks, and the graph view in Obsidian all work — no separate UI to learn. |
+| 2 | `dream` - the agent learns what you actually want | The nightly `dream` pass turns repeat corrections into rules: three signals on the same topic graduate to a confirmed preference. Its confidence rises every time the agent applies the rule and drops when it slips. No LLM inside the algorithm - counters and atomic file moves, nothing else. |
+| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows. |
+| 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osb✓` checkmark so re-runs skip it. |
+| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` summarise what changed; `o2b brain stale` flags rules nothing has applied in months. |
+| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node — Obsidian opens the underlying note. |
+| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |
+| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |
+| 9 | Full-text search across the whole vault | `o2b search "<query>" --property type=decision --property status=open` — SQLite + FTS5 plus frontmatter property filters. Faster and more precise than Obsidian's built-in search when you need to grep across thousands of notes. |
+| 10 | Pay Memory — audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
-For paid calls that should not happen until a human signs off, Pay
-Memory ships a pending-payment-request artifact under
-`AI Wiki/payments/_pending/` with a
-`pending → approved/rejected → consumed` state machine.
+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, and an operator dashboard. Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
-Agent side:
+## CLI
```bash
-o2b request-payment-approval \
- --service paysponge/fal \
- --reason "Generate one blog header image" \
- --expected-amount 0.05 --currency USDC
-# → AI Wiki/payments/_pending/req-2026-05-10-1000-fal-...md
+o2b status # Show config / vault status
+o2b init # Bootstrap the vault profile
+o2b doctor # Run vault + adapter checks
+o2b brain dream # Deterministic consolidation pass (idempotent)
+o2b brain digest # Recent transitions, markdown or JSON
+o2b search "<query>" # FTS5 over the vault
+o2b update # Update across detected runtimes
```
-Human side, after reviewing the request file in Obsidian:
+Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, Pay Memory) in [`docs/cli-reference.md`](docs/cli-reference.md).
-```bash
-o2b approve-payment-request --id <id> --approved-by <name>
-# or
-o2b reject-payment-request --id <id> --rejected-by <name> --reason "..."
-```
+## Safety
-Agent side, after the approved paid call succeeded and the receipt
-was saved:
+- Plain Markdown on your filesystem. No daemon, no background writes.
+- The MCP server is a stdio subprocess that exits with the parent runtime.
+- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.
+- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.
+- Hooks (Claude Code, Codex) only inject text into the agent's context; they never write to the vault directly.
+
+## Updating
```bash
-o2b consume-payment-request --id <id> \
- --receipt "AI Wiki/payments/2026-05-10/<receipt-slug>.md"
+o2b update # detect runtimes, skip unchanged, apply, verify
+o2b doctor # confirm the new manifest validates
```
-The MCP-server side mirrors `payment_request_approval`,
-`payment_request_status` (poll for approval), and
-`payment_request_consume`.
+Per-runtime upgrade paths and the canonical version source live in [`install.md`](install.md).
-### Optional: daily Telegram digest via Hermes cron
+## Documentation
-`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a
-4-line Russian summary suitable for delivery via Hermes cron
-`--script --no-agent` jobs. See
-[`docs/hermes-cron.md`](docs/hermes-cron.md) for the ready-to-paste
-`hermes cron create` command. The same command can be wrapped by
-any other scheduler that can pipe its stdout to a chat
-destination — the digest itself is runtime-neutral.
+| Topic | Doc |
+| --- | --- |
+| Mental model, vault layout, dream mechanics | [`docs/how-it-works.md`](docs/how-it-works.md) |
+| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](docs/mcp.md) |
+| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](docs/cli-reference.md) |
+| Pay Memory - audit for paid agent actions | [`docs/pay-memory.md`](docs/pay-memory.md) |
+| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](docs/hermes-cron.md) |
+| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](docs/cross-project-pointer.md) |
+| Architecture | [`docs/architecture.md`](docs/architecture.md) |
+| Origin idea | [`docs/idea.md`](docs/idea.md) |
-### Installing the `pay` CLI on a Linux VPS
-
-`pay` is the Solana-Foundation payment wrapper that turns a regular
-HTTP client into one that handles HTTP 402 payment challenges. It is
-published as a prebuilt static binary on GitHub Releases — no Rust
-toolchain or Node.js is needed on the host:
+## Uninstalling
```bash
-TAG=pay-v0.16.0 # pin a specific release
-gh release download "$TAG" -R solana-foundation/pay \
- -p 'pay-x86_64-unknown-linux-gnu.tar.gz' -p 'sha256sums.txt' -D /tmp
-cd /tmp && sha256sum -c --ignore-missing sha256sums.txt
-tar -xzf pay-x86_64-unknown-linux-gnu.tar.gz
-sudo install -m 0755 pay /usr/local/bin/pay
-pay --version
+o2b uninstall # print plan (read-only)
+o2b uninstall --apply-local --remove-cli # remove local state and symlinks
```
-Sandbox mode (`pay --sandbox curl <url>`) does **not** require
-running `pay setup` first — it generates an ephemeral Solana keypair
-and funds it locally via the Surfpool sandbox RPC. That makes it
-safe to wire into a CI / e2e test that exercises the full Pay Memory
-pipeline without spending real funds. See
-`tests/e2e/pay-memory-sandbox.sh` for a reference run.
+Your vault is never touched by the uninstall flow. Delete it yourself with normal filesystem tools if you want to.
-For non-sandbox use the local secure storage helper (macOS Keychain,
-GNOME Keyring, Windows Hello, 1Password) is configured by
-`pay setup`. Open Second Brain itself never holds wallet keys.
-
-## Updating
-
-The quickest path is `o2b update` — it detects all installed runtimes,
-skips unchanged payloads, applies updates sequentially, and verifies
-afterwards. For manual per-runtime updates, follow the matching
-`## 7. Update` section in `install.md`:
-
-- Hermes: `hermes plugins update open-second-brain && hermes gateway restart`
-- Claude Code: `claude plugin marketplace update open-second-brain && claude plugin update open-second-brain@open-second-brain`
-- Codex (Git source): `codex plugin marketplace upgrade open-second-brain`
-- Codex (local source): re-add the marketplace; there is no
- `upgrade` for local sources.
-- OpenClaw: `openclaw plugins update open-second-brain && openclaw gateway restart`
-
-The CLI symlinks created by `o2b install-cli` point into the cached
-plugin checkout and survive in-place updates — no need to re-run
-`install-cli`. After an update, run
-`o2b doctor --vault /path/to/vault --repo .` to confirm the new
-manifest still validates.
-
-The `version` field in each runtime manifest is informational; the
-canonical version lives in `package.json` and is mirrored by
-`bun run sync-version`.
-
-## Uninstalling
+## License
-Open Second Brain treats your vault as the source of truth and never
-removes Markdown notes, `Daily/`, or `AI Wiki/`. Uninstalling has
-three independent layers; do them in this order:
-
-1. Print a plan and review the leftovers (read-only):
-
- ```bash
- o2b uninstall
- ```
-
-2. Run your runtime's plugin-remove command (see the matching
- `## 8. Uninstall` section in `install.md`), then clean local
- state:
-
- ```bash
- o2b uninstall --apply-local --remove-cli
- ```
-
-3. Optionally delete the machine-local config directory (typically
- `~/.config/open-second-brain` or `$OPEN_SECOND_BRAIN_CONFIG`'s
- parent) — `--apply-local` handles this and refuses to touch
- anything outside that directory.
-
-The vault is never deleted by the uninstall flow, even with
-`--apply-local`. Delete it yourself with normal filesystem tools if
-you want to.
-
-## Safety model
-
-- Your notes stay as plain Markdown.
-- Secrets are not meant to be stored in the vault. Daily logs and
- config exports go through a best-effort redactor that masks
- common secret-name patterns.
-- Daily logs are append-only below `## Raw events`.
-- The plugin never starts background processes or daemons. The
- optional MCP server is a stdio subprocess that exits when its
- parent runtime exits.
-- Hooks (Claude Code, Codex) only inject text into the agent's
- context. They never write to the vault directly — every Brain
- entry goes through `brain_feedback` / `brain_apply_evidence`
- (MCP) or the equivalent CLI (`o2b brain *`).
-- Brain mutations (`o2b brain dream`, `merge`,
- `migrate-frontmatter`, `upgrade`) take an automatic pre-run
- snapshot (`Brain/.snapshots/<run_id>.tar.zst`) before any state
- change. From v0.10.6 the snapshot ships with a SHA-256 sidecar
- manifest (`<run_id>.manifest.json`); `o2b brain rollback`
- compares it against the live tree and aborts with exit 2 on
- drift (typically a Syncthing-delivered edit on another device
- between snapshot and rollback). Pass `--force-rollback` to
- overwrite anyway. Legacy snapshots without sidecar fall back to
- the pre-v0.10.6 direct-restore path with a stderr warning.
- Retention is configurable in `_brain.yaml`.
-
-## Partner tools
-
-OSB stays in the vault / Brain / prose lane. When the user works on
-code next to the vault, the agent benefits from a complementary index
-over the source - call graphs, callers, callees, impact. The
-[codegraph](https://github.com/colbymchenry/codegraph) CLI and its
-stdio MCP server cover that surface. OSB detects codegraph through
-`o2b doctor` (a `code_graph` line appears when a code project is in
-scope) and ships an agent-facing playbook at
-`skills/codegraph-partner/SKILL.md` that tells the agent when to
-recommend installation and how to disambiguate `codegraph_*` vs
-`brain_*` queries. OSB never installs, initializes, or writes data
-for codegraph - that stays in codegraph's own installer.
-
-## Repository
-
-GitHub: <https://github.com/itechmeat/open-second-brain>
-
-License: MIT.
+MIT. Source: <https://github.com/itechmeat/open-second-brain>.
diff --git a/docs/architecture.md b/docs/architecture.md
index 9f4562e0..9b0480e6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -14,18 +14,17 @@ Agent runtime
## Core responsibilities
-The core should eventually provide deterministic operations for:
+The core (`src/core/`) provides deterministic operations for:
-- locating configuration;
-- validating configuration;
-- initializing a vault profile;
-- appending event log entries;
+- locating and validating configuration;
+- initializing a vault profile (`o2b brain init`);
+- recording taste signals, applied-evidence, and narrative milestones into `Brain/log/<YYYY-MM-DD>.md` (plus a JSONL sidecar);
+- running the nightly `dream` learning pass (deterministic, no LLM calls);
- exporting redacted config snapshots;
-- checking vault health;
-- running migrations;
-- querying known indexes where available.
+- checking vault health (`o2b brain doctor`);
+- querying preferences, signals, and link-graph relationships through the MCP and CLI surface.
-The core should not depend on Hermes, Claude Code, Codex, OpenClaw, or Obsidian internals.
+The core does not depend on Hermes, Claude Code, Codex, OpenClaw, or Obsidian internals.
## Runtime adapters
@@ -76,32 +75,12 @@ v0 should keep Codex support simple: plugin manifest plus shared skills and scri
### OpenClaw adapter
-OpenClaw recognizes two plugin formats: **Native** (JS runtime module with `package.json` + `openclaw.plugin.json`) and **Bundle** (adapter directories like `.codex-plugin/`, `.claude-plugin/` mapped to OpenClaw features).
-
-Open Second Brain uses the **Native format** with a pure JavaScript entry that operates directly on the vault filesystem — no Python subprocess, no `child_process`:
-
-```text
-package.json # openclaw.extensions → ./openclaw/index.js
-openclaw/
- index.js # JS entry: definePluginEntry + api.registerTool (two-arg)
- vault.js # Pure JS: frontmatter parse/write, slugify, wikilinks, page listing
- event-log.js # Pure JS: daily note creation, chronological event insertion
-openclaw.plugin.json # Static discovery metadata (id, configSchema, contracts.tools)
-src/open_second_brain/
- cli.py # Python CLI (for Hermes/standalone usage)
- mcp.py # MCP server (optional, for runtimes that prefer MCP)
-.claude-plugin/ # Auto-detected by OpenClaw Bundle format
-.codex-plugin/ # Auto-detected by OpenClaw Bundle format
-```
-
-The integration flow:
-
-1. **Discovery**: OpenClaw reads `package.json`, finds `openclaw.extensions`, and loads `openclaw/index.js`.
-2. **Tool registration**: The JS entry calls `api.registerTool(tool, { name })` for each of the five tools (`second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`).
-3. **Pure JS execution**: Each tool's `execute()` runs entirely in the Node.js process using `node:fs/promises` and `node:path` to read/write the vault directory. No subprocess is spawned — this passes the OpenClaw security scanner which blocks `child_process` imports.
-4. **Config**: `api.pluginConfig` provides the vault path and instance name from OpenClaw's plugin config.
-
-The Python CLI (`o2b`) and MCP server (`o2b mcp`) remain available for Hermes and standalone usage, but the OpenClaw runtime is self-contained JavaScript.
+OpenClaw discovers Open Second Brain as a Native plugin via the
+`openclaw.extensions` entry in `package.json`. The entry
+(`src/openclaw/index.ts`) reads and writes the vault directory
+directly with `node:fs` / `node:path`; no subprocess is spawned, so
+the OpenClaw security scanner (which blocks `child_process` imports)
+accepts the plugin.
Installation (always installs the latest from `main`; do not append `@v...`):
@@ -109,7 +88,9 @@ Installation (always installs the latest from `main`; do not append `@v...`):
openclaw plugins install git:github.com/itechmeat/open-second-brain
```
-The OpenClaw adapter must remain compatible with the Hermes, Claude Code, and Codex adapters. The `o2b mcp` MCP server is still available for runtimes that prefer the MCP protocol.
+The OpenClaw adapter must remain compatible with the Hermes, Claude
+Code, and Codex adapters. The `o2b mcp` MCP server is the canonical
+way for any runtime to reach the writer / reader tools.
## Configuration model
@@ -135,7 +116,6 @@ runtime: hermes
environment_name: <hostname>
vault:
path: <absolute-path-to-Obsidian-vault>
- agent_dir: AI Wiki
identity:
agent_name: <chosen-agent-name>
user_language: <BCP-47 tag, e.g. en or ru>
@@ -147,24 +127,13 @@ Machine-local config may contain absolute paths. It must not contain secrets.
### Vault-portable config
-Vault-portable config lives inside the vault and travels with backup/sync.
+Vault-portable config lives at `<vault>/Brain/_brain.yaml` and travels
+with backup/sync. It describes:
-Suggested paths:
-
-```text
-<vault>/<agent_dir>/_open-second-brain.yaml
-<vault>/<agent_dir>/_OPEN_SECOND_BRAIN.md
-```
-
-It describes:
-
-- owner identity;
-- language/timezone preferences;
-- vault schema;
-- write boundaries;
-- known agents;
-- event log backend;
-- durable operating rules.
+- schema version + dream / retire / confidence / snapshot thresholds;
+- optional `notes.read_paths` (user-authored folders the agent may read);
+- optional `temporal:`, `link_graph:`, `guardrails:`, `discipline_report:` tuning blocks;
+- `vault.ignore_paths` (exclusion policy for every vault walker).
It must not contain secrets.
@@ -181,43 +150,38 @@ Recommended behavior:
## Vault layout
-A default vault layout may look like:
-
-```text
-AI Wiki/
- _OPEN_SECOND_BRAIN.md
- _open-second-brain.yaml
- index.md
- hot.md
- log.md
- identity/
- user.md
- agents.md
- system/
- config-snapshots/
- events/
-```
-
-This layout is intentionally agent-owned. The project should not mix agent-generated wiki pages into a user's personal notes without clear boundaries.
-
-`AI Wiki/` holds the static agent-facing wiki: identity, index, hot list, and the Pay Memory subtree (`payments/`, `assets/`, `drafts/`, `reports/`, `policies/`). Agents read it through `second_brain_query` and write into Pay Memory subdirectories via the `payment_*` tools. Durable observing memory — taste signals, accreted preferences, evidence, snapshots — lives in a separate top-level `Brain/` directory described in the next section.
-
-## Brain layer
-
-`Brain/` is a top-level directory parallel to `AI Wiki/` and `Daily/`. It is the observing-memory layer: where agents record taste signals, the `dream` pass accretes them into rules, and pre-run snapshots provide reversibility.
+The agent owns one directory in the vault: `Brain/`. Pay Memory nests
+under `Brain/payments/` so the write contract stays simple ("agent
+writes only under `Brain/`"). User-authored notes (daily journals,
+weekly notes) live wherever the operator names them; the agent reads
+those paths only when they are listed in `notes.read_paths`.
```text
Brain/
- _brain.yaml # schema + thresholds (validated by o2b brain doctor)
+ _brain.yaml # schema + thresholds + notes.read_paths (validated by o2b brain doctor)
_BRAIN.md # operating manual for agents (rendered by o2b brain init)
+ active.md # derived digest, auto-regenerated
inbox/ # raw taste signals, sig-<date>-<slug>.md
- processed/ # signals already folded into a preference
+ processed/ # signals already folded into a preference
preferences/ # active rules: pref-<slug>.md, status unconfirmed | confirmed
retired/ # ret-<slug>.md with retired_reason
log/ # YYYY-MM-DD.md, append-only event log (dream / apply-evidence / etc.)
+ payments/ # Pay Memory (optional, paid-action audit)
+ policies/spending.md # spending policy + optional spending.json
+ <YYYY-MM-DD>/<slug>.md # dated receipts
+ assets/ # generated-asset notes
+ drafts/ # draft artefacts
+ reports/ # daily reports
+ _pending/ # approval workflow
.snapshots/ # <run_id>.tar.zst, pre-run snapshots for o2b brain rollback
```
+This layout is intentionally agent-owned: every artefact Open Second
+Brain writes lives under `Brain/`. User-authored content elsewhere in
+the vault is read-only to the agent and stays under operator control.
+
+## Brain layer
+
Three architectural invariants:
- **Filesystem-first.** No database, no daemon. Every artifact is plain Markdown with YAML frontmatter; backup is `cp -r` or `tar`.
@@ -231,7 +195,7 @@ Agent runtime
-> runtime adapter/plugin
-> skills and commands (brain-memory skill, open-second-brain skill)
-> CLI/core library (src/core/brain/*)
- -> vault files: Brain/ (observing memory), AI Wiki/ + Daily/ (wiki + event log), Pay Memory (paid-action audit)
+ -> vault files: Brain/ (observing memory) + Brain/payments/ (paid-action audit)
```
Full design: [`docs/plans/2026-05-15-brain-observing-memory.md`](plans/2026-05-15-brain-observing-memory.md).
@@ -249,18 +213,14 @@ scope.
## Event log
-The event log is append-only. It records operational events, not polished knowledge.
-
-Default backend:
-
-```yaml
-event_log:
- backend: daily-markdown
- daily_dir: Daily
- section: Agent Events
-```
+The Brain event log is append-only. It records operational events,
+not polished knowledge.
-Later backends may include JSONL, SQLite, or both.
+Storage: `<vault>/Brain/log/<YYYY-MM-DD>.md` (Markdown for human
+reading) plus a JSONL sidecar at `<vault>/Brain/log/<YYYY-MM-DD>.jsonl`
+(machine-friendly for downstream tooling). Each event kind is one
+line per row, written through atomic temp+rename. The shared
+redactor strips secret-shaped tokens before write.
## Security rules
diff --git a/docs/brainstorm/brain-centric-layout/design.md b/docs/brainstorm/brain-centric-layout/design.md
new file mode 100644
index 00000000..c6799b34
--- /dev/null
+++ b/docs/brainstorm/brain-centric-layout/design.md
@@ -0,0 +1,136 @@
+# Brain-centric vault layout - one root, configurable user notes, no legacy siblings
+
+**Status:** draft
+**Author:** @claude-vps-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+The vault currently has three top-level agent-relevant directories (`Brain/`, `AI Wiki/`, `Daily/`) inherited from successive design iterations. Only `Brain/` carries its weight; the other two are vestigial:
+
+- **`AI Wiki/`** is empty scaffolding for most installations: `index.md`, `hot.md`, `log.md`, `identity/user.md`, `identity/agents.md`, `_OPEN_SECOND_BRAIN.md`, `_open-second-brain.yaml`. None of these are read or written by any current agent surface; they are leftovers from a v0.1-v0.5 "vault as curated knowledge base" idea that Brain replaced. The only live consumer is Pay Memory (which writes under `AI Wiki/payments/`, `AI Wiki/policies/`, ...) - and that placement is a historical accident, not a design choice.
+- **`Daily/`** is hardcoded into `src/core/event-log.ts` (writes `Daily/<date>.md`), into the OPEN_SECOND_BRAIN operating manual template ("chronological event log and human narrative"), and is referenced in five other files as a special case to exclude. The name `Daily/` is a user choice - everyone names their daily-notes folder differently or skips it entirely. Hardcoding the name into the agent's write paths violates that.
+
+Concrete pain:
+
+1. The README and `docs/how-it-works.md` have to apologise for three top-level directories where two of them do nothing.
+2. The agent's write contract is unclear: which legacy paths can it touch? The current answer ("Brain/ only - but `event_log_append` still writes `Daily/<date>.md`") is contradictory.
+3. Pay Memory sits under `AI Wiki/` for no reason other than "that was the only sibling directory at the time". Operators looking for receipts under `Brain/` find nothing.
+
+## Scope
+
+One named subsystem migration, one breaking release (v0.11.0):
+
+- **Pay Memory relocation** from `AI Wiki/{payments,policies,assets,drafts,reports,_pending}/` to `Brain/payments/{policies,assets,drafts,reports,_pending}/` plus the dated receipt subdirs (`YYYY-MM-DD/`).
+- **AI Wiki/ removal**: `o2b init` no longer scaffolds it; existing templates (`_OPEN_SECOND_BRAIN.md`, `_open-second-brain.yaml`, `index.md`, `hot.md`, `log.md`, `identity/*`) retire. The operating manual content folds into `Brain/_BRAIN.md` (already present).
+- **Daily/ de-hardcoding**: the legacy `event_log_append` write path (`appendEvent` in `event-log.ts` that creates `Daily/<date>.md`) is removed entirely. The CLI verb `o2b append-event` retires (its replacement `o2b brain note` already ships and writes to `Brain/log/<today>.md`). User-side daily notes - whatever the operator names them - become configurable read-only inputs.
+- **`notes.read_paths` config**: new optional block in `_brain.yaml`:
+ ```yaml
+ notes:
+ read_paths:
+ - "Daily" # operator chooses any path or names
+ - "Journal"
+ # omit the block entirely if you do not keep daily notes
+ ```
+ `o2b brain scan-inline` and `o2b brain import-session` honour the list; default is empty (no scanning). Agents never write to these paths - the type is `read_paths` for a reason.
+- **Doctor / manifest cleanup**: remove every special-case mention of `AI Wiki/` and `Daily/`. Brain owns `Brain/`; nothing else is special. `doctor`'s vault-scope walker uses `vault.ignore_paths` (existing config) as the only exclusion mechanism.
+- **Migration**: `o2b brain upgrade` (already exists for similar tasks) gains a migration step that detects an existing `AI Wiki/payments/` tree and moves it under `Brain/payments/`. The legacy AI Wiki/ root is left in place if the operator put their own notes there - only Open-Second-Brain-managed files are removed.
+
+## Out of scope
+
+- Replacing `o2b brain note` (already the right tool; nothing to change).
+- Changing the Brain/ subdirectory layout itself (`inbox/`, `preferences/`, `retired/`, `log/`, `.snapshots/` stay byte-identical).
+- Replacing `Brain/_BRAIN.md` (already the operating manual; no rename).
+- Building a generic vault folder taxonomy or a multi-folder MOC system; the user can do whatever they like outside Brain/.
+- Removing `second_brain_query` (read-only vault page lister) - it serves a real purpose and is not coupled to AI Wiki/.
+
+## Chosen approach
+
+A single layered refactor across one PR. The atom layer is `src/core/pay-memory/paths.ts` plus the new `BrainNotesConfig` type. The hub is `src/core/init.ts` (vault bootstrap) and `_brain.yaml` schema. The helpers are `scan-inline`, `import-session`, `doctor`, `manifest`. The migration is one new pass in `src/core/brain/upgrade.ts`.
+
+No new abstractions: the existing `BrainConfig` already carries optional sub-blocks (`temporal:`, `link_graph:`, `discipline_report:`); `notes:` is one more. Pay Memory's `paths.ts` swaps a string constant. Migration is a deterministic file-mover plus a sidecar manifest entry so re-running is a no-op.
+
+## Design decisions
+
+- **Pay Memory under `Brain/payments/`, not its own root.** Brain is the agent-writable area; Pay Memory writes (receipts, asset notes, reports). Putting them under `Brain/` makes the write contract trivial: "the agent writes only under Brain/". A separate `Payments/` root would re-introduce the same "many top-level dirs" problem this refactor is solving.
+- **No `notes.write_paths` field.** The type carries the rule. If a future feature genuinely needs the agent to write to user-facing notes (`brain_capture` rebirth?), it is a separate design conversation, not a hidden expansion of this config.
+- **`notes.read_paths` defaults to empty, not to `["Daily"]`.** Hardcoding a default would silently re-introduce the same hardcoded path. Empty default means new vaults opt in.
+- **`event_log_append` and `appendEvent` are removed, not deprecated-with-shim.** Both have replacements that ship for years (`brain_note` MCP tool, `o2b brain note` CLI). A shim that writes `Daily/<date>.md` "for backward compatibility" would be a crutch and contradict the rule that the agent does not write to user-named notes.
+- **AI Wiki/ removal is irreversible for new vaults but non-destructive for old ones.** `o2b init` no longer creates AI Wiki/ at all. `o2b brain upgrade` moves only OSB-managed files out of an existing AI Wiki/, leaves the empty directory or any user-authored content alone. Operators reading the migration log see exactly which files moved.
+- **`Brain/_BRAIN.md` already exists** - no new operating manual file, no rename. The current `_OPEN_SECOND_BRAIN.md` template is deleted; its non-overlapping content gets folded into `Brain/_BRAIN.md` (one-paragraph headline + pointer to docs).
+- **Doctor's exclusion list shifts to one mechanism.** Today `doctor` has an in-code "deliberately do NOT pull in legacy AI Wiki/ or Daily/" comment block. After this refactor, the only exclusion is `vault.ignore_paths` (a config-driven list). No path is special by name.
+
+## File changes
+
+### Atoms and config
+
+- **Modify:** `src/core/brain/types.ts` - add `BrainNotesConfig { read_paths: ReadonlyArray<string> }` and slot it into `BrainConfig.notes?` + `ResolvedBrainConfig.notes`.
+- **Modify:** `src/core/brain/policy.ts` - add `BRAIN_NOTES_DEFAULTS` (empty), `resolveNotes(cfg)`, validator (`notes.read_paths` is an array of vault-relative non-empty strings; rejects absolute paths and `..` traversal).
+- **Modify:** `src/core/pay-memory/paths.ts` - swap `"AI Wiki"` constant for `posix.join("Brain", "payments")`.
+
+### Init / scaffolding
+
+- **Modify:** `src/core/init.ts` - drop the seven `AI Wiki/...` template registrations; bootstrap stops at `Brain/` (already handled by `o2b brain init`). The CLI verb `o2b init` now only writes the profile config + `.open-second-brain/` index dir.
+- **Delete:** `src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl` and `_open-second-brain.yaml.tpl` (move any unique content into `Brain/_BRAIN.md.tpl`).
+- **Modify:** `src/core/brain/templates/_BRAIN.md.tpl` - remove `Daily/` and `AI Wiki/` paragraphs; add a one-line pointer to the configurable `notes.read_paths` block (with one example name like `"Daily"` clearly framed as "if you keep daily notes, list their folder here").
+
+### Legacy event log removal
+
+- **Delete:** the `appendEvent` function in `src/core/event-log.ts` (writes `Daily/<date>.md`). The file retains only the redactor + path safety helpers if they are reused elsewhere; otherwise the file goes too.
+- **Delete:** the `o2b append-event` CLI verb (`src/cli/append-event.ts` or equivalent) and its tests.
+- **Modify:** `src/cli/main.ts` - drop the subcommand registration.
+
+### Migration
+
+- **Modify:** `src/core/brain/upgrade.ts` - add a new step: detect `<vault>/AI Wiki/payments/`, `policies/`, `assets/`, `drafts/`, `reports/`, `_pending/`; atomically move each into `<vault>/Brain/payments/`. Detect and remove the seven OSB-managed scaffolding files; leave anything else under `AI Wiki/` untouched. Idempotent via sidecar `Brain/.upgrade-history.json` entry.
+- **Modify:** `src/core/brain/upgrade.ts` - same step removes top-level `Daily/<date>.md` files that were authored by `appendEvent` (detected by a marker comment we wrote at the top). User-authored daily notes are recognised by the absence of that marker and are left alone.
+
+### Scan / import
+
+- **Modify:** `src/core/brain/inline-scan.ts` - resolve scan roots from `notes.read_paths`; default to empty (no work to do, no error).
+- **Modify:** `src/core/brain/sessions/import.ts` - same pattern for the legacy session-import path scanner if it used `Daily/`.
+
+### Doctor / manifest
+
+- **Modify:** `src/core/brain/doctor.ts` - drop the AI Wiki/ + Daily/ exclusion paragraph; the only exclusion mechanism is `vault.ignore_paths`.
+- **Modify:** `src/core/brain/manifest.ts` - same cleanup.
+- **Modify:** `src/core/path-safety.ts` - the safety helper no longer needs the `AI Wiki/` allow-list.
+
+### MCP
+
+- **Modify:** `src/mcp/tools.ts` - drop the `event_log_append` historical comment block; rewrite the `second_brain_query` description to remove the AI Wiki framing.
+- **Modify:** `src/mcp/instructions.ts` - remove AI Wiki / Daily references.
+- **Modify:** `src/mcp/brain-tools.ts` - drop the `Daily/` fallback comment in `brain_note`'s docstring.
+
+### Tests
+
+- 24 tests touch `"AI Wiki"` or `"Daily/"`. Each one either:
+ - Updates expected paths from `AI Wiki/payments/...` to `Brain/payments/...`.
+ - Drops the test entirely if it covered the deleted `event_log_append` or `o2b append-event`.
+ - Adds a new test under `tests/core/brain/upgrade-aiwiki-migration.test.ts` that exercises the migration step.
+- New test: `tests/core/brain/notes-config.test.ts` covers the config block validator, defaults, and the `read_paths`-driven `scan-inline` resolution.
+
+### Docs
+
+- **Modify:** `README.md` - drop the `AI Wiki/` and `Daily/` mentions, including the line about `Brain/`, `AI Wiki/`, `Daily/` in the top features table row 1.
+- **Modify:** `docs/how-it-works.md` - rewrite the vault layout diagram (only `Brain/` + the derived index dir + an optional user-notes section); rewrite "Capture surfaces" so that "Inline" reads from `notes.read_paths` and stops naming `Daily/`.
+- **Modify:** `docs/pay-memory.md` - swap every `AI Wiki/...` path for `Brain/payments/...`.
+- **Modify:** `docs/cli-reference.md` - update the Pay Memory verb descriptions and the `init-pay-memory` command's docstring; drop `o2b append-event` from the helper section.
+- **Modify:** `docs/architecture.md` - drop AI Wiki/ and Daily/ from the layer diagram if mentioned.
+- **Modify:** `docs/mcp.md` - drop AI Wiki/notes/ from the `second_brain_query` description; drop the historical `event_log_append` references.
+- **Modify:** `install/prerequisites.md` - update the "what gets created in your vault" section.
+
+### Release
+
+- **Modify:** `package.json` - version `0.11.0` (breaking change).
+- **Modify:** `CHANGELOG.md` - one `[0.11.0]` entry summarising: removed AI Wiki/, removed Daily/ hardcoding, moved Pay Memory to Brain/payments/, removed `event_log_append` / `o2b append-event`, added `notes.read_paths` config, `o2b brain upgrade` migrates existing installations.
+- **Modify:** runtime manifests via `bun run sync-version`.
+
+## Risks and open questions
+
+- **Existing operators with custom content under `AI Wiki/`.** The migration moves only OSB-managed files; anything user-authored stays. Documented in the `[0.11.0]` CHANGELOG entry and the post-update doctor warning.
+- **Hermes / Claude Code / Codex plugins on older versions might still reference the retired MCP tool names.** The MCP server itself drops the registrations; clients that call `event_log_append` or `second_brain_capture` get a clean tool-not-found error, not a silent no-op. The corresponding tool was already removed from the surface in v0.10.8; this PR removes the now-dead historical comments and the internal `appendEvent` function it documented.
+- **`o2b brain upgrade` idempotency under partial failure.** If the migration crashes mid-move, re-running picks up where it left off via the sidecar manifest. A pre-run snapshot already covers full rollback.
+- **Naming `Brain/payments/` vs `Brain/pay/`.** Going with `payments/` (more explicit, matches the existing subdir name under AI Wiki/, eases the migration mental model).
+- **Should `notes.read_paths` accept globs (`Daily/*.md`)?** No. Each entry is a directory; the scanner walks it. Globs add complexity without solving a real need - if the operator wants to exclude files, `vault.ignore_paths` already exists.
+- **Backward compatibility for users still running `o2b append-event` from a shell script.** The verb is removed; the script breaks loudly with "unknown subcommand". Better than silently writing to a path the agent contract forbids.
diff --git a/docs/brainstorm/brain-centric-layout/plan.md b/docs/brainstorm/brain-centric-layout/plan.md
new file mode 100644
index 00000000..aef688ca
--- /dev/null
+++ b/docs/brainstorm/brain-centric-layout/plan.md
@@ -0,0 +1,99 @@
+# Brain-centric layout - implementation plan
+
+Order matters - the atom layer (config + path constants) must land before the helpers (init / pay-memory / scan-inline) that depend on it. Each task lands on `feat/brain-centric-layout` as a separate conventional commit on top of the brainstorm commit.
+
+## Tasks
+
+### Task 1: `notes` config block + atom types
+
+- **Files**: `src/core/brain/types.ts` (modified - add `BrainNotesConfig` + `ResolvedBrainNotesConfig`, slot `notes?` into `BrainConfig` + `notes` into `ResolvedBrainConfig`), `src/core/brain/policy.ts` (modified - add `BRAIN_NOTES_DEFAULTS = { read_paths: [] }`, `resolveNotes(cfg)`, validator), `tests/core/brain/notes-config.test.ts` (new).
+- **Acceptance**:
+ - `BrainNotesConfig.read_paths` is `ReadonlyArray<string>`, frozen.
+ - Absent block resolves to defaults (empty array).
+ - Validator rejects: non-array `read_paths`, non-string entries, empty strings, absolute paths (starts with `/`), parent-traversal (`..` segment anywhere).
+ - Tests cover happy path, defaults fallback, every rejection branch.
+- **Depends on**: none.
+
+### Task 2: Pay Memory path migration constant
+
+- **Files**: `src/core/pay-memory/paths.ts` (modified - swap root constant from `"AI Wiki"` to `posix.join("Brain", "payments")`; the sub-roots `policies/`, `assets/`, `drafts/`, `reports/`, `_pending/`, and the dated `YYYY-MM-DD/` receipt subdir become `Brain/payments/<sub>/`), `tests/core/pay-memory/paths.test.ts` (modified - update all expected paths).
+- **Acceptance**:
+ - Every Pay Memory write path resolves under `<vault>/Brain/payments/`.
+ - No file in `src/core/pay-memory/` references the literal `"AI Wiki"` after the change.
+ - Existing Pay Memory tests pass against the new paths after fixture updates.
+- **Depends on**: none.
+
+### Task 3: Init no longer scaffolds AI Wiki/
+
+- **Files**: `src/core/init.ts` (modified - drop the seven `AI Wiki/...` template registrations, drop the corresponding `relPath` blocks, drop the `agent-name` rewrite branch that targets `AI Wiki/identity/agents.md`), `src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl` (deleted), `src/core/brain/templates/_open-second-brain.yaml.tpl` (deleted if present), `src/core/brain/templates.ts` (modified - drop template registry entries for the deleted files), `tests/core/init.test.ts` (modified - update the expected scaffolding list).
+- **Acceptance**:
+ - `o2b init --vault <path>` writes the profile config + creates `.open-second-brain/` index dir only. No `<vault>/AI Wiki/` is created.
+ - `o2b brain init --vault <path>` continues to bootstrap `<vault>/Brain/` as before (no change there).
+ - Init tests verify the absence of `AI Wiki/` after a fresh init.
+- **Depends on**: none (independent of Tasks 1, 2).
+
+### Task 4: `_BRAIN.md` operating-manual cleanup
+
+- **Files**: `src/core/brain/templates/_BRAIN.md.tpl` (modified).
+- **Acceptance**:
+ - Removes the `AI Wiki/` and `Daily/` paragraphs from the template.
+ - Adds a one-line pointer: `For user-authored notes (daily journal, weekly notes, etc.), declare their folders under `notes.read_paths` in `_brain.yaml`; the agent only reads from those paths.`
+ - Snapshot test or golden-file test verifies the new template content matches expectations.
+- **Depends on**: Task 1 (config block must exist to reference).
+
+### Task 5: Remove legacy `event_log_append` write path
+
+- **Files**: `src/core/event-log.ts` (deleted if the file's only purpose was `appendEvent`; otherwise modified to remove `appendEvent` + the `Daily/<date>.md` writer + the redactor if unused), `src/cli/append-event.ts` (deleted), `src/cli/main.ts` (modified - drop the `append-event` subcommand registration), `tests/cli/append-event.test.ts` (deleted), `tests/core/event-log.test.ts` (deleted or trimmed).
+- **Acceptance**:
+ - `o2b append-event` is no longer a registered subcommand; running it exits with the standard "unknown command" message and exit code 2.
+ - The MCP `event_log_append` tool was already removed in v0.10.8; this task removes the dead `appendEvent` internal helper plus the historical comment blocks pointing at it (`src/mcp/tools.ts:21,166,236`, `src/openclaw/index.ts:11,28,218`, `src/core/brain/types.ts:195`, `src/mcp/brain-tools.ts:366`).
+ - Typecheck and lint pass.
+- **Depends on**: none.
+
+### Task 6: `scan-inline` honours `notes.read_paths`
+
+- **Files**: `src/core/brain/inline-scan.ts` (modified - resolve scan roots from `ResolvedBrainConfig.notes.read_paths`; default empty list = no work, exit 0 with a stderr note), `tests/core/brain/inline-scan.test.ts` (modified - add cases for: empty config, single read_path, multiple read_paths, read_path that does not exist on disk, ignore_paths inside a read_path).
+- **Acceptance**:
+ - With no `notes:` block, `o2b brain scan-inline` exits 0 and writes nothing.
+ - With `notes.read_paths: ["Daily"]`, the scanner walks `<vault>/Daily/` and captures `@osb` markers as before.
+ - With multiple paths, every listed root is walked.
+ - `vault.ignore_paths` is honoured for each root.
+- **Depends on**: Task 1.
+
+### Task 7: Doctor + manifest + path-safety cleanup
+
+- **Files**: `src/core/brain/doctor.ts` (modified - drop the `AI Wiki/` / `Daily/` exclusion comment block, rely on `vault.ignore_paths`), `src/core/brain/manifest.ts` (modified - same), `src/core/path-safety.ts` (modified - drop the `AI Wiki/` allow-list if present), `src/mcp/tools.ts` (modified - rewrite `second_brain_query`'s description to remove the `AI Wiki/notes/` framing), `src/mcp/instructions.ts` (modified - remove `AI Wiki/` and `Daily/` references), `src/mcp/brain-tools.ts` (modified - drop the `Daily/` fallback comment in `brain_note`'s docstring), `tests/core/brain/doctor.test.ts` + `tests/core/brain/manifest.test.ts` + `tests/core/path-safety.test.ts` (modified - update expected exclusions to be `vault.ignore_paths` only).
+- **Acceptance**:
+ - No source file under `src/` contains a hardcoded `"AI Wiki"` or `"Daily/"` string after this task (except the upgrade migration in Task 8, which uses them as detection inputs).
+ - Doctor and manifest tests pass with `vault.ignore_paths` as the only exclusion mechanism.
+- **Depends on**: Task 2 (Pay Memory already off `AI Wiki/`), Task 3 (init already off `AI Wiki/`), Task 5 (no more `Daily/`-writer).
+
+### Task 8: Migration in `brain upgrade`
+
+- **Files**: `src/core/brain/upgrade.ts` (modified - new step `migrateLegacyLayout(vault, dryRun)`), `src/core/brain/upgrade-migrations/legacy-aiwiki-payments.ts` (new - moves `<vault>/AI Wiki/{payments,policies,assets,drafts,reports,_pending}/**` to `<vault>/Brain/payments/<same>/**`), `src/core/brain/upgrade-migrations/legacy-aiwiki-scaffolding.ts` (new - removes the seven OSB-managed scaffolding files: `_OPEN_SECOND_BRAIN.md`, `_open-second-brain.yaml`, `index.md`, `hot.md`, `log.md`, `identity/user.md`, `identity/agents.md`; leaves the empty `AI Wiki/` directory if nothing else is in it; leaves any user-authored content alone), `src/core/brain/upgrade-migrations/legacy-daily-event-log.ts` (new - removes top-level `Daily/<date>.md` files whose first line matches the `appendEvent` marker comment; user-authored daily notes without that marker are left alone), `tests/core/brain/upgrade-aiwiki-migration.test.ts` (new - covers Pay Memory move, scaffolding removal, daily-event-log removal, user-content preservation, idempotency).
+- **Acceptance**:
+ - Running `o2b brain upgrade --apply` on a v0.10.x vault moves every OSB-managed file into the new location, removes the scaffolding, and leaves user-authored content untouched.
+ - Re-running on a migrated vault is a no-op (no log entry, no snapshot, idempotent via sidecar manifest entry).
+ - `--dry-run` reports the planned moves and removals without writing.
+ - A pre-run snapshot is taken before any move (existing `brain upgrade` behaviour).
+ - Post-migration doctor reports clean (no `AI Wiki/payments/` left, no `Daily/<date>.md` written by `appendEvent` left).
+- **Depends on**: Tasks 2, 3, 5 (these define the new layout the migration moves to).
+
+### Task 9: Docs update
+
+- **Files**: `README.md`, `docs/how-it-works.md`, `docs/pay-memory.md`, `docs/cli-reference.md`, `docs/architecture.md`, `docs/mcp.md`, `install/prerequisites.md`, `install/hermes.md` and any other `install/*.md` that names `AI Wiki/` or `Daily/`.
+- **Acceptance**:
+ - `grep -rE 'AI Wiki|/Daily/' README.md docs/ install/ skills/` returns zero matches outside `docs/plans/`, `docs/brainstorm/`, and `docs/legacy-skills/`.
+ - The `docs/how-it-works.md` vault layout shows only `Brain/` + `.open-second-brain/` + an optional `notes.read_paths` example pointing at any folder the operator names.
+ - `docs/pay-memory.md` uses `Brain/payments/...` paths throughout.
+ - Per the "no legacy framing in public docs" rule, the README + docs read as if this layout has always been the design; migration framing lives only in CHANGELOG and the brainstorm folder.
+- **Depends on**: all earlier tasks complete.
+
+### Task 10: Version bump + CHANGELOG
+
+- **Files**: `package.json` (version `0.11.0`), runtime manifests via `bun run sync-version`, `CHANGELOG.md`.
+- **Acceptance**:
+ - Major-minor bump to `0.11.0` (breaking change: removed `o2b append-event`, removed `event_log_append` MCP tool's last vestiges, Pay Memory paths changed).
+ - `CHANGELOG.md` carries a single `[0.11.0]` entry listing: removed AI Wiki/, removed Daily/ hardcoding, moved Pay Memory to Brain/payments/, removed legacy event log, added `notes.read_paths`, migration via `o2b brain upgrade`.
+ - `bun run sync-version` mirrors the version to every runtime manifest.
+- **Depends on**: Tasks 1-9.
diff --git a/docs/brainstorm/operational-friction-reduction/design.md b/docs/brainstorm/operational-friction-reduction/design.md
new file mode 100644
index 00000000..ca1d706d
--- /dev/null
+++ b/docs/brainstorm/operational-friction-reduction/design.md
@@ -0,0 +1,104 @@
+# Operational friction reduction - one update command, weekly trend visibility, deeper transcript probes
+
+**Status:** shipped (v0.10.12)
+**Shipped:** v0.10.12 (2026-05-20)
+**Author:** Sisyphus (via brainstorming)
+**Audience:** implementation
+
+## Problem statement
+
+Two pain points in daily Open Second Brain operation:
+
+1. **Manual per-runtime update on every release.** Operator runs five to seven steps per machine to update the Open Second Brain installation across all runtimes (Claude Code, Codex, Hermes, Cursor, ...). Error-prone and tedious.
+2. **No trend visibility.** The daily discipline report gives a single-day snapshot. There is no understanding of "how the agent learns over a week" - confidence trends, agent engagement quality, rule adoption patterns.
+
+A third papercut surfaced during scoping: the Cursor transcript probe uses mtime only, so the discipline report cannot say how many sessions or messages happened. And a fourth: double-clicking a node in `o2b brain explorer` does nothing - the operator has to context-switch into Obsidian by hand to inspect the underlying preference file.
+
+## Scope
+
+Four features, one PR, one release (v0.10.12):
+
+| # | Feature | Priority |
+|---|---------|----------|
+| 1 | `o2b update` CLI verb | Primary |
+| 2 | Weekly Brain digest (`--window 7d`) | Primary |
+| 3 | Cursor SQLite deep parsing | Companion |
+| 4 | Obsidian deep-link in explorer | Companion |
+
+## Out of scope
+
+- Window-triggers for Hermes cron (§25). Weekly digest relies on standard cron; if the VPS is offline during the Monday window, the digest is skipped. Window-trigger support (fire-on-next-boot-after-missed-window) is Hermes-side, not Open Second Brain core. Tracked separately.
+- `--scope project` for Cursor / opencode / kiro. Already deferred, trigger not met.
+- Live-refresh in explorer (SSE / WS). Already deferred, trigger not met.
+- Obsidian deep-link in export mode. Static export cannot provide the vault path; deep-link is live-mode only. If operators later request deep-link in exported HTML, an `--vault-path` flag at export time can opt in. Trigger: explicit request.
+
+## Chosen approach
+
+All four features layer on top of existing machinery; no new adapter interface, no new core abstraction.
+
+- **`o2b update`** is orchestration over the existing `InstallAdapter` pipeline (`detect -> plan -> apply -> verify`). A new additive `payload_hash` field in each runtime's `install.lock.json` lets the orchestrator skip targets whose payload has not changed.
+- **Weekly digest** reuses `o2b brain digest` with a parameterised window; the existing 24h default stays untouched. A new agent-quality summary section reads `Brain/log/<date>.md` plus the JSONL sidecar for the configured window. A second Hermes cron job (`osb-weekly-brain-digest`) delivers it on Mondays.
+- **Cursor SQLite parsing** replaces the mtime-only probe with a `bun:sqlite` read against `state.vscdb`. Any failure (schema drift, locked DB, missing table) falls back to mtime and logs a single stderr warning. No new dependencies.
+- **Explorer deep-link** is a ~30-line client-side handler that builds `obsidian://open?path=<absolute>` on double-click. The live HTTP server passes the absolute vault path through a new `__VAULT_PATH__` template placeholder; export mode keeps the placeholder empty and the handler is a no-op.
+
+## Design decisions
+
+- **Reuse InstallAdapter machinery entirely.** No new adapter interface, no new registry. The update logic is orchestration over existing `detect / plan / apply / verify`.
+- **Payload comparison via sidecar manifest.** `install.lock.json` already stores `applied_at`, `operation`, `owned_keys`, `owned_paths`. Extending it with `payload_hash` (sha256 of canonical `McpPayload` JSON) is backward-compatible: entries without the hash are treated as "unknown - apply on first update run", and the hash is written after the first successful update.
+- **Sequential, not parallel.** Runtimes share filesystem state (the vault, the skill symlinks). Sequential execution avoids race conditions; total time is still sub-second for most setups.
+- **`--force` bypasses payload-hash check.** Useful when the operator knows the payload changed but the hash did not (e.g. an env-variable update that does not affect the `McpPayload` struct but does affect runtime behaviour).
+- **`--window` not `--weekly`.** More general - the operator can request any window (`7d`, `14d`, `30d`). `--weekly` would lock the API into a boolean.
+- **Agent quality belongs in digest, not discipline.** Discipline answers "is the agent writing to Brain at all". Digest answers "what changed in Brain". The agent-quality summary references confirmed / retired rules, not just event counts, so digest is the right home.
+- **`bun:sqlite` only for Cursor.** Already in the stack. No new dependencies.
+- **`path=` not `vault=` for the Obsidian link.** `obsidian://open?path=<absolute>` works regardless of how the vault is registered in Obsidian. `vault=<name>` requires the registered name to match the directory basename, which is often not true.
+- **Silent fallback in the explorer.** If `window.open` does not trigger Obsidian (not installed, blocked by browser), copy the absolute path to the clipboard and show a brief tooltip. No modal dialogs.
+
+## File changes
+
+### Feature 1 - `o2b update`
+
+- **New:** `src/cli/update.ts` - CLI verb handler, arg parsing, orchestration loop.
+- **New:** `src/core/install/update.ts` - core update logic (detect -> plan -> compare -> apply -> verify).
+- **New:** `tests/cli/update.test.ts`, `tests/core/install/update.test.ts`.
+- **Modify:** `src/cli/main.ts` - register `update` subcommand.
+- **Modify:** `CHANGELOG.md` - v0.10.12 entry.
+
+Exit codes: `0` all targets updated or already up-to-date; `1` runtime error; `2` usage error; `3` `--check` found drift after update; `4` user-modified-block conflict (use `--force`).
+
+### Feature 2 - Weekly Brain digest
+
+- **Modify:** `src/core/brain/digest.ts` - accept `windowDays` in `RenderDigestOptions`; adjust the `since` calculation; add the agent-quality summary section to both Markdown and JSON output.
+- **Modify:** `src/cli/brain/verbs/digest.ts` - parse `--window`.
+- **Modify:** `bin/o2b-discipline-report` - accept `--window`, route to `o2b brain digest --window` when set.
+- **Modify:** `src/cli/discipline-install.ts` - add `--weekly` to the install verb.
+- **New:** `src/core/brain/digest-agent-summary.ts` - pure read over `Brain/log/`.
+- **New:** `tests/core/brain/digest-window.test.ts`, `tests/core/brain/digest-agent-summary.test.ts`.
+- **Modify:** `CHANGELOG.md`.
+
+Window parser accepts `Nd` (positive integer + `d`) and bare `N`. Invalid format or non-positive values exit `2` with an error message.
+
+### Feature 3 - Cursor SQLite deep parsing
+
+- **Modify:** `src/core/discipline/transcripts/cursor.ts` - replace the mtime probe with SQLite parsing.
+- **Modify:** `src/core/discipline/transcripts/types.ts` - extend `TranscriptRuntime` return type with session and message counts.
+- **Modify:** `src/core/discipline/transcripts/index.ts` - handle the new result shape.
+- **New:** `tests/core/discipline/transcripts/cursor-sqlite.test.ts`.
+- **Modify:** `CHANGELOG.md`.
+
+Query pattern: `SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'` against `state.vscdb`. Errors and unexpected JSON shapes fall back to mtime with a single stderr warning.
+
+### Feature 4 - Obsidian deep-link in explorer
+
+- **Modify:** `src/core/brain/explorer.ts` - pass `vaultPath` to the template in live-server mode only.
+- **Modify:** `templates/brain-explorer.html` - add `__VAULT_PATH__` placeholder plus the double-click handler.
+- **New:** `tests/core/brain/explorer-deeplink.test.ts`.
+- **Modify:** `CHANGELOG.md`.
+
+Path construction: `<vaultPath>/Brain/preferences/pref-<id>.md` URI-encoded into `obsidian://open?path=...`. Export mode leaves `__VAULT_PATH__` empty and the handler short-circuits.
+
+## Risks and open questions
+
+- Cursor's `state.vscdb` schema is private to the vendor and may change between versions. Mitigated by an aggressive fall-back to mtime on any error. Operators on older or newer Cursor builds see the same behaviour as before the change, plus one stderr warning.
+- `payload_hash` is sha256 of canonical JSON, but the canonicalisation routine has to be deterministic across Bun versions. Tests pin the canonical form (key sort + no whitespace) against a fixed expected hash.
+- Weekly cron silently skips runs when the host is offline (no window-trigger). Documented in §25 deferred work; the agent-quality summary itself is resilient to missing log days.
+- Obsidian deep-link relies on the OS having Obsidian installed and the `obsidian://` URI scheme registered. The silent clipboard fallback covers headless servers and locked-down workstations.
diff --git a/docs/brainstorm/operational-friction-reduction/plan.md b/docs/brainstorm/operational-friction-reduction/plan.md
new file mode 100644
index 00000000..66d4fe06
--- /dev/null
+++ b/docs/brainstorm/operational-friction-reduction/plan.md
@@ -0,0 +1,59 @@
+# Operational friction reduction - implementation plan
+
+Four atomic tasks, one feature each. Order does not matter beyond the version bump being last - the features are independent and each tasks lands as a separate conventional commit on `feat/operational-friction-reduction`.
+
+## Tasks
+
+### Task 1: `o2b update` CLI verb
+
+- **Files**: `src/cli/update.ts` (new), `src/core/install/update.ts` (new), `tests/cli/update.test.ts` (new), `tests/core/install/update.test.ts` (new), `src/cli/main.ts` (modified - register subcommand), `CHANGELOG.md` (modified).
+- **Acceptance**:
+ - `o2b update` detects every installed runtime via `adapter.detect(env)`, generates the current `McpPayload`, compares against the `payload_hash` field in `install.lock.json`, and applies only where the hash differs (or `--force` is set).
+ - `--target <name>` runs the same loop against a single runtime.
+ - `--dry-run` prints the planned per-target action (`up-to-date | apply | force-apply | skip`) without writing anything.
+ - `--json` emits a structured envelope `{targets: [{name, status, reason?, error?}], exit_code}`.
+ - Sequential per-target execution; failure on one target reports the error and continues with the next, returning the worst exit code across all targets.
+ - Exit codes: `0` all targets updated or already up-to-date; `1` runtime error; `2` usage error; `3` `--check` found drift after update; `4` user-modified-block conflict.
+ - Lock-file migration is backward-compatible: an entry without `payload_hash` is treated as "unknown - apply on first run" and the hash is written after the first successful apply.
+- **Depends on**: none.
+
+### Task 2: Weekly Brain digest
+
+- **Files**: `src/core/brain/digest.ts` (modified - `windowDays` option, agent-quality summary), `src/cli/brain/verbs/digest.ts` (modified - `--window` parsing), `bin/o2b-discipline-report` (modified - `--window` flag), `src/cli/discipline-install.ts` (modified - `--weekly` flag), `src/core/brain/digest-agent-summary.ts` (new), `tests/core/brain/digest-window.test.ts` (new), `tests/core/brain/digest-agent-summary.test.ts` (new), `CHANGELOG.md` (modified).
+- **Acceptance**:
+ - `o2b brain digest` without `--window` produces byte-identical output to the previous release (24h default unchanged).
+ - `--window 7d` (and bare `--window 7`) renders the 7-day digest with the same section list plus the agent-quality summary.
+ - Window parser accepts `Nd` and bare `N` for positive integers; invalid format or non-positive values exit `2` with a clear error.
+ - Agent-quality summary lists per-agent: total brain-event count, breakdown by event type, count of confirmed rules in the window where this agent first applied evidence, count of retired rules in the window traceable to this agent's signals.
+ - Graceful degradation: missing `Brain/log/<date>.md` files inside the window are skipped silently; the digest still renders with available data.
+ - `o2b discipline install --weekly --telegram-target <target> --at "59 8 * * 1"` registers a second Hermes cron job (`osb-weekly-brain-digest`) separate from the daily discipline report.
+- **Depends on**: none.
+
+### Task 3: Cursor SQLite deep parsing
+
+- **Files**: `src/core/discipline/transcripts/cursor.ts` (modified - replace mtime probe), `src/core/discipline/transcripts/types.ts` (modified - extend `TranscriptRuntime` return type), `src/core/discipline/transcripts/index.ts` (modified - handle the new shape), `tests/core/discipline/transcripts/cursor-sqlite.test.ts` (new), `CHANGELOG.md` (modified).
+- **Acceptance**:
+ - Cursor's `state.vscdb` is opened via `bun:sqlite`, queried with `SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'`, and the JSON `value` is parsed to extract session timestamps + message count per session for the day window.
+ - Return type carries `session_count` and `message_count` aggregates.
+ - Any SQL error (locked DB, missing table, unexpected JSON shape) falls back to the previous mtime-only behaviour and logs a single stderr warning prefixed with `cursor-sqlite:`.
+ - No changes to Claude Code or Codex transcript resolvers.
+- **Depends on**: none.
+
+### Task 4: Obsidian deep-link in explorer
+
+- **Files**: `src/core/brain/explorer.ts` (modified - pass `vaultPath` to template in live-server mode), `templates/brain-explorer.html` (modified - `__VAULT_PATH__` placeholder + double-click handler), `tests/core/brain/explorer-deeplink.test.ts` (new), `CHANGELOG.md` (modified).
+- **Acceptance**:
+ - In live mode, double-clicking a canvas node or a listbox item builds `obsidian://open?path=<encodeURIComponent(vaultPath + "/Brain/preferences/pref-<id>.md")>` and calls `window.open(uri, "_blank")`.
+ - If `window.open` returns falsy (browser blocked, no Obsidian protocol handler), the handler copies the absolute path to the clipboard and shows a brief tooltip "Obsidian not detected - path copied".
+ - Export mode leaves `__VAULT_PATH__` substituted with an empty string and the handler short-circuits.
+ - Template substitution is covered by a unit test against the rendered HTML (no browser automation needed).
+- **Depends on**: none.
+
+### Task 5: Version bump + CHANGELOG consolidation
+
+- **Files**: `package.json`, runtime manifests via `bun run sync-version`, `CHANGELOG.md`.
+- **Acceptance**:
+ - `package.json` version `0.10.12`.
+ - `bun run sync-version` mirrors the version to every runtime manifest.
+ - `CHANGELOG.md` carries a single `[0.10.12]` entry that lists the four features.
+- **Depends on**: Task 1, Task 2, Task 3, Task 4.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
new file mode 100644
index 00000000..22506afd
--- /dev/null
+++ b/docs/cli-reference.md
@@ -0,0 +1,134 @@
+# CLI reference
+
+The full set of `o2b` verbs. After `o2b install-cli` they are on PATH; the local checkout can also be used without installing the symlinks by running commands through `scripts/o2b` and `scripts/vault-log`.
+
+Most verbs accept `--vault <path>` and `--config <path>`; the values default to the active profile from `o2b init`. JSON output is available via `--json` on every read verb.
+
+## Core
+
+```text
+o2b status Show config / vault status
+o2b init Bootstrap the vault profile (idempotent)
+o2b init --interactive Guided first-time setup wizard
+o2b install-cli Symlink o2b and o2b-hook into ~/.local/bin
+o2b doctor Run vault + adapter checks
+o2b index Rebuild the Markdown page index
+o2b export-config Write a redacted config snapshot
+o2b mcp Run the MCP tool server (stdio)
+o2b tool-call Invoke an MCP tool handler from the CLI
+o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks
+o2b update Update Open Second Brain across all detected runtimes; --target <name> / --dry-run / --force / --json
+```
+
+## Brain (observing memory)
+
+```text
+o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set
+o2b brain feedback Record one taste signal (--topic, --signal, --principle, ...)
+o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
+o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
+o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
+o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback
+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 Open-Second-Brain-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; drift abort vs --force-rollback)
+o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes
+o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])
+o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode).
+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 folders listed under `notes.read_paths` in _brain.yaml
+o2b brain import-session Replay signals from a Claude / Codex / Hermes session .jsonl (or directory)
+o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
+```
+
+### Time axis (since v0.10.18)
+
+```text
+o2b brain timeline Chronological event list; filter by --pref-id / --topic / --kind / --since / --until / --limit
+o2b brain evolution Per-preference or per-topic belief evolution with running evidence counts, walks supersedes / superseded_by retire chains
+o2b brain stale Structural staleness report (preferences / signals / log files) using configurable per-kind thresholds
+o2b brain daily Daily brief: counters, transitions, source pointers
+o2b brain weekly 7-day synthesis with contradictions list (signal-suppressed events + apply-evidence violated rows)
+```
+
+### Maintenance and operator surfaces
+
+```text
+o2b brain actions Ranked next-step list combining doctor / dream warnings and lint candidates
+o2b brain summary Operator dashboard - trust verdict (clean | watch | investigate), doctor / dream counts, verification delta, instruction-file ceiling warnings, top maintenance actions
+o2b brain page-dedup Page-level duplicate detector (by content hash + frontmatter similarity)
+o2b brain lint Self-healing structural drift fixer; --consolidate folds multi-source duplicates
+o2b brain token-footprint Token-budget monitor across instruction files and active.md
+o2b brain context-pack Bounded-token vault slice for priming an agent's context window (--max-tokens N)
+o2b brain synthesise Concept-scoped JSON envelope: target node + linkers + optional unlinked mentions
+o2b brain moc-audit Per-MOC coverage audit: classify cluster members into well-covered / fragile / candidate-missing
+o2b brain unlinked Raw-text mentions outside `[[...]]` (Unicode-aware boundaries)
+```
+
+## Vault scope
+
+Single exclusion policy for every vault walker.
+
+```text
+o2b vault status Walks the vault under the active policy; reports include / exclude counts and which rules fired
+o2b vault inspect <relpath> Point-check one vault-relative path; reports matched rule, source, and whether the path exists on disk
+```
+
+## Discipline (daily logging cron)
+
+```text
+o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime activity); status ok | info | alert
+o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digest
+o2b discipline uninstall Remove the cron job; --weekly removes only the weekly digest, without flag removes both
+```
+
+See [`hermes-cron.md`](hermes-cron.md) for the cron envelope and Telegram delivery shape.
+
+## Pay Memory
+
+```text
+o2b init-pay-memory Bootstrap Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)
+o2b append-payment-receipt Save a Markdown receipt for a paid API call
+o2b capture-asset Save a Markdown note for a generated asset
+o2b payment-report Aggregate a date's receipts into a Markdown report
+o2b check-payment-policy Evaluate a paid call against policies/spending.json
+o2b request-payment-approval Create a pending payment request (human must approve)
+o2b approve-payment-request Mark a pending request as approved
+o2b reject-payment-request Mark a pending request as rejected
+o2b consume-payment-request Link an approved request to its resulting receipt
+o2b list-pending-payments List pending / approved / etc. requests
+o2b payment-digest Render a 4-line digest for a date
+```
+
+Full Pay Memory walkthrough: [`pay-memory.md`](pay-memory.md).
+
+## Search
+
+```text
+o2b search "<query>" FTS5 full-text search across the vault
+ --property type=decision --property status=open
+ filters on frontmatter scalars (post-FTS phase)
+ --json for structured output
+o2b search reindex Rebuild the SQLite + FTS5 index from scratch
+```
+
+## Helpers
+
+```text
+o2b-hook Internal launcher invoked by hooks/hooks.json (Claude Code & Codex)
+vault-log Shell mirror of brain_note (one-liner narrative milestones)
+```
+
+## Conventions
+
+- Every CLI mutation that touches Brain takes a pre-run snapshot under `Brain/.snapshots/` with a SHA-256 sidecar manifest. `o2b brain rollback` aborts on drift unless `--force-rollback`.
+- `o2b ... --json` exists on every read verb and most write verbs (the JSON payload mirrors the MCP tool's response shape).
+- `--dry-run` is supported by every mutating verb that touches more than a single file (`brain merge`, `brain rollback`, `brain upgrade`, `brain import-claude-memory`, `update`, ...).
+- `--vault` always overrides the profile path; useful for multi-vault hosts where the config-resolved default is not the right target.
diff --git a/docs/hermes-cron.md b/docs/hermes-cron.md
index 45e78bbd..f50c1472 100644
--- a/docs/hermes-cron.md
+++ b/docs/hermes-cron.md
@@ -56,7 +56,7 @@ hermes cron remove pay-memory-daily-digest
💳 Оплачено сервисов: **2**
💰 Сумма: **0.07 USDC**
📁 Файлы чеков: **2**
-🔗 Отчёт: `/root/vault/AI Wiki/reports/payment-report-2026-05-09.md`
+🔗 Отчёт: `/root/vault/Brain/payments/reports/payment-report-2026-05-09.md`
```
When there were no receipts the day before, the literal token `[SILENT]` is emitted (or empty / a one-line summary, per `--empty-mode`).
@@ -119,7 +119,7 @@ hermes cron remove brain-digest-daily
## Confirmed
-- [[pref-prefer-typed-errors]] — coding, first applied in [[Daily/2026.05.14]]
+- [[pref-prefer-typed-errors]] — coding, first applied in [[src/cli/main.ts]]
## Retired
@@ -141,3 +141,25 @@ When `--silent-if-empty` is set and the window has no changes, the command write
```
`dream` is itself idempotent — running it on top of an unchanged Brain is a no-op (no log entry written, no snapshot taken). The chained form is safe at any cadence.
+
+## Discipline report (daily logging-discipline sanity-check)
+
+`o2b discipline report` renders a deterministic Telegram MarkdownV2 block comparing brain-event counts per agent (parsed from `Brain/log/<yesterday>.md`) against runtime-agnostic activity proxies (git on watched repos + mtime walk on watched non-repo paths + vault delta on `Brain/inbox|preferences|retired/`). Status is binary - `alert` if taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero, `info` for a quiet day, `ok` otherwise. No LLM in the report path.
+
+`o2b discipline install --vault <v> --telegram-target <target>` writes one cron entry into the Hermes scheduler (job id derived from `sha256(vault)` so multiple vaults on one host do not collide). The configuration block lives in `Brain/_brain.yaml`:
+
+```yaml
+discipline_report:
+ enabled: true
+ timezone: "Europe/Belgrade"
+ watched_paths:
+ - "/srv/projects/open-second-brain"
+ - "/root/.hermes/plugins"
+ known_agents:
+ - "@claude-vps-agent"
+ - "@codex-vps-agent"
+```
+
+When the section is absent or `enabled: false`, the report exits `0` with a stderr note and the cron job stays silent.
+
+A weekly digest variant ships under `--weekly` (Monday 08:59 local timezone by default); `o2b discipline uninstall --weekly` removes only the weekly job, without the flag removes both.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 85e0e036..d041699a 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -22,13 +22,14 @@ no surprise, no hallucinated memory.
## Vault layout
-The vault holds three top-level agent-facing directories. Brain owns
-its own, plus a sibling derived-index directory.
+The agent owns one top-level directory in the vault: `Brain/`. Pay
+Memory writes nest under `Brain/payments/`, so the agent's entire
+write contract is "I touch only `Brain/`".
```text
<vault>/
-├── Brain/ # observing memory (agent-writable)
-│ ├── _brain.yaml # schema, thresholds, retention, vault.ignore_paths
+├── Brain/ # agent-writable
+│ ├── _brain.yaml # schema, thresholds, retention, vault.ignore_paths, notes.read_paths
│ ├── _BRAIN.md # operating manual for agents
│ ├── active.md # derived: confirmed + quarantine + recently retired
│ ├── inbox/ # raw taste signals
@@ -40,20 +41,21 @@ its own, plus a sibling derived-index directory.
│ │ └── ret-<slug>.md # retired_reason: stale-no-evidence | expired-unconfirmed | rebutted | user-rejected | quarantine-violated | superseded-by-context
│ ├── log/ # daily event log
│ │ └── YYYY-MM-DD.md # append-only, typed events
+│ ├── payments/ # Pay Memory (optional, paid-action audit)
+│ │ ├── policies/spending.md
+│ │ ├── <YYYY-MM-DD>/<slug>.md # dated receipts
+│ │ ├── assets/ # generated-asset notes
+│ │ ├── drafts/ # draft artefacts
+│ │ ├── reports/ # daily reports
+│ │ └── _pending/ # approval workflow
│ └── .snapshots/ # pre-dream snapshots
│ └── dream-<run-id>.tar.zst
│
├── .open-second-brain/ # derived search index (rebuildable)
│ └── brain.sqlite # SQLite + FTS5 + optional sqlite-vec
│
-├── AI Wiki/ # curated knowledge surface
-│ ├── identity/ # user.md, agents.md
-│ ├── index.md / hot.md
-│ ├── payments/ / assets/ / drafts/ / reports/ / policies/ ← Pay Memory subtree
-│ └── system/ # config snapshots, etc.
-│
-└── Daily/ # chronological event log + human narrative
- └── YYYY.MM.DD.md
+└── Daily/ # OPERATOR-OWNED user notes (any folder name)
+ └── 2026-05-14.md # listed in notes.read_paths for @osb scanning
```
`Brain/active.md` and `.open-second-brain/brain.sqlite` are **derived** —
@@ -66,21 +68,19 @@ flowchart LR
Agent[Agent / MCP client]
subgraph Vault
Brain[Brain/]
- Wiki[AI Wiki/]
- Daily[Daily/]
- PayMem[(Pay Memory subtree<br/>under AI Wiki/)]
+ Notes[("Operator notes<br/>(any folder)")]
end
Agent -- "brain_* (read + write)" --> Brain
- Agent -- "second_brain_query (read)" --> Wiki
- Agent -- "second_brain_query (read)" --> Daily
- Agent -- "payment_* (read + write)" --> PayMem
+ Agent -- "payment_* (read + write)" --> Brain
+ Agent -- "scan-inline (read-only)" --> Notes
```
-`Brain/` is the only area where the agent records its observing
-memory. `AI Wiki/` and `Daily/` are read surfaces for the agent (the
-Pay Memory subtree under `AI Wiki/` is the exception: agents write
-there through the `payment_*` tools).
+`Brain/` is the only area where the agent writes. User-authored notes
+(daily journals, weekly notes, etc.) live in folders the operator
+names — wherever they want them. List those folders under
+`notes.read_paths` in `_brain.yaml` to opt the agent into scanning
+them for `@osb` markers.
## A preference's lifecycle
@@ -190,6 +190,22 @@ Two important properties of this flow:
- Every state change is durable on disk before `dream` returns. There
is no in-memory buffer that could be lost on crash.
+## Capture surfaces
+
+Three independent paths land a signal in `Brain/inbox/`:
+
+- **Live** - the agent calls `brain_feedback` (MCP) or `o2b brain feedback` (CLI) the moment the rule is formulated. This is the path the end-to-end sequence above documents.
+- **Inline** - the user (or agent) writes an `@osb` marker into any vault Markdown file. `o2b brain scan-inline` finds every marker, creates the corresponding signal, and annotates the source file with `@osb✓ [[sig-...]]` so a re-run is a no-op. Two marker shapes: a single line `@osb feedback negative topic=... principle="..."` or a fenced ` ```osb` block with YAML inside.
+- **Session import** - `o2b brain import-session <path>` reads a Claude Code / Codex CLI / Hermes session JSONL and extracts both `@osb` markers from message text and replays of `brain_feedback` tool-use calls. Useful when MCP was not available at recording time or the agent did not make the call live.
+
+All three paths share a normalised payload hash so the same rule captured twice from different surfaces dedups automatically. Pinned preferences are exempt from automatic retire (`stale-no-evidence`, `expired-unconfirmed`, `rebutted`); only `o2b brain reject` can retire them.
+
+### Cross-project setup
+
+When coding work happens in a project directory that is not the vault itself, add a pointer snippet to your project's `CLAUDE.md` or `AGENTS.md` so the agent knows where to read preferences from. The canonical snippet, the rules for multi-device Syncthing setups, and the `o2b brain set-primary` invocation are in [`cross-project-pointer.md`](cross-project-pointer.md).
+
+A vault shared across hosts should declare a single `primary_agent` in `Brain/_brain.yaml` - the runtime that owns the dream cron. Dream runs from a different agent emit a non-fatal warning (stderr for CLI, `warnings` array for MCP) and tag the dream summary log with `non_primary_agent: <caller>`.
+
## The dream pass in detail
A single dream invocation is a deterministic pipeline:
@@ -739,7 +755,6 @@ flowchart LR
Init --> Skel["Create Brain/inbox, preferences, retired, log, .snapshots"]
Init --> Yaml[Render Brain/_brain.yaml with defaults]
Init --> Manual[Render Brain/_BRAIN.md operating manual]
- Init --> Overview[Write AI Wiki/_OPEN_SECOND_BRAIN.md vault overview]
```
`Brain/_brain.yaml` defaults are sensible for most uses; tune them in
diff --git a/docs/images/readme-poster.jpg b/docs/images/readme-poster.jpg
new file mode 100644
index 00000000..1dd28c30
Binary files /dev/null and b/docs/images/readme-poster.jpg differ
diff --git a/docs/mcp.md b/docs/mcp.md
index 3042c97d..5c3e434b 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -22,22 +22,18 @@ in Open Second Brain depends on the MCP server being running.
| --- | --- | --- |
| `second_brain_status` | Report config and vault status, with secrets redacted. | — |
| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |
-| `second_brain_capture` | Write a Markdown note under `AI Wiki/notes/` with frontmatter. | `title`, `content` |
-| `event_log_append` | Append a single-line event to the daily Markdown event log. | `message` |
| `vault_health` | Run vault, config, and plugin manifest health checks. | — |
-| `payment_memory_init` | Bootstrap `AI Wiki/{policies,payments,assets,drafts,reports}/` and write the spending policy template. | — |
+| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | — |
| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
-| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `AI Wiki/reports/`. | `date` |
+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |
| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |
| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |
| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |
| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |
`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).
-`second_brain_capture` also accepts `tags` (array of strings) and `overwrite`
-(boolean). `event_log_append` accepts `agent`, `date` (YYYY.MM.DD), and `time`
-(HH:MM). `vault_health` accepts `repo` (string) for plugin manifest validation.
+`vault_health` accepts `repo` (string) for plugin manifest validation.
`payment_memory_init` accepts `agent` (string) and `overwrite` (boolean — to
refresh the policy template). `payment_receipt_append` accepts the same
@@ -48,12 +44,9 @@ optional fields as the CLI: `agent`, `category`, `endpoint`, `expected_cost`,
`overwrite`. `payment_report_generate` accepts `title`, `task`, `slug`,
`overwrite`.
-> **Date format note.** `event_log_append` uses `YYYY.MM.DD` to match the
-> `Daily/<date>.md` filename convention; Pay Memory tools (`payment_receipt_append`,
-> `payment_report_generate`, `payment_policy_check`, `payment_request_approval`)
-> use ISO 8601 `YYYY-MM-DD` because the `AI Wiki/payments/<date>/`
-> subdirectory layout is independent of `Daily/`. Both accept the matching
-> `--date` form on the CLI.
+> **Date format note.** Brain and Pay Memory tools use ISO 8601
+> `YYYY-MM-DD` throughout; the `Brain/log/<date>.md` and
+> `Brain/payments/<date>/` subdirectory layouts share that convention.
`payment_policy_check` accepts `expected_amount` (number or numeric
string), `currency`, `category`, and `date`. `payment_request_approval`
@@ -161,8 +154,6 @@ mcp_servers:
include:
- second_brain_status
- second_brain_query
- - second_brain_capture
- - event_log_append
- vault_health
# Pay Memory tools (v0.8.0+); drop any line below to disable a
# specific tool, or remove the whole `tools.include` block to
@@ -249,12 +240,20 @@ its plugin manifest, so the MCP entrypoint is reachable from a Codex shell as
well. There is no auto-registration into Codex's MCP discovery — add the
server to your Codex MCP config the same way as Hermes.
+## Writer split (Claude Code 2.1.121+)
+
+The plugin's `.mcp.json` ships **two** MCP-server entries:
+
+- `open-second-brain` - the full surface (31 tools); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
+- `open-second-brain-writer` - a minimal always-loaded surface of four tools: `brain_feedback`, `brain_apply_evidence`, `brain_note` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md`, v0.10.10). The agent records taste signals, evidence events, and milestone notes - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
+
+Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).
+
## Safety notes
- The vault path is bound to the server instance at startup. Tools cannot
escape it.
-- `second_brain_capture` writes only under `<vault>/AI Wiki/notes/` and rejects
- collisions unless `overwrite: true` is supplied.
- `second_brain_status` reuses the same redaction logic as `o2b export-config`.
-- `event_log_append` appends below the `## Raw events` section using the same
- locking strategy as the CLI.
+- Brain writers (`brain_feedback`, `brain_apply_evidence`, `brain_note`)
+ go through atomic-rename writes so an interrupted call leaves either
+ the prior or the new file, never a torn hybrid.
diff --git a/docs/pay-memory.md b/docs/pay-memory.md
new file mode 100644
index 00000000..743eb1e3
--- /dev/null
+++ b/docs/pay-memory.md
@@ -0,0 +1,133 @@
+# Pay Memory
+
+Pay Memory is an audit layer for paid agent actions. The agent makes the paid API call itself (typically through `pay` from [solana-foundation/pay](https://github.com/solana-foundation/pay)); Open Second Brain records the reason, the policy check, the receipt, and any generated asset as plain Markdown inside the vault. It never executes payments and never holds wallet keys.
+
+## Bootstrap
+
+```bash
+o2b init-pay-memory --vault /path/to/vault
+# -> Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs) and policies/spending.md
+```
+
+## Recording a paid call
+
+After running `pay --sandbox curl ...` and capturing the output:
+
+```bash
+o2b append-payment-receipt \
+ --vault /path/to/vault \
+ --service paysponge/fal \
+ --status success \
+ --reason "Generate one original blog header image" \
+ --actual-amount 0.05 --currency USDC \
+ --result-ref https://fal-cdn.example/img.png \
+ --result-note "Brain/payments/assets/blog-header.md" \
+ --raw-output-file /tmp/pay-output.txt
+
+o2b capture-asset \
+ --vault /path/to/vault \
+ --title "Blog Header: Pay Memory" \
+ --service paysponge/fal \
+ --result-url https://fal-cdn.example/img.png \
+ --source-receipt "Brain/payments/2026-05-10/<receipt-slug>.md"
+
+o2b payment-report --vault /path/to/vault --date 2026-05-10
+```
+
+The `--raw-output-file` of a receipt is run through a redactor that masks values for `api_key` / `token` / `secret` / `bearer` / `authorization` / `private_key` / `password` / `passwd` / `pwd` / `credential` / `session_token` in env, YAML, JSON, and HTTP-header shapes. Best-effort only - verify the saved receipt before sharing it externally.
+
+The spending policy at `Brain/payments/policies/spending.md` is read by the agent before each paid call; the MVP does not enforce policy at runtime.
+
+## Machine-readable spending policy (optional)
+
+To enable runtime enforcement, drop a JSON companion at `Brain/payments/policies/spending.json`:
+
+```json
+{
+ "schema_version": 1,
+ "currency": "USDC",
+ "max_total_per_day": 0.10,
+ "max_single_call": 0.07,
+ "allowed_services": ["paysponge/fal"],
+ "max_per_category": { "media_generation": 1 },
+ "require_approval_above": 0.05
+}
+```
+
+Then check before each paid call:
+
+```bash
+o2b check-payment-policy --service paysponge/fal --expected-amount 0.05
+```
+
+Exit codes are `0` (allowed), `1` (denied), `3` (approval required) so a shell script can branch. The MCP tool `payment_policy_check` returns the same structured decision. If `spending.json` is absent, the check fails open (`has_policy: false`) - existing flows that rely on the Markdown-only policy keep working.
+
+## Approval workflow (optional)
+
+For paid calls that should not happen until a human signs off, Pay Memory ships a pending-payment-request artifact under `Brain/payments/_pending/` with a `pending -> approved/rejected -> consumed` state machine.
+
+Agent side:
+
+```bash
+o2b request-payment-approval \
+ --service paysponge/fal \
+ --reason "Generate one blog header image" \
+ --expected-amount 0.05 --currency USDC
+# -> Brain/payments/_pending/req-2026-05-10-1000-fal-...md
+```
+
+Human side, after reviewing the request file in Obsidian:
+
+```bash
+o2b approve-payment-request --id <id> --approved-by <name>
+# or
+o2b reject-payment-request --id <id> --rejected-by <name> --reason "..."
+```
+
+Agent side, after the approved paid call succeeded and the receipt was saved:
+
+```bash
+o2b consume-payment-request --id <id> \
+ --receipt "Brain/payments/2026-05-10/<receipt-slug>.md"
+```
+
+The MCP-server side mirrors `payment_request_approval`, `payment_request_status` (poll for approval), and `payment_request_consume`.
+
+## Daily Telegram digest via Hermes cron (optional)
+
+`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a 4-line summary suitable for delivery via Hermes cron `--script --no-agent` jobs. See [`hermes-cron.md`](hermes-cron.md) for the ready-to-paste `hermes cron create` command. The same command can be wrapped by any other scheduler that pipes its stdout to a chat destination - the digest itself is runtime-neutral.
+
+## Installing the `pay` CLI on a Linux VPS
+
+`pay` is the Solana-Foundation payment wrapper that turns a regular HTTP client into one that handles HTTP 402 payment challenges. It is published as a prebuilt static binary on GitHub Releases - no Rust toolchain or Node.js is needed on the host:
+
+```bash
+TAG=pay-v0.16.0 # pin a specific release
+gh release download "$TAG" -R solana-foundation/pay \
+ -p 'pay-x86_64-unknown-linux-gnu.tar.gz' -p 'sha256sums.txt' -D /tmp
+cd /tmp && sha256sum -c --ignore-missing sha256sums.txt
+tar -xzf pay-x86_64-unknown-linux-gnu.tar.gz
+sudo install -m 0755 pay /usr/local/bin/pay
+pay --version
+```
+
+Sandbox mode (`pay --sandbox curl <url>`) does not require running `pay setup` first - it generates an ephemeral Solana keypair and funds it locally via the Surfpool sandbox RPC. That makes it safe to wire into a CI / e2e test that exercises the full Pay Memory pipeline without spending real funds. See `tests/e2e/pay-memory-sandbox.sh` for a reference run.
+
+For non-sandbox use the local secure storage helper (macOS Keychain, GNOME Keyring, Windows Hello, 1Password) is configured by `pay setup`. Open Second Brain itself never holds wallet keys.
+
+## MCP tool surface
+
+Eight Pay Memory tools, all on the full MCP scope:
+
+| Tool | Purpose |
+| --- | --- |
+| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)`. |
+| `payment_receipt_append` | Save a redacted Markdown receipt for one paid API call. |
+| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. |
+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. |
+| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json`. |
+| `payment_request_approval` | Create a pending-payment-request the user must approve. |
+| `payment_request_status` | Look up a pending request by id (agent uses this to poll). |
+| `payment_request_consume` | Mark an approved request as consumed and link the resulting receipt. |
+
+See [`mcp.md`](mcp.md) for the protocol envelope and lifecycle.
diff --git a/docs/roadmap.md b/docs/roadmap.md
deleted file mode 100644
index 50b9fa03..00000000
--- a/docs/roadmap.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# Roadmap
-
-## v0: portable package skeleton
-
-Goal: create an understandable open-source package that can be installed or inspected by Hermes, Claude Code, Codex, and humans.
-
-Scope:
-
-- README and design documentation;
-- architecture notes;
-- tested CLI foundation;
-- event log concept;
-- skills for Open Second Brain and event logging;
-- Hermes plugin skeleton;
-- Claude Code plugin manifest;
-- Codex plugin manifest;
-- no daemon;
-- no required MCP server;
-- no automatic background writes.
-
-## v0.1: deterministic CLI ✅
-
-Implemented:
-
-```text
-o2b status
-o2b init
-o2b doctor
-o2b export-config
-o2b append-event
-vault-log
-```
-
-- `o2b status` — locate config and list known keys.
-- `o2b init` — bootstrap a vault profile with AI Wiki structure.
-- `o2b doctor` — run health checks on vault, config, and plugin manifests.
-- `o2b export-config` — write a redacted config snapshot.
-- `o2b append-event` — append an event to the daily Markdown backend.
-- `vault-log` — compatibility wrapper for existing vault-log users.
-
-All commands are dependency-free and tested with Python `unittest` (34 tests).
-
-## v0.2: vault profile bootstrap ✅
-
-`o2b init` creates:
-
-```text
-AI Wiki/_OPEN_SECOND_BRAIN.md
-AI Wiki/_open-second-brain.yaml
-AI Wiki/index.md
-AI Wiki/hot.md
-AI Wiki/log.md
-AI Wiki/identity/user.md
-AI Wiki/identity/agents.md
-```
-
-Implemented:
-- vault-local operating manual (`_OPEN_SECOND_BRAIN.md`) to drive agent behavior;
-- query helpers for the wiki layer (`parse_frontmatter`, `extract_wikilinks`, `list_vault_pages`);
-- `o2b index` to regenerate `AI Wiki/index.md` from discovered vault pages.
-
-## v0.3: runtime polish ✅
-
-Implemented:
-
-- Hermes plugin health checks with safe best-effort registration;
-- Claude Code plugin command metadata for `status`, `doctor`, `init`, `index`, `append-event`, `export-config`, and `vault-log`;
-- Codex, Claude, and Hermes plugin manifest validation in `o2b doctor --repo`;
-- better install and runtime notes in README;
-- test fixtures for sandbox vaults and plugin manifest repos.
-
-## v1: MCP tool server ✅
-
-Implemented in v0.4.0 (`docs/mcp.md`):
-
-- stdio JSON-RPC 2.0 server on protocol version `2025-06-18`;
-- five tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`;
-- `o2b mcp` subcommand and `o2b-mcp` console script;
-- Hermes/Claude/Codex manifest metadata referencing the MCP entrypoint;
-- documentation for `~/.hermes/config.yaml mcp_servers` registration.
-
-The MCP server is optional. The CLI remains the supported baseline.
-
-## v2: richer automation
-
-Possible future work:
-
-- opt-in event capture hooks;
-- local indexing;
-- semantic retrieval;
-- background compaction;
-- automatic knowledge synthesis;
-- documentation site;
-- package registries and marketplaces.
-
-Automation must remain explicit and reversible.
diff --git a/docs/superpowers/specs/2026-05-20-v0.10.12-design.md b/docs/superpowers/specs/2026-05-20-v0.10.12-design.md
deleted file mode 100644
index dde16bd9..00000000
--- a/docs/superpowers/specs/2026-05-20-v0.10.12-design.md
+++ /dev/null
@@ -1,291 +0,0 @@
-# v0.10.12 — Operational Friction Reduction
-
-**Date:** 2026-05-20
-**Status:** draft
-**Author:** Sisyphus (via brainstorming)
-**Audience:** implementation
-
-## Problem Statement
-
-Two pain points in daily OSB operation:
-
-1. **Manual per-runtime update on every release.** Operator runs 5-7 steps per machine to update OSB installation across all runtimes (Claude Code, Codex, Hermes, Cursor, etc.). Error-prone and tedious.
-2. **No trend visibility.** Daily discipline report gives a single-day snapshot. No understanding of "how the agent learns over a week" — confidence trends, agent engagement quality, rule adoption patterns.
-
-## Scope
-
-Four features, one PR, one release (v0.10.12):
-
-| # | Feature | Priority |
-|---|---------|----------|
-| 1 | `o2b update` CLI verb | Primary |
-| 2 | Weekly Brain Digest (`--window 7d`) | Primary |
-| 3 | Cursor SQLite deep parsing | Companion |
-| 4 | Obsidian deep-link in explorer | Companion |
-
-**Out of scope (explicitly deferred):**
-- Window-triggers for Hermes cron (§25) — Hermes-side change, tracked separately
-- `--scope project` for Cursor/opencode/kiro — already deferred, trigger not met
-- Live-refresh in explorer (SSE/WS) — already deferred, trigger not met
-
----
-
-## Feature 1: `o2b update`
-
-### What it does
-
-One command that updates OSB installation across all detected runtimes by re-running the InstallAdapter pipeline with the current version's payload. Skips runtimes where the payload hasn't changed.
-
-### User-facing surface
-
-```bash
-# Update all detected runtimes
-o2b update
-
-# Update a specific runtime
-o2b update --target claudecode
-
-# Dry-run: show what would change without applying
-o2b update --dry-run
-
-# Force apply even if payload appears unchanged
-o2b update --force
-
-# JSON output for scripting
-o2b update --json
-```
-
-### Behavior
-
-For each target (or `--target X`):
-
-1. **Detect** — run `adapter.detect(env)` to check runtime status
-2. **Plan** — generate current `McpPayload` and call `adapter.plan(payload, env)`
-3. **Compare** — check sidecar manifest (`install.lock.json`) for previous payload; if identical, skip with "up-to-date" note
-4. **Apply** — if payload differs (or `--force`), call `adapter.apply(plan, payload, env, opts)`
-5. **Post-notes** — emit per-runtime restart hints (e.g., "restart Claude Code", `hermes gateway restart`)
-6. **Verify** — run `o2b install --check` at the end for all targets
-
-If a runtime fails to update: clear error message with hint pointing to the required manual step. No auto-recovery for cases requiring user decision.
-
-### Exit codes
-
-| Code | Meaning |
-|------|---------|
-| 0 | All targets updated or already up-to-date |
-| 1 | Runtime error (I/O, subprocess failure) |
-| 2 | Usage error (unknown target, bad flags) |
-| 3 | `--check` found drift after update |
-| 4 | User-modified-block conflict (use `--force` to override) |
-
-### File changes
-
-- **New:** `src/cli/update.ts` — CLI verb handler, arg parsing, orchestration loop
-- **New:** `src/core/install/update.ts` — core update logic (detect → plan → compare → apply → verify)
-- **New:** `tests/cli/update.test.ts`
-- **New:** `tests/core/install/update.test.ts`
-- **Modify:** `src/cli/main.ts` — register `update` subcommand
-- **Modify:** `CHANGELOG.md` — v0.10.12 entry
-
-### Design decisions
-
-- **Reuse InstallAdapter machinery entirely.** No new adapter interface, no new registry. The update logic is orchestration over existing `detect/plan/apply/verify`.
-- **Payload comparison via sidecar manifest.** The `install.lock.json` already stores `applied_at`, `operation`, `owned_keys`, `owned_paths`. We extend it with an additive `payload_hash` field (sha256 of the canonical McpPayload JSON) so update can skip unchanged targets without re-applying. This is backward-compatible: entries without `payload_hash` are treated as "unknown — apply on first update run", and the hash is written after the first successful update.
-- **Sequential, not parallel.** Runtimes share filesystem state (the vault, the skill symlinks). Sequential execution avoids race conditions. The total time is still sub-second for most setups.
-- **`--force` bypasses payload hash check.** Useful when operator knows the payload changed but the hash didn't (e.g., env variable update that doesn't affect the McpPayload struct but affects runtime behavior).
-
----
-
-## Feature 2: Weekly Brain Digest
-
-### What it does
-
-Extends `brain_digest` to accept a `--window` parameter for arbitrary time windows (e.g., `7d`, `14d`, `30d`). Adds a weekly cron job that delivers a 7-day digest every Monday morning.
-
-### CLI surface
-
-```bash
-# Default: 24h (unchanged)
-o2b brain digest
-
-# Weekly window
-o2b brain digest --window 7d
-
-# Custom window
-o2b brain digest --window 14d
-
-# JSON output
-o2b brain digest --window 7d --json
-```
-
-### Window parser
-
-Accepts `Nd` format where N is a positive integer (e.g., `1d`, `7d`, `14d`, `30d`). Bare integers without `d` suffix are also accepted (e.g., `7` → 7 days). Invalid format or non-positive values → exit 2 with error message.
-
-### Digest content (weekly mode)
-
-Same sections as daily, but over the 7-day window:
-
-1. **New confirmed rules** — preferences with `confirmed_at` inside the window
-2. **Confidence downshifts** — rules whose confidence_band dropped during the window
-3. **Top-5 most-applied** — by evidence-application count within the window
-4. **Agent quality summary** — per-agent breakdown:
- - Total brain-events (feedback + apply-evidence + note)
- - Breakdown by event type
- - How many events led to confirmed rules in the same window
- - How many events led to retired rules in the same window
-
-### Agent quality summary implementation
-
-Read `Brain/log/<date>.md` (or `.jsonl`) for all dates in the window. Group events by `agent` field. For each agent:
-
-- Count events by type (`feedback`, `apply-evidence`, `note`)
-- Cross-reference with `Brain/preferences/` — count preferences whose `confirmed_at` falls in the window AND whose first `applied` event matches this agent (via `evidenced_by` wikilink or log entry `preference` field)
-- Cross-reference with `Brain/retired/` — count retirements in window traceable to this agent's signals
-
-### Cron integration
-
-**Parameterize `bin/o2b-discipline-report`:**
-
-Add `--window` flag to the script. When set, it calls `o2b brain digest --window <value>` instead of the daily discipline report.
-
-**New install verb:**
-
-```bash
-o2b discipline install --weekly --telegram-target telegram:-100<chat>:<topic> --at "59 8 * * 1"
-```
-
-Creates a second Hermes cron job (separate from daily) with:
-- `name: "osb-weekly-brain-digest"`
-- `script: "bin/o2b-discipline-report --window 7d"`
-- `schedule: "59 8 * * 1"` (Monday 08:59 UTC — Monday morning in Europe/Belgrade)
-
-### File changes
-
-- **Modify:** `src/core/brain/digest.ts` — accept `windowDays` parameter in `RenderDigestOptions`; adjust `since` calculation; add agent quality summary section to Markdown/JSON output
-- **Modify:** `src/cli/brain/verbs/digest.ts` — parse `--window` flag
-- **Modify:** `bin/o2b-discipline-report` — accept `--window` flag, route to `o2b brain digest --window`
-- **Modify:** `src/cli/discipline-install.ts` — add `--weekly` flag to install verb
-- **New:** `src/core/brain/digest-agent-summary.ts` — agent quality summary computation (pure read over Brain/log/)
-- **New:** `tests/core/brain/digest-window.test.ts`
-- **New:** `tests/core/brain/digest-agent-summary.test.ts`
-- **Modify:** `CHANGELOG.md`
-
-### Design decisions
-
-- **`--window` not `--weekly`.** More general — operator can request any window. `--weekly` would lock us into a boolean.
-- **Agent quality in the digest core, not discipline.** Discipline report is about "is the agent writing to Brain at all". Digest is about "what changed in Brain". Agent quality summary belongs in digest because it references confirmed/retired rules, not just event counts.
-- **Graceful degradation.** If log files are missing for some days in the window, the digest still renders with available data. No crash on partial data.
-
----
-
-## Feature 3: Cursor SQLite Deep Parsing
-
-### What it does
-
-Replace the mtime-only probe for Cursor transcripts with actual SQLite parsing. Returns the number of unique sessions and total message count for the day.
-
-### Data extracted
-
-From `state.vscdb`:
-- **Session count** — number of unique `sessionId` values with activity in the day window
-- **Message count** — total number of messages/turns across all sessions in the window
-
-No per-turn timestamps stored or returned. Just aggregate counts.
-
-### SQLite schema assumption
-
-Cursor uses the standard VSCode-derived `state.vscdb` with a `ItemTable` containing `key` and `value` columns. Session data is stored as JSON in the `value` column under keys like `sessionData.<sessionId>`.
-
-The query pattern:
-```sql
-SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'
-```
-
-Parse the JSON value to extract message count and session timestamps.
-
-**Important:** The exact schema may vary between Cursor versions. The implementation must:
-1. Try the known schema first
-2. If the query fails (SQL error, missing table, locked database), fall back to the mtime probe and log a warning to stderr
-3. If the query returns rows but the JSON structure is unexpected, fall back to mtime and log a warning
-4. Never crash the discipline report — all SQLite errors are caught and degraded gracefully
-
-### File changes
-
-- **Modify:** `src/core/discipline/transcripts/cursor.ts` — replace mtime probe with SQLite parsing
-- **Modify:** `src/core/discipline/transcripts/types.ts` — extend `TranscriptRuntime` return type to include session/message counts (or use a new result type)
-- **Modify:** `src/core/discipline/transcripts/index.ts` — handle new result shape
-- **New:** `tests/core/discipline/transcripts/cursor-sqlite.test.ts`
-- **Modify:** `CHANGELOG.md`
-
-### Design decisions
-
-- **`bun:sqlite` only.** Already in the stack. No new dependencies.
-- **Fallback to mtime on any SQLite error.** If the schema changed, the database is locked, or permissions are wrong, we degrade gracefully to the old mtime behavior.
-- **Isolated in one file.** No changes to other transcript resolvers (Claude Code, Codex).
-
----
-
-## Feature 4: Obsidian Deep-Link in Explorer
-
-### What it does
-
-Double-click on a node in live-mode `o2b brain explorer` opens the corresponding `pref-X.md` file directly in Obsidian via `obsidian://open?path=<absolute_path>`.
-
-### Implementation
-
-1. **Server-side:** `buildLiveServer` passes `vaultPath` to the HTML template via a new placeholder `__VAULT_PATH__` (similar to `__GRAPH_JSON__`).
-2. **Template:** Add `__VAULT_PATH__` placeholder and ~30 lines of JS:
- - On double-click of a canvas node or listbox item
- - Construct `obsidian://open?path=${encodeURIComponent(absolutePath)}`
- - Attempt to open via `window.open(uri, '_blank')`
- - Fallback: copy absolute path to clipboard + show tooltip "Obsidian not detected — path copied"
-
-3. **Path construction:** `<vaultPath>/Brain/preferences/pref-<id>.md`
-
-Only active in live-mode. Export-mode has no vault path, so no deep-link.
-
-### File changes
-
-- **Modify:** `src/core/brain/explorer.ts` — pass `vaultPath` to template in live server mode
-- **Modify:** `templates/brain-explorer.html` — add `__VAULT_PATH__` placeholder + double-click handler
-- **New:** `tests/core/brain/explorer-deeplink.test.ts`
-- **Modify:** `CHANGELOG.md`
-
-### Design decisions
-
-- **`path=` not `vault=`.** `obsidian://open?path=<absolute>` works regardless of how the vault is registered in Obsidian. `vault=<name>` requires the vault name to match Obsidian's registered name, which may differ from the directory basename.
-- **Silent fallback.** If `window.open` doesn't trigger Obsidian (not installed, blocked by browser), copy path to clipboard and show a brief tooltip. No modal dialogs.
-- **No server-side code for the fallback.** Pure client-side JS. The server only provides the vault path.
-
----
-
-## Cross-Cutting Concerns
-
-### Testing strategy
-
-- All new core logic has unit tests
-- CLI verbs tested via synthetic argv
-- SQLite parsing tested with a mock `state.vscdb` fixture
-- Explorer deep-link tested via template substitution unit test (no browser automation needed)
-
-### Backward compatibility
-
-- `o2b brain digest` without `--window` behaves identically to current (24h default)
-- `o2b update` is a new verb — no existing behavior changed
-- Cursor transcript fallback ensures no regression for users with incompatible Cursor versions
-- Explorer deep-link only adds behavior — existing click/keyboard interaction unchanged
-
-### Version bump
-
-- `package.json` version → `0.10.12`
-- `CHANGELOG.md` entry with all four features
-
----
-
-## Deferred Items (update _summary.md)
-
-Add to the Deferred work section:
-
-- **§25 Window-triggers for Hermes cron.** Weekly digest relies on standard cron scheduling. If VPS is offline during the Monday window, the digest is skipped. Window-trigger support (fire-on-next-boot-after-missed-window) is a Hermes-side feature, not OSB-core. Track separately.
-- **§14 Obsidian deep-link — export mode.** Static export cannot provide vault path, so deep-link is live-mode only. If operators request deep-link in exported HTML, we would need to embed vault path at export time (operator provides `--vault-path` flag). Trigger: explicit request.
diff --git a/install/prerequisites.md b/install/prerequisites.md
index 37aa6533..df66f15d 100644
--- a/install/prerequisites.md
+++ b/install/prerequisites.md
@@ -17,21 +17,21 @@ fallback exists.
`o2b init` persists two values into `~/.config/open-second-brain/config.yaml`:
-- **`agent_name`** — prefix used in every `Daily/` entry and every
- `Brain/log/` event written by an MCP server pointing at this vault.
- Pick a deliberate value (`<runtime>-<host>` is a good default).
+- **`agent_name`** — prefix attached to every `Brain/log/` event the
+ MCP server records against this vault. Pick a deliberate value
+ (`<runtime>-<host>` is a good default).
- **`timezone`** — IANA name (`Europe/Belgrade`, `America/New_York`,
- `UTC`). Used to stamp `Daily/` entries regardless of the host's
+ `UTC`). Used to stamp event timestamps regardless of the host's
local clock.
If the vault was initialized previously, check the registry first:
- `~/.config/open-second-brain/config.yaml` `agent_name` (authoritative)
-- `<vault>/AI Wiki/identity/agents.md` (human-readable list)
-- `<vault>/Daily/*.md` (recurring `@<name>` lines)
+- `<vault>/Brain/_brain.yaml` `primary_agent` (when set)
+- `<vault>/Brain/log/*.{md,jsonl}` (recurring `agent` field)
-A repeat `o2b init --agent-name X` is safe: it appends `X` to the
-registry without removing the previous agents.
+A repeat `o2b init --agent-name X` is safe — it updates the
+machine-local config in place.
## Vault path discovery
@@ -57,9 +57,9 @@ o2b install --check
(per-target managed-block / MCP-ping verification). `o2b doctor`
covers vault invariants — they are complementary, not substitutes.
-Then send one event without an explicit `agent` argument and confirm
-that the new `Daily/YYYY.MM.DD.md` line begins with the chosen
-`@<agent_name>` prefix, not the literal `@agent` placeholder.
+Then call `brain_note` once (via MCP or `o2b brain note "..."` on the
+CLI) and confirm that the new line in `Brain/log/<today>.md` carries
+the chosen `agent` value, not the literal `agent` placeholder.
## Plays well with codegraph
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 3e1eeaa5..8af74050 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.18",
+ "version": "0.11.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
@@ -28,11 +28,11 @@
},
"agentName": {
"type": "string",
- "description": "Identity used in Daily/*.md event log entries (e.g. 'openclaw-main'). Falls back to VAULT_AGENT_NAME env, then to '@agent'."
+ "description": "Identity used in Brain/log/*.md event log entries (e.g. 'openclaw-main'). Falls back to VAULT_AGENT_NAME env, then to '@agent'."
},
"timezone": {
"type": "string",
- "description": "IANA timezone name (e.g. 'Europe/Belgrade', 'America/New_York', 'UTC') used to stamp Daily/*.md entries in the user's local time. Falls back to VAULT_TIMEZONE env, then to the host's local clock."
+ "description": "IANA timezone name (e.g. 'Europe/Belgrade', 'America/New_York', 'UTC') used to stamp Brain/log/*.md entries in the user's local time. Falls back to VAULT_TIMEZONE env, then to the host's local clock."
},
"mcpEnabled": {
"type": "boolean",
@@ -52,11 +52,11 @@
},
"agentName": {
"label": "Agent Name",
- "help": "Identity used in Daily/*.md as @agent-name for event log entries."
+ "help": "Identity used in Brain/log/*.md as @agent-name for event log entries."
},
"timezone": {
"label": "Timezone",
- "help": "IANA timezone name (e.g. Europe/Belgrade) for HH:MM stamps in Daily/*.md."
+ "help": "IANA timezone name (e.g. Europe/Belgrade) for HH:MM stamps in Brain/log/*.md."
},
"mcpEnabled": {
"label": "Enable MCP Server",
diff --git a/openclaw/index.js b/openclaw/index.js
index e8c65170..05ca41fa 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1478,12 +1478,12 @@ var require_adapter = __commonJS((exports, module) => {
return newFs;
}
function toPromise(method) {
- return (...args) => new Promise((resolve3, reject) => {
+ return (...args) => new Promise((resolve4, reject) => {
args.push((err, result) => {
if (err) {
reject(err);
} else {
- resolve3(result);
+ resolve4(result);
}
});
method(...args);
@@ -1554,7 +1554,7 @@ var require_proper_lockfile = __commonJS((exports, module) => {
// src/openclaw/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import { existsSync as existsSync5 } from "node:fs";
+import { existsSync as existsSync6 } from "node:fs";
import { resolve as resolvePath } from "node:path";
// src/core/config.ts
@@ -1737,7 +1737,7 @@ function expandTilde(p) {
// src/core/doctor.ts
import {
- existsSync as existsSync2,
+ existsSync as existsSync3,
mkdirSync as mkdirSync2,
openSync as openSync2,
readFileSync as readFileSync2,
@@ -1745,12 +1745,172 @@ import {
writeSync as writeSync2,
closeSync as closeSync2
} from "node:fs";
-import { dirname as dirname2, join as join3 } from "node:path";
+import { dirname as dirname3, join as join4 } from "node:path";
+
+// src/core/partner/codegraph.ts
+import { existsSync as existsSync2, readdirSync, statSync as statSync2 } from "node:fs";
+import { dirname as dirname2, join as join3, resolve } from "node:path";
+var CODE_MANIFESTS = [
+ "package.json",
+ "pyproject.toml",
+ "Cargo.toml",
+ "go.mod",
+ "tsconfig.json",
+ "Gemfile",
+ "composer.json",
+ "build.gradle",
+ "pom.xml"
+];
+var DEFAULT_LIMIT = 50;
+var CODEGRAPH_REPO = "https://github.com/colbymchenry/codegraph";
+function isDir(path) {
+ try {
+ return statSync2(path).isDirectory();
+ } catch {
+ return false;
+ }
+}
+function isCodeProject(dir) {
+ try {
+ if (!existsSync2(dir))
+ return false;
+ if (!isDir(join3(dir, ".git")))
+ return false;
+ return CODE_MANIFESTS.some((m) => existsSync2(join3(dir, m)));
+ } catch {
+ return false;
+ }
+}
+function findCodeProjects(opts) {
+ const limit = opts.limit ?? DEFAULT_LIMIT;
+ const seen = new Set;
+ const found = [];
+ let scanned = 0;
+ const consider = (raw) => {
+ if (scanned >= limit)
+ return;
+ const path = resolve(raw);
+ if (seen.has(path))
+ return;
+ seen.add(path);
+ if (!isDir(path))
+ return;
+ scanned += 1;
+ if (isCodeProject(path))
+ found.push(path);
+ };
+ consider(opts.cwd);
+ const vaultParent = dirname2(resolve(opts.vault));
+ if (isDir(vaultParent)) {
+ let entries = [];
+ try {
+ entries = readdirSync(vaultParent);
+ } catch {
+ entries = [];
+ }
+ entries.sort((a, b) => a.localeCompare(b));
+ for (const name of entries) {
+ if (scanned >= limit)
+ break;
+ consider(join3(vaultParent, name));
+ }
+ }
+ for (const extra of opts.scanExtraPaths ?? []) {
+ if (scanned >= limit)
+ break;
+ consider(extra);
+ }
+ return found;
+}
+function defaultWhichCodegraph() {
+ if (typeof Bun !== "undefined" && typeof Bun.which === "function") {
+ const found = Bun.which("codegraph");
+ return found ?? null;
+ }
+ return null;
+}
+function defaultRunStatusJson(projectPath) {
+ try {
+ const proc = Bun.spawnSync({
+ cmd: ["codegraph", "status", "-j", projectPath],
+ stdout: "pipe",
+ stderr: "pipe"
+ });
+ const stdout = new TextDecoder().decode(proc.stdout).trim();
+ const stderr = new TextDecoder().decode(proc.stderr).trim();
+ if (!proc.success) {
+ if (stdout) {
+ try {
+ const parsed2 = JSON.parse(stdout);
+ return { ok: true, data: parsed2 };
+ } catch {}
+ }
+ return { ok: false, error: stderr || `codegraph status exited ${proc.exitCode}` };
+ }
+ if (!stdout) {
+ return { ok: false, error: stderr || "empty status output" };
+ }
+ const parsed = JSON.parse(stdout);
+ return { ok: true, data: parsed };
+ } catch (exc) {
+ return { ok: false, error: exc.message ?? String(exc) };
+ }
+}
+function checkCodegraph(opts, deps) {
+ if (opts.disabled)
+ return null;
+ const projects = findCodeProjects(opts);
+ if (projects.length === 0)
+ return null;
+ const project = projects[0];
+ const whichFn = deps?.whichCodegraph ?? defaultWhichCodegraph;
+ const cliPath = whichFn();
+ if (!cliPath) {
+ return {
+ name: "code_graph",
+ ok: false,
+ message: `code project at ${project}: codegraph not installed (install: ${CODEGRAPH_REPO})`
+ };
+ }
+ const indexDir = join3(project, ".codegraph");
+ if (!isDir(indexDir)) {
+ return {
+ name: "code_graph",
+ ok: false,
+ message: `code project at ${project}: not indexed (run: codegraph init ${project})`
+ };
+ }
+ const runFn = deps?.runStatusJson ?? defaultRunStatusJson;
+ const status = runFn(project);
+ if (!status.ok) {
+ return {
+ name: "code_graph",
+ ok: false,
+ message: `code project at ${project}: codegraph status failed: ${status.error}`
+ };
+ }
+ if (!status.data.initialized) {
+ return {
+ name: "code_graph",
+ ok: false,
+ message: `code project at ${project}: not indexed (run: codegraph init ${project})`
+ };
+ }
+ const nodes = status.data.nodeCount ?? 0;
+ const files = status.data.fileCount ?? 0;
+ return {
+ name: "code_graph",
+ ok: true,
+ message: `code project at ${project}: indexed (${nodes} nodes, ${files} files)`
+ };
+}
+
+// src/core/doctor.ts
function checkVaultWriteable(vault) {
- if (!existsSync2(vault)) {
+ if (!existsSync3(vault)) {
return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };
}
- const probe = join3(vault, ".open-second-brain-doctor-test");
+ const probe = join4(vault, ".open-second-brain-doctor-test");
try {
const fd = openSync2(probe, "w");
closeSync2(fd);
@@ -1767,8 +1927,8 @@ function checkVaultWriteable(vault) {
function checkConfigWriteable(config) {
let createdForCheck = false;
try {
- mkdirSync2(dirname2(config), { recursive: true });
- if (!existsSync2(config))
+ mkdirSync2(dirname3(config), { recursive: true });
+ if (!existsSync3(config))
createdForCheck = true;
const fd = openSync2(config, "a");
writeSync2(fd, "");
@@ -1945,7 +2105,7 @@ function checkOpenclawManifest(path) {
}
function checkOpenclawInstallability(repoRoot) {
const results = [];
- const pkgPath = join3(repoRoot, "package.json");
+ const pkgPath = join4(repoRoot, "package.json");
const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
results.push(result);
if (!data)
@@ -1974,7 +2134,7 @@ function checkOpenclawInstallability(repoRoot) {
});
continue;
}
- const entryPath = join3(repoRoot, entry);
+ const entryPath = join4(repoRoot, entry);
if (isFile(entryPath)) {
results.push({
name: `openclaw_entry_${entry}`,
@@ -1998,20 +2158,28 @@ function doctor(opts) {
results.push(checkConfigWriteable(opts.config));
if (opts.repoRoot) {
const root = opts.repoRoot;
- results.push(checkClaudeManifest(join3(root, ".claude-plugin", "plugin.json")));
- results.push(checkCodexManifest(join3(root, ".codex-plugin", "plugin.json")));
- results.push(checkHermesManifest(join3(root, "plugins", "hermes", "plugin.yaml")));
- results.push(checkOpenclawManifest(join3(root, "openclaw.plugin.json")));
+ results.push(checkClaudeManifest(join4(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join4(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join4(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join4(root, "openclaw.plugin.json")));
results.push(...checkOpenclawInstallability(root));
}
+ const cg = checkCodegraph({
+ cwd: opts.cwd ?? process.cwd(),
+ vault: opts.vault,
+ scanExtraPaths: opts.partner?.codegraph?.scanExtraPaths,
+ disabled: opts.partner?.codegraph?.disabled
+ });
+ if (cg)
+ results.push(cg);
return results;
}
// src/core/identity-reminder.ts
import { readFileSync as readFileSync3 } from "node:fs";
-import { dirname as dirname3, resolve } from "node:path";
+import { dirname as dirname4, resolve as resolve2 } from "node:path";
import { fileURLToPath } from "node:url";
-var TEMPLATE_PATH = resolve(dirname3(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
+var TEMPLATE_PATH = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
var KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"];
function isRuntimeTarget(value) {
return typeof value === "string" && KNOWN_RUNTIME_TARGETS.includes(value);
@@ -2028,10 +2196,10 @@ function loadReminderTemplate() {
throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`);
}
}
-var TEMPLATES_DIR = resolve(dirname3(fileURLToPath(import.meta.url)), "..", "..", "templates");
+var TEMPLATES_DIR = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");
var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [
t,
- resolve(TEMPLATES_DIR, `identity-reminder.${t}.txt`)
+ resolve2(TEMPLATES_DIR, `identity-reminder.${t}.txt`)
])));
var TEMPLATE_CACHE = new Map;
function tryReadTargetTemplate(target) {
@@ -2074,18 +2242,21 @@ function buildReminder(agent, target) {
}
// src/core/pay-memory/paths.ts
-import { join as join4 } from "node:path";
+import { join as join6, posix as posix3 } from "node:path";
+
+// src/core/brain/paths.ts
+import { join as join5, posix as posix2 } from "node:path";
// src/core/path-safety.ts
-import { existsSync as existsSync3, realpathSync } from "node:fs";
-import { dirname as dirname4, posix, relative, resolve as resolve2, sep } from "node:path";
+import { existsSync as existsSync4, realpathSync } from "node:fs";
+import { dirname as dirname5, posix, relative, resolve as resolve3, sep } from "node:path";
function ensureInsideVault(target, vault) {
- const resolvedTarget = resolve2(target);
- const resolvedVault = resolve2(vault);
+ const resolvedTarget = resolve3(target);
+ const resolvedVault = resolve3(vault);
if (!isLexicallyInside(resolvedTarget, resolvedVault)) {
throw new Error(`path escapes vault: ${target}`);
}
- if (existsSync3(resolvedVault)) {
+ if (existsSync4(resolvedVault)) {
const realVault = safeRealpath(resolvedVault);
const realAncestor = safeRealpath(deepestExistingAncestor(resolvedTarget));
if (!isLexicallyInside(realAncestor, realVault)) {
@@ -2101,8 +2272,8 @@ function isLexicallyInside(target, root) {
}
function deepestExistingAncestor(target) {
let cur = target;
- while (!existsSync3(cur)) {
- const parent = dirname4(cur);
+ while (!existsSync4(cur)) {
+ const parent = dirname5(cur);
if (parent === cur)
return cur;
cur = parent;
@@ -2119,37 +2290,56 @@ function safeRealpath(p) {
}
}
function vaultRelative(target, vault) {
- const rel = relative(resolve2(vault), resolve2(target));
+ const rel = relative(resolve3(vault), resolve3(target));
return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);
}
+// src/core/brain/paths.ts
+var BRAIN_ROOT_REL = "Brain";
+var BRAIN_INBOX_REL = posix2.join(BRAIN_ROOT_REL, "inbox");
+var BRAIN_PROCESSED_REL = posix2.join(BRAIN_INBOX_REL, "processed");
+var BRAIN_PREFERENCES_REL = posix2.join(BRAIN_ROOT_REL, "preferences");
+var BRAIN_RETIRED_REL = posix2.join(BRAIN_ROOT_REL, "retired");
+var BRAIN_LOG_REL = posix2.join(BRAIN_ROOT_REL, "log");
+var BRAIN_SNAPSHOTS_REL = posix2.join(BRAIN_ROOT_REL, ".snapshots");
+var BRAIN_INDEX_FILE = "_INDEX.md";
+var BRAIN_INDEX_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);
+
// src/core/pay-memory/paths.ts
+var PAY_MEMORY_ROOT_REL = posix3.join(BRAIN_ROOT_REL, "payments");
+var PAY_MEMORY_POLICIES_REL = posix3.join(PAY_MEMORY_ROOT_REL, "policies");
+var PAY_MEMORY_ASSETS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "assets");
+var PAY_MEMORY_DRAFTS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "drafts");
+var PAY_MEMORY_REPORTS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "reports");
+var PAY_MEMORY_PENDING_REL = posix3.join(PAY_MEMORY_ROOT_REL, "_pending");
+var PAY_MEMORY_SPENDING_MD_REL = posix3.join(PAY_MEMORY_POLICIES_REL, "spending.md");
+var PAY_MEMORY_SPENDING_JSON_REL = posix3.join(PAY_MEMORY_POLICIES_REL, "spending.json");
var ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
var HHMM_RE = /^(\d{2}):(\d{2})$/;
function payMemoryDirs(vault) {
- const root = join4(vault, "AI Wiki");
return {
- policies: join4(root, "policies"),
- payments: join4(root, "payments"),
- assets: join4(root, "assets"),
- drafts: join4(root, "drafts"),
- reports: join4(root, "reports")
+ policies: join6(vault, PAY_MEMORY_POLICIES_REL),
+ payments: join6(vault, PAY_MEMORY_ROOT_REL),
+ assets: join6(vault, PAY_MEMORY_ASSETS_REL),
+ drafts: join6(vault, PAY_MEMORY_DRAFTS_REL),
+ reports: join6(vault, PAY_MEMORY_REPORTS_REL),
+ pending: join6(vault, PAY_MEMORY_PENDING_REL)
};
}
function policyPath(vault) {
- return join4(payMemoryDirs(vault).policies, "spending.md");
+ return join6(vault, PAY_MEMORY_SPENDING_MD_REL);
}
function paymentsDateDir(vault, date) {
- return join4(payMemoryDirs(vault).payments, validateIsoDate(date));
+ return join6(payMemoryDirs(vault).payments, validateIsoDate(date));
}
function receiptPath(vault, date, slug) {
- return join4(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);
+ return join6(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);
}
function assetPath(vault, slug) {
- return join4(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);
+ return join6(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);
}
function reportPath(vault, slug) {
- return join4(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);
+ return join6(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);
}
var WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
function validateSlug(slug) {
@@ -2301,8 +2491,8 @@ function redactRawOutput(text) {
return out;
}
// src/core/pay-memory/policy.ts
-import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
-import { dirname as dirname5 } from "node:path";
+import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
+import { dirname as dirname6 } from "node:path";
var DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policy
This file is read by the agent before any paid action. The agent MUST cite
@@ -2351,15 +2541,15 @@ The agent must save:
- payment amount, if available
- service endpoint, if available
- generated asset URL or response identifier
-- payment receipt note in \`AI Wiki/payments/<date>/\`
+- payment receipt note in \`${PAY_MEMORY_ROOT_REL}/<date>/\`
- daily event log entry referencing the receipt
`;
function writePolicyIfMissing(vault, opts = {}) {
const target = policyPath(vault);
const overwrite = opts.overwrite ?? false;
- mkdirSync3(dirname5(target), { recursive: true });
+ mkdirSync3(dirname6(target), { recursive: true });
if (overwrite) {
- const existed = existsSync4(target);
+ const existed = existsSync5(target);
atomicWriteFileSync(target, DEFAULT_POLICY_TEMPLATE);
return existed ? buildPolicyResult(target, "overwritten") : buildPolicyResult(target, "created");
}
@@ -2383,8 +2573,8 @@ function buildPolicyResult(path, status) {
};
}
// src/core/vault.ts
-import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, writeFileSync } from "node:fs";
-import { dirname as dirname6, join as join5, relative as relative2 } from "node:path";
+import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync } from "node:fs";
+import { dirname as dirname7, join as join7, relative as relative2 } from "node:path";
var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
var PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
@@ -2497,12 +2687,12 @@ function listVaultPages(vaultDir, opts = {}) {
function walk(root, dir, skipDirs, skipFiles, out) {
let entries;
try {
- entries = readdirSync(dir, { withFileTypes: true });
+ entries = readdirSync2(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
- const full = join5(dir, entry.name);
+ const full = join7(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
@@ -2703,7 +2893,7 @@ function renderPolicySection(input) {
break;
case "not_checked":
default:
- out.push("Not checked. The receipt was created without a policy decision —", "either no `AI Wiki/policies/spending.json` is configured, or the", "caller chose not to evaluate the policy. This is *not* a claim", "that the call was allowed.");
+ out.push("Not checked. The receipt was created without a policy decision —", `either no \`${PAY_MEMORY_SPENDING_JSON_REL}\` is configured, or the`, "caller chose not to evaluate the policy. This is *not* a claim", "that the call was allowed.");
break;
}
if (input.policyRule?.trim()) {
@@ -2720,7 +2910,7 @@ function renderPolicySection(input) {
if (input.approvalRequestId?.trim() || input.approvalStatus?.trim() || input.approvedBy?.trim()) {
out.push("", "Approval:");
if (input.approvalRequestId?.trim()) {
- out.push("", `Request: [[AI Wiki/payments/_pending/${input.approvalRequestId.trim()}]]`);
+ out.push("", `Request: [[${PAY_MEMORY_PENDING_REL}/${input.approvalRequestId.trim()}]]`);
}
if (input.approvalStatus?.trim()) {
out.push(`Status: \`${input.approvalStatus.trim()}\``);
@@ -2758,7 +2948,7 @@ function renderReceiptBody(input) {
"",
"Policy file:",
"",
- "[[AI Wiki/policies/spending]]",
+ `[[${stripMarkdownExt(PAY_MEMORY_SPENDING_MD_REL)}]]`,
"",
...renderPolicySection(input),
"## Expected cost",
@@ -2888,14 +3078,14 @@ function renderAssetBody(input) {
`);
}
// src/core/pay-memory/report.ts
-import { readdirSync as readdirSync2 } from "node:fs";
-import { join as join6 } from "node:path";
+import { readdirSync as readdirSync3 } from "node:fs";
+import { join as join8 } from "node:path";
var REPORT_FRONTMATTER_TYPE = "payment-report";
function aggregateReceipts(vault, date) {
const dir = paymentsDateDir(vault, date);
let entries;
try {
- entries = readdirSync2(dir, { withFileTypes: true });
+ entries = readdirSync3(dir, { withFileTypes: true });
} catch (err) {
if (err?.code === "ENOENT")
return [];
@@ -2907,7 +3097,7 @@ function aggregateReceipts(vault, date) {
continue;
if (!entry.name.toLowerCase().endsWith(".md"))
continue;
- const full = join6(dir, entry.name);
+ const full = join8(dir, entry.name);
let meta;
try {
[meta] = parseFrontmatter(full);
@@ -3008,10 +3198,10 @@ function renderReportBody(date, title, task, summaries) {
}
// src/core/pay-memory/policy-rules.ts
import { readFileSync as readFileSync6 } from "node:fs";
-import { join as join7 } from "node:path";
+import { join as join9 } from "node:path";
var POLICY_SCHEMA_VERSION = 1;
function policyJsonPath(vault) {
- return join7(payMemoryDirs(vault).policies, "spending.json");
+ return join9(payMemoryDirs(vault).policies, "spending.json");
}
function loadPolicyRules(vault) {
const target = policyJsonPath(vault);
@@ -3173,13 +3363,13 @@ function checkPolicy(vault, request) {
}
// src/core/pay-memory/approval.ts
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
-import { join as join8 } from "node:path";
+import { join as join10 } from "node:path";
var PENDING_REQUEST_FRONTMATTER_TYPE = "pending-payment-request";
function pendingDir(vault) {
- return join8(payMemoryDirs(vault).payments, "_pending");
+ return join10(vault, PAY_MEMORY_PENDING_REL);
}
function pendingRequestPath(vault, id) {
- return join8(pendingDir(vault), `${validateSlug(id)}.md`);
+ return join10(pendingDir(vault), `${validateSlug(id)}.md`);
}
function writePendingRequest(vault, input) {
if (!input.service?.trim())
@@ -3490,7 +3680,7 @@ var openclaw_default = definePluginEntry({
config_keys: Object.keys(discovery.data).sort(),
config: redactMapping(discovery.data),
vault_path: vault,
- vault_exists: existsSync5(vault)
+ vault_exists: existsSync6(vault)
};
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
@@ -3516,7 +3706,7 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync5(vault))
+ if (!existsSync6(vault))
throw new Error(`vault directory missing: ${vault}`);
const pattern = params["pattern"] ?? null;
const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
@@ -3580,7 +3770,7 @@ var openclaw_default = definePluginEntry({
const created = [];
const skipped = [];
for (const dir of [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports]) {
- const existed = existsSync5(dir);
+ const existed = existsSync6(dir);
mkdirSync5(dir, { recursive: true });
(existed ? skipped : created).push(vaultRelative(dir, vault));
}
@@ -3758,7 +3948,7 @@ var openclaw_default = definePluginEntry({
});
api.registerTool({
name: "payment_report_generate",
- description: "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",
+ description: `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,
parameters: {
type: "object",
properties: {
@@ -3790,7 +3980,7 @@ var openclaw_default = definePluginEntry({
});
api.registerTool({
name: "payment_policy_check",
- description: "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",
+ description: `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,
parameters: {
type: "object",
properties: {
diff --git a/package.json b/package.json
index fa418373..c6c0d2a9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.18",
+ "version": "0.11.0",
"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 c7ea9c75..c2efaf38 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.18"
+version: "0.11.0"
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 41d86cb0..ee83dcef 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.18",
+ "version": "0.11.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index c02f1226..bd7e2b65 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.18"
+version: "0.11.0"
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 c2374fcf..e75ab3f4 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.18"
+version = "0.11.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.md
index 12ff502a..4d22a4df 100644
--- a/skills/brain-memory/SKILL.md
+++ b/skills/brain-memory/SKILL.md
@@ -36,7 +36,7 @@ Optional but **strongly recommended**:
Optional:
- `scope`: soft category for later application-scope matching — `writing`, `coding`, `process`, `design`, `infra`, `docs`. Pick the narrowest accurate one.
-- `source`: array of wikilinks to the artifacts or notes that triggered the signal — `[[Daily/2026.05.14]]`, `[[blog-header-draft]]`. Improves later auditability.
+- `source`: array of wikilinks to the artifacts or notes that triggered the signal — `[[src/cli/main.ts]]`, `[[docs/release-notes/v0.11.0]]`. Improves later auditability.
The server creates `Brain/inbox/sig-<date>-<slug>.md` and resolves collisions deterministically.
@@ -53,7 +53,7 @@ Discover applicable preferences first. Options:
Parameters:
- `pref_id`: id of the preference you are recording against (`pref-no-internal-abbrev`).
-- `artifact`: wikilink identifying what you produced — `[[Daily/2026.05.14#section-blog-post]]`, `[[src/cli/main.ts]]`, `[[docs/release-notes/v0.9.0.md]]`. The wikilink resolves in Obsidian; use `#anchor` to point at a specific section when relevant.
+- `artifact`: wikilink identifying what you produced — `[[src/cli/main.ts]]`, `[[docs/release-notes/v0.11.0.md]]`, `[[Brain/preferences/pref-no-internal-abbrev]]`. The wikilink resolves in Obsidian; use `#anchor` to point at a specific section when relevant.
- `result`: `applied` if the rule held in this artifact, `violated` if you (or another agent) broke it. Recording a `violated` event is not a failure — it is what trains the system.
- `agent`: your runtime identity.
@@ -99,7 +99,7 @@ o2b brain feedback \
o2b brain apply-evidence \
--pref pref-no-internal-abbrev \
- --artifact "[[Daily/2026.05.14#blog-post]]" \
+ --artifact "[[src/cli/main.ts#L120]]" \
--result applied \
--agent claude
```
diff --git a/skills/open-second-brain/SKILL.md b/skills/open-second-brain/SKILL.md
index 73a822b2..e00fe6a3 100644
--- a/skills/open-second-brain/SKILL.md
+++ b/skills/open-second-brain/SKILL.md
@@ -1,24 +1,24 @@
---
name: open-second-brain
-description: Use Open Second Brain to read, write, and maintain an agent-owned second brain in an Obsidian-compatible Markdown vault. The writable agent-facing surface is the `Brain/` layer (see the `brain-memory` skill for signal/evidence recording). `AI Wiki/` and `Daily/` are read surfaces; Pay Memory is a separate orthogonal layer for paid-action audit.
+description: Use Open Second Brain to read, write, and maintain an agent-owned second brain in an Obsidian-compatible Markdown vault. The agent owns one top-level directory (`Brain/`); Pay Memory nests under `Brain/payments/`. User-authored notes live wherever the operator names them and are read-only inputs when listed in `notes.read_paths`.
---
# Open Second Brain
Use this skill when a user asks an agent to use, configure, inspect, or maintain Open Second Brain.
-## Layers
+## Layout
-Open Second Brain organises the vault into three agent-facing layers. Know which one to touch and when.
+Open Second Brain owns one top-level directory in the vault: `Brain/`. Everything the agent writes lives under it.
-- **`Brain/`** — agent-writable observing memory. Taste signals, accreted preferences (unconfirmed → confirmed → retired), evidence log, snapshots. This is where you record what the user prefers and how you applied those preferences in real work. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_digest`, `brain_query`, `brain_doctor` — see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *` (11 verbs).
-- **`AI Wiki/`** and **`Daily/`** — read surfaces. `AI Wiki/` holds identity files, index/hot list, system snapshots, and the Pay Memory subtree. `Daily/` holds the chronological event log and human narrative. Read through `second_brain_query` and `vault_health`. Brain operations do not write here; the only writes into `AI Wiki/` come from the Pay Memory tools (next bullet).
-- **Pay Memory** — orthogonal audit layer for paid agent actions (`AI Wiki/payments/`, `assets/`, `drafts/`, `reports/`, `policies/`). Agents use `payment_*` MCP tools when they make paid API calls. Pay Memory operates independently of Brain.
+- **`Brain/`** - agent-writable observing memory. Taste signals, accreted preferences (unconfirmed → confirmed → retired), evidence log, snapshots. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_digest`, `brain_query`, `brain_doctor` - see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *`.
+- **`Brain/payments/`** - Pay Memory subtree (optional). Receipts, generated-asset notes, drafts, reports, policies, pending-approval requests. Agents use `payment_*` MCP tools when they make paid API calls. Same write contract as the rest of `Brain/` - one root.
+- **User-authored notes** - the operator's daily journal, weekly notes, project notes, etc. Folder names are operator-chosen. The agent reads these paths only when they appear under `notes.read_paths` in `Brain/_brain.yaml`; the agent never writes to them.
## Core principles
- Treat the vault as user-owned durable knowledge.
-- Write only into the `Brain/` layer (signals and evidence) or, for paid actions, into the Pay Memory subtree under `AI Wiki/`. Do not write into `AI Wiki/notes/`, `AI Wiki/identity/`, `Daily/`, or any non-Pay-Memory area under `AI Wiki/`.
+- Write only into `Brain/` (covers both the observing-memory layer and the optional Pay Memory subtree). Never write to user-authored note folders.
- Keep raw operational evidence separate from synthesized knowledge: per-event records go to `Brain/log/`, preferences live in `Brain/preferences/`.
- Never write secrets, tokens, passwords, private keys, or credential-bearing connection strings.
- Prefer deterministic CLI commands (`o2b brain ...`, `o2b doctor`, `o2b status`) over guessing file paths.
@@ -27,14 +27,14 @@ Open Second Brain organises the vault into three agent-facing layers. Know which
1. Check whether Open Second Brain is configured: `o2b status` or `second_brain_status` MCP tool.
2. Read the machine-local config if available (vault path, agent identity, timezone).
-3. Read the vault-local operating manual `Brain/_BRAIN.md` — this is the per-vault contract for agents.
+3. Read the vault-local operating manual `Brain/_BRAIN.md` - this is the per-vault contract for agents.
4. Record taste signals as they arrive in dialogue via `brain_feedback` (see the `brain-memory` skill).
5. After producing a durable artifact, check applicable preferences and record evidence via `brain_apply_evidence` (see the `brain-memory` skill).
-6. For read access to `AI Wiki/` or `Daily/` content, use `second_brain_query`.
+6. For read access to vault pages by title, use `second_brain_query`.
## Safety
-If a write operation might affect personal notes or anything outside the `Brain/` layer (and not Pay Memory), ask for explicit confirmation. When in doubt, prefer `Brain/`.
+If a write operation might affect anything outside the `Brain/` directory, ask for explicit confirmation. When in doubt, prefer `Brain/`.
## See also
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 9934e1d7..5b576667 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -30,7 +30,6 @@ import {
cmdBrainExport,
cmdBrainUpgrade,
handleBrainSnapshotSubcommand,
- cmdBrainMigrateFrontmatter,
cmdBrainScanInline,
cmdBrainImportSession,
cmdBrainImportClaudeMemory,
@@ -84,7 +83,6 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
case "rollback": return await cmdBrainRollback(rest);
case "doctor": return await cmdBrainDoctor(rest);
case "backlinks": return await cmdBrainBacklinks(rest);
- case "migrate-frontmatter": return await cmdBrainMigrateFrontmatter(rest);
case "scan-inline": return await cmdBrainScanInline(rest);
case "import-session": return await cmdBrainImportSession(rest);
case "import-claude-memory": return await cmdBrainImportClaudeMemory(rest);
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 99dc37fe..c1bc5983 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -32,8 +32,7 @@ Brain verbs (observing memory):
--dry-run previews via the same diff renderer)
doctor Validate Brain invariants (--strict promotes warnings to exit 2)
backlinks List inbound references to a Brain artifact id
- migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'
- scan-inline Capture @osb markers from vault markdown files (Daily/, project notes, etc.)
+ scan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yaml
import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)
import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferences
page-dedup Detect (and optionally merge) near-duplicate vault pages
@@ -123,12 +122,6 @@ export const VERB_HELP: Record<string, string> = {
backlinks:
"usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
"List inbound references to the given Brain artifact id (preference, retired, signal).\n",
- "migrate-frontmatter":
- "usage: o2b brain migrate-frontmatter [--vault <path>] [--apply] [--yes] [--json]\n" +
- "Rewrite legacy Group C frontmatter keys ('status:', 'applied_count:', ...)\n" +
- "to the '_'-prefixed shape across Brain/preferences/ and Brain/retired/.\n" +
- "Default is --dry-run; --apply takes a pre-run snapshot (rollback via run_id).\n" +
- "--apply requires --yes in non-interactive mode (--json or non-TTY stdin).\n",
"set-primary":
"usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
" o2b brain set-primary --clear [--vault <path>] [--json]\n" +
@@ -187,9 +180,9 @@ export const VERB_HELP: Record<string, string> = {
upgrade:
"usage: o2b brain upgrade [--vault <path>] [--dry-run | --apply | --check]\n" +
" [--yes] [--json]\n" +
- "Migrate the three release-owned files (`Brain/_brain.yaml`,\n" +
- "`Brain/_BRAIN.md`, `AI Wiki/_OPEN_SECOND_BRAIN.md`) forward to the\n" +
- "shape the installed open-second-brain release ships.\n" +
+ "Migrate the release-owned files (`Brain/_brain.yaml`,\n" +
+ "`Brain/_BRAIN.md`) forward to the shape the installed\n" +
+ "open-second-brain release ships.\n" +
"User-owned content (preferences/, retired/, inbox/, log/) is\n" +
"never touched.\n" +
"--dry-run (default) prints a per-file plan with a unified diff\n" +
@@ -200,9 +193,8 @@ export const VERB_HELP: Record<string, string> = {
"via run_id) and rewrites every pending file. Requires --yes in\n" +
"non-interactive mode (--json or non-TTY stdin).\n" +
"_brain.yaml merge is purely additive: missing schema-keys are\n" +
- "appended, existing values stay. _BRAIN.md and\n" +
- "_OPEN_SECOND_BRAIN.md are byte-compared against the rendered\n" +
- "template and overwritten when they differ.\n",
+ "appended, existing values stay. _BRAIN.md is byte-compared\n" +
+ "against the rendered template and overwritten when it differs.\n",
explorer:
"usage: o2b brain explorer [--port <n>] [--vault <path>]\n" +
" o2b brain explorer --export <path> [--force] [--vault <path>]\n" +
diff --git a/src/cli/brain/rollback-prompt.ts b/src/cli/brain/rollback-prompt.ts
index 251dad75..da82e9ae 100644
--- a/src/cli/brain/rollback-prompt.ts
+++ b/src/cli/brain/rollback-prompt.ts
@@ -15,6 +15,8 @@
import { existsSync, readdirSync, statSync, type Dirent } from "node:fs";
import { resolve } from "node:path";
+import { BRAIN_ROOT_REL } from "../../core/brain/paths.ts";
+
export interface DiffSummary {
readonly preferences: number;
readonly retired: number;
@@ -22,7 +24,7 @@ export interface DiffSummary {
}
export function diffSummary(vault: string): DiffSummary {
- const root = resolve(vault, "Brain");
+ const root = resolve(vault, BRAIN_ROOT_REL);
const safeCount = (p: string): number => {
if (!existsSync(p)) return 0;
try {
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 8818197e..7bed78f2 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -17,7 +17,6 @@ export { cmdBrainExplorer } from "./explorer.ts";
export { cmdBrainExport } from "./export.ts";
export { cmdBrainUpgrade } from "./upgrade.ts";
export { cmdBrainSnapshotDiff, handleBrainSnapshotSubcommand } from "./snapshot.ts";
-export { cmdBrainMigrateFrontmatter } from "./migrate-frontmatter.ts";
export { cmdBrainScanInline } from "./scan-inline.ts";
export { cmdBrainImportSession } from "./import-session.ts";
export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";
diff --git a/src/cli/brain/verbs/migrate-frontmatter.ts b/src/cli/brain/verbs/migrate-frontmatter.ts
deleted file mode 100644
index d7dc3e8e..00000000
--- a/src/cli/brain/verbs/migrate-frontmatter.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
-import { planMigration, applyMigration, MigrationError } from "../../../core/brain/migrate-frontmatter.ts";
-import { appendLogEvent } from "../../../core/brain/log.ts";
-import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
-import { isoSecond } from "../../../core/brain/time.ts";
-import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
-
-export async function cmdBrainMigrateFrontmatter(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- apply: { type: "boolean" },
- yes: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = resolveAgentName(config);
-
- if (flags["dry-run"] && flags["apply"]) return fail("brain migrate-frontmatter: --dry-run and --apply are mutually exclusive");
- const apply = Boolean(flags["apply"]);
-
- if (apply && !flags["yes"] && (flags["json"] || !process.stdin.isTTY)) {
- return fail("brain migrate-frontmatter --apply requires --yes in non-interactive mode (--json or non-TTY stdin)");
- }
-
- if (!apply) {
- let plan;
- try { plan = planMigration(vault); }
- catch (exc) { return fail(`migrate-frontmatter plan failed: ${(exc as Error).message ?? exc}`); }
- if (flags["json"]) {
- okJson({
- files_scanned: plan.files_scanned,
- files_to_migrate: plan.files_to_migrate.length,
- files_already_new: plan.files_already_new.length,
- collisions: plan.collisions.length,
- collision_files: plan.collisions.map((c) => ({ path: c.path, field: c.field })),
- });
- return 0;
- }
- ok(`files_scanned: ${plan.files_scanned}`);
- ok(`files_to_migrate: ${plan.files_to_migrate.length}`);
- ok(`files_already_new: ${plan.files_already_new.length}`);
- ok(`collisions: ${plan.collisions.length}`);
- if (plan.collisions.length > 0) {
- info("Collisions (both legacy and '_'-prefixed shape present):");
- for (const c of plan.collisions) info(` - ${c.path} (field: ${c.field})`);
- }
- if (plan.files_to_migrate.length === 0) ok("nothing to migrate; re-run with --apply --yes when there is.");
- else ok("re-run with --apply --yes to rewrite these files.");
- return 0;
- }
-
- let result;
- try { result = await applyMigration(vault, { snapshot: true, now: new Date() }); }
- catch (exc) {
- if (exc instanceof MigrationError) { process.stderr.write(`error: ${exc.message}\n`); return 1; }
- return fail(`migrate-frontmatter failed: ${(exc as Error).message ?? exc}`);
- }
-
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date()),
- eventType: BRAIN_LOG_EVENT_KIND.migrateFrontmatter,
- body: {
- run_id: result.run_id, agent,
- snapshot: result.snapshot_path ?? "(none)",
- files_scanned: String(result.plan.files_scanned),
- files_migrated: String(result.files_migrated.length),
- files_already_new: String(result.plan.files_already_new.length),
- collisions: String(result.plan.collisions.length),
- },
- });
- } catch (err) { process.stderr.write(`warning: append migrate-frontmatter log failed: ${(err as Error).message}\n`); }
-
- if (flags["json"]) {
- okJson({
- run_id: result.run_id, snapshot_path: result.snapshot_path,
- files_scanned: result.plan.files_scanned,
- files_migrated: result.files_migrated.length,
- files_already_new: result.plan.files_already_new.length,
- collisions: result.plan.collisions.length,
- });
- return 0;
- }
- ok(`run_id: ${result.run_id}`);
- ok(`snapshot: ${result.snapshot_path ?? "(none)"}`);
- ok(`files_migrated: ${result.files_migrated.length}`);
- ok(`files_already_new: ${result.plan.files_already_new.length}`);
- return 0;
-}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index fd3aa9a7..09da2b65 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -15,13 +15,10 @@ import {
defaultConfigPath,
discoverConfig,
redactMapping,
- resolveAgentName,
- resolveTimezone,
setConfigValue,
} from "../core/config.ts";
+import { BRAIN_INDEX_REL } from "../core/brain/paths.ts";
import { doctor } from "../core/doctor.ts";
-import { appendEvent } from "../core/event-log.ts";
-import { bootstrapVault } from "../core/init.ts";
import { listVaultPages, writeFrontmatter } from "../core/vault.ts";
import { CliError, parseFlags } from "./argparse.ts";
import { handleBrainSubcommand } from "./brain.ts";
@@ -30,7 +27,6 @@ import { handleSearchSubcommand } from "./search.ts";
import { handleVaultSubcommand } from "./vault.ts";
import {
NoVaultConfiguredError,
- normalizeFlagString,
requireVault,
resolveSemanticConfigState,
sortedReplacer,
@@ -136,28 +132,13 @@ async function cmdInit(argv: string[]): Promise<number> {
}
}
- let created: string[];
- try {
- created = bootstrapVault(vault, {
- name: String(flags["name"] ?? "Second Brain"),
- agentName,
- force: Boolean(flags["force"]),
- });
- } catch (exc) {
- process.stderr.write(`error: failed to initialize vault: ${(exc as Error).message ?? exc}\n`);
- return 1;
- }
-
- if (created.length > 0) {
- process.stdout.write(`initialized vault: ${vault}\n`);
- for (const p of created) process.stdout.write(` created: ${p}\n`);
- } else {
- process.stdout.write(`vault already initialized: ${vault}\n`);
- process.stdout.write("use --force to overwrite existing files\n");
- }
- // Persist vault/agent/timezone in one guarded block so a write failure
- // (read-only config dir, disk full) surfaces as a clean CLI exit instead
- // of an uncaught exception after the vault scaffolding is already on disk.
+ // v0.11.0: `o2b init` no longer writes content into the vault.
+ // Content scaffolding belongs to `o2b brain init` (the Brain layer).
+ // This verb persists machine-local config (vault path, agent name,
+ // timezone) so other CLI verbs default to the right vault without
+ // a --vault flag.
+ void flags["force"]; // accepted for backward CLI compat; unused
+ void flags["name"]; // accepted for backward CLI compat; unused
let configPath: string;
try {
configPath = setConfigValue("vault", resolve(vault));
@@ -169,6 +150,7 @@ async function cmdInit(argv: string[]): Promise<number> {
);
return 1;
}
+ process.stdout.write(`initialized vault: ${resolve(vault)}\n`);
process.stdout.write(`vault path persisted to: ${configPath}\n`);
if (agentName) {
process.stdout.write(`agent name registered: ${agentName}\n`);
@@ -262,50 +244,6 @@ async function cmdDoctor(argv: string[]): Promise<number> {
return allOk ? 0 : 1;
}
-async function cmdAppendEvent(argv: string[]): Promise<number> {
- const { flags, positional } = parseFlags(argv, {
- vault: { type: "string" },
- as: { type: "string" },
- date: { type: "string" },
- time: { type: "string" },
- config: { type: "string" },
- });
- if (positional.length < 1) {
- process.stderr.write("error: append-event requires a message argument\n");
- return 2;
- }
- const message = positional[0]!;
- // §32F (v0.10.8): resolve the agent identity through the shared
- // resolver instead of the literal `"agent"` fallback. The resolver
- // chain honours `--as` -> `VAULT_AGENT_NAME` env -> `agent_name`
- // from the plugin config -> the placeholder `"agent"` (only as the
- // very last resort). Cron-jobs and shell scripts get the
- // config-declared identity instead of corrupted `@agent` entries.
- const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const tz = resolveTimezone(config);
- const explicit = normalizeFlagString(flags["as"]);
- if (flags["as"] !== undefined && explicit === null) {
- process.stderr.write("error: --as must be a non-empty string when provided\n");
- return 2;
- }
- const agent = explicit ?? resolveAgentName(config);
-
- let path: string;
- try {
- path = await appendEvent(vault, agent, message, {
- date: (flags["date"] as string | undefined) ?? null,
- time: (flags["time"] as string | undefined) ?? null,
- tz,
- });
- } catch (exc) {
- process.stderr.write(`error: failed to append event: ${(exc as Error).message ?? exc}\n`);
- return 1;
- }
- process.stdout.write(`appended: ${resolve(path)}\n`);
- return 0;
-}
-
async function cmdExportConfig(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, {
config: { type: "string" },
@@ -353,7 +291,7 @@ async function cmdIndex(argv: string[]): Promise<number> {
const rel = p.path.startsWith(vault) ? p.path.slice(vault.length).replace(/^\/+/, "") : p.path;
lines.push(`- [[${p.title}]] \`${rel}\``);
}
- const indexPath = resolve(vault, "AI Wiki", "index.md");
+ const indexPath = resolve(vault, BRAIN_INDEX_REL);
try {
writeFrontmatter(indexPath, { title: "Index", type: "index" }, lines.join("\n"));
} catch (exc) {
@@ -526,7 +464,6 @@ Commands:
status Show Open Second Brain configuration status
init Initialize a vault profile with required files
doctor Run health checks on vault, config, and plugins
- append-event Append an event to the configured event log backend
export-config Write a redacted config snapshot
index Regenerate the vault index from discovered pages
mcp Run the optional MCP tool server (stdio JSON-RPC)
@@ -601,8 +538,8 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
"Read-only by default. Prints the Hermes commands you must run yourself " +
"(this tool never touches ~/.hermes/config.yaml or the installed plugin). " +
"With --apply-local it may remove the machine-local Open Second Brain " +
- "config directory only. Your vault, Daily/, AI Wiki/, and Markdown notes " +
- "are never removed. With --remove-cli it also removes the o2b/vault-log " +
+ "config directory only. Your vault and Markdown notes are never removed. " +
+ "With --remove-cli it also removes the o2b/vault-log " +
"symlinks created by 'o2b install-cli'.\n",
);
}
@@ -617,8 +554,6 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
return await cmdInit(rest);
case "doctor":
return await cmdDoctor(rest);
- case "append-event":
- return await cmdAppendEvent(rest);
case "export-config":
return await cmdExportConfig(rest);
case "index":
diff --git a/src/cli/uninstall.ts b/src/cli/uninstall.ts
index 11cb5a17..ceca5bd8 100644
--- a/src/cli/uninstall.ts
+++ b/src/cli/uninstall.ts
@@ -151,7 +151,7 @@ export function renderPlan(plan: UninstallPlan): string {
} else {
lines.push(" (no vault path recorded in config; check your runtime settings)");
}
- lines.push(" Your Markdown notes, Daily/, and AI Wiki/ stay exactly as they are.");
+ lines.push(" Your Markdown notes stay exactly as they are.");
lines.push("");
if (plan.applyLocal) {
diff --git a/src/core/brain/claude-memory-manifest.ts b/src/core/brain/claude-memory-manifest.ts
index cf18f8a3..2f401909 100644
--- a/src/core/brain/claude-memory-manifest.ts
+++ b/src/core/brain/claude-memory-manifest.ts
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
export interface ClaudeMemoryManifestEntry {
readonly pref_id: string;
@@ -15,7 +16,7 @@ export interface ClaudeMemoryManifest {
}
function manifestPath(vault: string): string {
- return join(vault, "Brain", ".imports", "claude-memory.json");
+ return join(vault, BRAIN_ROOT_REL, ".imports", "claude-memory.json");
}
/**
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index c3d03e88..78e09c44 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -57,7 +57,6 @@ import {
import { checkInstructionFileCeiling } from "./trust/instruction-file-ceiling.ts";
import { brainConfigPath, brainDirs } from "./paths.ts";
import {
- BrainDoubleShapeError,
BrainStatusFolderMismatchError,
parsePreference,
parseRetired,
@@ -517,17 +516,6 @@ function checkPreferences(
path,
message: err.message,
});
- } else if (err instanceof BrainDoubleShapeError) {
- // §24 dual-shape parser collision is operator-actionable
- // (run `o2b brain migrate-frontmatter --apply` or hand-edit
- // the file). Surface as warning, not error, so the dream
- // loop still proceeds for the rest of the vault.
- issues.push({
- severity: "warning",
- code: "frontmatter-double-shape",
- path,
- message: err.message,
- });
} else {
// Distinguish field-missing errors (write-time contract) from
// unexpected throws so the CLI report stays useful.
@@ -602,13 +590,6 @@ function checkRetired(
path,
message: err.message,
});
- } else if (err instanceof BrainDoubleShapeError) {
- issues.push({
- severity: "warning",
- code: "frontmatter-double-shape",
- path,
- message: err.message,
- });
} else {
const msg = (err as Error).message ?? String(err);
const isMissingField = /missing field/.test(msg);
@@ -726,16 +707,13 @@ function checkWikilinks(
}
/**
- * Build the universe of valid wikilink targets inside `Brain/`. We
- * deliberately do NOT pull in legacy `AI Wiki/` or `Daily/` notes — a
- * Brain artifact pointing at a Daily entry (artifact wikilink in a
- * `apply-evidence` event) is valid, but those targets sit outside the
- * Brain layer and are out of scope for this doctor pass.
+ * Build the universe of valid wikilink targets inside `Brain/`. The
+ * doctor pass is scoped to Brain content; cross-layer wikilinks
+ * pointing at user-authored notes outside Brain/ are out of scope
+ * and stay accepted.
*
- * To keep the check honest for cross-layer wikilinks (e.g. a
- * `retired_by: [[Brain/log/2026-05-14]]`), we accept *any* `.md` file
- * inside `Brain/`. The set is keyed by basename (without `.md`) so
- * Obsidian's basename match works.
+ * Set is keyed by basename (without `.md`) so Obsidian's basename
+ * match works.
*/
function checkBrokenBacklinks(
vault: string,
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 0b41492a..10af4c13 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -1449,12 +1449,10 @@ function planRefresh(
// still has the v0.9.x placeholder will fail the body check and
// get rewritten on the next pass.
const previousValue = rec.pref.confidence_value;
- // For numeric drift, `null` on disk (legacy pre-v0.10.3 file) is
- // treated as "matches whatever we just computed" so a no-op
- // rerun stays a no-op. The body-bytes check in
- // `wouldRewritePreference` below still triggers the one-off
- // migration write because the legacy frontmatter shape will not
- // match the new one byte-for-byte.
+ // A `null` previous value (file not yet touched by dream) is
+ // treated as "matches whatever we just computed" — the
+ // body-bytes check in `wouldRewritePreference` is what triggers
+ // the write that populates the field.
const valueDifferent =
previousValue !== null
&& Math.abs(previousValue - confidence.value) > 1e-6;
@@ -1528,35 +1526,20 @@ function planRefresh(
}
/**
- * Confidence computation. Returns both the categorical band (the
- * existing agent-visible contract) and the numeric value behind it
- * (§10 Tier-A addition).
+ * Confidence computation. Returns both the numeric value and the
+ * categorical band derived from it.
*
- * The numeric value is `Wilson 95% lower bound × freshness decay`:
+ * `value = wilson_low(applied, n) * freshness`:
*
- * - `wilson_low(applied, n)` where `n = applied + violated` —
- * a conservative lower bound on the application rate. `n == 0`
- * yields `0`.
+ * - `wilson_low(applied, n)` where `n = applied + violated` -
+ * a conservative 95% lower bound on the application rate.
+ * `n == 0` yields `0`.
* - `freshness` linearly decays from `1.0` at age 0 to `0.0` at
* `retire.stale_evidence_days`. `null` last_evidence_at → `0`.
*
- * Band derivation is the **max** of two views:
- *
- * 1. The legacy step-function (kept verbatim) — preserves every
- * published boundary so existing tests and agent contracts stay
- * intact: `applied <= low_max_applied` ⇒ `low`,
- * `violated >= applied` ⇒ `low`, `applied >= high_min_applied ∧
- * violated == 0 ∧ fresh` ⇒ `high`, else `medium`.
- * 2. The numeric thresholds (`medium_min`, `high_min`) applied to
- * `value` — gives a `low | medium | high` view that can only
- * lift the legacy band, never lower it.
- *
- * Taking the max means a future operator can lower `high_min` to
- * promote `medium` prefs to `high` based on observed performance,
- * without ever demoting a pref that the legacy view already calls
- * `high` (because the legacy floor sticks). The numeric value is
- * always returned and is what the digest's drop tracker compares
- * across runs.
+ * Band thresholds (`confidence.medium_min`, `confidence.high_min`)
+ * are applied to `value` directly. The numeric value is what the
+ * digest's drop tracker compares across runs.
*/
export interface ConfidenceComputeResult {
readonly value: number;
@@ -1601,47 +1584,14 @@ export function computeConfidence(
const rawValue = wilsonLow * freshness;
const value = Math.round(rawValue * 10000) / 10000;
- // Legacy step-function band (the published contract).
- let legacyBand: BrainConfidence = BRAIN_CONFIDENCE.medium;
- if (applied <= cfg.confidence.low_max_applied) {
- legacyBand = BRAIN_CONFIDENCE.low;
- } else if (applied > 0 && violated >= applied) {
- legacyBand = BRAIN_CONFIDENCE.low;
- } else {
- let highEligibleFresh = false;
- if (lastEvidenceAt) {
- const ageMs = now.getTime() - Date.parse(lastEvidenceAt);
- const freshLimitMs =
- cfg.retire.stale_evidence_days *
- cfg.confidence.high_freshness_factor *
- 24 *
- 3600 *
- 1000;
- highEligibleFresh = Number.isFinite(ageMs) && ageMs < freshLimitMs;
- }
- if (
- applied >= cfg.confidence.high_min_applied
- && violated === 0
- && highEligibleFresh
- ) {
- legacyBand = BRAIN_CONFIDENCE.high;
- } else {
- legacyBand = BRAIN_CONFIDENCE.medium;
- }
- }
-
- // Numeric-threshold band (can only lift legacy when paired via max).
- let numericBand: BrainConfidence;
+ let band: BrainConfidence;
if (value >= cfg.confidence.high_min) {
- numericBand = BRAIN_CONFIDENCE.high;
+ band = BRAIN_CONFIDENCE.high;
} else if (value >= cfg.confidence.medium_min) {
- numericBand = BRAIN_CONFIDENCE.medium;
+ band = BRAIN_CONFIDENCE.medium;
} else {
- numericBand = BRAIN_CONFIDENCE.low;
+ band = BRAIN_CONFIDENCE.low;
}
-
- const band =
- BAND_RANK[numericBand] > BAND_RANK[legacyBand] ? numericBand : legacyBand;
return Object.freeze({ value, band });
}
diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.ts
index d34acd73..c4668940 100644
--- a/src/core/brain/import-claude-memory.ts
+++ b/src/core/brain/import-claude-memory.ts
@@ -15,7 +15,7 @@ import {
import { planAction, type PlannedFile } from "./claude-memory-plan.ts";
import { renderPreferenceFromMemory, slugifyMemoryName } from "./claude-memory-render.ts";
import { assertSafeMemoryPath } from "./claude-memory-paths.ts";
-import { preferencePath } from "./paths.ts";
+import { BRAIN_PREFERENCES_REL, preferencePath } from "./paths.ts";
export interface ImportClaudeMemoryOpts {
readonly vault: string;
@@ -175,7 +175,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
const applied: PlannedFile[] = [];
if (filesToWrite.length > 0) {
- mkdirSync(join(opts.vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(opts.vault, BRAIN_PREFERENCES_REL), { recursive: true });
}
for (const { plan, body: freshBody, sha256, slug } of filesToWrite) {
const prefFile = preferencePath(opts.vault, slug);
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 38ac67b1..a5afd5ea 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -2,23 +2,15 @@
* Brain layer bootstrap.
*
* Creates the `<vault>/Brain/` directory tree, drops the default
- * `_brain.yaml`, and renders the two Markdown templates the agent reads
- * each session: `Brain/_BRAIN.md` (operating manual for the writable
- * layer) and `AI Wiki/_OPEN_SECOND_BRAIN.md` (Brain-first vault
- * overview that replaces the legacy file).
+ * `_brain.yaml`, and renders the operating manual the agent reads each
+ * session at `Brain/_BRAIN.md`.
*
- * Behaviour summary (design doc §15 Task 5, §12.1):
+ * Behaviour summary:
*
* - Directory creation is idempotent.
* - `Brain/_brain.yaml` and `Brain/_BRAIN.md` are written on first
* run; subsequent runs without `force` skip them. `force: true`
* overwrites both.
- * - `AI Wiki/_OPEN_SECOND_BRAIN.md` is **always** overwritten on every
- * bootstrap, regardless of `force`. The design owner accepted this
- * trade-off at near-zero current user count: the file is the
- * instruction surface agents read first; stale copy hurts more
- * than the (negligible) risk of overwriting a manual edit. The
- * legacy file's prior content is not backed up.
* - Bootstrap refuses to run if the machine-level plugin config (the
* one `o2b init` writes) is missing, since callers must register
* the vault before any Brain operation. The error message names
@@ -41,6 +33,7 @@ import { fileURLToPath } from "node:url";
import { defaultConfigPath } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import {
+ BRAIN_ROOT_REL,
brainConfigPath,
brainDirs,
brainManualPath,
@@ -50,11 +43,7 @@ import {
DEFAULT_BRAIN_CONFIG_YAML,
formatPrimaryAgentYamlValue,
} from "./policy.ts";
-import {
- LEGACY_OVERVIEW_REL_PATH,
- renderBrainManual,
- renderLegacyOverview,
-} from "./templates.ts";
+import { renderBrainManual } from "./templates.ts";
const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;
@@ -111,7 +100,7 @@ export function copyStarterBundle(
throw err;
}
for (const sub of STARTER_TARGETS) {
- const dir = join(vault, "Brain", sub);
+ const dir = join(vault, BRAIN_ROOT_REL, sub);
let entries;
try {
// `withFileTypes` returns Dirent objects so we avoid a `statSync`
@@ -150,7 +139,7 @@ export function copyStarterBundle(
for (const sub of STARTER_TARGETS) {
const srcDir = join(src, sub);
if (!existsSync(srcDir)) continue;
- const destDir = join(vault, "Brain", sub);
+ const destDir = join(vault, BRAIN_ROOT_REL, sub);
// Single recursive copy per subdir — orders of magnitude fewer
// syscalls than file-by-file. The filter rejects dotfiles
// (`.gitkeep`, `.DS_Store`) so the bundle stays focused on
@@ -165,7 +154,7 @@ export function copyStarterBundle(
// that we did not copy and should not surface as starter entries.
for (const name of readdirSync(srcDir)) {
if (name.startsWith(".")) continue;
- copied.push(join("Brain", sub, name));
+ copied.push(join(BRAIN_ROOT_REL, sub, name));
}
}
return Object.freeze({ copied });
@@ -297,24 +286,6 @@ export function bootstrapBrain(
created.push(manualRel);
}
- // 4. `AI Wiki/_OPEN_SECOND_BRAIN.md` — always overwritten. The
- // parent directory may not exist if the caller never ran
- // `o2b init` against this vault directly (e.g. they registered a
- // different vault path in the machine config and ran Brain init
- // elsewhere). We create it on demand: the file is meaningful even
- // without the rest of `AI Wiki/`.
- const overviewPath = join(vault, LEGACY_OVERVIEW_REL_PATH);
- const overviewRel = LEGACY_OVERVIEW_REL_PATH;
- mkdirSync(dirname(overviewPath), { recursive: true });
- const overviewBody = renderLegacyOverview(vault);
- const overviewExisted = existsSync(overviewPath);
- atomicWriteFileSync(overviewPath, overviewBody);
- if (overviewExisted) {
- overwritten.push(overviewRel);
- } else {
- created.push(overviewRel);
- }
-
if (opts.starter === true) {
const starterResult = copyStarterBundle(vault, {
starterPath: opts.starterPath,
diff --git a/src/core/brain/inline-rewrite.ts b/src/core/brain/inline-rewrite.ts
index c712cee7..e855e67c 100644
--- a/src/core/brain/inline-rewrite.ts
+++ b/src/core/brain/inline-rewrite.ts
@@ -15,8 +15,7 @@
* interpret HTML comments inside fenced blocks).
*
* Concurrency: a `proper-lockfile` lock on the parent directory
- * serialises rewrites — the same shared-lock pattern as
- * {@link appendEvent}. Per-file locks would race against the temp
+ * serialises rewrites. Per-file locks would race against the temp
* file `atomicWriteFileSync` itself creates next to the target.
*
* Atomicity: writes go through {@link atomicWriteFileSync}, which
@@ -52,7 +51,7 @@ export async function rewriteMarkers(
if (ops.length === 0) return;
// proper-lockfile requires the target to exist; locking the parent
- // dir mirrors what `appendEvent` does for Daily/.
+ // directory serialises concurrent rewrites of the same file.
const parent = dirname(path);
mkdirSync(parent, { recursive: true });
diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.ts
index 2e17cc8d..d1690fa9 100644
--- a/src/core/brain/inline-scan.ts
+++ b/src/core/brain/inline-scan.ts
@@ -40,6 +40,8 @@ import {
} from "./dedup-hash.ts";
import { discoverMarkersDetailed } from "./inline.ts";
import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+import { loadNotesConfigSafe } from "./policy.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
@@ -92,20 +94,40 @@ export async function scanInline(
const errors: ScanInlineErrorEntry[] = [];
const filesWithMarkers: ScanInlineFileSummary[] = [];
- // Build dedup index once per run. Parse failures get surfaced
- // through the per-file errors array so the JSON report exposes
- // them; doctor flags malformed signals separately.
- const dedupIndex: Map<string, DedupIndexEntry> = buildDedupIndex(vault, {
- onError: (path, message) => errors.push({ path, message }),
- });
-
let scanned = 0;
let found = 0;
let created = 0;
let deduped = 0;
let malformed = 0; // reserved — not surfaced separately yet
- const includePrefixes = (opts.paths ?? []).map((p) => normalisePrefix(p));
+ // v0.11.0: explicit `opts.paths` always wins. When absent or empty,
+ // fall back to `notes.read_paths` from `_brain.yaml`. An empty
+ // resolved list means "no folders to scan" — return immediately so
+ // the agent never walks the vault without an operator opt-in.
+ const explicitPaths = (opts.paths ?? []).filter((p) => p.trim().length > 0);
+ const resolvedPaths =
+ explicitPaths.length > 0
+ ? explicitPaths
+ : [...loadNotesConfigSafe(vault).read_paths];
+ if (resolvedPaths.length === 0) {
+ return Object.freeze({
+ scanned: 0,
+ found: 0,
+ created: 0,
+ deduped: 0,
+ malformed: 0,
+ errors: Object.freeze([]) as ReadonlyArray<ScanInlineErrorEntry>,
+ filesWithMarkers: Object.freeze([]) as ReadonlyArray<ScanInlineFileSummary>,
+ });
+ }
+ const includePrefixes = resolvedPaths.map((p) => normalisePrefix(p));
+
+ // Build dedup index once per run. Parse failures get surfaced
+ // through the per-file errors array so the JSON report exposes
+ // them; doctor flags malformed signals separately.
+ const dedupIndex: Map<string, DedupIndexEntry> = buildDedupIndex(vault, {
+ onError: (path, message) => errors.push({ path, message }),
+ });
// Effective rule set (v0.10.9):
// - shared `vault.ignore_paths` from Brain/_brain.yaml (or defaults)
@@ -118,7 +140,7 @@ export async function scanInline(
// `path` (not `name`) so the hard-skip targets only the top-level
// `<vault>/Brain/` directory; a project file like
// `projects/Brain/notes.md` keeps being scanned.
- { raw: "Brain", kind: "path" },
+ { raw: BRAIN_ROOT_REL, kind: "path" },
...(opts.exclude ?? []).map(
(raw): VaultIgnoreRule => ({ raw: normalisePrefix(raw), kind: "path" }),
),
diff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.ts
index cece3e3f..f4cfa9b6 100644
--- a/src/core/brain/lint-consolidate.ts
+++ b/src/core/brain/lint-consolidate.ts
@@ -28,7 +28,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
-import { brainDirs } from "./paths.ts";
+import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";
import {
PAGE_LIFECYCLE,
PAGE_STALE_DAYS_DEFAULT,
@@ -196,7 +196,7 @@ export function lintConsolidate(
const fixes: LintFix[] = [];
let scanned = 0;
let filesWritten = 0;
- const brainRoot = join(vault, "Brain");
+ const brainRoot = join(vault, BRAIN_ROOT_REL);
if (existsSync(brainRoot)) {
const stack: string[] = [brainRoot];
while (stack.length > 0) {
diff --git a/src/core/brain/manifest.ts b/src/core/brain/manifest.ts
index 0c18b5bc..e038f0b4 100644
--- a/src/core/brain/manifest.ts
+++ b/src/core/brain/manifest.ts
@@ -17,7 +17,7 @@ import {
import { join, relative } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
-import { brainDirs } from "./paths.ts";
+import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";
import { isoSecond } from "./time.ts";
export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;
@@ -31,7 +31,7 @@ export interface BrainManifest {
readonly schema_version: typeof BRAIN_MANIFEST_SCHEMA_VERSION;
/** ISO-8601 UTC, second precision. */
readonly generated_at: string;
- readonly brain_root: "Brain";
+ readonly brain_root: typeof BRAIN_ROOT_REL;
/** Keys are vault-relative paths under `Brain/`, sorted lexicographically. */
readonly files: Readonly<Record<string, BrainManifestEntry>>;
}
@@ -54,7 +54,7 @@ export interface BrainManifestDiff {
* Walk `brainRoot` (the `<vault>/Brain/` directory) and hash every
* regular file. The caller is responsible for pointing at the
* `Brain/` directory itself — passing a vault root would silently
- * include sibling content like `Daily/` or `AI Wiki/`.
+ * include sibling user content the Brain layer does not own.
*
* The walker is iterative (explicit stack) to keep recursion depth
* predictable on deeply-nested vault trees. Files are hashed
@@ -133,7 +133,7 @@ function freezeManifest(
return Object.freeze({
schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
generated_at,
- brain_root: "Brain",
+ brain_root: BRAIN_ROOT_REL,
files: Object.freeze(files),
});
}
@@ -281,7 +281,7 @@ export function readManifestSidecar(
if (parsed === null || typeof parsed !== "object") return null;
const obj = parsed as Record<string, unknown>;
if (obj["schema_version"] !== BRAIN_MANIFEST_SCHEMA_VERSION) return null;
- if (obj["brain_root"] !== "Brain") return null;
+ if (obj["brain_root"] !== BRAIN_ROOT_REL) return null;
if (typeof obj["generated_at"] !== "string") return null;
const files = obj["files"];
if (files === null || typeof files !== "object") return null;
@@ -306,7 +306,7 @@ export function readManifestSidecar(
return Object.freeze({
schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,
generated_at: obj["generated_at"],
- brain_root: "Brain",
+ brain_root: BRAIN_ROOT_REL,
files: Object.freeze(entries),
});
}
diff --git a/src/core/brain/migrate-frontmatter.ts b/src/core/brain/migrate-frontmatter.ts
deleted file mode 100644
index 37ff3598..00000000
--- a/src/core/brain/migrate-frontmatter.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * Opt-in helper that rewrites legacy-shape Group C frontmatter keys
- * (`status:`, `applied_count:`, ...) to the `_`-prefixed form (§24)
- * across `Brain/preferences/` and `Brain/retired/`.
- *
- * Two-phase contract:
- *
- * - {@link planMigration} (pure scan) — walks the directories,
- * reports per-file classification: already-new, to-migrate, or
- * collision (both shapes present in the same file). Read-only.
- *
- * - {@link applyMigration} (rewriting) — runs `planMigration` first,
- * aborts if collisions are present, optionally takes a `Brain/`
- * snapshot (so `o2b brain rollback migrate-...` works), then
- * atomically rewrites every to-migrate file.
- *
- * The migration is deliberately non-default: dream-driven natural
- * rewrites also migrate files lazily on every refresh pass, which
- * keeps the upgrade painless. `migrate-frontmatter` exists for users
- * who want immediate, snapshot-fenced migration.
- */
-
-import { existsSync, readdirSync } from "node:fs";
-import { join } from "node:path";
-
-import type { FrontmatterMap } from "../types.ts";
-import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
-import { brainDirs } from "./paths.ts";
-import { DERIVED_FIELDS } from "./preference.ts";
-import { createSnapshot } from "./snapshot.ts";
-import { isoSecond } from "./time.ts";
-
-/**
- * On `brain-retired` files, `status` is identity (the literal
- * `"retired"`), not derived. Filter the shared Group C list
- * accordingly so migration leaves retired-file `status:` exactly
- * where it is.
- */
-function derivedFieldsForKind(kind: unknown): ReadonlyArray<string> {
- if (kind === "brain-retired") {
- return DERIVED_FIELDS.filter((f) => f !== "status");
- }
- return DERIVED_FIELDS;
-}
-
-export class MigrationError extends Error {
- readonly code: "COLLISION" | "PARSE" | "IO";
- readonly collisions?: ReadonlyArray<{ path: string; field: string }>;
-
- constructor(
- code: "COLLISION" | "PARSE" | "IO",
- message: string,
- collisions?: ReadonlyArray<{ path: string; field: string }>,
- ) {
- super(message);
- this.name = "MigrationError";
- this.code = code;
- if (collisions !== undefined) this.collisions = collisions;
- }
-}
-
-export interface MigrationPlan {
- readonly files_scanned: number;
- readonly files_to_migrate: ReadonlyArray<string>;
- readonly files_already_new: ReadonlyArray<string>;
- readonly collisions: ReadonlyArray<{ path: string; field: string }>;
-}
-
-export interface MigrationResult {
- readonly run_id: string;
- /** `null` when `snapshot: false`, otherwise the .tar.zst path. */
- readonly snapshot_path: string | null;
- readonly plan: MigrationPlan;
- readonly files_migrated: ReadonlyArray<string>;
-}
-
-export interface ApplyMigrationOptions {
- /** Take a pre-run `Brain/` snapshot before rewriting. */
- readonly snapshot: boolean;
- /** Wall clock used to build the `run_id`. Tests pin this. */
- readonly now?: Date;
-}
-
-// ----- Internal helpers -----------------------------------------------------
-
-/**
- * Classify a single file's frontmatter against the dual-shape policy.
- * Returns `'new'` if every Group C key present is already `_`-prefixed,
- * `'legacy'` if at least one is in legacy form (and no collisions),
- * `'collision'` if any key has BOTH shapes (caller surfaces).
- *
- * Files that fail to parse are classified as `'parse-error'`. Doctor
- * is the surface that reports parse errors to the operator — migration
- * skips them silently.
- */
-function classifyFile(
- path: string,
-): { kind: "new" | "legacy" | "collision" | "parse-error"; conflictField?: string } {
- let meta: Record<string, unknown>;
- try {
- [meta] = parseFrontmatter(path);
- } catch {
- return { kind: "parse-error" };
- }
- let sawLegacy = false;
- const derived = derivedFieldsForKind(meta["kind"]);
- for (const name of derived) {
- const hasLegacy = name in meta && meta[name] !== undefined;
- const hasModern = `_${name}` in meta && meta[`_${name}`] !== undefined;
- if (hasLegacy && hasModern) {
- return { kind: "collision", conflictField: name };
- }
- if (hasLegacy) sawLegacy = true;
- }
- return { kind: sawLegacy ? "legacy" : "new" };
-}
-
-/**
- * In-place rename of legacy Group C keys to their `_`-prefixed form.
- * Returns a new `FrontmatterMap` — the input is left untouched. Order
- * is preserved (Object.entries iteration order survives rename).
- */
-function rewriteLegacyKeys(meta: Record<string, unknown>): FrontmatterMap {
- const out: FrontmatterMap = {};
- const derived = new Set(derivedFieldsForKind(meta["kind"]));
- for (const [k, v] of Object.entries(meta)) {
- if (derived.has(k)) {
- out[`_${k}`] = v as never;
- } else {
- out[k] = v as never;
- }
- }
- return out;
-}
-
-function listMarkdown(dir: string, prefix: string): string[] {
- if (!existsSync(dir)) return [];
- const out: string[] = [];
- for (const name of readdirSync(dir)) {
- if (!name.endsWith(".md")) continue;
- if (!name.startsWith(prefix)) continue;
- out.push(join(dir, name));
- }
- out.sort();
- return out;
-}
-
-// ----- Public API -----------------------------------------------------------
-
-export function planMigration(vault: string): MigrationPlan {
- const dirs = brainDirs(vault);
- const files = [
- ...listMarkdown(dirs.preferences, "pref-"),
- ...listMarkdown(dirs.retired, "ret-"),
- ];
- const toMigrate: string[] = [];
- const alreadyNew: string[] = [];
- const collisions: { path: string; field: string }[] = [];
- let scanned = 0;
- for (const path of files) {
- scanned++;
- const c = classifyFile(path);
- if (c.kind === "collision") {
- collisions.push({ path, field: c.conflictField! });
- } else if (c.kind === "legacy") {
- toMigrate.push(path);
- } else if (c.kind === "new") {
- alreadyNew.push(path);
- }
- // 'parse-error': silently skipped; doctor reports separately
- }
- return Object.freeze({
- files_scanned: scanned,
- files_to_migrate: Object.freeze(toMigrate),
- files_already_new: Object.freeze(alreadyNew),
- collisions: Object.freeze(collisions),
- });
-}
-
-export async function applyMigration(
- vault: string,
- opts: ApplyMigrationOptions,
-): Promise<MigrationResult> {
- const now = opts.now ?? new Date();
- const plan = planMigration(vault);
-
- if (plan.collisions.length > 0) {
- const first = plan.collisions[0]!;
- throw new MigrationError(
- "COLLISION",
- `migration aborted: ${plan.collisions.length} file(s) carry both legacy ` +
- `and '_'-prefixed shape for the same field. ` +
- `First: ${first.path} (field '${first.field}'). ` +
- `Hand-edit the file(s) to keep one form, then re-run.`,
- plan.collisions,
- );
- }
-
- // run_id uses isoSecond with `:` replaced — same shape dream uses,
- // accepted by validateRunId.
- const runId = `migrate-${isoSecond(now).replace(/:/g, "-")}`;
- let snapshotPath: string | null = null;
- if (opts.snapshot) {
- const snap = createSnapshot(vault, runId);
- snapshotPath = snap.path;
- }
-
- const migrated: string[] = [];
- for (const path of plan.files_to_migrate) {
- let raw: Record<string, unknown>;
- let body: string;
- try {
- [raw, body] = parseFrontmatter(path);
- } catch (err) {
- throw new MigrationError(
- "PARSE",
- `failed to parse ${path}: ${(err as Error).message ?? String(err)}`,
- );
- }
- const renamed = rewriteLegacyKeys(raw);
- writeFrontmatterAtomic(path, renamed, body, {
- overwrite: true,
- existsErrorKind: "preference",
- vaultForRelativePath: vault,
- });
- migrated.push(path);
- }
-
- return Object.freeze({
- run_id: runId,
- snapshot_path: snapshotPath,
- plan,
- files_migrated: Object.freeze(migrated),
- });
-}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 27202d88..e565f1a7 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -25,12 +25,38 @@
*/
import { existsSync } from "node:fs";
-import { join } from "node:path";
+import { join, posix } from "node:path";
import { ensureInsideVault, vaultRelative } from "../path-safety.ts";
export { ensureInsideVault, vaultRelative } from "../path-safety.ts";
+// ----- Canonical vault-relative path constants ------------------------------
+//
+// Single source of truth. Every module that builds a path inside the
+// Brain layer imports these instead of repeating the literal. A
+// future rename ("Brain" → something else) is a one-line change here.
+
+/** Vault-relative root of the Brain layer. */
+export const BRAIN_ROOT_REL = "Brain";
+
+/** Vault-relative Brain subdirectory names. */
+export const BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");
+export const BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");
+export const BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");
+export const BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");
+export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");
+export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");
+
+/** Brain-internal artefact filenames at the root of `Brain/`. */
+export const BRAIN_CONFIG_FILE = "_brain.yaml";
+export const BRAIN_MANUAL_FILE = "_BRAIN.md";
+export const BRAIN_ACTIVE_FILE = "active.md";
+export const BRAIN_INDEX_FILE = "_INDEX.md";
+
+/** Vault-relative path of the `o2b index` output file. */
+export const BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);
+
const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
// Run IDs follow `dream-<YYYY-MM-DD>-<HHMMSS>`; we accept the same generic
@@ -59,26 +85,32 @@ export interface BrainDirs {
* `readdirSync`. Each path is verified to resolve inside the vault.
*/
export function brainDirs(vault: string): BrainDirs {
- const brain = ensureInsideVault(join(vault, "Brain"), vault);
+ const brain = ensureInsideVault(join(vault, BRAIN_ROOT_REL), vault);
return {
brain,
- inbox: ensureInsideVault(join(brain, "inbox"), vault),
- processed: ensureInsideVault(join(brain, "inbox", "processed"), vault),
- preferences: ensureInsideVault(join(brain, "preferences"), vault),
- retired: ensureInsideVault(join(brain, "retired"), vault),
- log: ensureInsideVault(join(brain, "log"), vault),
- snapshots: ensureInsideVault(join(brain, ".snapshots"), vault),
+ inbox: ensureInsideVault(join(vault, BRAIN_INBOX_REL), vault),
+ processed: ensureInsideVault(join(vault, BRAIN_PROCESSED_REL), vault),
+ preferences: ensureInsideVault(join(vault, BRAIN_PREFERENCES_REL), vault),
+ retired: ensureInsideVault(join(vault, BRAIN_RETIRED_REL), vault),
+ log: ensureInsideVault(join(vault, BRAIN_LOG_REL), vault),
+ snapshots: ensureInsideVault(join(vault, BRAIN_SNAPSHOTS_REL), vault),
};
}
/** Path of `Brain/_brain.yaml`. */
export function brainConfigPath(vault: string): string {
- return ensureInsideVault(join(brainDirs(vault).brain, "_brain.yaml"), vault);
+ return ensureInsideVault(
+ join(brainDirs(vault).brain, BRAIN_CONFIG_FILE),
+ vault,
+ );
}
/** Path of the Brain operating manual rendered into the vault. */
export function brainManualPath(vault: string): string {
- return ensureInsideVault(join(brainDirs(vault).brain, "_BRAIN.md"), vault);
+ return ensureInsideVault(
+ join(brainDirs(vault).brain, BRAIN_MANUAL_FILE),
+ vault,
+ );
}
/**
@@ -88,7 +120,10 @@ export function brainManualPath(vault: string): string {
* `osb://preferences/active`.
*/
export function brainActivePath(vault: string): string {
- return ensureInsideVault(join(brainDirs(vault).brain, "active.md"), vault);
+ return ensureInsideVault(
+ join(brainDirs(vault).brain, BRAIN_ACTIVE_FILE),
+ vault,
+ );
}
/** Active-signal path: `Brain/inbox/sig-<date>-<slug>.md`. */
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index eb057e87..7c8401b1 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -26,12 +26,14 @@ import type {
BrainConfig,
BrainGuardrailConfig,
BrainLinkGraphConfig,
+ BrainNotesConfig,
BrainMostAppliedConfig,
BrainTemporalConfig,
BrainVaultConfig,
DisciplineReportConfig,
ResolvedBrainGuardrailConfig,
ResolvedBrainLinkGraphConfig,
+ ResolvedBrainNotesConfig,
ResolvedBrainTemporalConfig,
} from "./types.ts";
// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to
@@ -215,6 +217,46 @@ export function resolveTemporal(
};
}
+/**
+ * Default `notes:` block (v0.11.0). Empty `read_paths` list means
+ * the agent does not scan any user-authored notes. The operator
+ * opts in by listing folders in `_brain.yaml`.
+ */
+export const BRAIN_NOTES_DEFAULTS: ResolvedBrainNotesConfig = Object.freeze(
+ { read_paths: Object.freeze([]) as ReadonlyArray<string> },
+) as ResolvedBrainNotesConfig;
+
+/**
+ * Merge a parsed `notes` block (or `undefined`) with
+ * `BRAIN_NOTES_DEFAULTS`. The resulting struct (and its inner array)
+ * are frozen so consumers can pass the slice around without copying.
+ */
+export function resolveNotes(cfg: BrainConfig): ResolvedBrainNotesConfig {
+ const block = cfg.notes;
+ if (block === undefined || block.read_paths === undefined) {
+ return BRAIN_NOTES_DEFAULTS;
+ }
+ return Object.freeze({
+ read_paths: Object.freeze([...block.read_paths]) as ReadonlyArray<string>,
+ }) as ResolvedBrainNotesConfig;
+}
+
+/**
+ * Load + resolve the `notes:` block, falling back to
+ * `BRAIN_NOTES_DEFAULTS` when the config file is missing, malformed,
+ * or otherwise unreadable. Same pattern as `loadTemporalConfigSafe`.
+ * Used by `scan-inline` and any future scanner so a freshly-cloned
+ * vault that has not been `brain init`-ed still produces a clean
+ * "no user folders to read" result.
+ */
+export function loadNotesConfigSafe(vault: string): ResolvedBrainNotesConfig {
+ try {
+ return resolveNotes(loadBrainConfig(vault));
+ } catch {
+ return BRAIN_NOTES_DEFAULTS;
+ }
+}
+
/**
* Load + resolve the `temporal:` block, falling back to
* `BRAIN_TEMPORAL_DEFAULTS` when the config file is missing,
@@ -251,8 +293,6 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
}),
confidence: Object.freeze({
low_max_applied: 2,
- high_min_applied: 10,
- high_freshness_factor: 0.8,
medium_min: 0.40,
high_min: 0.75,
}),
@@ -286,14 +326,12 @@ retire:
stale_evidence_days: 90
confidence:
+ # low_max_applied gates the "low-evidence-confirmed" doctor warning
+ # and the auto-promotion of unconfirmed preferences to confirmed.
low_max_applied: 2
- high_min_applied: 10
- high_freshness_factor: 0.8
- # Derived-band thresholds on the numeric confidence_value (Wilson
- # lower bound × freshness decay). The count-based hard floors
- # above still take precedence: low_max_applied / violated >=
- # applied / missing-fresh keep a rule at low / medium regardless
- # of the numeric value.
+ # Band thresholds on the numeric confidence_value (Wilson lower
+ # bound times freshness decay). value >= high_min ⇒ high;
+ # value >= medium_min ⇒ medium; else low.
medium_min: 0.40
high_min: 0.75
@@ -395,7 +433,6 @@ export interface LoadBrainConfigResult {
* - YAML shape errors
* - unsupported `schema_version`
* - non-integer / out-of-range thresholds
- * - `high_freshness_factor` outside `(0, 1]`
* - non-integer / non-positive `snapshots.retention_count`
*
* Unknown top-level keys are reported as warnings, not errors.
@@ -569,23 +606,6 @@ export function validateBrainConfigDetailed(
confidence.low_max_applied,
source,
);
- requirePositiveInteger(
- "confidence.high_min_applied",
- confidence.high_min_applied,
- source,
- );
- if (
- typeof confidence.high_freshness_factor !== "number" ||
- !Number.isFinite(confidence.high_freshness_factor) ||
- confidence.high_freshness_factor <= 0 ||
- confidence.high_freshness_factor > 1
- ) {
- throw new BrainConfigError(
- `must be a number in (0, 1]; got ${JSON.stringify(confidence.high_freshness_factor)}`,
- "confidence.high_freshness_factor",
- source,
- );
- }
requireUnitInterval(
"confidence.medium_min",
confidence.medium_min,
@@ -1128,6 +1148,90 @@ export function validateBrainConfigDetailed(
: {};
}
+ // Optional `notes:` block (v0.11.0). Shape:
+ // notes:
+ // read_paths:
+ // - Daily
+ // - Journal/Weekly
+ // Absent block → `cfg.notes` undefined; resolveNotes returns the
+ // bit-identical defaults (empty `read_paths`). The list is purely
+ // a READ surface; agents never write to these paths.
+ let notes: BrainNotesConfig | undefined;
+ if ("notes" in obj) {
+ const rawNotes = obj["notes"];
+ if (
+ typeof rawNotes !== "object" ||
+ rawNotes === null ||
+ Array.isArray(rawNotes)
+ ) {
+ throw new BrainConfigError(
+ "notes must be a mapping",
+ "notes",
+ source,
+ );
+ }
+ const notesObj = rawNotes as Record<string, unknown>;
+ const partialNotes: Record<string, unknown> = {};
+ if ("read_paths" in notesObj) {
+ const v = notesObj["read_paths"];
+ if (!Array.isArray(v)) {
+ throw new BrainConfigError(
+ "must be an array of vault-relative folder paths",
+ "notes.read_paths",
+ source,
+ );
+ }
+ const cleaned: string[] = [];
+ v.forEach((entry, idx) => {
+ if (typeof entry !== "string") {
+ throw new BrainConfigError(
+ `must be a string; got ${describe(entry)}`,
+ `notes.read_paths[${idx}]`,
+ source,
+ );
+ }
+ const trimmed = entry.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "must be a non-empty string",
+ `notes.read_paths[${idx}]`,
+ source,
+ );
+ }
+ if (trimmed.startsWith("/") || trimmed.startsWith("\\")) {
+ throw new BrainConfigError(
+ "must be a vault-relative path (no leading slash)",
+ `notes.read_paths[${idx}]`,
+ source,
+ );
+ }
+ const segments = trimmed.split(/[\\/]/);
+ if (segments.some((s) => s === "..")) {
+ throw new BrainConfigError(
+ "must not contain '..' segments",
+ `notes.read_paths[${idx}]`,
+ source,
+ );
+ }
+ cleaned.push(trimmed);
+ });
+ partialNotes["read_paths"] = cleaned;
+ }
+ // Forward-compat: unknown sub-keys under `notes:` → warning.
+ for (const key of Object.keys(notesObj)) {
+ if (key !== "read_paths") {
+ warnings.push({
+ path: source ?? "<config>",
+ message: `notes.${key}: unknown field ignored (forward-compat)`,
+ });
+ }
+ }
+ notes =
+ Object.keys(partialNotes).length > 0
+ ? (partialNotes as BrainNotesConfig)
+ : {};
+ }
+
// Forward-compat: unknown top-level keys → warning, not error.
const known = new Set([
"schema_version",
@@ -1142,6 +1246,7 @@ export function validateBrainConfigDetailed(
"guardrails",
"link_graph",
"temporal",
+ "notes",
]);
for (const key of Object.keys(obj)) {
if (!known.has(key)) {
@@ -1165,8 +1270,6 @@ export function validateBrainConfigDetailed(
},
confidence: {
low_max_applied: confidence.low_max_applied as number,
- high_min_applied: confidence.high_min_applied as number,
- high_freshness_factor: confidence.high_freshness_factor as number,
medium_min: confidence.medium_min as number,
high_min: confidence.high_min as number,
},
@@ -1179,6 +1282,7 @@ export function validateBrainConfigDetailed(
...(guardrails !== undefined ? { guardrails } : {}),
...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),
...(temporal !== undefined ? { temporal } : {}),
+ ...(notes !== undefined ? { notes } : {}),
};
return { config, warnings };
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 6f9649be..f0c46249 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -64,26 +64,6 @@ import type { PageTier } from "./page-meta/tier.ts";
// ----- Errors ---------------------------------------------------------------
-/**
- * Raised when a preference / retired file carries the same Group C
- * field in both legacy (`status:`) and `_`-prefixed (`_status:`)
- * shapes. The doctor downgrades this to a `frontmatter-double-shape`
- * warning; `o2b brain migrate-frontmatter` aborts on it. Doing the
- * dispatch by typed class (rather than regex-matching the message)
- * keeps the contract stable across error-text rewording.
- */
-export class BrainDoubleShapeError extends Error {
- readonly field: string;
- constructor(field: string) {
- super(
- `preference field collision: both '_${field}' and legacy '${field}' present; ` +
- `pick one (run \`o2b brain migrate-frontmatter --apply\` or hand-edit)`,
- );
- this.name = "BrainDoubleShapeError";
- this.field = field;
- }
-}
-
/**
* Raised when a preference / retired file disagrees with the folder
* it lives in. Surfaces both pieces of information so the caller (and
@@ -482,26 +462,23 @@ export const DERIVED_FIELDS: ReadonlyArray<string> = Object.freeze([
]);
/**
- * Resolve dual-shape Group C keys to their canonical (un-prefixed)
- * form so every downstream `meta[name]` call site keeps working. When
- * both `name` and `_name` are present in the same file, throws
- * {@link BrainDoubleShapeError} — the manual-edit corruption case
- * `brain_doctor` surfaces as `frontmatter-double-shape`.
- *
- * Returns a shallow copy of `meta`; original is untouched. Exported
- * because the backlink index and other raw-frontmatter consumers
- * need the same normalisation rules.
+ * Rename `_`-prefixed Group C keys (`_status`, `_applied_count`, ...)
+ * to their canonical un-prefixed form so every downstream
+ * `meta[name]` call site keeps working. Returns a shallow copy of
+ * `meta`; original is untouched. Exported because the backlink
+ * index and other raw-frontmatter consumers need the same rule.
*/
export function normalizeDerivedKeys(meta: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = { ...meta };
for (const name of DERIVED_FIELDS) {
- const prefixed = `_${name}`;
- const hasLegacy = name in out && out[name] !== undefined;
- const hasModern = prefixed in out && out[prefixed] !== undefined;
- if (hasLegacy && hasModern) {
- throw new BrainDoubleShapeError(name);
+ if (name in out && out[name] !== undefined) {
+ throw new Error(
+ `frontmatter field '${name}' must use the '_'-prefixed shape ('_${name}'); ` +
+ "un-prefixed Group C keys are no longer accepted",
+ );
}
- if (hasModern) {
+ const prefixed = `_${name}`;
+ if (prefixed in out && out[prefixed] !== undefined) {
out[name] = out[prefixed];
delete out[prefixed];
}
@@ -515,10 +492,9 @@ export function normalizeDerivedKeys(meta: Record<string, unknown>): Record<stri
* the file lives in `preferences/` but its `status` reads `retired`
* (or any other state outside `unconfirmed` / `confirmed`).
*
- * Accepts both the legacy frontmatter shape (`status:`,
- * `applied_count:`, …) and the new `_`-prefixed shape (`_status:`,
- * `_applied_count:`, …). Presence of both forms for the same field
- * is a hard error — see {@link normalizeDerivedKeys}.
+ * Derived Group C fields use the `_`-prefixed shape on disk
+ * (`_status:`, `_applied_count:`, ...); {@link normalizeDerivedKeys}
+ * renames them to the un-prefixed form for downstream readers.
*/
export function parsePreference(path: string): BrainPreference {
const [rawMeta, _body] = parseFrontmatter(path);
@@ -756,6 +732,7 @@ export function moveToRetired(
// verbatim (`topic`, `principle`, `evidenced_by`, counters, …), drop
// the active-state fields that no longer apply (`unconfirmed_until`,
// `confirmed_at`), and stamp the retire metadata on top.
+ const derivedSet = new Set<string>(DERIVED_FIELDS);
const newMeta: FrontmatterMap = {};
for (const [k, v] of Object.entries(meta)) {
// Identity keys overwritten below.
@@ -771,11 +748,19 @@ export function moveToRetired(
);
continue;
}
+ // Group C derived fields go to disk in the `_`-prefixed shape so
+ // parseRetired's `normalizeDerivedKeys` accepts the file. `meta`
+ // is the normalised in-memory view, so the keys here are still
+ // un-prefixed and need re-prefixing on write.
+ if (derivedSet.has(k)) {
+ newMeta[`_${k}`] = v as never;
+ continue;
+ }
newMeta[k] = v as never;
}
newMeta["kind"] = "brain-retired";
newMeta["id"] = newId;
- newMeta["status"] = "retired";
+ newMeta["_status"] = "retired";
newMeta["retired_at"] = opts.now.toISOString();
newMeta["retired_reason"] = reason;
newMeta["retired_by"] = opts.retired_by;
diff --git a/src/core/brain/protect.ts b/src/core/brain/protect.ts
index a8937646..c7d10db2 100644
--- a/src/core/brain/protect.ts
+++ b/src/core/brain/protect.ts
@@ -37,7 +37,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { escapeRegex } from "../strings.ts";
-import { brainConfigPath, brainDirs } from "./paths.ts";
+import { BRAIN_ROOT_REL, brainConfigPath, brainDirs } from "./paths.ts";
/** Bumped on any structural change to manifest / fence layout. */
export const PROTECT_SCHEMA_VERSION = 1;
@@ -187,7 +187,7 @@ function inferVault(rules: ReadonlyArray<ProtectRule>): string {
{ code: "EMPTY_RULES" },
);
}
- return first.path.split("/Brain/")[0]!;
+ return first.path.split(`/${BRAIN_ROOT_REL}/`)[0]!;
}
// ─── Codex rendering ──────────────────────────────────────────────────
@@ -390,9 +390,9 @@ export function removeManifestEntry(
// ─── Apply / unprotect ────────────────────────────────────────────────
function ensureVaultBootstrapped(vault: string): void {
- if (!existsSync(join(vault, "Brain"))) {
+ if (!existsSync(join(vault, BRAIN_ROOT_REL))) {
throw new BrainProtectError(
- `vault at ${vault} has no Brain/ directory; run \`o2b brain init\` first`,
+ `vault at ${vault} has no ${BRAIN_ROOT_REL}/ directory; run \`o2b brain init\` first`,
{ code: "VAULT_NOT_BOOTSTRAPPED" },
);
}
diff --git a/src/core/brain/snapshot-diff.ts b/src/core/brain/snapshot-diff.ts
index 4781aad7..d8a2a85d 100644
--- a/src/core/brain/snapshot-diff.ts
+++ b/src/core/brain/snapshot-diff.ts
@@ -300,7 +300,6 @@ function scanFile(_root: string, abs: string, rel: string): ScannedFile {
rel === "_brain.yaml"
|| rel === "_BRAIN.md"
|| rel === "active.md"
- || rel === "_OPEN_SECOND_BRAIN.md"
) {
return {
entry: {
diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.ts
index 3b9962d4..aa96b246 100644
--- a/src/core/brain/snapshot.ts
+++ b/src/core/brain/snapshot.ts
@@ -54,7 +54,12 @@ import {
manifestSidecarPath,
writeManifestSidecar,
} from "./manifest.ts";
-import { brainDirs, snapshotPath, validateRunId } from "./paths.ts";
+import {
+ BRAIN_ROOT_REL,
+ brainDirs,
+ snapshotPath,
+ validateRunId,
+} from "./paths.ts";
// ----- Errors ---------------------------------------------------------------
@@ -101,8 +106,8 @@ export interface SnapshotInfo {
readonly size_bytes: number;
/**
* Absolute path of the sidecar manifest, or `null` when the
- * archive predates v0.10.6 (legacy snapshot without drift-check
- * support). Rollback gracefully degrades on `null`.
+ * sidecar write failed at snapshot time (read-only directory or
+ * similar). Rollback gracefully degrades on `null`.
*/
readonly manifest_path: string | null;
}
@@ -211,7 +216,7 @@ export function createSnapshot(
// Build `tar -c -C <vault> Brain/<entry> Brain/<entry>...` so paths
// inside the archive start at `Brain/` — matching the rollback
// contract that the archive is "the Brain/ tree".
- const tarArgs = ["-c", "-C", vault, "--", ...topEntries.map((e) => `Brain/${e}`)];
+ const tarArgs = ["-c", "-C", vault, "--", ...topEntries.map((e) => `${BRAIN_ROOT_REL}/${e}`)];
if (tools.zstd) {
runArchivePipeline(["tar", tarArgs], ["zstd", ["-19", "-q", "-o", outPath, "-"]], runId);
@@ -234,13 +239,13 @@ export function createSnapshot(
);
}
- // Sidecar manifest (§22 + §5-tail). Failure is non-fatal: the
- // archive is the load-bearing artifact, and a snapshot without a
- // manifest just degrades rollback's drift detection to the
- // pre-v0.10.6 silent-overwrite path (with a warning at rollback
- // time). The alternative — failing the whole snapshot because the
- // sidecar could not be written — would block dream from making any
- // progress on a read-only `.snapshots/` directory.
+ // Sidecar manifest. Failure is non-fatal: the archive is the
+ // load-bearing artifact, and a snapshot without a manifest just
+ // degrades rollback's drift detection to a silent-overwrite path
+ // (with a warning at rollback time). The alternative — failing
+ // the whole snapshot because the sidecar could not be written —
+ // would block dream from making any progress on a read-only
+ // `.snapshots/` directory.
try {
writeManifestSidecar(vault, runId, buildManifest(dirs.brain));
} catch (err) {
@@ -438,8 +443,9 @@ export function pruneSnapshots(
// stays put. The next dream run will try again.
}
// Remove the matching sidecar manifest if present. Independent
- // try/catch: a missing sidecar (legacy snapshot from pre-v0.10.6)
- // must not abort the prune of subsequent victims.
+ // try/catch so a missing sidecar (snapshot whose sidecar write
+ // failed at creation time) must not abort the prune of
+ // subsequent victims.
if (v.manifest_path !== null) {
try {
rmSync(v.manifest_path, { force: true });
@@ -580,10 +586,10 @@ export function extractSnapshotToTemp(
}
}
- const extractedBrain = join(tmp, "Brain");
+ const extractedBrain = join(tmp, BRAIN_ROOT_REL);
if (!existsSync(extractedBrain)) {
throw new BrainSnapshotError(
- "archive does not contain a Brain/ root",
+ `archive does not contain a ${BRAIN_ROOT_REL}/ root`,
runId,
);
}
diff --git a/src/core/brain/status.ts b/src/core/brain/status.ts
index e4b3cef8..e7bbed56 100644
--- a/src/core/brain/status.ts
+++ b/src/core/brain/status.ts
@@ -162,24 +162,12 @@ function countZst(dir: string): number {
function readFrontmatterStatus(path: string): string {
// Use the canonical frontmatter parser instead of a regex sniff so
- // quoted values (`status: "confirmed"`) and other legal YAML
+ // quoted values (`_status: "confirmed"`) and other legal YAML
// shapes round-trip correctly. Files we can't parse bucket under
// `unknown` — doctor surfaces them as schema errors elsewhere.
- //
- // Read both legacy `status:` and the `_status:` shape (§24).
- // When both shapes are present we treat the file as `unknown` —
- // same collision policy as `normalizeDerivedKeys` (doctor flags
- // it as `frontmatter-double-shape`). Counting it as the modern
- // value here would silently mask the corruption.
try {
const [meta] = parseFrontmatter(path);
- // Presence-based collision detection so an empty `_status:`
- // alongside a populated `status:` (or vice versa) is still flagged
- // as a double-shape file — matches `normalizeDerivedKeys`.
- const hasLegacy = "status" in meta && meta["status"] !== undefined;
- const hasModern = "_status" in meta && meta["_status"] !== undefined;
- if (hasLegacy && hasModern) return "unknown";
- const value = hasModern ? meta["_status"] : meta["status"];
+ const value = meta["_status"];
if (typeof value !== "string") return "unknown";
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : "unknown";
diff --git a/src/core/brain/templates.ts b/src/core/brain/templates.ts
index ff1a6c7c..ffd7e3cb 100644
--- a/src/core/brain/templates.ts
+++ b/src/core/brain/templates.ts
@@ -28,20 +28,6 @@ const TEMPLATE_DIR = resolve(
/** Operating manual rendered at `Brain/_BRAIN.md`. */
export const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");
-/**
- * Brain-first overview rendered at `AI Wiki/_OPEN_SECOND_BRAIN.md`.
- * The legacy file's prior content is not preserved on render — the
- * file is the agent's first-read surface and must match the
- * release.
- */
-export const LEGACY_OVERVIEW_TEMPLATE_PATH = join(
- TEMPLATE_DIR,
- "_OPEN_SECOND_BRAIN.md.tpl",
-);
-
-/** Vault-relative path of the legacy-overview target file. */
-export const LEGACY_OVERVIEW_REL_PATH = join("AI Wiki", "_OPEN_SECOND_BRAIN.md");
-
/**
* Read a template file from disk. A missing template would indicate a
* broken open-second-brain install — the message names the canonical
@@ -110,20 +96,6 @@ export function renderBrainManual(
);
}
-/**
- * Render the Brain-first overview the way the current release ships
- * it for `vault`. Used by both `bootstrapBrain` and `planUpgrade`.
- */
-export function renderLegacyOverview(
- vault: string,
- config: BrainConfig = DEFAULT_BRAIN_CONFIG,
-): string {
- return renderTemplate(
- readTemplate(LEGACY_OVERVIEW_TEMPLATE_PATH),
- buildSubstitutions(vault, config),
- );
-}
-
/**
* Best-effort display name for the vault: the trailing directory name
* with separators stripped. Falls back to the literal `Second Brain`
diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tpl
index e56b0736..598b0f5b 100644
--- a/src/core/brain/templates/_BRAIN.md.tpl
+++ b/src/core/brain/templates/_BRAIN.md.tpl
@@ -116,10 +116,11 @@ Schedule it on a cron with confidence — duplicate runs do not pollute.
- Do not edit files in `retired/` to undo a retirement. The reason is
preserved on purpose; a rule that should return becomes a new
preference with `supersedes: [[ret-...]]`.
-- Do not write into `AI Wiki/` or `Daily/` through Brain tools. Those
- layers serve different purposes (curated wiki / event log) and Brain
- operations stay scoped to `Brain/`. Pay Memory is the dedicated
- writer of `AI Wiki/payments/` and `AI Wiki/assets/`.
+- Brain operations stay scoped to `Brain/`. Pay Memory writes under
+ `Brain/payments/` (receipts, policies, assets, drafts, reports) -
+ the same root, different subtree. User-authored notes (daily
+ journals, etc.) are read-only inputs whose folders are listed in
+ `_brain.yaml:notes.read_paths`; the agent never writes there.
- Do not invent topics. Reuse an existing topic slug if the rule space
is the same; `dream` collapses near-duplicates only by exact match.
@@ -139,7 +140,7 @@ them as part of normal agent work.
- `o2b brain pin <pref-id>` / `unpin <pref-id>` — protect a preference
from automatic retirement (still subject to explicit reject).
- `o2b brain upgrade` — migrate the release-owned files (`_brain.yaml`,
- `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward when a new
+ `_BRAIN.md`) forward when a new
open-second-brain version ships. `--dry-run` (default) prints a
per-file plan; `--apply` rewrites the files after taking a snapshot
named `upgrade-<ts>`.
diff --git a/src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl b/src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl
deleted file mode 100644
index 9b8e95ff..00000000
--- a/src/core/brain/templates/_OPEN_SECOND_BRAIN.md.tpl
+++ /dev/null
@@ -1,63 +0,0 @@
----
-open_second_brain_version: 1
-layer: brain-first
----
-
-# Open Second Brain — vault overview
-
-This vault is managed by Open Second Brain. The vault holds three
-top-level agent-facing directories, each with a distinct purpose.
-
-## Layers
-
-- **`Brain/`** — observing memory. Signals, preferences, retired
- rules, log, snapshots. Mutated only through `o2b brain *` commands
- and the `brain_*` MCP tools. The full operating manual lives at
- `Brain/_BRAIN.md` — read it before any Brain operation.
-
-- **`AI Wiki/`** — curated knowledge surface. Identity files
- (`identity/`), index and hot list, system snapshots, and the Pay
- Memory subtree (`payments/`, `assets/`, `drafts/`, `reports/`,
- `policies/`). Agents read it via `second_brain_query` and write
- into the Pay Memory subtree via the `payment_*` MCP tools; they
- do not otherwise mutate this area through Brain tools.
-
-- **`Daily/`** — chronological event log and human narrative.
- Visible to `second_brain_query` for cross-referencing past
- activity; Brain operations do not write here.
-
-## Where agents write
-
-- Taste signals and rule applications go through Brain: call
- `brain_feedback` after a stylistic accept/reject, call
- `brain_apply_evidence` after a durable artifact that exercised an
- active preference, and let `brain_dream` (scheduled or manual)
- promote, confirm, and retire rules from that evidence.
-
-- Paid actions go through Pay Memory. `AI Wiki/payments/`,
- `AI Wiki/assets/`, and the spending policy at
- `AI Wiki/policies/spending.json` remain the audit surface for any
- call that costs money. Pay Memory is orthogonal to Brain — both
- layers coexist on the same vault without overlap.
-
-## Where agents read
-
-`second_brain_query` covers the whole vault. Use it to recall an
-`AI Wiki/` note, look up a `Daily/` entry, or surface a specific
-Brain preference by id. Read-only.
-
-## Conventions
-
-- All notes are Markdown with YAML frontmatter. No databases, no
- daemons. `cp -r` is a full backup.
-- Cross-references are Obsidian wikilinks (`[[basename]]`). No
- relative paths.
-- Never write secrets, tokens, or credentials into any file.
-
-## Quick start
-
-1. Read `Brain/_BRAIN.md` — the operating manual for the writable layer.
-2. Read `AI Wiki/identity/user.md` and `AI Wiki/identity/agents.md` —
- who owns the vault and which agents are registered.
-3. When in doubt about a Brain command, see
- `docs/plans/2026-05-15-brain-observing-memory.md` in the repo.
diff --git a/src/core/brain/token-footprint.ts b/src/core/brain/token-footprint.ts
index 89c48853..fa78ef0b 100644
--- a/src/core/brain/token-footprint.ts
+++ b/src/core/brain/token-footprint.ts
@@ -17,7 +17,7 @@ import {
} from "node:fs";
import { join } from "node:path";
-import { brainDirs } from "./paths.ts";
+import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";
import { estimateTokens } from "./text/tokenizer.ts";
export const TOKEN_WARN_THRESHOLD_DEFAULT = 200_000;
@@ -112,7 +112,7 @@ export function computeTokenFootprint(
// already accounted for. We do not recurse into unknown subdirs
// so a runaway plugin dropping junk under Brain/exotic-thing/ is
// not silently included; the digest action list flags it instead.
- const brainRoot = join(vault, "Brain");
+ const brainRoot = join(vault, BRAIN_ROOT_REL);
if (existsSync(brainRoot)) {
let otherTokens = 0;
let otherFiles = 0;
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 91afaaa2..97152b45 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -160,13 +160,6 @@ export const BRAIN_LOG_EVENT_KIND = {
* file; payload references the file and adapter id.
*/
importSession: "import-session",
- /**
- * `migrate-frontmatter` (§24) — operator ran
- * `o2b brain migrate-frontmatter --apply` to rewrite legacy
- * frontmatter to the `_`-prefixed shape. Payload carries the run
- * 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`
@@ -315,11 +308,11 @@ export interface BrainPreference {
/** ISO-8601 UTC of most recent `apply-evidence` entry. */
readonly last_evidence_at: string | null;
/**
- * Categorical band — `low | medium | high`. Derived from
- * {@link confidence_value} after the count-based hard floors
- * (`applied <= low_max_applied`, `violated >= applied`, etc.) are
- * applied. Stays on the public type so MCP / digest consumers that
- * predate the numeric field keep working unchanged.
+ * Categorical band — `low | medium | high`. Derived directly from
+ * {@link confidence_value} via the `confidence.medium_min` and
+ * `confidence.high_min` thresholds. Stays on the public type so
+ * MCP / digest consumers that predate the numeric field keep
+ * working unchanged.
*/
readonly confidence: BrainConfidence;
/**
@@ -558,16 +551,6 @@ export interface BrainImportSessionLogEvent extends BrainLogEventBase {
readonly kind: typeof BRAIN_LOG_EVENT_KIND.importSession;
}
-/**
- * `migrate-frontmatter` entry — operator ran
- * `o2b brain migrate-frontmatter --apply`. Payload carries the run
- * id, snapshot path, and per-bucket counters.
- */
-export interface BrainMigrateFrontmatterLogEvent extends BrainLogEventBase {
- readonly kind: typeof BRAIN_LOG_EVENT_KIND.migrateFrontmatter;
- readonly run_id: string;
-}
-
/**
* `merge` entry — operator ran `o2b brain merge <keep> <drop>`.
* Payload carries the titled wikilinks to both prefs plus the
@@ -603,10 +586,9 @@ export interface BrainImportClaudeMemoryLogEvent extends BrainLogEventBase {
}
/**
- * `note` entry (§32B, v0.10.8) — one narrative-milestone line. Not
- * consumed by the dream pass; it exists so an agent has a Brain-native
- * home for "I shipped X" / "PR Y merged" lines instead of falling back
- * to the deprecated Daily/ event log.
+ * `note` entry — one narrative-milestone line. Not consumed by the
+ * dream pass; it exists so an agent has a Brain-native home for
+ * "I shipped X" / "PR Y merged" lines.
*/
export interface BrainNoteLogEvent extends BrainLogEventBase {
readonly kind: typeof BRAIN_LOG_EVENT_KIND.note;
@@ -630,7 +612,6 @@ export type BrainLogEvent =
| BrainRollbackLogEvent
| BrainScanInlineLogEvent
| BrainImportSessionLogEvent
- | BrainMigrateFrontmatterLogEvent
| BrainMergeLogEvent
| BrainUpgradeLogEvent
| BrainImportClaudeMemoryLogEvent
@@ -653,26 +634,23 @@ export interface BrainRetireConfig {
}
export interface BrainConfidenceConfig {
- /** `applied_count <= low_max_applied` → confidence `low`. */
- readonly low_max_applied: number;
- /** `applied_count >= high_min_applied` is required for `high`. */
- readonly high_min_applied: number;
/**
- * Fresh-evidence factor: `now - last_evidence_at <
- * stale_evidence_days * high_freshness_factor`. Must be in `(0, 1]`.
+ * Gate for the "low-evidence-confirmed" doctor warning and the
+ * auto-promotion of unconfirmed preferences to confirmed.
+ * `applied_count <= low_max_applied` keeps a confirmed pref on the
+ * doctor watch-list.
*/
- readonly high_freshness_factor: number;
+ readonly low_max_applied: number;
/**
* Lower threshold on the numeric `confidence_value` for the
- * derived `medium` band. Anything below this lands as `low` after
- * the legacy count-based hard floors. Must be in `[0, 1]` and
- * strictly less than {@link high_min}.
+ * `medium` band. Must be in `[0, 1]` and strictly less than
+ * {@link high_min}.
*/
readonly medium_min: number;
/**
* Lower threshold on the numeric `confidence_value` for the
- * derived `high` band. Must be in `[0, 1]` and strictly greater
- * than {@link medium_min}.
+ * `high` band. Must be in `[0, 1]` and strictly greater than
+ * {@link medium_min}.
*/
readonly high_min: number;
}
@@ -825,6 +803,33 @@ export interface BrainConfig {
* `resolveTemporal`.
*/
readonly temporal?: BrainTemporalConfig;
+ /**
+ * Optional `notes:` block (v0.11.0). Declares vault-relative
+ * folders the agent may READ user-authored notes from (daily
+ * journal, weekly notes, ...). Absent or empty list means the
+ * agent does not read any user-authored notes. Agents never write
+ * to these paths - the type is `read_paths` for a reason.
+ */
+ readonly notes?: BrainNotesConfig;
+}
+
+/**
+ * Optional `notes:` block (v0.11.0). User-authored notes the agent
+ * may read from. The list is purely a READ surface: `scan-inline`
+ * and session-import scan these roots for `@osb` markers. The agent
+ * never writes here; user-named folders (`Daily/`, `Journal/`, ...)
+ * stay user-owned.
+ */
+export interface BrainNotesConfig {
+ /**
+ * Vault-relative folders the agent may read from. Empty or absent
+ * list means "no user-authored notes to scan".
+ */
+ readonly read_paths?: ReadonlyArray<string>;
+}
+
+export interface ResolvedBrainNotesConfig {
+ readonly read_paths: ReadonlyArray<string>;
}
/**
diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.ts
index 9fda7926..e6bbaf26 100644
--- a/src/core/brain/upgrade.ts
+++ b/src/core/brain/upgrade.ts
@@ -1,6 +1,6 @@
/**
* Brain managed-file upgrade for the three release-owned files in
- * `Brain/` (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`).
+ * `Brain/` (`_brain.yaml`, `_BRAIN.md`).
* User-owned content (`preferences/`, `retired/`, `inbox/`, `log/`)
* is never touched.
*
@@ -29,11 +29,7 @@ import {
loadBrainConfig,
} from "./policy.ts";
import { createSnapshot } from "./snapshot.ts";
-import {
- LEGACY_OVERVIEW_REL_PATH,
- renderBrainManual,
- renderLegacyOverview,
-} from "./templates.ts";
+import { renderBrainManual } from "./templates.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
@@ -93,9 +89,8 @@ export class BrainUpgradeError extends Error {
* Compute the upgrade plan for `vault` without touching disk.
*
* Order of files in `plan.files` is fixed: `_brain.yaml`,
- * `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`. This is the order the CLI
- * renders the per-file diff so the operator's eye lands at the same
- * spot on every run.
+ * `_BRAIN.md`. This is the order the CLI renders the per-file diff
+ * so the operator's eye lands at the same spot on every run.
*/
export function planUpgrade(vault: string): UpgradePlan {
const files: UpgradeFilePlan[] = [
@@ -106,12 +101,6 @@ export function planUpgrade(vault: string): UpgradePlan {
vaultRelative(brainManualPath(vault), vault),
() => renderBrainManual(vault),
),
- planManagedPath(
- vault,
- join(vault, LEGACY_OVERVIEW_REL_PATH),
- LEGACY_OVERVIEW_REL_PATH,
- () => renderLegacyOverview(vault),
- ),
];
const pending = files.filter((f) => f.status === "update").length;
const errors = files.filter((f) => f.status === "error").length;
diff --git a/src/core/config.ts b/src/core/config.ts
index 852a978b..00d7d9b2 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -145,8 +145,9 @@ export function resolveVault(configPath?: string): string | null {
* Resolve the agent identity used when no explicit `agent` is supplied.
*
* Order: `VAULT_AGENT_NAME` env → `agent_name`/`agentName` in plugin config →
- * the literal placeholder `"agent"`. Shared between MCP server's
- * `event_log_append` default-agent resolution and the Hermes pre_llm_call hook.
+ * the literal placeholder `"agent"`. Used by every Brain writer that needs
+ * an `agent:` field (signals, evidence rows, log entries) and by the
+ * Hermes pre_llm_call hook.
*/
export function resolveAgentName(configPath?: string): string {
const env = process.env["VAULT_AGENT_NAME"];
diff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.ts
index 913888d1..c956a664 100644
--- a/src/core/discipline/decision.ts
+++ b/src/core/discipline/decision.ts
@@ -41,7 +41,7 @@ export function decideStatus(
activity: ActivitySummary,
): DisciplineStatus {
// Taste events only: feedback + apply_evidence. The `other` bucket
- // (snapshot / dream-pass / import-claude-memory / migrate-frontmatter)
+ // (snapshot / dream-pass / import-claude-memory)
// would otherwise mask a real "agent shipped artifacts but recorded
// zero taste signals" day — exactly the regression §D exists to catch.
let tasteEvents = 0;
diff --git a/src/core/discipline/vault-delta.ts b/src/core/discipline/vault-delta.ts
index d4d28729..ef273375 100644
--- a/src/core/discipline/vault-delta.ts
+++ b/src/core/discipline/vault-delta.ts
@@ -1,5 +1,11 @@
import { existsSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
+
+import {
+ BRAIN_INBOX_REL,
+ BRAIN_PREFERENCES_REL,
+ BRAIN_RETIRED_REL,
+} from "../brain/paths.ts";
import type { ActivityWindow } from "./activity-git.ts";
export interface VaultDelta {
@@ -37,9 +43,9 @@ function countInWindow(dir: string, win: ActivityWindow): number {
}
export function vaultDelta(vault: string, win: ActivityWindow): VaultDelta {
- const newSignals = countInWindow(join(vault, "Brain", "inbox"), win);
- const newPreferences = countInWindow(join(vault, "Brain", "preferences"), win);
- const newRetired = countInWindow(join(vault, "Brain", "retired"), win);
+ const newSignals = countInWindow(join(vault, BRAIN_INBOX_REL), win);
+ const newPreferences = countInWindow(join(vault, BRAIN_PREFERENCES_REL), win);
+ const newRetired = countInWindow(join(vault, BRAIN_RETIRED_REL), win);
return {
newSignals, newPreferences, newRetired,
total: newSignals + newPreferences + newRetired,
diff --git a/src/core/event-log.ts b/src/core/event-log.ts
deleted file mode 100644
index 7745b789..00000000
--- a/src/core/event-log.ts
+++ /dev/null
@@ -1,249 +0,0 @@
-/**
- * Daily event log: append-only Markdown notes with chronological order and
- * cross-process safety.
- *
- * Mirrors `src/open_second_brain/event_log.py`. The locking strategy uses
- * `proper-lockfile` because Bun/Node lack a portable `fcntl.flock` equivalent;
- * `proper-lockfile` is the de-facto standard (lockfile + retry with stale
- * detection) and survives the same multi-process append test.
- */
-
-import lockfile from "proper-lockfile";
-import { existsSync, mkdirSync, readFileSync } from "node:fs";
-import { join } from "node:path";
-
-import { atomicWriteFileSync } from "./fs-atomic.ts";
-
-const SECRET_ASSIGNMENT_RE = /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)\S+/gi;
-const EVENT_RE = /^- (\d{2}:\d{2}) — @/;
-const DATE_RE = /^(\d{4})\.(\d{2})\.(\d{2})$/;
-const TIME_RE = /^(\d{2}):(\d{2})$/;
-
-/** Match PEM block headers for private-key-like types. */
-const PEM_BEGIN_RE = /-----BEGIN\s+(?:RSA\s+)?(?:EC\s+)?(?:DSA\s+)?(?:OPENSSH\s+)?(?:ENCRYPTED\s+)?(?:PGP\s+)?PRIVATE KEY-----/;
-const PEM_END_RE = /-----END\s+(?:RSA\s+)?(?:EC\s+)?(?:DSA\s+)?(?:OPENSSH\s+)?(?:ENCRYPTED\s+)?(?:PGP\s+)?PRIVATE KEY-----/;
-
-/**
- * Conservative JWT-shaped token heuristic: three base64url segments
- * (alphanumeric, `-`, `_`) separated by dots, total length ≥ 32 chars.
- * Excludes common false positives like version numbers (`1.2.3`) by
- * requiring each segment to be at least 4 characters.
- */
-const JWT_RE = /\b[a-zA-Z0-9_-]{4,}\.[a-zA-Z0-9_-]{4,}\.[a-zA-Z0-9_-]{4,}\b/g;
-
-/** Redact PEM private-key blocks with a `<REDACTED>` marker. */
-function redactPemBlocks(text: string): string {
- const lines = text.split("\n");
- const out: string[] = [];
- let inside = false;
- for (const line of lines) {
- if (!inside) {
- if (PEM_BEGIN_RE.test(line)) {
- inside = true;
- out.push("[REDACTED PRIVATE KEY]");
- } else {
- out.push(line);
- }
- } else {
- if (PEM_END_RE.test(line)) {
- inside = false;
- // The END line itself is consumed by the redaction marker.
- }
- // All interior lines are silently dropped.
- }
- }
- return out.join("\n");
-}
-
-/** Mask standalone JWT-shaped tokens to last 4 chars. */
-function redactJwtTokens(text: string): string {
- return text.replace(JWT_RE, (match) => {
- const tail = match.slice(-4);
- return `***REDACTED_JWT_${tail}`;
- });
-}
-
-/** Replace secret-like value assignments with `[REDACTED]`. */
-function redactSecretAssignments(text: string): string {
- return text.replace(SECRET_ASSIGNMENT_RE, (_match, field, sep) => `${field}${sep}[REDACTED]`);
-}
-
-/**
- * Multi-pass redaction: PEM blocks → JWT tokens → secret assignments.
- * PEM runs line-by-line first so multi-line blocks are consumed before
- * the regex-based passes see the interior base64 data.
- */
-export function redactText(text: string): string {
- return redactSecretAssignments(redactJwtTokens(redactPemBlocks(text)));
-}
-
-/**
- * Current date as `YYYY.MM.DD` in `tz` (or host local).
- *
- * When `tz` is supplied, the date is computed in that zone — relevant around
- * midnight when host UTC and user local fall on different days.
- */
-export function currentDate(tz?: string | null): string {
- const fmt = new Intl.DateTimeFormat("en-CA", {
- timeZone: tz ?? undefined,
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- });
- // en-CA gives YYYY-MM-DD; replace separators to get YYYY.MM.DD.
- return fmt.format(new Date()).replace(/-/g, ".");
-}
-
-/** Current time as `HH:MM` (24h) in `tz` (or host local). */
-export function currentTime(tz?: string | null): string {
- const parts = new Intl.DateTimeFormat("en-US", {
- timeZone: tz ?? undefined,
- hour: "2-digit",
- minute: "2-digit",
- hourCycle: "h23",
- }).formatToParts(new Date());
- const get = (type: string) => parts.find((p) => p.type === type)!.value;
- return `${get("hour")}:${get("minute")}`;
-}
-
-/** Path of the daily note file for `date` inside `vaultDir`. */
-export function dailyNotePath(vaultDir: string, date: string): string {
- return join(vaultDir, "Daily", `${validateEventDate(date)}.md`);
-}
-
-/** Empty-daily-note template. */
-export function newDailyNote(date: string): string {
- return `---\nformatted: false\n---\n\n# ${date}\n\n## Raw events\n\n`;
-}
-
-/** Validate a `HH:MM` 24-hour time string. Throws on invalid. */
-export function validateEventTime(value: string): string {
- const m = TIME_RE.exec(value);
- if (!m) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- const hour = parseInt(m[1]!, 10);
- const minute = parseInt(m[2]!, 10);
- if (hour > 23 || minute > 59) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- return value;
-}
-
-/** Validate a `YYYY.MM.DD` date string. Throws on invalid. */
-export function validateEventDate(value: string): string {
- const m = DATE_RE.exec(value);
- if (!m) {
- throw new Error("event date must use YYYY.MM.DD format");
- }
- const year = parseInt(m[1]!, 10);
- const month = parseInt(m[2]!, 10);
- const day = parseInt(m[3]!, 10);
- const utc = new Date(Date.UTC(year, month - 1, day));
- if (
- utc.getUTCFullYear() !== year ||
- utc.getUTCMonth() !== month - 1 ||
- utc.getUTCDate() !== day
- ) {
- throw new Error("event date must use YYYY.MM.DD format");
- }
- return value;
-}
-
-/**
- * Insert an event entry into the `## Raw events` section, preserving
- * chronological order. Pure function — no I/O, easy to unit-test.
- */
-export function insertEventEntry(content: string, entry: string): string {
- const marker = "## Raw events";
- const idx = content.indexOf(marker);
- if (idx === -1) {
- return content.trimEnd() + "\n\n" + marker + "\n\n" + entry + "\n";
- }
- const before = content.slice(0, idx);
- let after = content.slice(idx + marker.length).replace(/^\n+/, "");
- const lines = after.split("\n").filter((line) => line.trim());
-
- // Entry shape: "- HH:MM — @..."
- const entryTime = entry.slice(2, 7);
- let inserted = false;
- const output: string[] = [];
- for (const line of lines) {
- const m = EVENT_RE.exec(line);
- if (!inserted && m && m[1]! > entryTime) {
- output.push(entry);
- inserted = true;
- }
- output.push(line);
- }
- if (!inserted) output.push(entry);
-
- let raw = output.join("\n");
- if (raw) raw += "\n";
- return before + marker + "\n\n" + raw;
-}
-
-export interface AppendEventOptions {
- readonly date?: string | null;
- readonly time?: string | null;
- readonly tz?: string | null;
-}
-
-/**
- * Append a single event to today's (or a specified) Daily note.
- *
- * Behavior parity with the Python implementation:
- * - creates `<vault>/Daily/<date>.md` if missing, with a `## Raw events` section;
- * - inserts the entry chronologically;
- * - cross-process safe via `proper-lockfile` on the daily file path;
- * - atomic write (temp + rename + fsync of file and parent dir);
- * - redacts secret-like assignments in `message` before writing;
- * - replaces newlines in message with spaces (one entry = one line).
- *
- * Returns the absolute path of the daily note that was written.
- */
-export async function appendEvent(
- vaultDir: string,
- agent: string,
- message: string,
- opts: AppendEventOptions = {},
-): Promise<string> {
- const tz = opts.tz ?? null;
- const eventDate = validateEventDate(opts.date ?? currentDate(tz));
- const eventTime = validateEventTime(opts.time ?? currentTime(tz));
- const path = dailyNotePath(vaultDir, eventDate);
-
- const cleanMessage = redactText(message).replace(/\r?\n/g, " ");
- const entry = `- ${eventTime} — @${agent} — ${cleanMessage}`;
-
- // proper-lockfile requires the target to exist for `lock(path)`. We lock the
- // parent directory (`Daily/`) instead, which is created up-front and shared
- // across all daily files. Locking the directory is the same scope used by
- // the Python fcntl.flock on a sibling `.{name}.lock` file.
- const dailyDir = join(vaultDir, "Daily");
- mkdirSync(dailyDir, { recursive: true });
-
- const release = await lockfile.lock(dailyDir, {
- retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
- stale: 10_000,
- realpath: false,
- });
-
- try {
- let content: string;
- if (existsSync(path)) {
- content = readFileSync(path, "utf8");
- } else {
- content = newDailyNote(eventDate);
- }
- if (!content.includes("## Raw events")) {
- content = content.trimEnd() + "\n\n## Raw events\n\n";
- }
- const updated = insertEventEntry(content, entry);
- atomicWriteFileSync(path, updated);
- } finally {
- await release();
- }
-
- return path;
-}
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
index a7b5021a..4ec28a57 100644
--- a/src/core/fs-atomic.ts
+++ b/src/core/fs-atomic.ts
@@ -77,9 +77,9 @@ function withTempFile(
mkdirSync(dir, { recursive: true });
// pid + ms timestamp alone collide when two writes for the same target
- // hit within the same millisecond (e.g. concurrent appendEvent calls
- // bypassing the lockfile path). The random suffix makes openSync(..., "wx")
- // safely unique even in that race.
+ // hit within the same millisecond (concurrent writers bypassing the
+ // lockfile path). The random suffix makes openSync(..., "wx") safely
+ // unique even in that race.
const tmpName = `.${basename(target)}.${process.pid}.${Date.now()}.${Math.random()
.toString(16)
.slice(2)}.tmp`;
diff --git a/src/core/init.ts b/src/core/init.ts
deleted file mode 100644
index fd69641a..00000000
--- a/src/core/init.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
- * Vault bootstrap: scaffolding the canonical Open Second Brain layout
- * (`AI Wiki/...`) into a fresh or partially-initialized vault directory.
- *
- * Mirrors `src/open_second_brain/init.py`. Idempotent — re-running on an
- * already-initialized vault only creates missing files (or rewrites the
- * registered-agents list if a new `agentName` is supplied).
- */
-
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, posix, normalize } from "node:path";
-
-export const VAULT_FILES: ReadonlyArray<string> = [
- posix.join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- posix.join("AI Wiki", "_open-second-brain.yaml"),
- posix.join("AI Wiki", "index.md"),
- posix.join("AI Wiki", "hot.md"),
- posix.join("AI Wiki", "log.md"),
- posix.join("AI Wiki", "identity", "user.md"),
- posix.join("AI Wiki", "identity", "agents.md"),
-];
-
-export const AGENTS_PLACEHOLDER =
- "- (add your agents here, e.g., my-agent: operator on my-server)";
-
-const AGENTS_REGISTERED_HEADING = "## Registered agents";
-
-interface Template {
- readonly relPath: string;
- readonly render: (ctx: TemplateContext) => string;
-}
-
-interface TemplateContext {
- readonly name: string;
- readonly created: string;
- readonly agentsBlock: string;
-}
-
-const TEMPLATES: ReadonlyArray<Template> = [
- {
- relPath: posix.join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- render: ({ name, created }) =>
- `---\nopen_second_brain_version: 1\nname: ${name}\ncreated: ${created}\n---\n\n` +
- `# ${name}\n\n` +
- "This vault is managed by Open Second Brain.\n\n" +
- "## Rules\n\n" +
- "- Raw operational evidence goes into event log (Daily/).\n" +
- "- Synthesized knowledge goes into the wiki (AI Wiki/).\n" +
- "- Never write secrets, tokens, or credentials here.\n" +
- "- Read the identity files before acting on this vault.\n",
- },
- {
- relPath: posix.join("AI Wiki", "_open-second-brain.yaml"),
- render: ({ name, created }) => `version: 1\nname: ${name}\ncreated: ${created}\n`,
- },
- {
- relPath: posix.join("AI Wiki", "index.md"),
- render: ({ name }) =>
- `# ${name}\n\n` +
- `Welcome to the ${name} second brain.\n\n` +
- "## Key pages\n\n" +
- "- [[hot]] — short-term priority items.\n" +
- "- [[log]] — durable operation log.\n" +
- "- [[identity/user]] — owner profile.\n" +
- "- [[identity/agents]] — allowed agents and scopes.\n",
- },
- {
- relPath: posix.join("AI Wiki", "hot.md"),
- render: () =>
- "# Hot\n\n" +
- "Short-term items, current focus, active decisions.\n\n" +
- "Items fade to cold over time.\n",
- },
- {
- relPath: posix.join("AI Wiki", "log.md"),
- render: () =>
- "# Operation Log\n\n" +
- "Durable operations, major decisions, and infrastructure changes.\n\n" +
- "The event log (Daily/) is raw chronological evidence.\n" +
- "This page is synthesized operational knowledge.\n",
- },
- {
- relPath: posix.join("AI Wiki", "identity", "user.md"),
- render: () =>
- "# User Identity\n\n" +
- "Owner of this vault.\n\n" +
- "## Profile\n\n" +
- "- Name: (set your name)\n" +
- "- Timezone: (set your timezone)\n" +
- "- Contact: (set your primary contact)\n\n" +
- "## Preferences\n\n" +
- "(add durable preferences here so agents can read them)\n",
- },
- {
- relPath: posix.join("AI Wiki", "identity", "agents.md"),
- render: ({ agentsBlock }) =>
- "# Agent Identity\n\n" +
- "Allowed agents and their scopes.\n\n" +
- "## Registered agents\n\n" +
- `${agentsBlock}\n\n` +
- "## Scopes\n\n" +
- "- Write scope: AI Wiki/, Daily/\n" +
- "- Read scope: whole vault\n",
- },
-];
-
-export interface BootstrapVaultOptions {
- readonly name?: string;
- readonly agentName?: string | null;
- readonly force?: boolean;
-}
-
-/**
- * Bootstrap the canonical layout. Returns the list of relative paths that
- * were created or rewritten in this invocation (caller uses this to print
- * a summary).
- */
-export function bootstrapVault(vaultDir: string, opts: BootstrapVaultOptions = {}): string[] {
- const name = opts.name ?? "Second Brain";
- const agentName = opts.agentName ?? null;
- const force = opts.force ?? false;
- const created: string[] = [];
- const ctx: TemplateContext = {
- name,
- created: nowIsoZ(),
- agentsBlock: agentsBlock(agentName),
- };
-
- for (const tmpl of TEMPLATES) {
- const target = join(vaultDir, tmpl.relPath);
- mkdirSync(dirname(target), { recursive: true });
-
- if (existsSync(target) && !force) {
- // Special-case: agents.md may need to be rewritten to register a new
- // agent identity even though the file already exists. This is what
- // makes `o2b init --agent-name X` idempotent and additive across
- // multiple runtimes installing Open Second Brain on the same vault.
- if (tmpl.relPath === posix.join("AI Wiki", "identity", "agents.md") && agentName) {
- if (upgradeAgentsFile(target, agentName)) {
- created.push(normalize(tmpl.relPath));
- }
- }
- continue;
- }
- writeFileSync(target, tmpl.render(ctx), "utf8");
- created.push(normalize(tmpl.relPath));
- }
- return created;
-}
-
-function agentsBlock(agentName: string | null): string {
- if (agentName) return `- ${agentName}: primary agent on this server`;
- return AGENTS_PLACEHOLDER;
-}
-
-/**
- * Register `agentName` in the existing `agents.md` registry.
- *
- * Cases handled, in order:
- * - file still has bootstrap placeholder → replace with agent line.
- * - agent already registered → no-op (idempotent re-init).
- * - file initialised with another agent's entry → append the new line
- * under `## Registered agents`, before the next `##` heading.
- *
- * Returns `true` when the file was actually rewritten.
- */
-function upgradeAgentsFile(path: string, agentName: string): boolean {
- let text: string;
- try {
- text = readFileSync(path, "utf8");
- } catch {
- return false;
- }
-
- const entry = `- ${agentName}: primary agent on this server`;
- if (text.includes(entry)) return false;
-
- if (text.includes(AGENTS_PLACEHOLDER)) {
- writeFileSync(path, text.replace(AGENTS_PLACEHOLDER, entry), "utf8");
- return true;
- }
-
- const headingIdx = text.indexOf(AGENTS_REGISTERED_HEADING);
- if (headingIdx === -1) return false;
-
- const afterHeading = headingIdx + AGENTS_REGISTERED_HEADING.length;
- const rest = text.slice(afterHeading);
- const nextSectionRel = rest.indexOf("\n## ");
-
- let newText: string;
- if (nextSectionRel === -1) {
- newText = text.slice(0, afterHeading) + rest.replace(/\s+$/, "") + `\n${entry}\n`;
- } else {
- const boundary = afterHeading + nextSectionRel;
- const before = text.slice(0, boundary).replace(/\s+$/, "");
- const after = text.slice(boundary);
- newText = before + `\n${entry}\n` + after;
- }
- writeFileSync(path, newText, "utf8");
- return true;
-}
-
-function nowIsoZ(): string {
- return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
-}
diff --git a/src/core/path-safety.ts b/src/core/path-safety.ts
index 855b33b3..662b631c 100644
--- a/src/core/path-safety.ts
+++ b/src/core/path-safety.ts
@@ -24,7 +24,7 @@ import { dirname, posix, relative, resolve, sep } from "node:path";
* ancestor of the target, then re-runs the prefix check on the
* resolved real paths. This blocks the case where a directory
* *inside* the vault is itself a symlink to somewhere outside it
- * (`<vault>/AI Wiki/payments/escape -> /tmp/outside`) — without
+ * (`<vault>/Brain/payments/escape -> /tmp/outside`) — without
* realpath, the lexical check would happily admit the path.
*
* Returns the resolved (lexical) absolute path of `target`. Callers that
diff --git a/src/core/pay-memory/approval.ts b/src/core/pay-memory/approval.ts
index e946ab8f..1f9099de 100644
--- a/src/core/pay-memory/approval.ts
+++ b/src/core/pay-memory/approval.ts
@@ -1,7 +1,7 @@
/**
* Approval workflow for paid agent actions (spec §17.6).
*
- * Adds a `pending-payment-request` artifact under `AI Wiki/payments/_pending/`.
+ * Adds a `pending-payment-request` artifact under `Brain/payments/_pending/`.
* The flow is:
*
* 1. Agent creates a pending request (`writePendingRequest`).
@@ -42,7 +42,7 @@ import {
isoDateNow,
isoTimeNow,
isoTimestampZ,
- payMemoryDirs,
+ PAY_MEMORY_PENDING_REL,
validateIsoDate,
validateIsoTime,
validateSlug,
@@ -109,7 +109,7 @@ export interface PendingRequestSummary {
}
export function pendingDir(vault: string): string {
- return join(payMemoryDirs(vault).payments, "_pending");
+ return join(vault, PAY_MEMORY_PENDING_REL);
}
export function pendingRequestPath(vault: string, id: string): string {
diff --git a/src/core/pay-memory/index.ts b/src/core/pay-memory/index.ts
index f62fe758..1f26fd07 100644
--- a/src/core/pay-memory/index.ts
+++ b/src/core/pay-memory/index.ts
@@ -10,6 +10,14 @@
// pay-memory package — adapters only need to know about the directory
// roots and the vault-relative renderer.
export {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
payMemoryDirs,
policyPath,
vaultRelative as vaultRelativePath,
diff --git a/src/core/pay-memory/paths.ts b/src/core/pay-memory/paths.ts
index babe1472..61a471de 100644
--- a/src/core/pay-memory/paths.ts
+++ b/src/core/pay-memory/paths.ts
@@ -1,25 +1,54 @@
/**
* Filesystem paths and date utilities for the Pay Memory layout.
*
- * The layout sits inside `<vault>/AI Wiki/`:
+ * The layout sits inside `<vault>/Brain/payments/`:
* - policies/spending.md
- * - payments/YYYY-MM-DD/<slug>.md
+ * - YYYY-MM-DD/<slug>.md (receipts go directly under the root)
* - assets/<slug>.md
- * - drafts/<slug>.md (written by other tools — kept here for completeness)
+ * - drafts/<slug>.md (written by other tools)
* - reports/<slug>.md
+ * - _pending/<id>.md (approval workflow)
*
- * Date subdirectories use the hyphenated `YYYY-MM-DD` form (ISO 8601 calendar
- * date). This intentionally differs from the dotted `YYYY.MM.DD` used by the
- * Daily event log — the two systems are independent.
+ * Date subdirectories use the hyphenated `YYYY-MM-DD` form (ISO 8601
+ * calendar date).
*/
-import { join } from "node:path";
+import { join, posix } from "node:path";
+
+import { BRAIN_ROOT_REL } from "../brain/paths.ts";
export {
ensureInsideVault,
vaultRelative,
} from "../path-safety.ts";
+// ----- Canonical Pay Memory path constants ----------------------------------
+//
+// Every path the Pay Memory layer writes to is named here. Other
+// modules (receipt, report, approval, policy, MCP tool descriptions,
+// CLI help text) import these instead of repeating the literal so a
+// future rename cascades from one edit.
+
+/** Vault-relative root of Pay Memory under the Brain layer. */
+export const PAY_MEMORY_ROOT_REL = posix.join(BRAIN_ROOT_REL, "payments");
+
+/** Vault-relative Pay Memory subdirectory names. */
+export const PAY_MEMORY_POLICIES_REL = posix.join(PAY_MEMORY_ROOT_REL, "policies");
+export const PAY_MEMORY_ASSETS_REL = posix.join(PAY_MEMORY_ROOT_REL, "assets");
+export const PAY_MEMORY_DRAFTS_REL = posix.join(PAY_MEMORY_ROOT_REL, "drafts");
+export const PAY_MEMORY_REPORTS_REL = posix.join(PAY_MEMORY_ROOT_REL, "reports");
+export const PAY_MEMORY_PENDING_REL = posix.join(PAY_MEMORY_ROOT_REL, "_pending");
+
+/** Spending-policy file paths (vault-relative). */
+export const PAY_MEMORY_SPENDING_MD_REL = posix.join(
+ PAY_MEMORY_POLICIES_REL,
+ "spending.md",
+);
+export const PAY_MEMORY_SPENDING_JSON_REL = posix.join(
+ PAY_MEMORY_POLICIES_REL,
+ "spending.json",
+);
+
const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const HHMM_RE = /^(\d{2}):(\d{2})$/;
@@ -29,21 +58,22 @@ export interface PayMemoryDirs {
readonly assets: string;
readonly drafts: string;
readonly reports: string;
+ readonly pending: string;
}
export function payMemoryDirs(vault: string): PayMemoryDirs {
- const root = join(vault, "AI Wiki");
return {
- policies: join(root, "policies"),
- payments: join(root, "payments"),
- assets: join(root, "assets"),
- drafts: join(root, "drafts"),
- reports: join(root, "reports"),
+ policies: join(vault, PAY_MEMORY_POLICIES_REL),
+ payments: join(vault, PAY_MEMORY_ROOT_REL),
+ assets: join(vault, PAY_MEMORY_ASSETS_REL),
+ drafts: join(vault, PAY_MEMORY_DRAFTS_REL),
+ reports: join(vault, PAY_MEMORY_REPORTS_REL),
+ pending: join(vault, PAY_MEMORY_PENDING_REL),
};
}
export function policyPath(vault: string): string {
- return join(payMemoryDirs(vault).policies, "spending.md");
+ return join(vault, PAY_MEMORY_SPENDING_MD_REL);
}
export function paymentsDateDir(vault: string, date: string): string {
diff --git a/src/core/pay-memory/policy-rules.ts b/src/core/pay-memory/policy-rules.ts
index 06571e96..37e07d9e 100644
--- a/src/core/pay-memory/policy-rules.ts
+++ b/src/core/pay-memory/policy-rules.ts
@@ -1,5 +1,5 @@
/**
- * Machine-readable spending policy (`AI Wiki/policies/spending.json`).
+ * Machine-readable spending policy (`Brain/payments/policies/spending.json`).
*
* Optional, opt-in companion to `spending.md`. When the JSON file is present,
* it can be evaluated by the agent (or by `o2b check-payment-policy`) before
@@ -22,7 +22,7 @@ import { isoDateNow, payMemoryDirs, validateIsoDate } from "./paths.ts";
export const POLICY_SCHEMA_VERSION = 1;
/**
- * Schema for `AI Wiki/policies/spending.json`. All fields are optional —
+ * Schema for `Brain/payments/policies/spending.json`. All fields are optional —
* unspecified rules are interpreted as "no constraint".
*/
export interface PolicyRules {
diff --git a/src/core/pay-memory/policy.ts b/src/core/pay-memory/policy.ts
index 430a80d4..87132b1e 100644
--- a/src/core/pay-memory/policy.ts
+++ b/src/core/pay-memory/policy.ts
@@ -15,7 +15,7 @@ import {
atomicCreateFileSyncExclusive,
atomicWriteFileSync,
} from "../fs-atomic.ts";
-import { policyPath } from "./paths.ts";
+import { PAY_MEMORY_ROOT_REL, policyPath } from "./paths.ts";
export const DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policy
@@ -65,7 +65,7 @@ The agent must save:
- payment amount, if available
- service endpoint, if available
- generated asset URL or response identifier
-- payment receipt note in \`AI Wiki/payments/<date>/\`
+- payment receipt note in \`${PAY_MEMORY_ROOT_REL}/<date>/\`
- daily event log entry referencing the receipt
`;
diff --git a/src/core/pay-memory/receipt.ts b/src/core/pay-memory/receipt.ts
index 04ab58ef..d46cd406 100644
--- a/src/core/pay-memory/receipt.ts
+++ b/src/core/pay-memory/receipt.ts
@@ -23,6 +23,9 @@ import {
isoDateNow,
isoTimeNow,
isoTimestampZ,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
receiptPath,
validateIsoDate,
validateIsoTime,
@@ -141,7 +144,7 @@ function renderPolicySection(input: ReceiptInput): string[] {
default:
out.push(
"Not checked. The receipt was created without a policy decision —",
- "either no `AI Wiki/policies/spending.json` is configured, or the",
+ `either no \`${PAY_MEMORY_SPENDING_JSON_REL}\` is configured, or the`,
"caller chose not to evaluate the policy. This is *not* a claim",
"that the call was allowed.",
);
@@ -166,7 +169,7 @@ function renderPolicySection(input: ReceiptInput): string[] {
if (input.approvalRequestId?.trim()) {
out.push(
"",
- `Request: [[AI Wiki/payments/_pending/${input.approvalRequestId.trim()}]]`,
+ `Request: [[${PAY_MEMORY_PENDING_REL}/${input.approvalRequestId.trim()}]]`,
);
}
if (input.approvalStatus?.trim()) {
@@ -209,7 +212,7 @@ function renderReceiptBody(input: ReceiptInput): string {
"",
"Policy file:",
"",
- "[[AI Wiki/policies/spending]]",
+ `[[${stripMarkdownExt(PAY_MEMORY_SPENDING_MD_REL)}]]`,
"",
...renderPolicySection(input),
"## Expected cost",
diff --git a/src/core/pay-memory/report.ts b/src/core/pay-memory/report.ts
index 2169c886..457ac5a7 100644
--- a/src/core/pay-memory/report.ts
+++ b/src/core/pay-memory/report.ts
@@ -1,10 +1,10 @@
/**
* Daily payment report aggregator.
*
- * `aggregateReceipts` walks `<vault>/AI Wiki/payments/<date>/`, parses each
+ * `aggregateReceipts` walks `<vault>/Brain/payments/<date>/`, parses each
* `.md` file's frontmatter, and returns the receipts that match the expected
* `type: agent-payment-receipt` shape. `writeReport` then renders a Markdown
- * summary into `<vault>/AI Wiki/reports/<slug>.md`.
+ * summary into `<vault>/Brain/payments/reports/<slug>.md`.
*
* Receipts whose frontmatter cannot be parsed (or whose `type` is missing)
* are silently skipped — the report is best-effort and meant to surface
diff --git a/src/core/vault-scope/defaults.ts b/src/core/vault-scope/defaults.ts
index 36172742..7007c65f 100644
--- a/src/core/vault-scope/defaults.ts
+++ b/src/core/vault-scope/defaults.ts
@@ -9,6 +9,8 @@
* Anchored in docs/plans/2026-05-19-vault-scope-design.md §5.
*/
+import { BRAIN_SNAPSHOTS_REL } from "../brain/paths.ts";
+
export interface VaultIgnoreRule {
/** Entry exactly as written in `Brain/_brain.yaml`. */
readonly raw: string;
@@ -27,7 +29,7 @@ export const DEFAULT_VAULT_IGNORE_PATHS: ReadonlyArray<string> = Object.freeze([
".obsidian",
".trash",
".stversions",
- "Brain/.snapshots",
+ BRAIN_SNAPSHOTS_REL,
]);
/**
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 4eae4949..932b56f5 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -362,11 +362,9 @@ async function toolBrainApplyEvidence(
// ----- brain_note (§32B, v0.10.8) ------------------------------------------
/**
- * Append one narrative-milestone line to today's Brain log. This is the
- * Brain-native replacement for the deprecated `event_log_append` tool:
- * agents now record release / merged-PR / discovered-fact lines under
- * the `note` event kind in `Brain/log/<today>.md` (and the JSONL
- * sidecar) instead of falling back to `Daily/`.
+ * Append one narrative-milestone line to today's Brain log. Agents
+ * record release / merged-PR / discovered-fact lines under the `note`
+ * event kind in `Brain/log/<today>.md` (and the JSONL sidecar).
*
* The body lives in `appendBrainNote` so the CLI verb (`o2b brain
* note`) and this MCP handler share one code path. Validation errors
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index f0b8bc10..6b5723e4 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -1,13 +1,14 @@
/**
* Server-supplied instructions returned in `initialize.instructions`.
*
- * In v0.9.0 the wording shifts from a single event-log-centric flow to
- * the Brain observing-memory layer. Six new `brain_*` tools are the
- * canonical writable surface; `event_log_append` and
- * `second_brain_capture` are no longer advertised to agents (their
- * handlers remain on disk for shell-side use).
+ * The Brain observing-memory layer is the canonical writable surface:
+ * three writer tools (`brain_feedback`, `brain_apply_evidence`,
+ * `brain_note`) plus the read-only `brain_context` reader live on the
+ * always-loaded writer scope; the remaining `brain_*` surface ships on
+ * the deferred full server.
*/
+import { PAY_MEMORY_SPENDING_JSON_REL } from "../core/pay-memory/paths.ts";
import type { ToolScope } from "./tools.ts";
export interface BuildInstructionsOpts {
@@ -91,13 +92,13 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string
"real patterns from repeat events, so prefer precision over " +
"coverage.\n\n" +
"Other tools: second_brain_status (config status), " +
- "vault_health (verify vault), second_brain_query (look up legacy " +
- "AI Wiki / Daily notes — read-only).\n\n" +
+ "vault_health (verify vault), second_brain_query (list vault pages " +
+ "by title - read-only).\n\n" +
"Pay Memory tools record paid agent actions as inspectable Markdown:\n" +
" - payment_memory_init bootstraps the layout and writes the " +
"spending policy template (run once per vault).\n" +
" - payment_policy_check evaluates a prospective paid call against " +
- "`AI Wiki/policies/spending.json` (allowed / approval_required / denied).\n" +
+ `\`${PAY_MEMORY_SPENDING_JSON_REL}\` (allowed / approval_required / denied).\n` +
" - payment_request_approval creates a pending-payment-request the " +
"user must approve before you run `pay`; payment_request_status polls " +
"for approval; payment_request_consume links the eventual receipt.\n" +
diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.ts
index cc036acc..025c1ce1 100644
--- a/src/mcp/pay-memory-tools.ts
+++ b/src/mcp/pay-memory-tools.ts
@@ -24,6 +24,8 @@ import {
consumePendingRequest,
loadPendingRequest,
payMemoryDirs,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
vaultRelativePath,
writeAsset,
writePendingRequest,
@@ -493,7 +495,7 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "payment_policy_check",
description:
- "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",
+ `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,
inputSchema: {
type: "object",
properties: {
@@ -514,7 +516,7 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "payment_report_generate",
description:
- "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",
+ `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,
inputSchema: {
type: "object",
properties: {
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 8dbd4e45..e7b7e231 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -17,12 +17,6 @@
*
* Each slice owns its own handlers and tool definitions; this file
* only assembles them in a stable order and applies scope filtering.
- *
- * §32 (v0.10.8) retires `event_log_append` and `second_brain_capture`
- * from every runtime. The `appendEvent` function in
- * `src/core/event-log.ts` stays for the human-side CLI verb
- * (`o2b append-event`) and cron-jobs; the MCP surface no longer
- * advertises either tool.
*/
import {
@@ -163,11 +157,6 @@ async function toolQuery(ctx: ServerContext, args: Record<string, unknown>): Pro
};
}
-// §32G (v0.10.8): the `event_log_append` MCP handler is gone. The
-// bare `appendEvent` function in `src/core/event-log.ts` stays for
-// the CLI verb (`o2b append-event`) and cron-jobs that target the
-// human-side `Daily/` log; the MCP surface no longer advertises it.
-
async function toolVaultHealth(
ctx: ServerContext,
args: Record<string, unknown>,
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index 5f52b5bc..f29e41f3 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -1,15 +1,11 @@
/**
* OpenClaw native plugin entry for Open Second Brain.
*
- * Pure TypeScript that delegates to `src/core/*` so the JS implementation
- * is no longer a hand-translated copy of the Python original — both runtimes
- * share the same source of truth.
+ * Pure TypeScript that delegates to `src/core/*` so the OpenClaw runtime
+ * shares the same source of truth as the CLI and MCP server.
*
- * The plugin exposes the current Open Second Brain tool surface:
- * `second_brain_status`, `second_brain_query`, `vault_health`, plus the
- * eight Pay Memory tools added in v0.8.0. Legacy write tools
- * (`second_brain_capture`, `event_log_append`) are retired from this
- * agent-facing runtime.
+ * Exposes the current tool surface: `second_brain_status`,
+ * `second_brain_query`, `vault_health`, plus the eight Pay Memory tools.
* No subprocess creation; passes the OpenClaw security scanner.
*/
@@ -24,10 +20,6 @@ import {
resolveTimezone,
} from "../core/config.ts";
import { doctor } from "../core/doctor.ts";
-// §32G (v0.10.8): `appendEvent` / `validateEventTime` are no longer
-// needed by the OpenClaw bundle — the `event_log_append` tool was
-// retired from this runtime. The functions still live in
-// `src/core/event-log.ts` for the human-side `o2b append-event` CLI.
import { buildReminder } from "../core/identity-reminder.ts";
import {
checkPolicy,
@@ -40,6 +32,8 @@ import {
writeReceipt,
writeReport,
payMemoryDirs,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
} from "../core/pay-memory/index.ts";
import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
import { mkdirSync } from "node:fs";
@@ -214,12 +208,9 @@ export default definePluginEntry({
},
);
- // §32G (v0.10.8): the OpenClaw `second_brain_capture` and
- // `event_log_append` registrations are gone. Agents on this runtime
- // now record via the Brain writer tools served by the MCP server
- // (`brain_feedback`, `brain_apply_evidence`, `brain_note`); the
- // human-side `o2b append-event` CLI is the only remaining caller of
- // `appendEvent`.
+ // Agents on this runtime record observations via the Brain writer
+ // tools served by the MCP server (`brain_feedback`,
+ // `brain_apply_evidence`, `brain_note`).
api.registerTool(
{
@@ -468,7 +459,7 @@ export default definePluginEntry({
api.registerTool({
name: "payment_report_generate",
description:
- "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",
+ `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,
parameters: {
type: "object",
properties: {
@@ -502,7 +493,7 @@ export default definePluginEntry({
api.registerTool({
name: "payment_policy_check",
description:
- "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",
+ `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,
parameters: {
type: "object",
properties: {
diff --git a/templates/brain-starter/retired/ret-no-emojis-in-code.md b/templates/brain-starter/retired/ret-no-emojis-in-code.md
index 413dfc3a..fbf0b380 100644
--- a/templates/brain-starter/retired/ret-no-emojis-in-code.md
+++ b/templates/brain-starter/retired/ret-no-emojis-in-code.md
@@ -13,7 +13,7 @@ pinned: false
scope: writing
kind: brain-retired
id: ret-no-emojis-in-code
-status: retired
+_status: retired
retired_at: "2026-05-15T16:00:00.000Z"
retired_reason: rebutted
retired_by: "[[Brain/log/2026-05-15]]"
diff --git a/templates/brain-starter/retired/ret-prefer-curl-over-wget.md b/templates/brain-starter/retired/ret-prefer-curl-over-wget.md
index d304aa81..89e12707 100644
--- a/templates/brain-starter/retired/ret-prefer-curl-over-wget.md
+++ b/templates/brain-starter/retired/ret-prefer-curl-over-wget.md
@@ -13,7 +13,7 @@ pinned: false
scope: infra
kind: brain-retired
id: ret-prefer-curl-over-wget
-status: retired
+_status: retired
retired_at: "2026-05-15T18:00:00.000Z"
retired_reason: stale-no-evidence
retired_by: "[[Brain/log/2026-05-15]]"
diff --git a/templates/brain-starter/retired/ret-tabs-over-spaces.md b/templates/brain-starter/retired/ret-tabs-over-spaces.md
index 52664b06..58ffde76 100644
--- a/templates/brain-starter/retired/ret-tabs-over-spaces.md
+++ b/templates/brain-starter/retired/ret-tabs-over-spaces.md
@@ -13,7 +13,7 @@ pinned: false
scope: coding
kind: brain-retired
id: ret-tabs-over-spaces
-status: retired
+_status: retired
retired_at: "2026-05-16T11:00:00.000Z"
retired_reason: user-rejected
retired_by: "[[Brain/log/2026-05-16]]"
diff --git a/tests/cli/append-event.test.ts b/tests/cli/append-event.test.ts
deleted file mode 100644
index 953c4319..00000000
--- a/tests/cli/append-event.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- readdirSync,
- rmSync,
- writeFileSync,
-} from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-import { runCli } from "../helpers/run-cli.ts";
-
-/**
- * §32F (v0.10.8). The `o2b append-event` CLI verb stays as the human /
- * cron-job surface for the legacy Daily/ event log. The bug it fixes:
- * before v0.10.8 the resolver fell back to the literal `"agent"` when
- * `--as` and `VAULT_AGENT_NAME` were absent, even when the plugin
- * config carried an `agent_name`. Daily entries from cron-jobs
- * therefore showed up as `@agent` instead of the configured identity.
- */
-
-let tmp: string;
-let configDir: string;
-let vault: string;
-let configPath: string;
-
-beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), "o2b-append-event-"));
- configDir = mkdtempSync(join(tmpdir(), "o2b-append-event-cfg-"));
- vault = join(tmp, "vault");
- configPath = join(configDir, "config.yaml");
- mkdirSync(vault, { recursive: true });
-});
-
-afterEach(() => {
- rmSync(tmp, { recursive: true, force: true });
- rmSync(configDir, { recursive: true, force: true });
-});
-
-describe("o2b append-event identity resolution (§32F)", () => {
- test("uses config agent_name when --as and env are absent", async () => {
- writeFileSync(
- configPath,
- `vault: ${vault}\nagent_name: cli-test-bot\n`,
- "utf8",
- );
-
- const r = await runCli(["append-event", "hello world"], {
- env: {
- OPEN_SECOND_BRAIN_CONFIG: configPath,
- VAULT_AGENT_NAME: "",
- },
- });
-
- expect(r.returncode).toBe(0);
- const dailyDir = join(vault, "Daily");
- expect(existsSync(dailyDir)).toBe(true);
- const files = readdirSync(dailyDir);
- expect(files).toHaveLength(1);
- const body = readFileSync(join(dailyDir, files[0]!), "utf8");
- expect(body).toContain("@cli-test-bot");
- expect(body).not.toContain("@agent ");
- expect(body).toContain("hello world");
- });
-
- test("--as wins over the config agent_name", async () => {
- writeFileSync(
- configPath,
- `vault: ${vault}\nagent_name: cli-test-bot\n`,
- "utf8",
- );
-
- const r = await runCli(
- ["append-event", "--as", "explicit-bot", "another line"],
- {
- env: {
- OPEN_SECOND_BRAIN_CONFIG: configPath,
- VAULT_AGENT_NAME: "",
- },
- },
- );
-
- expect(r.returncode).toBe(0);
- const dailyDir = join(vault, "Daily");
- const files = readdirSync(dailyDir);
- const body = readFileSync(join(dailyDir, files[0]!), "utf8");
- expect(body).toContain("@explicit-bot");
- expect(body).not.toContain("@cli-test-bot");
- });
-
- test("VAULT_AGENT_NAME env wins when --as is absent", async () => {
- writeFileSync(
- configPath,
- `vault: ${vault}\nagent_name: cli-test-bot\n`,
- "utf8",
- );
-
- const r = await runCli(["append-event", "env wins"], {
- env: {
- OPEN_SECOND_BRAIN_CONFIG: configPath,
- VAULT_AGENT_NAME: "env-bot",
- },
- });
-
- expect(r.returncode).toBe(0);
- const dailyDir = join(vault, "Daily");
- const files = readdirSync(dailyDir);
- const body = readFileSync(join(dailyDir, files[0]!), "utf8");
- expect(body).toContain("@env-bot");
- });
-});
diff --git a/tests/cli/brain-synthesise-cli.test.ts b/tests/cli/brain-synthesise-cli.test.ts
index fb9f58ba..a2055cc2 100644
--- a/tests/cli/brain-synthesise-cli.test.ts
+++ b/tests/cli/brain-synthesise-cli.test.ts
@@ -14,13 +14,29 @@ let vault: string;
let configHome: string;
let configPath: string;
+const DERIVED_KEYS = new Set([
+ "status",
+ "applied_count",
+ "violated_count",
+ "last_evidence_at",
+ "confidence",
+ "confidence_value",
+ "evidenced_by",
+ "contradicted_by",
+ "lifecycle",
+ "confirmed_at",
+]);
+
function writePref(
slug: string,
frontmatter: Record<string, string>,
body = "",
): void {
const lines = ["---"];
- for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ for (const [k, v] of Object.entries(frontmatter)) {
+ const key = DERIVED_KEYS.has(k) ? `_${k}` : k;
+ lines.push(`${key}: ${v}`);
+ }
lines.push("---", "", body);
writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
}
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index f4fcd78b..61b530fe 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -1206,7 +1206,7 @@ describe("brain scan-inline", () => {
"utf8",
);
- const r = await runCli(["brain", "scan-inline", "--vault", vault], {
+ const r = await runCli(["brain", "scan-inline", "--vault", vault, "--path", "Daily"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(0);
@@ -1232,7 +1232,7 @@ describe("brain scan-inline", () => {
const before = readFileSync(notePath, "utf8");
const r = await runCli(
- ["brain", "scan-inline", "--vault", vault, "--dry-run"],
+ ["brain", "scan-inline", "--vault", vault, "--dry-run", "--path", "Daily"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
@@ -1250,7 +1250,7 @@ describe("brain scan-inline", () => {
"utf8",
);
const r = await runCli(
- ["brain", "scan-inline", "--vault", vault, "--json"],
+ ["brain", "scan-inline", "--vault", vault, "--json", "--path", "Daily"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
@@ -1269,7 +1269,7 @@ describe("brain scan-inline", () => {
"utf8",
);
const r = await runCli(
- ["brain", "scan-inline", "--vault", vault, "--strict"],
+ ["brain", "scan-inline", "--vault", vault, "--strict", "--path", "Daily"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(2);
@@ -1356,130 +1356,6 @@ describe("brain vault resolution", () => {
});
});
-// ── §24 migrate-frontmatter CLI ─────────────────────────────────────────────
-
-describe("brain migrate-frontmatter", () => {
- /** Write a legacy-shape pref file under the bootstrapped vault. */
- function writeLegacyPref(slug: string): string {
- const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
- writeFileSync(
- path,
- [
- "---",
- "kind: brain-preference",
- `id: pref-${slug}`,
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- `tags: [brain, brain/preference, brain/topic/${slug}]`,
- `topic: ${slug}`,
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "confirmed_at: 2026-05-15T10:00:00Z",
- "evidenced_by: []",
- "applied_count: 1",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
- "---",
- "",
- ].join("\n"),
- "utf8",
- );
- return path;
- }
-
- test("--dry-run (default) prints plan and modifies no files", async () => {
- await bootstrap();
- const prefPath = writeLegacyPref("dry-rule");
- const before = readFileSync(prefPath, "utf8");
-
- const r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- expect(r.stdout).toMatch(/files_to_migrate: 1/);
- expect(readFileSync(prefPath, "utf8")).toBe(before);
- });
-
- test("--apply --yes rewrites files and takes a snapshot", async () => {
- await bootstrap();
- const prefPath = writeLegacyPref("apply-rule");
-
- const r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
-
- const raw = readFileSync(prefPath, "utf8");
- expect(raw).toMatch(/^_status: confirmed$/m);
- expect(raw).not.toMatch(/^status: /m);
-
- const snapDir = join(vault, "Brain", ".snapshots");
- const snaps = readdirSync(snapDir).filter((n) => n.startsWith("migrate-"));
- expect(snaps.length).toBeGreaterThan(0);
- });
-
- test("--apply without --yes in non-interactive mode exits 1", async () => {
- await bootstrap();
- writeLegacyPref("no-yes");
- const r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault, "--apply"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(1);
- expect(r.stderr.toLowerCase()).toMatch(/--yes/);
- });
-
- test("--json emits machine-readable summary", async () => {
- await bootstrap();
- writeLegacyPref("json-rule");
- const r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault, "--json"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- const parsed = JSON.parse(r.stdout);
- expect(parsed.ok).toBe(true);
- expect(parsed.files_scanned).toBe(1);
- expect(parsed.files_to_migrate).toBe(1);
- });
-
- test("--apply on collision file aborts with exit 1", async () => {
- await bootstrap();
- // Write a file with both shapes
- const path = join(vault, "Brain", "preferences", "pref-collision.md");
- writeFileSync(
- path,
- [
- "---",
- "kind: brain-preference",
- "id: pref-collision",
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- "tags: [brain, brain/preference, brain/topic/collision]",
- "topic: collision",
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "_status: confirmed",
- "evidenced_by: []",
- "---",
- "",
- ].join("\n"),
- "utf8",
- );
- const r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(1);
- expect(r.stderr).toMatch(/collision/i);
- });
-});
-
describe("brain protect", () => {
test("--target claudecode --print returns the JSON shape, exit 0", async () => {
await bootstrap();
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index 895fe806..d1cb4f7f 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
+import { BRAIN_INDEX_REL, BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
import { runCli } from "../helpers/run-cli.ts";
@@ -35,26 +36,10 @@ describe("status", () => {
});
describe("init", () => {
- test("creates vault structure", async () => {
+ test("prints initialized vault message", async () => {
const r = await runCli(["init", "--vault", tmp, "--name", "Test"]);
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("initialized vault:");
- expect(existsSync(join(tmp, "AI Wiki", "_OPEN_SECOND_BRAIN.md"))).toBe(true);
- expect(existsSync(join(tmp, "AI Wiki", "identity", "agents.md"))).toBe(true);
- });
-
- test("with agent-name writes identity entry", async () => {
- const vault = join(tmp, "vault");
- const config = join(tmp, "config.yaml");
- const r = await runCli(
- ["init", "--vault", vault, "--name", "Test", "--agent-name", "openclaw-main"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("agent name registered: openclaw-main");
- const txt = readFileSync(join(vault, "AI Wiki", "identity", "agents.md"), "utf8");
- expect(txt).toContain("- openclaw-main: primary agent on this server");
- expect(txt).not.toContain("(add your agents here");
});
test("with agent-name persists to plugin config", async () => {
@@ -122,69 +107,6 @@ describe("init", () => {
expect(readFileSync(config, "utf8")).toContain("hermes-vps-agent");
});
- test("already initialized does not overwrite", async () => {
- await runCli(["init", "--vault", tmp, "--name", "First"]);
- const index = join(tmp, "AI Wiki", "index.md");
- writeFileSync(index, "custom");
- const r = await runCli(["init", "--vault", tmp, "--name", "Second"]);
- expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("already initialized");
- expect(readFileSync(index, "utf8")).toBe("custom");
- });
-
- test("--force overwrites", async () => {
- await runCli(["init", "--vault", tmp, "--name", "First"]);
- const index = join(tmp, "AI Wiki", "index.md");
- writeFileSync(index, "old");
- const r = await runCli(["init", "--vault", tmp, "--name", "Second", "--force"]);
- expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("initialized vault:");
- expect(readFileSync(index, "utf8")).not.toBe("old");
- });
-});
-
-describe("append-event", () => {
- test("errors when no vault anywhere", async () => {
- const cfg = join(tmp, "config.yaml");
- const r = await runCli(["append-event", "msg", "--as", "tester"], {
- env: { OPEN_SECOND_BRAIN_CONFIG: cfg },
- });
- expect(r.returncode).not.toBe(0);
- expect(r.stderr.toLowerCase()).toContain("no vault configured");
- });
-
- test("prints absolute path on success", async () => {
- const vault = join(tmp, "vault");
- mkdirSync(vault);
- const cfg = join(tmp, "config.yaml");
- const r = await runCli(
- ["append-event", "absolute-path-test", "--vault", vault, "--as", "tester"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: cfg } },
- );
- expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("appended: ");
- const printed = r.stdout.split("appended: ")[1]!.trim().split("\n")[0]!;
- expect(printed.startsWith("/")).toBe(true);
- expect(printed.startsWith(resolve(vault))).toBe(true);
- });
-
- test("writes daily note", async () => {
- const r = await runCli([
- "append-event",
- "created CLI",
- "--vault",
- tmp,
- "--as",
- "test-agent",
- "--date",
- "2026.05.06",
- "--time",
- "10:15",
- ]);
- expect(r.returncode).toBe(0);
- const daily = join(tmp, "Daily", "2026.05.06.md");
- expect(readFileSync(daily, "utf8")).toContain("- 10:15 — @test-agent — created CLI");
- });
});
describe("doctor", () => {
@@ -238,14 +160,14 @@ describe("index", () => {
expect(r.stderr.toLowerCase()).toContain("no vault configured");
});
- test("generates wikilink index", async () => {
+ test("generates wikilink index under Brain/", async () => {
const vault = tmp;
- mkdirSync(join(vault, "AI Wiki"), { recursive: true });
+ mkdirSync(join(vault, BRAIN_ROOT_REL), { recursive: true });
writeFileSync(join(vault, "Concept.md"), "---\ntitle: Concept\n---\n\nBody.");
writeFileSync(join(vault, "Other.md"), "No frontmatter.");
const r = await runCli(["index", "--vault", vault]);
expect(r.returncode).toBe(0);
- const indexPath = join(vault, "AI Wiki", "index.md");
+ const indexPath = join(vault, BRAIN_INDEX_REL);
expect(existsSync(indexPath)).toBe(true);
const content = readFileSync(indexPath, "utf8");
expect(content).toContain("[[Concept]]");
@@ -266,26 +188,6 @@ describe("export-config", () => {
});
});
-describe("vault-log compat command (append-event under another name)", () => {
- test("produces same daily note as append-event", async () => {
- const r = await runCli([
- "append-event",
- "compat entry",
- "--as",
- "compat-agent",
- "--vault",
- tmp,
- "--date",
- "2026.05.06",
- "--time",
- "10:30",
- ]);
- expect(r.returncode).toBe(0);
- const daily = join(tmp, "Daily", "2026.05.06.md");
- expect(readFileSync(daily, "utf8")).toContain("- 10:30 — @compat-agent — compat entry");
- });
-});
-
describe("mcp subcommand", () => {
test("errors when no vault anywhere", async () => {
const cfg = join(tmp, "config.yaml");
diff --git a/tests/cli/pay-memory.test.ts b/tests/cli/pay-memory.test.ts
index 08d8cbed..cd39ebd9 100644
--- a/tests/cli/pay-memory.test.ts
+++ b/tests/cli/pay-memory.test.ts
@@ -3,6 +3,16 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "no
import { tmpdir } from "node:os";
import { join } from "node:path";
+import {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
+} from "../../src/core/pay-memory/paths.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -28,17 +38,18 @@ describe("init-pay-memory", () => {
expect(r.returncode).toBe(0);
expect(r.stdout).toContain("pay-memory layout initialized:");
expect(r.stdout).toContain("agent: hermes-vps-agent");
- for (const sub of ["policies", "payments", "assets", "drafts", "reports"]) {
- expect(existsSync(join(vault, "AI Wiki", sub))).toBe(true);
+ expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL))).toBe(true);
+ for (const sub of ["policies", "assets", "drafts", "reports"]) {
+ expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL, sub))).toBe(true);
}
- expect(existsSync(join(vault, "AI Wiki", "policies", "spending.md"))).toBe(true);
+ expect(existsSync(join(vault, PAY_MEMORY_SPENDING_MD_REL))).toBe(true);
});
test("re-running is idempotent and skips the policy by default", async () => {
await runCli(["init-pay-memory", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
- const policy = join(vault, "AI Wiki", "policies", "spending.md");
+ const policy = join(vault, PAY_MEMORY_SPENDING_MD_REL);
writeFileSync(policy, "edited\n", "utf8");
const r = await runCli(["init-pay-memory", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
@@ -52,7 +63,7 @@ describe("init-pay-memory", () => {
await runCli(["init-pay-memory", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
- const policy = join(vault, "AI Wiki", "policies", "spending.md");
+ const policy = join(vault, PAY_MEMORY_SPENDING_MD_REL);
writeFileSync(policy, "stale\n", "utf8");
const r = await runCli(["init-pay-memory", "--vault", vault, "--overwrite"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
@@ -69,9 +80,9 @@ describe("init-pay-memory", () => {
expect(r.returncode).toBe(0);
const payload = JSON.parse(r.stdout);
expect(payload.vault_path).toBe(vault);
- expect(payload.policy_path).toBe("AI Wiki/policies/spending.md");
+ expect(payload.policy_path).toBe(PAY_MEMORY_SPENDING_MD_REL);
expect(payload.policy_status).toBe("created");
- expect(payload.created).toContain("AI Wiki/policies");
+ expect(payload.created).toContain(PAY_MEMORY_POLICIES_REL);
});
});
@@ -101,7 +112,7 @@ describe("append-payment-receipt", () => {
"--actual-amount", "0.05",
"--currency", "USDC",
"--result-ref", "https://fal-cdn.example/img.png",
- "--result-note", "AI Wiki/assets/blog-header.md",
+ "--result-note", `${PAY_MEMORY_ASSETS_REL}/blog-header.md`,
"--raw-output-file", rawFile,
"--date", "2026-05-10",
"--time", "17:20",
@@ -109,7 +120,7 @@ describe("append-payment-receipt", () => {
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("receipt: AI Wiki/payments/2026-05-10/");
+ expect(r.stdout).toContain(`receipt: ${PAY_MEMORY_ROOT_REL}/2026-05-10/`);
const receiptPath = r.stdout.match(/^receipt: (.+)$/m)![1]!.trim();
const text = readFileSync(join(vault, receiptPath), "utf8");
expect(text).toContain("paysponge/fal");
@@ -168,19 +179,19 @@ describe("capture-asset", () => {
"--title", "Blog Header: Pay Memory",
"--service", "paysponge/fal",
"--result-url", "https://fal-cdn.example/img.png",
- "--source-receipt", "AI Wiki/payments/2026-05-10/fal-blog.md",
+ "--source-receipt", `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-blog.md`,
"--prompt-file", promptFile,
- "--used-in", "AI Wiki/drafts/blog-post.md",
+ "--used-in", `${PAY_MEMORY_DRAFTS_REL}/blog-post.md`,
],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
- expect(r.stdout).toContain("asset: AI Wiki/assets/");
+ expect(r.stdout).toContain(`asset: ${PAY_MEMORY_ASSETS_REL}/`);
const assetPath = r.stdout.match(/^asset: (.+)$/m)![1]!.trim();
const text = readFileSync(join(vault, assetPath), "utf8");
expect(text).toContain("# Blog Header: Pay Memory");
expect(text).toContain("> A recursive technical illustration");
- expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');
+ expect(text).toContain(`source_receipt: "[[${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-blog]]"`);
});
});
@@ -219,7 +230,7 @@ describe("payment-report", () => {
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(report.returncode).toBe(0);
- expect(report.stdout).toContain("report: AI Wiki/reports/");
+ expect(report.stdout).toContain(`report: ${PAY_MEMORY_REPORTS_REL}/`);
expect(report.stdout).toContain("receipts: 2");
const reportPath = report.stdout.match(/^report: (.+)$/m)![1]!.trim();
const text = readFileSync(join(vault, reportPath), "utf8");
@@ -262,7 +273,7 @@ describe("check-payment-policy", () => {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
writeFileSync(
- join(vault, "AI Wiki", "policies", "spending.json"),
+ join(vault, PAY_MEMORY_SPENDING_JSON_REL),
JSON.stringify({ allowed_services: ["paysponge/fal"] }),
"utf8",
);
@@ -280,7 +291,7 @@ describe("check-payment-policy", () => {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
writeFileSync(
- join(vault, "AI Wiki", "policies", "spending.json"),
+ join(vault, PAY_MEMORY_SPENDING_JSON_REL),
JSON.stringify({
allowed_services: ["x/y"],
require_approval_above: 0.05,
@@ -317,7 +328,7 @@ describe("check-payment-policy", () => {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
writeFileSync(
- join(vault, "AI Wiki", "policies", "spending.json"),
+ join(vault, PAY_MEMORY_SPENDING_JSON_REL),
JSON.stringify({
allowed_services: ["x/y"],
max_single_call: 0.05,
@@ -357,7 +368,7 @@ describe("approval workflow (request → approve → consume)", () => {
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(req.returncode).toBe(0);
- expect(req.stdout).toContain("pending: AI Wiki/payments/_pending/demo-1.md");
+ expect(req.stdout).toContain(`pending: ${PAY_MEMORY_PENDING_REL}/demo-1.md`);
const approve = await runCli(
[
@@ -377,7 +388,7 @@ describe("approval workflow (request → approve → consume)", () => {
"consume-payment-request",
"--vault", vault,
"--id", "demo-1",
- "--receipt", "AI Wiki/payments/2026-05-10/fal-1.md",
+ "--receipt", `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-1.md`,
],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
@@ -385,12 +396,12 @@ describe("approval workflow (request → approve → consume)", () => {
expect(consume.stdout).toContain("status: consumed");
const text = readFileSync(
- join(vault, "AI Wiki", "payments", "_pending", "demo-1.md"),
+ join(vault, PAY_MEMORY_PENDING_REL, "demo-1.md"),
"utf8",
);
expect(text).toContain("status: consumed");
expect(text).toContain("approved_by: sergey");
- expect(text).toContain("receipt: AI Wiki/payments/2026-05-10/fal-1.md");
+ expect(text).toContain(`receipt: ${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-1.md`);
});
test("reject blocks subsequent approve", async () => {
diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.ts
index 86998a1f..c1b02200 100644
--- a/tests/cli/uninstall.test.ts
+++ b/tests/cli/uninstall.test.ts
@@ -137,10 +137,10 @@ describe("planUninstall", () => {
describe("safety invariants", () => {
test("apply-local never touches vault", () => {
const vault = join(tmp, "vault");
- mkdirSync(join(vault, "AI Wiki"), { recursive: true });
- mkdirSync(join(vault, "Daily"), { recursive: true });
- writeFileSync(join(vault, "AI Wiki", "page.md"), "# Page\n");
- writeFileSync(join(vault, "Daily", "2026.05.06.md"), "# Daily\n");
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ mkdirSync(join(vault, "Journal"), { recursive: true });
+ writeFileSync(join(vault, "Notes", "page.md"), "# Page\n");
+ writeFileSync(join(vault, "Journal", "2026-05-06.md"), "# Journal\n");
const configDir = join(tmp, "open-second-brain");
mkdirSync(configDir);
@@ -150,8 +150,8 @@ describe("safety invariants", () => {
planUninstall({ configPath: config, applyLocal: true });
expect(existsSync(vault)).toBe(true);
- expect(existsSync(join(vault, "AI Wiki", "page.md"))).toBe(true);
- expect(existsSync(join(vault, "Daily", "2026.05.06.md"))).toBe(true);
+ expect(existsSync(join(vault, "Notes", "page.md"))).toBe(true);
+ expect(existsSync(join(vault, "Journal", "2026-05-06.md"))).toBe(true);
});
test("apply-local never touches the Hermes config file", async () => {
@@ -193,8 +193,7 @@ describe("renderPlan", () => {
test("states vault is preserved", () => {
const text = basicPlan(false);
expect(text).toMatch(/Vault \(NEVER removed by this tool\)/);
- expect(text).toContain("Daily/");
- expect(text).toContain("AI Wiki/");
+ expect(text).toContain("Your Markdown notes stay exactly as they are");
});
test("states Hermes config is not edited", () => {
diff --git a/tests/core/brain.body-hygiene.test.ts b/tests/core/brain.body-hygiene.test.ts
index 108fc76d..6eae751d 100644
--- a/tests/core/brain.body-hygiene.test.ts
+++ b/tests/core/brain.body-hygiene.test.ts
@@ -166,17 +166,17 @@ describe("retired body — re-rendered to v0.10.1 shape on retire", () => {
"kind: brain-preference",
"id: pref-legacy",
"created_at: 2026-05-10T00:00:00Z",
- "confirmed_at: 2026-05-10T00:00:00Z",
+ "_confirmed_at: 2026-05-10T00:00:00Z",
"unconfirmed_until: 2026-05-24T00:00:00Z",
"tags: [brain, brain/preference, brain/topic/legacy]",
"topic: legacy",
- "status: confirmed",
+ "_status: confirmed",
"principle: legacy rule",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -219,7 +219,7 @@ describe("§6 signal suppression", () => {
"---",
"kind: brain-retired",
"id: ret-noisy",
- "status: retired",
+ "_status: retired",
"retired_at: 2026-05-10T00:00:00Z",
"retired_reason: user-rejected",
"retired_by: '[[Brain/log/2026-05-10]]'",
@@ -227,11 +227,11 @@ describe("§6 signal suppression", () => {
"tags: [brain, brain/retired, brain/topic/noisy]",
"topic: noisy",
"principle: stop spamming",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"user_rejected_reason: rule was wrong",
"---",
@@ -279,7 +279,7 @@ describe("§6 signal suppression", () => {
"---",
"kind: brain-retired",
"id: ret-scoped",
- "status: retired",
+ "_status: retired",
"retired_at: 2026-05-10T00:00:00Z",
"retired_reason: user-rejected",
"retired_by: '[[Brain/log/2026-05-10]]'",
@@ -288,11 +288,11 @@ describe("§6 signal suppression", () => {
"topic: scoped",
"scope: writing",
"principle: writing-scoped rule",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"user_rejected_reason: writing-scope was the issue",
"---",
@@ -341,17 +341,17 @@ describe("dream — body migration of v0.9.x preferences", () => {
"kind: brain-preference",
"id: pref-migrate-me",
"created_at: 2026-05-10T00:00:00Z",
- "confirmed_at: 2026-05-10T00:00:00Z",
+ "_confirmed_at: 2026-05-10T00:00:00Z",
"unconfirmed_until: 2026-05-24T00:00:00Z",
"tags: [brain, brain/preference, brain/topic/migrate-me]",
"topic: migrate-me",
- "status: confirmed",
+ "_status: confirmed",
"principle: migrate me",
- 'evidenced_by: ["[[sig-2026-05-09-migrate-me]]"]',
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ '_evidenced_by: ["[[sig-2026-05-09-migrate-me]]"]',
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
diff --git a/tests/core/brain.confidence-value.test.ts b/tests/core/brain.confidence-value.test.ts
index 5223d1ca..05ac96d2 100644
--- a/tests/core/brain.confidence-value.test.ts
+++ b/tests/core/brain.confidence-value.test.ts
@@ -62,57 +62,45 @@ describe("computeConfidence — numeric value", () => {
expect(Math.round(r.value * 10000) / 10000).toBe(r.value);
});
- test("hard floor: applied <= low_max_applied keeps band low", () => {
+ test("applied=2, violated=0, fresh → low (Wilson ≈ 0.34, below medium_min)", () => {
const r = computeConfidence(2, 0, iso("2026-05-15"), cfg, NOW);
expect(r.band).toBe("low");
});
- test("hard floor: violated >= applied keeps band low", () => {
+ test("violated >= applied → low (Wilson collapses on noisy signal)", () => {
const r = computeConfidence(5, 5, iso("2026-05-15"), cfg, NOW);
expect(r.band).toBe("low");
});
- test("step-function eligibility: 10 applied / no violated / fresh → high", () => {
+ test("applied=10, violated=0, fresh → medium (Wilson ≈ 0.72, below high_min)", () => {
const r = computeConfidence(10, 0, iso("2026-05-15"), cfg, NOW);
+ expect(r.band).toBe("medium");
+ });
+
+ test("applied=20, violated=0, fresh → high (Wilson ≈ 0.84, crosses high_min)", () => {
+ const r = computeConfidence(20, 0, iso("2026-05-15"), cfg, NOW);
expect(r.band).toBe("high");
});
- test("step-function eligibility lost when stale → falls to medium", () => {
- // last evidence ~78 days ago — past high_freshness_factor cutoff
- // but not past stale_evidence_days.
+ test("applied=10, violated=0, stale → low (freshness collapses the value)", () => {
+ // last evidence ~78 days ago — freshness multiplier near zero
+ // but not past stale_evidence_days. Wilson ≈ 0.72 * freshness ≈
+ // 0.13 yields value ≈ 0.10 — squarely in the low band.
const r = computeConfidence(10, 0, iso("2026-02-26"), cfg, NOW);
- expect(r.band).toBe("medium");
+ expect(r.band).toBe("low");
});
- test("numeric band max-lift: legacy=medium + numeric=high → high", () => {
- // Lower high_min so a 9-applied / 0-violated / fresh pref crosses
- // the numeric threshold even though legacy step-function would
- // cap it at medium (needs applied >= 10).
+ test("threshold tuning lifts the band on the same evidence", () => {
+ // The same 9-applied / 0-violated / fresh pref reads as medium
+ // under the default thresholds and high once we lower high_min.
+ const r1 = computeConfidence(9, 0, iso("2026-05-15"), cfg, NOW);
+ expect(r1.band).toBe("medium");
const tunedCfg = {
...cfg,
- confidence: {
- ...cfg.confidence,
- high_min: 0.5,
- medium_min: 0.30,
- },
+ confidence: { ...cfg.confidence, high_min: 0.5, medium_min: 0.30 },
};
- const r = computeConfidence(9, 0, iso("2026-05-15"), tunedCfg, NOW);
- expect(r.band).toBe("high");
- });
-
- test("numeric never demotes a legacy-high band", () => {
- // Legacy step → high; tighten numeric thresholds to demand
- // 0.99. Max-with-legacy keeps band at high.
- const strictCfg = {
- ...cfg,
- confidence: {
- ...cfg.confidence,
- high_min: 0.99,
- medium_min: 0.99,
- },
- };
- const r = computeConfidence(10, 0, iso("2026-05-15"), strictCfg, NOW);
- expect(r.band).toBe("high");
+ const r2 = computeConfidence(9, 0, iso("2026-05-15"), tunedCfg, NOW);
+ expect(r2.band).toBe("high");
});
test("value is in [0, 1]", () => {
diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.ts
index 8eb94ac8..d21eebf3 100644
--- a/tests/core/brain.doctor.test.ts
+++ b/tests/core/brain.doctor.test.ts
@@ -93,17 +93,17 @@ describe("status-vs-folder mismatch", () => {
"kind: brain-preference",
"id: pref-broken",
"created_at: 2026-05-14T10:42:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: 2026-05-28T10:42:00Z",
"tags: [brain, brain/preference]",
"topic: broken",
- "status: retired",
+ "_status: retired",
"principle: Hand-crafted mismatch",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -192,17 +192,17 @@ describe("duplicate id", () => {
"kind: brain-preference",
"id: pref-alpha", // intentional duplicate
"created_at: 2026-05-14T10:00:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: 2026-05-28T10:00:00Z",
"tags: [brain, brain/preference]",
"topic: alpha",
- "status: unconfirmed",
+ "_status: unconfirmed",
"principle: Duplicate id",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -224,17 +224,17 @@ describe("invalid ISO", () => {
"kind: brain-preference",
"id: pref-bad-iso",
"created_at: 2026-05-14T10:42:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: not-a-real-iso",
"tags: [brain, brain/preference]",
"topic: bad-iso",
- "status: unconfirmed",
+ "_status: unconfirmed",
"principle: Hand-crafted",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -293,8 +293,8 @@ describe("schema_version", () => {
"",
"confidence:",
" low_max_applied: 2",
- " high_min_applied: 10",
- " high_freshness_factor: 0.8",
+ " medium_min: 0.40",
+ " high_min: 0.75",
"",
"snapshots:",
" retention_count: 10",
@@ -375,7 +375,7 @@ describe("retired entries", () => {
"---",
"kind: brain-retired",
"id: ret-alpha",
- "status: retired",
+ "_status: retired",
"retired_at: 2026-08-12T05:00:00Z",
"retired_reason: stale-no-evidence",
'retired_by: "[[2026-08-12]]"',
@@ -383,11 +383,11 @@ describe("retired entries", () => {
"tags: [brain, brain/retired]",
"topic: alpha",
"principle: rule",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -737,79 +737,6 @@ describe("broken backlinks", () => {
});
});
-// ── §24 dual-shape lint ─────────────────────────────────────────────────────
-
-describe("frontmatter-double-shape lint (§24)", () => {
- test("flags a preference with both 'status:' and '_status:'", () => {
- const path = preferencePath(tmp, "double-shape");
- const content = [
- "---",
- "kind: brain-preference",
- "id: pref-double-shape",
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- "tags: [brain, brain/preference, brain/topic/double-shape]",
- "topic: double-shape",
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "_status: confirmed",
- "evidenced_by: []",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
-
- const res = runDoctor(tmp);
- const found = res.warnings.find((w) => w.code === "frontmatter-double-shape");
- expect(found).toBeDefined();
- expect(found!.path).toBe(path);
- expect(found!.message).toMatch(/_status.*legacy 'status'/);
- });
-
- test("flags a retired with both 'applied_count:' and '_applied_count:'", () => {
- const path = retiredPath(tmp, "double-shape-ret");
- const content = [
- "---",
- "kind: brain-retired",
- "id: ret-double-shape-ret",
- "created_at: 2026-05-14T10:42:00Z",
- "retired_at: 2026-08-12T05:00:00Z",
- "retired_reason: stale-no-evidence",
- "retired_by: '[[Brain/log/2026-08-12]]'",
- "tags: [brain, brain/retired, brain/topic/double-shape-ret]",
- "topic: double-shape-ret",
- "principle: Some rule",
- "status: retired",
- "pinned: false",
- "applied_count: 3",
- "_applied_count: 3",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
-
- const res = runDoctor(tmp);
- const found = res.warnings.find((w) => w.code === "frontmatter-double-shape");
- expect(found).toBeDefined();
- expect(found!.message).toMatch(/_applied_count.*legacy 'applied_count'/);
- });
-
- test("does NOT flag a file using only the new '_status:' shape", () => {
- writePreference(tmp, {
- slug: "clean-new",
- topic: "clean-new",
- principle: "Some rule",
- created_at: "2026-05-14T10:42:00Z",
- unconfirmed_until: "2026-05-28T10:42:00Z",
- status: "unconfirmed",
- evidenced_by: [],
- });
- const res = runDoctor(tmp);
- expect(res.warnings.filter((w) => w.code === "frontmatter-double-shape")).toHaveLength(0);
- });
-});
-
describe("vault-ignore-missing-path lint (v0.10.9)", () => {
test("warns when vault.ignore_paths contains a path-style entry that does not exist", () => {
atomicWriteFileSync(
diff --git a/tests/core/brain.dream.test.ts b/tests/core/brain.dream.test.ts
index 9076580f..9e0025e1 100644
--- a/tests/core/brain.dream.test.ts
+++ b/tests/core/brain.dream.test.ts
@@ -391,9 +391,8 @@ describe("dream — unconfirmed → confirmed promotion on first applied evidenc
describe("dream — confidence formula at boundaries", () => {
// We exercise the formula indirectly: seed evidence, run dream, read
// pref.confidence. Default config (from policy.ts):
- // low_max_applied: 2, high_min_applied: 10
- // stale_evidence_days: 90, high_freshness_factor: 0.8
- // → "fresh" means last_evidence_at < 72 days ago.
+ // low_max_applied: 2, stale_evidence_days: 90,
+ // medium_min: 0.40, high_min: 0.75.
function setupForConfidence(slug: string, applied: number, violated: number, fresh: boolean): void {
writePreference(vault, {
slug,
@@ -405,8 +404,10 @@ describe("dream — confidence formula at boundaries", () => {
evidenced_by: [],
});
// Generate apply-evidence entries spread over days. The most
- // recent one drives `last_evidence_at`.
- const baseDate = fresh ? "2026-05-01" : "2026-01-01";
+ // recent one drives `last_evidence_at`. "fresh" anchors near
+ // `now` so freshness ≈ 1.0; "stale" puts evidence ~78 days back
+ // so the freshness multiplier collapses confidence_value.
+ const baseDate = fresh ? "2026-05-14" : "2026-01-01";
for (let i = 0; i < applied; i++) {
const d = new Date(`${baseDate}T10:00:0${i % 10}Z`);
appendApplyEvidence(
@@ -448,8 +449,15 @@ describe("dream — confidence formula at boundaries", () => {
expect(p.confidence).toBe("medium");
});
- test("applied=10, violated=0, fresh → high", () => {
- setupForConfidence("c-high", 10, 0, true);
+ test("applied=10, violated=0, fresh → medium (Wilson ≈ 0.72, below high_min)", () => {
+ setupForConfidence("c-medium-10", 10, 0, true);
+ dream(vault, { now: new Date("2026-05-15T00:00:00Z") });
+ const p = parsePreference(preferencePath(vault, "c-medium-10"));
+ expect(p.confidence).toBe("medium");
+ });
+
+ test("applied=20, violated=0, fresh → high (Wilson ≈ 0.84, crosses high_min)", () => {
+ setupForConfidence("c-high", 20, 0, true);
dream(vault, { now: new Date("2026-05-15T00:00:00Z") });
const p = parsePreference(preferencePath(vault, "c-high"));
expect(p.confidence).toBe("high");
@@ -462,14 +470,15 @@ describe("dream — confidence formula at boundaries", () => {
expect(p.confidence).toBe("low");
});
- test("applied=10, violated=0, stale → medium (not high — freshness fails)", () => {
+ test("applied=10, violated=0, stale → low (freshness collapses the numeric value)", () => {
setupForConfidence("c-stale", 10, 0, false);
- // now is well beyond freshness boundary (72 days from 2026-01-01)
- // but BEFORE the stale_evidence_days retire boundary (90 days).
- // 2026-04-01 = 90 days after 2026-01-01, so we use 2026-03-20.
+ // Now is well beyond the freshness boundary but BEFORE the
+ // stale_evidence_days retire boundary (90 days). 2026-03-20 sits
+ // 78 days after the seeded evidence; freshness ≈ 0.13 multiplied
+ // by Wilson ≈ 0.72 yields value ≈ 0.10 — squarely in the low band.
dream(vault, { now: new Date("2026-03-20T00:00:00Z") });
const p = parsePreference(preferencePath(vault, "c-stale"));
- expect(p.confidence).toBe("medium");
+ expect(p.confidence).toBe("low");
});
});
diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.ts
index 1ce26077..c6301c61 100644
--- a/tests/core/brain.init.test.ts
+++ b/tests/core/brain.init.test.ts
@@ -57,15 +57,13 @@ describe("bootstrapBrain — empty vault", () => {
expect(statSync(dir).isDirectory()).toBe(true);
}
- // Files: _brain.yaml, _BRAIN.md, AI Wiki/_OPEN_SECOND_BRAIN.md.
+ // Files: _brain.yaml, _BRAIN.md. (No more AI Wiki/_OPEN_SECOND_BRAIN.md
+ // in v0.11.0; the operating manual lives at Brain/_BRAIN.md only.)
expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);
expect(existsSync(join(vault, "Brain", "_BRAIN.md"))).toBe(true);
- expect(existsSync(join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"))).toBe(
- true,
- );
- // Counts: three created, none overwritten, none skipped.
- expect(result.created.length).toBe(3);
+ // Counts: two created, none overwritten, none skipped.
+ expect(result.created.length).toBe(2);
expect(result.overwritten.length).toBe(0);
expect(result.skipped.length).toBe(0);
@@ -78,20 +76,11 @@ describe("bootstrapBrain — empty vault", () => {
// wrong-template / no-substitution regression cheaply.
const manual = readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8");
expect(manual).toContain("# Brain — operating manual");
-
- // Legacy overview carries the Brain-first heading and mentions the
- // two writable surfaces.
- const overview = readFileSync(
- join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- "utf8",
- );
- expect(overview).toContain("Open Second Brain");
- expect(overview).toContain("Brain/");
});
});
describe("bootstrapBrain — idempotent rerun", () => {
- test("second invocation without force skips Brain/ files and overwrites the legacy overview", () => {
+ test("second invocation without force skips both Brain/ files", () => {
// First run sets the baseline.
bootstrapBrain(vault, { configPath });
@@ -112,19 +101,9 @@ describe("bootstrapBrain — idempotent rerun", () => {
"user manual edits\n",
);
- // Legacy overview is ALWAYS overwritten by design (zero-active-users
- // trade-off; see §12.1 of the design doc and the init.ts comment).
- expect(second.overwritten).toContain(
- join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- );
- const overview = readFileSync(
- join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- "utf8",
- );
- expect(overview).toContain("Open Second Brain");
-
- // Nothing newly created on the second run.
+ // Nothing newly created or overwritten on the second run.
expect(second.created.length).toBe(0);
+ expect(second.overwritten.length).toBe(0);
});
test("directories are recreated idempotently with no error", () => {
@@ -135,25 +114,17 @@ describe("bootstrapBrain — idempotent rerun", () => {
});
describe("bootstrapBrain — force overwrite", () => {
- test("force: true rewrites all three managed files", () => {
+ test("force: true rewrites both managed files", () => {
bootstrapBrain(vault, { configPath });
// Stomp on the canonical content so we can detect the rewrite.
writeFileSync(join(vault, "Brain", "_brain.yaml"), "stale\n", "utf8");
writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n", "utf8");
- writeFileSync(
- join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- "stale\n",
- "utf8",
- );
const result = bootstrapBrain(vault, { configPath, force: true });
expect(result.overwritten).toContain(join("Brain", "_brain.yaml"));
expect(result.overwritten).toContain(join("Brain", "_BRAIN.md"));
- expect(result.overwritten).toContain(
- join("AI Wiki", "_OPEN_SECOND_BRAIN.md"),
- );
expect(result.skipped.length).toBe(0);
expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(
@@ -162,9 +133,6 @@ describe("bootstrapBrain — force overwrite", () => {
expect(
readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8"),
).not.toBe("stale\n");
- expect(
- readFileSync(join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"), "utf8"),
- ).not.toBe("stale\n");
});
});
diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.ts
index 9d2fb1e3..1f541f21 100644
--- a/tests/core/brain.inline-scan.test.ts
+++ b/tests/core/brain.inline-scan.test.ts
@@ -37,7 +37,14 @@ beforeEach(() => {
]) {
mkdirSync(d, { recursive: true });
}
- atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);
+ // v0.11.0: scanInline walks only folders listed under
+ // `notes.read_paths`. All existing tests use Daily/ as the marker
+ // container, so we declare it here once; specific tests that need
+ // a different shape override this file.
+ atomicWriteFileSync(
+ join(dirs.brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n`,
+ );
});
afterEach(() => {
@@ -51,6 +58,74 @@ function writeMd(rel: string, content: string): string {
return path;
}
+describe("scanInline empty notes.read_paths", () => {
+ test("no notes config + no opts.paths -> scanInline does no work", async () => {
+ // Override the beforeEach config to drop notes.read_paths entirely.
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ DEFAULT_BRAIN_CONFIG_YAML,
+ );
+ // Plant a marker in Daily/ — old behaviour would find it.
+ writeMd(
+ "Daily/2026-05-16.md",
+ "@osb feedback negative topic=should-be-skipped principle=p\n",
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.scanned).toBe(0);
+ expect(result.found).toBe(0);
+ expect(result.created).toBe(0);
+ });
+
+ test("opts.paths still overrides absent config (explicit > config)", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ DEFAULT_BRAIN_CONFIG_YAML,
+ );
+ writeMd(
+ "Journal/2026-05-16.md",
+ "@osb feedback negative topic=explicit-override principle=p\n",
+ );
+ const result = await scanInline(tmp, {
+ agent: "test",
+ paths: ["Journal"],
+ });
+ expect(result.found).toBe(1);
+ expect(result.created).toBe(1);
+ });
+
+ test("notes.read_paths with multiple entries walks each root", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n - Journal\n`,
+ );
+ writeMd(
+ "Daily/2026-05-16.md",
+ "@osb feedback negative topic=daily-one principle=p\n",
+ );
+ writeMd(
+ "Journal/2026-05-16.md",
+ "@osb feedback negative topic=journal-one principle=p\n",
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(2);
+ expect(result.created).toBe(2);
+ });
+
+ test("read_path that does not exist on disk is skipped silently", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n - Missing\n`,
+ );
+ writeMd(
+ "Daily/2026-05-16.md",
+ "@osb feedback negative topic=found-here principle=p\n",
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(1);
+ expect(result.errors.length).toBe(0);
+ });
+});
+
describe("scanInline", () => {
test("finds an inline marker in Daily/ and creates a signal in inbox/", async () => {
writeMd(
@@ -142,6 +217,10 @@ describe("scanInline", () => {
});
test("processes a fenced 'osb' block and writes signal + rewrites info-string", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Projects\n`,
+ );
const notePath = writeMd(
"Projects/foo.md",
[
@@ -205,6 +284,10 @@ describe("scanInline", () => {
});
test("skips files larger than 1 MiB", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Big\n`,
+ );
// Build a marker preceded by 1.5 MiB of filler.
const filler = "x".repeat(1_500_000);
writeMd(
@@ -262,6 +345,10 @@ describe("scanInline", () => {
});
test("v0.10.9: hardcoded Brain rule is path-scoped — nested 'Brain' dirs keep being scanned", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - projects\n`,
+ );
// The hard-skip targets `<vault>/Brain` specifically. A project
// directory like `projects/Brain/notes.md` is unrelated to the
// derived layer and must still be discoverable by scan-inline.
@@ -280,7 +367,7 @@ describe("scanInline", () => {
test("v0.10.9: vault.ignore_paths additions are respected", async () => {
atomicWriteFileSync(
join(brainDirs(tmp).brain, "_brain.yaml"),
- `schema_version: 1\nvault:\n ignore_paths:\n - Drafts\n`,
+ `schema_version: 1\nvault:\n ignore_paths:\n - Drafts\nnotes:\n read_paths:\n - Drafts\n - Daily\n`,
);
writeMd(
"Drafts/x.md",
diff --git a/tests/core/brain.migrate-frontmatter.test.ts b/tests/core/brain.migrate-frontmatter.test.ts
deleted file mode 100644
index 047030cd..00000000
--- a/tests/core/brain.migrate-frontmatter.test.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-/**
- * Tests for `migrate-frontmatter` — the opt-in helper that rewrites
- * legacy-shape Group C frontmatter keys (`status:`, `applied_count:`,
- * ...) to the `_`-prefixed form (§24) across `Brain/preferences/`
- * and `Brain/retired/`.
- */
-
-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 {
- brainDirs,
- preferencePath,
- retiredPath,
-} from "../../src/core/brain/paths.ts";
-import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
-import {
- applyMigration,
- MigrationError,
- planMigration,
-} from "../../src/core/brain/migrate-frontmatter.ts";
-import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
-import { listSnapshots } from "../../src/core/brain/snapshot.ts";
-
-let tmp: string;
-
-beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), "o2b-brain-migrate-"));
- const dirs = brainDirs(tmp);
- for (const d of [
- dirs.brain,
- dirs.inbox,
- dirs.processed,
- dirs.preferences,
- dirs.retired,
- dirs.log,
- dirs.snapshots,
- ]) {
- mkdirSync(d, { recursive: true });
- }
- // Required for createSnapshot's config-load step
- atomicWriteFileSync(
- join(dirs.brain, "_brain.yaml"),
- DEFAULT_BRAIN_CONFIG_YAML,
- );
-});
-
-afterEach(() => {
- rmSync(tmp, { recursive: true, force: true });
-});
-
-function writeLegacyPref(slug: string): string {
- const path = preferencePath(tmp, slug);
- const content = [
- "---",
- "kind: brain-preference",
- `id: pref-${slug}`,
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- `tags: [brain, brain/preference, brain/topic/${slug}]`,
- `topic: ${slug}`,
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "confirmed_at: 2026-05-15T10:00:00Z",
- "evidenced_by: []",
- "applied_count: 1",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
- return path;
-}
-
-function writeNewPref(slug: string): string {
- const path = preferencePath(tmp, slug);
- const content = [
- "---",
- "kind: brain-preference",
- `id: pref-${slug}`,
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- `tags: [brain, brain/preference, brain/topic/${slug}]`,
- `topic: ${slug}`,
- "principle: Some rule",
- "pinned: false",
- "_status: confirmed",
- "_confirmed_at: 2026-05-15T10:00:00Z",
- "_evidenced_by: []",
- "_applied_count: 1",
- "_violated_count: 0",
- "_last_evidence_at: null",
- "_confidence: low",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
- return path;
-}
-
-function writeCollisionPref(slug: string): string {
- const path = preferencePath(tmp, slug);
- const content = [
- "---",
- "kind: brain-preference",
- `id: pref-${slug}`,
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- `tags: [brain, brain/preference, brain/topic/${slug}]`,
- `topic: ${slug}`,
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "_status: confirmed",
- "evidenced_by: []",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
- return path;
-}
-
-function writeLegacyRetired(slug: string): string {
- const path = retiredPath(tmp, slug);
- const content = [
- "---",
- "kind: brain-retired",
- `id: ret-${slug}`,
- "created_at: 2026-05-14T10:42:00Z",
- "retired_at: 2026-08-12T05:00:00Z",
- "retired_reason: stale-no-evidence",
- "retired_by: '[[Brain/log/2026-08-12]]'",
- `tags: [brain, brain/retired, brain/topic/${slug}]`,
- `topic: ${slug}`,
- "principle: Some rule",
- "status: retired",
- "pinned: false",
- "evidenced_by: []",
- "applied_count: 4",
- "violated_count: 1",
- "last_evidence_at: 2026-05-20T10:00:00Z",
- "confidence: medium",
- "---",
- "",
- ].join("\n");
- writeFileSync(path, content, "utf8");
- return path;
-}
-
-describe("planMigration", () => {
- test("counts legacy / new / collision files", () => {
- writeLegacyPref("legacy-a");
- writeNewPref("new-a");
- writeCollisionPref("collision-a");
- writeLegacyRetired("legacy-r");
-
- const plan = planMigration(tmp);
-
- expect(plan.files_scanned).toBe(4);
- expect(plan.files_to_migrate.length).toBe(2); // legacy pref + legacy retired
- expect(plan.files_already_new.length).toBe(1);
- expect(plan.collisions.length).toBe(1);
- expect(plan.collisions[0]!.field).toBe("status");
- });
-
- test("returns zero counts on an empty vault", () => {
- const plan = planMigration(tmp);
- expect(plan.files_scanned).toBe(0);
- expect(plan.files_to_migrate.length).toBe(0);
- expect(plan.files_already_new.length).toBe(0);
- expect(plan.collisions.length).toBe(0);
- });
-});
-
-describe("applyMigration", () => {
- test("rewrites legacy keys to _-prefixed", async () => {
- const path = writeLegacyPref("alpha");
- const result = await applyMigration(tmp, {
- snapshot: false,
- now: new Date("2026-05-16T10:15:22Z"),
- });
-
- expect(result.files_migrated.length).toBe(1);
-
- const raw = readFileSync(path, "utf8");
- expect(raw).toMatch(/^_status: confirmed$/m);
- expect(raw).toMatch(/^_applied_count: 1$/m);
- expect(raw).toMatch(/^_confidence: low$/m);
- expect(raw).not.toMatch(/^status: /m);
- expect(raw).not.toMatch(/^applied_count: /m);
- });
-
- test("preserves identity fields and body", async () => {
- const path = writeLegacyPref("beta");
- const original = readFileSync(path, "utf8");
- expect(original).toMatch(/^principle: Some rule$/m);
-
- await applyMigration(tmp, { snapshot: false, now: new Date() });
- const after = readFileSync(path, "utf8");
- expect(after).toMatch(/^principle: Some rule$/m);
- expect(after).toMatch(/^topic: beta$/m);
- expect(after).toMatch(/^kind: brain-preference$/m);
- expect(after).toMatch(/^id: pref-beta$/m);
- });
-
- test("is idempotent (second run is a no-op)", async () => {
- writeLegacyPref("gamma");
- const first = await applyMigration(tmp, { snapshot: false, now: new Date() });
- const second = await applyMigration(tmp, { snapshot: false, now: new Date() });
- expect(first.files_migrated.length).toBe(1);
- expect(second.files_migrated.length).toBe(0);
- });
-
- test("takes a snapshot when snapshot: true", async () => {
- writeLegacyPref("delta");
- const result = await applyMigration(tmp, {
- snapshot: true,
- now: new Date("2026-05-16T10:15:22Z"),
- });
- expect(result.snapshot_path).toBeTruthy();
- expect(existsSync(result.snapshot_path!)).toBe(true);
- const snaps = listSnapshots(tmp);
- expect(snaps.length).toBe(1);
- expect(snaps[0]!.run_id).toMatch(/^migrate-/);
- });
-
- test("aborts with MigrationError when a collision file is present", async () => {
- writeLegacyPref("ok");
- writeCollisionPref("bad");
- await expect(
- applyMigration(tmp, { snapshot: false, now: new Date() }),
- ).rejects.toThrow(MigrationError);
- });
-
- test("collision check runs BEFORE any rewrite (atomic-ish abort)", async () => {
- const okPath = writeLegacyPref("ok");
- writeCollisionPref("bad");
- const before = readFileSync(okPath, "utf8");
- try {
- await applyMigration(tmp, { snapshot: false, now: new Date() });
- } catch {
- /* expected */
- }
- const after = readFileSync(okPath, "utf8");
- expect(after).toBe(before);
- });
-
- test("processes retired/ as well as preferences/", async () => {
- const retPath = writeLegacyRetired("epsilon");
- await applyMigration(tmp, { snapshot: false, now: new Date() });
- const raw = readFileSync(retPath, "utf8");
- expect(raw).toMatch(/^_applied_count: 4$/m);
- expect(raw).not.toMatch(/^applied_count: /m);
- // `status: retired` is identity on retired files, must stay unprefixed.
- expect(raw).toMatch(/^status: retired$/m);
- });
-});
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index 625a11b2..6b4a19a0 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -43,8 +43,8 @@ describe("DEFAULT_BRAIN_CONFIG", () => {
expect(DEFAULT_BRAIN_CONFIG.dream.contradiction_window_days).toBe(14);
expect(DEFAULT_BRAIN_CONFIG.retire.stale_evidence_days).toBe(90);
expect(DEFAULT_BRAIN_CONFIG.confidence.low_max_applied).toBe(2);
- expect(DEFAULT_BRAIN_CONFIG.confidence.high_min_applied).toBe(10);
- expect(DEFAULT_BRAIN_CONFIG.confidence.high_freshness_factor).toBe(0.8);
+ expect(DEFAULT_BRAIN_CONFIG.confidence.medium_min).toBe(0.40);
+ expect(DEFAULT_BRAIN_CONFIG.confidence.high_min).toBe(0.75);
expect(DEFAULT_BRAIN_CONFIG.snapshots.retention_count).toBe(10);
});
@@ -79,7 +79,7 @@ describe("validateBrainConfig — happy path", () => {
const config = validateBrainConfig({ schema_version: 1 }, "<test>");
expect(config.dream.candidate_threshold).toBe(3);
expect(config.retire.stale_evidence_days).toBe(90);
- expect(config.confidence.high_freshness_factor).toBe(0.8);
+ expect(config.confidence.medium_min).toBe(0.40);
expect(config.snapshots.retention_count).toBe(10);
});
@@ -234,38 +234,6 @@ describe("validateBrainConfig — error cases", () => {
).toThrow(/positive integer/);
});
- test("high_freshness_factor <= 0 → error", () => {
- expect(() =>
- validateBrainConfig(
- { schema_version: 1, confidence: { high_freshness_factor: 0 } },
- "<test>",
- ),
- ).toThrow(/\(0, 1\]/);
- expect(() =>
- validateBrainConfig(
- { schema_version: 1, confidence: { high_freshness_factor: -0.1 } },
- "<test>",
- ),
- ).toThrow(/\(0, 1\]/);
- });
-
- test("high_freshness_factor > 1 → error", () => {
- expect(() =>
- validateBrainConfig(
- { schema_version: 1, confidence: { high_freshness_factor: 1.5 } },
- "<test>",
- ),
- ).toThrow(/\(0, 1\]/);
- });
-
- test("high_freshness_factor == 1 is accepted (inclusive upper bound)", () => {
- const cfg = validateBrainConfig(
- { schema_version: 1, confidence: { high_freshness_factor: 1 } },
- "<test>",
- );
- expect(cfg.confidence.high_freshness_factor).toBe(1);
- });
-
test("snapshots.retention_count must be positive integer", () => {
expect(() =>
validateBrainConfig(
@@ -537,11 +505,11 @@ describe("parseBrainYaml", () => {
test("parses inline scalar arrays", () => {
const parsed = parseBrainYaml(
- `schema_version: 1\nvault:\n ignore_paths: [Drafts, "AI Wiki/cache"]\n`,
+ `schema_version: 1\nvault:\n ignore_paths: [Drafts, "Drafts/cache"]\n`,
);
expect((parsed["vault"] as { ignore_paths: unknown }).ignore_paths).toEqual([
"Drafts",
- "AI Wiki/cache",
+ "Drafts/cache",
]);
});
diff --git a/tests/core/brain.preference.test.ts b/tests/core/brain.preference.test.ts
index 3567d576..0ed9a581 100644
--- a/tests/core/brain.preference.test.ts
+++ b/tests/core/brain.preference.test.ts
@@ -115,17 +115,17 @@ describe("writePreference + parsePreference", () => {
"kind: brain-preference",
"id: pref-no-pin-field",
"created_at: 2026-05-14T10:42:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: 2026-05-28T10:42:00Z",
"tags: [brain, brain/preference, brain/topic/no-pin-field]",
"topic: no-pin-field",
- "status: unconfirmed",
+ "_status: unconfirmed",
"principle: Some rule",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"---",
"",
"## Principle",
@@ -236,17 +236,17 @@ describe("status-vs-folder mismatch", () => {
"kind: brain-preference",
"id: pref-broken",
"created_at: 2026-05-14T10:42:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: 2026-05-28T10:42:00Z",
"tags: [brain, brain/preference]",
"topic: broken",
- "status: retired",
+ "_status: retired",
"principle: Hand-crafted mismatch",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -282,7 +282,7 @@ describe("status-vs-folder mismatch", () => {
"created_at: 2026-05-14T10:42:00Z",
"tags: [brain, brain/preference]",
"topic: broken",
- "status: retired",
+ "_status: retired",
"principle: Hand-crafted mismatch",
"---",
"",
@@ -306,17 +306,17 @@ describe("status enum validation", () => {
"kind: brain-preference",
"id: pref-invalid-status",
"created_at: 2026-05-14T10:42:00Z",
- "confirmed_at: null",
+ "_confirmed_at: null",
"unconfirmed_until: 2026-05-28T10:42:00Z",
"tags: [brain, brain/preference]",
"topic: invalid-status",
- "status: hilarious",
+ "_status: hilarious",
"principle: Hand-crafted invalid status",
- "evidenced_by: []",
- "applied_count: 0",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ "_last_evidence_at: null",
+ "_confidence: low",
"pinned: false",
"---",
"",
@@ -380,31 +380,12 @@ const RET_BASE_FM = (slug: string): string[] => [
`tags: [brain, brain/retired, brain/topic/${slug}]`,
`topic: ${slug}`,
"principle: Some rule",
- "status: retired",
+ "_status: retired",
"pinned: false",
];
-describe("parsePreference accepts both legacy and _-prefixed shapes (§24)", () => {
- test("reads legacy 'status:' form", () => {
- const path = writeRawPref(tmp, "legacy-status", [
- ...PREF_BASE_FM("legacy-status"),
- "status: confirmed",
- "confirmed_at: 2026-05-15T10:00:00Z",
- "evidenced_by: []",
- "applied_count: 1",
- "violated_count: 0",
- "last_evidence_at: 2026-05-20T10:00:00Z",
- "confidence: low",
- ]);
- const parsed = parsePreference(path);
- expect(parsed.status).toBe("confirmed");
- expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");
- expect(parsed.applied_count).toBe(1);
- expect(parsed.confidence).toBe("low");
- expect(parsed.last_evidence_at).toBe("2026-05-20T10:00:00Z");
- });
-
- test("reads new '_status:' form", () => {
+describe("parsePreference Group C frontmatter (§24)", () => {
+ test("reads '_status:' and other '_'-prefixed Group C fields", () => {
const path = writeRawPref(tmp, "new-status", [
...PREF_BASE_FM("new-status"),
"_status: confirmed",
@@ -422,64 +403,10 @@ describe("parsePreference accepts both legacy and _-prefixed shapes (§24)", ()
expect(parsed.confidence).toBe("low");
expect(parsed.last_evidence_at).toBe("2026-05-20T10:00:00Z");
});
-
- test("throws when both 'status' and '_status' are present", () => {
- const path = writeRawPref(tmp, "collision", [
- ...PREF_BASE_FM("collision"),
- "status: confirmed",
- "_status: confirmed",
- "evidenced_by: []",
- ]);
- expect(() => parsePreference(path)).toThrow(
- /both '_status' and legacy 'status' present/,
- );
- });
-
- test("throws when both 'applied_count' and '_applied_count' are present", () => {
- const path = writeRawPref(tmp, "applied-collision", [
- ...PREF_BASE_FM("applied-collision"),
- "_status: confirmed",
- "applied_count: 3",
- "_applied_count: 3",
- "evidenced_by: []",
- ]);
- expect(() => parsePreference(path)).toThrow(
- /both '_applied_count' and legacy 'applied_count' present/,
- );
- });
-
- test("reads mixed (some legacy, some new) shape without collision", () => {
- const path = writeRawPref(tmp, "mixed", [
- ...PREF_BASE_FM("mixed"),
- "_status: confirmed", // new form
- "confirmed_at: 2026-05-15T10:00:00Z", // legacy form
- "evidenced_by: []", // legacy form
- "_applied_count: 2", // new form
- ]);
- const parsed = parsePreference(path);
- expect(parsed.status).toBe("confirmed");
- expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");
- expect(parsed.applied_count).toBe(2);
- });
});
-describe("parseRetired accepts both legacy and _-prefixed shapes (§24)", () => {
- test("reads legacy form", () => {
- const path = writeRawRetired(tmp, "legacy-ret", [
- ...RET_BASE_FM("legacy-ret"),
- "evidenced_by: ['[[sig-x]]']",
- "applied_count: 5",
- "violated_count: 1",
- "last_evidence_at: 2026-05-20T10:00:00Z",
- "confidence: medium",
- ]);
- const parsed = parseRetired(path);
- expect(parsed.applied_count).toBe(5);
- expect(parsed.confidence).toBe("medium");
- expect(parsed.evidenced_by).toEqual(["[[sig-x]]"]);
- });
-
- test("reads new '_'-prefixed form", () => {
+describe("parseRetired Group C frontmatter (§24)", () => {
+ test("reads '_'-prefixed Group C fields", () => {
const path = writeRawRetired(tmp, "new-ret", [
...RET_BASE_FM("new-ret"),
"_evidenced_by: ['[[sig-x]]']",
@@ -493,17 +420,6 @@ describe("parseRetired accepts both legacy and _-prefixed shapes (§24)", () =>
expect(parsed.confidence).toBe("medium");
expect(parsed.evidenced_by).toEqual(["[[sig-x]]"]);
});
-
- test("throws on legacy+new collision", () => {
- const path = writeRawRetired(tmp, "ret-collision", [
- ...RET_BASE_FM("ret-collision"),
- "applied_count: 3",
- "_applied_count: 3",
- ]);
- expect(() => parseRetired(path)).toThrow(
- /both '_applied_count' and legacy 'applied_count' present/,
- );
- });
});
describe("writePreference emits _-prefixed Group C fields (§24)", () => {
@@ -592,6 +508,6 @@ describe("moveToRetired carries _-prefixed shape forward (§24)", () => {
expect(raw).toMatch(/^_applied_count: 3$/m);
expect(raw).not.toMatch(/^applied_count: /m);
// 'status:' on the retired file is identity (always 'retired'), not derived.
- expect(raw).toMatch(/^status: retired$/m);
+ expect(raw).toMatch(/^_status: retired$/m);
});
});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 6a1538ae..782a6fd4 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -70,10 +70,9 @@ describe("BRAIN_* const enums", () => {
"pin",
"unpin",
"rollback",
- // capture extensions + frontmatter migration
+ // capture extensions
"scan-inline",
"import-session",
- "migrate-frontmatter",
// §12 merge (v0.10.5)
"merge",
// §22 upgrade (v0.10.6)
@@ -192,8 +191,6 @@ describe("interface shape smoke (compile-time)", () => {
retire: { stale_evidence_days: 90 },
confidence: {
low_max_applied: 2,
- high_min_applied: 10,
- high_freshness_factor: 0.8,
medium_min: 0.40,
high_min: 0.75,
},
diff --git a/tests/core/brain/backlinks-anchor-alias.test.ts b/tests/core/brain/backlinks-anchor-alias.test.ts
index b9482fe0..effdbd98 100644
--- a/tests/core/brain/backlinks-anchor-alias.test.ts
+++ b/tests/core/brain/backlinks-anchor-alias.test.ts
@@ -86,7 +86,7 @@ describe("buildBacklinkIndex - anchor / block populated from body wikilinks", ()
"---",
"kind: preference",
"topic: foo",
- "status: confirmed",
+ "_status: confirmed",
"principle: example",
"---",
"",
@@ -107,7 +107,7 @@ describe("buildBacklinkIndex - anchor / block populated from body wikilinks", ()
"---",
"kind: preference",
"topic: foo",
- "status: confirmed",
+ "_status: confirmed",
"principle: example",
"---",
"",
@@ -128,7 +128,7 @@ describe("buildBacklinkIndex - anchor / block populated from body wikilinks", ()
"---",
"kind: preference",
"topic: foo",
- "status: confirmed",
+ "_status: confirmed",
"principle: example",
"---",
"",
@@ -151,7 +151,7 @@ describe("buildBacklinkIndex - alias resolution", () => {
"---",
"kind: preference",
"topic: second-order",
- "status: confirmed",
+ "_status: confirmed",
"principle: thinking ahead",
"aliases: [downstream]",
"---",
@@ -165,7 +165,7 @@ describe("buildBacklinkIndex - alias resolution", () => {
"---",
"kind: preference",
"topic: linker",
- "status: confirmed",
+ "_status: confirmed",
"principle: example",
"---",
"",
@@ -186,7 +186,7 @@ describe("buildBacklinkIndex - alias resolution", () => {
"---",
"kind: preference",
"topic: c",
- "status: confirmed",
+ "_status: confirmed",
"principle: x",
"aliases: [other-name]",
"---",
@@ -198,7 +198,7 @@ describe("buildBacklinkIndex - alias resolution", () => {
"---",
"kind: preference",
"topic: l",
- "status: confirmed",
+ "_status: confirmed",
"principle: y",
"---",
"",
@@ -222,7 +222,7 @@ describe("buildBacklinkIndex - alias resolution", () => {
"---",
"kind: preference",
"topic: a",
- "status: confirmed",
+ "_status: confirmed",
"principle: x",
"---",
"",
diff --git a/tests/core/brain/digest-actions.test.ts b/tests/core/brain/digest-actions.test.ts
index 7aaa3de5..a63ebda3 100644
--- a/tests/core/brain/digest-actions.test.ts
+++ b/tests/core/brain/digest-actions.test.ts
@@ -19,6 +19,19 @@ import { renderDigest } from "../../../src/core/brain/digest.ts";
let vault: string;
+const DERIVED_KEYS = new Set([
+ "status",
+ "applied_count",
+ "violated_count",
+ "last_evidence_at",
+ "confidence",
+ "confidence_value",
+ "evidenced_by",
+ "contradicted_by",
+ "lifecycle",
+ "confirmed_at",
+]);
+
function writePref(slug: string, fields: Record<string, string>) {
const lines = [
"---",
@@ -26,7 +39,10 @@ function writePref(slug: string, fields: Record<string, string>) {
`id: pref-${slug}`,
"tags: [brain, brain/preference]",
];
- for (const [k, v] of Object.entries(fields)) lines.push(`${k}: ${v}`);
+ for (const [k, v] of Object.entries(fields)) {
+ const key = DERIVED_KEYS.has(k) ? `_${k}` : k;
+ lines.push(`${key}: ${v}`);
+ }
lines.push("---", "");
writeFileSync(
join(vault, "Brain", "preferences", `pref-${slug}.md`),
diff --git a/tests/core/brain/digest-most-applied.test.ts b/tests/core/brain/digest-most-applied.test.ts
index 74936819..6826ad84 100644
--- a/tests/core/brain/digest-most-applied.test.ts
+++ b/tests/core/brain/digest-most-applied.test.ts
@@ -31,18 +31,18 @@ beforeEach(() => {
kind: brain-preference
id: pref-a
created_at: 2026-04-01T00:00:00Z
-confirmed_at: 2026-04-05T00:00:00Z
+_confirmed_at: 2026-04-05T00:00:00Z
unconfirmed_until: 2026-04-08T00:00:00Z
tags: []
topic: a
-status: confirmed
+_status: confirmed
principle: principle a
-evidenced_by: []
-applied_count: 0
-violated_count: 0
-last_evidence_at: null
-confidence: medium
-confidence_value: 0.5
+_evidenced_by: []
+_applied_count: 0
+_violated_count: 0
+_last_evidence_at: null
+_confidence: medium
+_confidence_value: 0.5
pinned: false
---
body
diff --git a/tests/core/brain/link-graph/concept-cluster.test.ts b/tests/core/brain/link-graph/concept-cluster.test.ts
index 82ac5cb0..2d6e26c3 100644
--- a/tests/core/brain/link-graph/concept-cluster.test.ts
+++ b/tests/core/brain/link-graph/concept-cluster.test.ts
@@ -23,9 +23,25 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
let vault: string;
+const DERIVED_KEYS = new Set([
+ "status",
+ "applied_count",
+ "violated_count",
+ "last_evidence_at",
+ "confidence",
+ "confidence_value",
+ "evidenced_by",
+ "contradicted_by",
+ "lifecycle",
+ "confirmed_at",
+]);
+
function writePref(slug: string, fm: Record<string, string>, body = ""): void {
const lines = ["---"];
- for (const [k, v] of Object.entries(fm)) lines.push(`${k}: ${v}`);
+ for (const [k, v] of Object.entries(fm)) {
+ const key = DERIVED_KEYS.has(k) ? `_${k}` : k;
+ lines.push(`${key}: ${v}`);
+ }
lines.push("---", "", body);
writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
}
diff --git a/tests/core/brain/link-graph/moc-audit.test.ts b/tests/core/brain/link-graph/moc-audit.test.ts
index 59a68ee2..de269949 100644
--- a/tests/core/brain/link-graph/moc-audit.test.ts
+++ b/tests/core/brain/link-graph/moc-audit.test.ts
@@ -23,9 +23,25 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
let vault: string;
+const DERIVED_KEYS = new Set([
+ "status",
+ "applied_count",
+ "violated_count",
+ "last_evidence_at",
+ "confidence",
+ "confidence_value",
+ "evidenced_by",
+ "contradicted_by",
+ "lifecycle",
+ "confirmed_at",
+]);
+
function writePref(slug: string, fm: Record<string, string>, body = ""): void {
const lines = ["---"];
- for (const [k, v] of Object.entries(fm)) lines.push(`${k}: ${v}`);
+ for (const [k, v] of Object.entries(fm)) {
+ const key = DERIVED_KEYS.has(k) ? `_${k}` : k;
+ lines.push(`${key}: ${v}`);
+ }
lines.push("---", "", body);
writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
}
diff --git a/tests/core/brain/notes-config.test.ts b/tests/core/brain/notes-config.test.ts
new file mode 100644
index 00000000..6fd4cdbd
--- /dev/null
+++ b/tests/core/brain/notes-config.test.ts
@@ -0,0 +1,144 @@
+/**
+ * Task 1: `notes:` config block + atom types.
+ *
+ * Asserts the optional `notes:` block on `_brain.yaml`:
+ * - `BRAIN_NOTES_DEFAULTS` exposes an empty `read_paths` slot.
+ * - `resolveNotes(cfg)` returns a fully-populated struct.
+ * - The validator rejects non-arrays, non-strings, empty strings,
+ * absolute paths, and `..` traversal.
+ * - Unknown sub-keys emit a forward-compat warning, not an error.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ BrainConfigError,
+ BRAIN_NOTES_DEFAULTS,
+ parseBrainYaml,
+ resolveNotes,
+ validateBrainConfigDetailed,
+} from "../../../src/core/brain/policy.ts";
+
+function validate(yaml: string) {
+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");
+}
+
+const HEAD = `schema_version: 1\n`;
+
+describe("BRAIN_NOTES_DEFAULTS", () => {
+ test("starts with an empty read_paths array", () => {
+ expect(BRAIN_NOTES_DEFAULTS.read_paths).toEqual([]);
+ });
+
+ test("is frozen and the array is frozen", () => {
+ expect(Object.isFrozen(BRAIN_NOTES_DEFAULTS)).toBe(true);
+ expect(Object.isFrozen(BRAIN_NOTES_DEFAULTS.read_paths)).toBe(true);
+ });
+});
+
+describe("notes config block", () => {
+ test("absent block - cfg.notes undefined; resolveNotes returns defaults", () => {
+ const { config } = validate(HEAD);
+ expect(config.notes).toBeUndefined();
+ expect(resolveNotes(config)).toEqual(BRAIN_NOTES_DEFAULTS);
+ });
+
+ test("present with a single read_path", () => {
+ const { config } = validate(
+ HEAD + `notes:\n read_paths:\n - Daily\n`,
+ );
+ expect(config.notes).toEqual({ read_paths: ["Daily"] });
+ expect(resolveNotes(config).read_paths).toEqual(["Daily"]);
+ });
+
+ test("present with multiple read_paths preserves order", () => {
+ const { config } = validate(
+ HEAD +
+ `notes:\n` +
+ ` read_paths:\n` +
+ ` - Daily\n` +
+ ` - Journal/Weekly\n` +
+ ` - Notes\n`,
+ );
+ expect(resolveNotes(config).read_paths).toEqual([
+ "Daily",
+ "Journal/Weekly",
+ "Notes",
+ ]);
+ });
+
+ test("explicit empty array preserves the empty-list intent", () => {
+ const { config } = validate(HEAD + `notes:\n read_paths: []\n`);
+ expect(config.notes).toEqual({ read_paths: [] });
+ expect(resolveNotes(config).read_paths).toEqual([]);
+ });
+
+ test("rejects non-mapping notes", () => {
+ expect(() => validate(HEAD + `notes: Daily\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("rejects non-array read_paths", () => {
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths: Daily\n`),
+ ).toThrow(BrainConfigError);
+ });
+
+ test("rejects non-string entries", () => {
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - 42\n`),
+ ).toThrow(BrainConfigError);
+ });
+
+ test("rejects empty / whitespace-only string entries", () => {
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - ""\n`),
+ ).toThrow(BrainConfigError);
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - " "\n`),
+ ).toThrow(BrainConfigError);
+ });
+
+ test("rejects absolute paths", () => {
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - /etc/daily\n`),
+ ).toThrow(BrainConfigError);
+ });
+
+ test("rejects parent-traversal", () => {
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - ../escape\n`),
+ ).toThrow(BrainConfigError);
+ expect(() =>
+ validate(HEAD + `notes:\n read_paths:\n - Daily/../etc\n`),
+ ).toThrow(BrainConfigError);
+ });
+
+ test("trims surrounding whitespace on each entry", () => {
+ const { config } = validate(
+ HEAD + `notes:\n read_paths:\n - " Daily "\n`,
+ );
+ expect(resolveNotes(config).read_paths).toEqual(["Daily"]);
+ });
+
+ test("unknown sub-keys emit a forward-compat warning, not an error", () => {
+ const { config, warnings } = validate(
+ HEAD +
+ `notes:\n` +
+ ` read_paths:\n - Daily\n` +
+ ` future_field: hello\n`,
+ );
+ expect(config.notes).toEqual({ read_paths: ["Daily"] });
+ expect(
+ warnings.some((w) => w.message.includes("notes.future_field")),
+ ).toBe(true);
+ });
+
+ test("resolveNotes returns frozen output", () => {
+ const { config } = validate(HEAD);
+ const resolved = resolveNotes(config);
+ expect(Object.isFrozen(resolved)).toBe(true);
+ expect(Object.isFrozen(resolved.read_paths)).toBe(true);
+ });
+});
diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.ts
index 4f137b83..4b30aae2 100644
--- a/tests/core/brain/starter.test.ts
+++ b/tests/core/brain/starter.test.ts
@@ -138,8 +138,8 @@ describe("bootstrapBrain --starter", () => {
configPath: config,
starter: true,
});
- // 3 baseline file entries (_brain.yaml, _BRAIN.md, AI Wiki overview)
- // plus 18 from the starter bundle.
+ // 2 baseline file entries (_brain.yaml, _BRAIN.md) plus 18 from
+ // the starter bundle.
const starterEntries = r.created.filter((p) =>
p.startsWith("Brain/preferences/")
|| p.startsWith("Brain/retired/")
diff --git a/tests/core/brain/temporal/stale-watch.test.ts b/tests/core/brain/temporal/stale-watch.test.ts
index 5e93230b..776c626d 100644
--- a/tests/core/brain/temporal/stale-watch.test.ts
+++ b/tests/core/brain/temporal/stale-watch.test.ts
@@ -52,11 +52,11 @@ describe("findStaleEntries", () => {
test("preference stale when last_evidence_at older than stale_pref_days", () => {
writeFileSync(
join(VAULT, "Brain", "preferences", "pref-fresh.md"),
- `---\nid: pref-fresh\nkind: brain-preference\nstatus: confirmed\ncreated_at: 2026-04-01T00:00:00Z\nunconfirmed_until: 2026-04-14T00:00:00Z\ntags: ["brain"]\ntopic: fresh\nprinciple: Fresh\nevidenced_by: []\nconfidence: medium\nlast_evidence_at: 2026-05-20T00:00:00Z\n---\n`,
+ `---\nid: pref-fresh\nkind: brain-preference\n_status: confirmed\ncreated_at: 2026-04-01T00:00:00Z\nunconfirmed_until: 2026-04-14T00:00:00Z\ntags: ["brain"]\ntopic: fresh\nprinciple: Fresh\n_evidenced_by: []\n_confidence: medium\n_last_evidence_at: 2026-05-20T00:00:00Z\n---\n`,
);
writeFileSync(
join(VAULT, "Brain", "preferences", "pref-stale.md"),
- `---\nid: pref-stale\nkind: brain-preference\nstatus: confirmed\ncreated_at: 2025-12-01T00:00:00Z\nunconfirmed_until: 2025-12-14T00:00:00Z\ntags: ["brain"]\ntopic: stale\nprinciple: Stale\nevidenced_by: []\nconfidence: medium\nlast_evidence_at: 2026-01-01T00:00:00Z\n---\n`,
+ `---\nid: pref-stale\nkind: brain-preference\n_status: confirmed\ncreated_at: 2025-12-01T00:00:00Z\nunconfirmed_until: 2025-12-14T00:00:00Z\ntags: ["brain"]\ntopic: stale\nprinciple: Stale\n_evidenced_by: []\n_confidence: medium\n_last_evidence_at: 2026-01-01T00:00:00Z\n---\n`,
);
const idx = buildTimelineIndex(VAULT, {});
const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {
@@ -70,7 +70,7 @@ describe("findStaleEntries", () => {
test("preference without last_evidence_at uses created_at as staleness anchor", () => {
writeFileSync(
join(VAULT, "Brain", "preferences", "pref-old.md"),
- `---\nid: pref-old\nkind: brain-preference\nstatus: unconfirmed\ncreated_at: 2025-10-01T00:00:00Z\nunconfirmed_until: 2025-10-14T00:00:00Z\ntags: ["brain"]\ntopic: old\nprinciple: Old\nevidenced_by: []\nconfidence: low\nlast_evidence_at: null\n---\n`,
+ `---\nid: pref-old\nkind: brain-preference\n_status: unconfirmed\ncreated_at: 2025-10-01T00:00:00Z\nunconfirmed_until: 2025-10-14T00:00:00Z\ntags: ["brain"]\ntopic: old\nprinciple: Old\n_evidenced_by: []\n_confidence: low\n_last_evidence_at: null\n---\n`,
);
const idx = buildTimelineIndex(VAULT, {});
const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {
diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.ts
index 0c0c9b34..a1966888 100644
--- a/tests/core/brain/upgrade.test.ts
+++ b/tests/core/brain/upgrade.test.ts
@@ -27,7 +27,6 @@ import {
} from "../../../src/core/brain/upgrade.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { brainConfigPath, brainManualPath } from "../../../src/core/brain/paths.ts";
-import { LEGACY_OVERVIEW_REL_PATH } from "../../../src/core/brain/templates.ts";
import { listSnapshots } from "../../../src/core/brain/snapshot.ts";
let vault: string;
@@ -61,8 +60,6 @@ retire:
confidence:
low_max_applied: 2
- high_min_applied: 10
- high_freshness_factor: 0.8
medium_min: 0.40
high_min: 0.75
@@ -111,8 +108,6 @@ retire:
confidence:
low_max_applied: 2
- high_min_applied: 10
- high_freshness_factor: 0.8
medium_min: 0.40
snapshots:
@@ -142,8 +137,6 @@ retire:
confidence:
low_max_applied: 2
- high_min_applied: 10
- high_freshness_factor: 0.8
medium_min: 0.40
high_min: 0.75
@@ -167,12 +160,11 @@ describe("planUpgrade", () => {
}
});
- test("file ordering is _brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md", () => {
+ test("file ordering is _brain.yaml, _BRAIN.md", () => {
const plan = planUpgrade(vault);
expect(plan.files.map((f) => f.path)).toEqual([
"Brain/_brain.yaml",
"Brain/_BRAIN.md",
- LEGACY_OVERVIEW_REL_PATH,
]);
});
@@ -224,15 +216,6 @@ describe("planUpgrade", () => {
expect(manualPlan.after).toContain("Brain");
});
- test("missing _OPEN_SECOND_BRAIN.md → status update with empty before", () => {
- const overviewPath = join(vault, LEGACY_OVERVIEW_REL_PATH);
- rmSync(overviewPath, { force: true });
- const plan = planUpgrade(vault);
- const ovPlan = plan.files.find((f) => f.path === LEGACY_OVERVIEW_REL_PATH)!;
- expect(ovPlan.status).toBe("update");
- expect(ovPlan.before).toBe("");
- expect(ovPlan.after.length).toBeGreaterThan(0);
- });
});
describe("applyUpgrade", () => {
diff --git a/tests/core/event-log.test.ts b/tests/core/event-log.test.ts
deleted file mode 100644
index 399f8630..00000000
--- a/tests/core/event-log.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-import {
- appendEvent,
- insertEventEntry,
- redactText,
- validateEventDate,
- validateEventTime,
-} from "../../src/core/event-log.ts";
-
-let tmp: string;
-
-beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), "o2b-eventlog-test-"));
-});
-
-afterEach(() => {
- rmSync(tmp, { recursive: true, force: true });
-});
-
-describe("redactText", () => {
- test("removes secret-like assignments", () => {
- expect(redactText("api_key=abc token: xyz password = qwerty")).toBe(
- "api_key=[REDACTED] token: [REDACTED] password = [REDACTED]",
- );
- });
-
- test("redacts PEM private-key blocks", () => {
- const input = `Here is a key:
------BEGIN RSA PRIVATE KEY-----
-MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF8PbnGy0AHB7MhgHcTz6sE2I2yPB
-aFDrBz9vFqU4yL3mW5mG3qFqR1vF0F3F1F1F1F1F1F1F1F1F1F1F1F
------END RSA PRIVATE KEY-----
-And some more text.`;
- const result = redactText(input);
- expect(result).toContain("[REDACTED PRIVATE KEY]");
- expect(result).not.toContain("MIIEpA");
- expect(result).toContain("And some more text.");
- });
-
- test("redacts EC private-key blocks", () => {
- const input = "-----BEGIN EC PRIVATE KEY-----\nsecretstuff\n-----END EC PRIVATE KEY-----";
- expect(redactText(input)).toBe("[REDACTED PRIVATE KEY]");
- });
-
- test("masks JWT-shaped tokens", () => {
- const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
- const result = redactText(`token is ${jwt}`);
- expect(result).toContain("***REDACTED_JWT_sw5c");
- expect(result).not.toContain("eyJhbG");
- });
-
- test("does not mask version numbers as JWTs", () => {
- expect(redactText("version 1.2.3 is fine")).toBe("version 1.2.3 is fine");
- });
-
- test("combined: PEM + JWT + secret assignment", () => {
- const input = `api_key=secret123
------BEGIN PRIVATE KEY-----
-base64content
------END PRIVATE KEY-----
-bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.abc123def456ghi789`;
- const result = redactText(input);
- expect(result).toContain("api_key=[REDACTED]");
- expect(result).toContain("[REDACTED PRIVATE KEY]");
- expect(result).not.toContain("base64content");
- expect(result).toContain("***REDACTED_JWT_");
- });
-});
-
-describe("validateEventTime", () => {
- test("accepts HH:MM in 24-hour range", () => {
- expect(validateEventTime("00:00")).toBe("00:00");
- expect(validateEventTime("23:59")).toBe("23:59");
- });
-
- test("rejects malformed inputs", () => {
- for (const bad of ["9:00", "25:00", "bad", "10:60", "abc:de"]) {
- expect(() => validateEventTime(bad)).toThrow(/HH:MM/);
- }
- });
-});
-
-describe("validateEventDate", () => {
- test("accepts YYYY.MM.DD calendar dates", () => {
- expect(validateEventDate("2026.05.06")).toBe("2026.05.06");
- expect(validateEventDate("2024.02.29")).toBe("2024.02.29");
- });
-
- test("rejects malformed, impossible, or path-like inputs", () => {
- for (const bad of [
- "2026-05-06",
- "2026.5.6",
- "2026.13.01",
- "2026.02.30",
- "../AI Wiki/notes/pwn",
- ]) {
- expect(() => validateEventDate(bad)).toThrow(/YYYY\.MM\.DD/);
- }
- });
-});
-
-describe("insertEventEntry", () => {
- test("inserts at the end when no other events", () => {
- const out = insertEventEntry("# Day\n\n## Raw events\n\n", "- 09:30 — @x — first");
- expect(out).toBe("# Day\n\n## Raw events\n\n- 09:30 — @x — first\n");
- });
-
- test("preserves chronological order", () => {
- let content = "# Day\n\n## Raw events\n\n";
- content = insertEventEntry(content, "- 11:00 — @x — later");
- content = insertEventEntry(content, "- 09:00 — @x — earlier");
- expect(content.indexOf("09:00")).toBeLessThan(content.indexOf("11:00"));
- });
-});
-
-describe("appendEvent", () => {
- test("creates daily note with raw events section", async () => {
- const path = await appendEvent(tmp, "test-agent", "created project skeleton", {
- date: "2026.05.06",
- time: "09:30",
- });
- expect(path).toBe(join(tmp, "Daily", "2026.05.06.md"));
- const text = readFileSync(path, "utf8");
- expect(text).toBe(
- "---\nformatted: false\n---\n\n# 2026.05.06\n\n## Raw events\n\n- 09:30 — @test-agent — created project skeleton\n",
- );
- });
-
- test("preserves manual content above raw events", async () => {
- const daily = join(tmp, "Daily", "2026.05.06.md");
- mkdirSync(join(tmp, "Daily"), { recursive: true });
- writeFileSync(
- daily,
- "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 — @old — old entry\n",
- );
- await appendEvent(tmp, "new", "new entry", { date: "2026.05.06", time: "09:00" });
- expect(readFileSync(daily, "utf8")).toBe(
- "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 — @old — old entry\n- 09:00 — @new — new entry\n",
- );
- });
-
- test("rejects invalid explicit times", async () => {
- for (const bad of ["9:00", "25:00", "bad"]) {
- await expect(
- appendEvent(tmp, "agent", "msg", { date: "2026.05.06", time: bad }),
- ).rejects.toThrow(/HH:MM/);
- }
- });
-
- test("rejects invalid explicit dates before building the output path", async () => {
- for (const bad of ["2026-05-06", "2026.02.30", "../AI Wiki/notes/pwn"]) {
- await expect(
- appendEvent(tmp, "agent", "msg", { date: bad, time: "09:00" }),
- ).rejects.toThrow(/YYYY\.MM\.DD/);
- }
- });
-
- test("concurrent process appends keep all entries", async () => {
- const helper = join(import.meta.dir, "..", "helpers", "concurrent-append-runner.ts");
- const N = 12;
- const procs = Array.from({ length: N }, (_, i) =>
- Bun.spawn(["bun", "run", helper, tmp, String(i)], {
- stdout: "pipe",
- stderr: "pipe",
- }),
- );
- const codes = await Promise.all(procs.map((p) => p.exited));
- for (let i = 0; i < N; i++) {
- if (codes[i] !== 0) {
- const stderr = await new Response(procs[i]!.stderr).text();
- throw new Error(`worker ${i} exited ${codes[i]}: ${stderr}`);
- }
- }
- const content = readFileSync(join(tmp, "Daily", "2026.05.06.md"), "utf8");
- for (let i = 0; i < N; i++) {
- const stamp = `- 10:${String(i).padStart(2, "0")} — @worker — entry ${i}`;
- expect(content).toContain(stamp);
- }
- const matches = content.match(/@worker — entry/g);
- expect(matches).not.toBeNull();
- expect(matches!.length).toBe(N);
- }, 30_000);
-});
diff --git a/tests/core/init.test.ts b/tests/core/init.test.ts
deleted file mode 100644
index 3a7f4ecd..00000000
--- a/tests/core/init.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join, normalize } from "node:path";
-
-import {
- AGENTS_PLACEHOLDER,
- VAULT_FILES,
- bootstrapVault,
-} from "../../src/core/init.ts";
-
-let tmp: string;
-
-beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), "o2b-init-test-"));
-});
-
-afterEach(() => {
- rmSync(tmp, { recursive: true, force: true });
-});
-
-describe("bootstrapVault", () => {
- test("creates the canonical structure", () => {
- const created = bootstrapVault(tmp, { name: "Test Brain" });
- expect(created.length).toBeGreaterThan(0);
- for (const rel of VAULT_FILES) {
- expect(existsSync(join(tmp, rel))).toBe(true);
- }
- const manual = readFileSync(join(tmp, "AI Wiki", "_OPEN_SECOND_BRAIN.md"), "utf8");
- expect(manual).toContain("Test Brain");
- });
-
- test("writes agent_name into agents.md", () => {
- bootstrapVault(tmp, { name: "Test", agentName: "openclaw-main" });
- const txt = readFileSync(join(tmp, "AI Wiki", "identity", "agents.md"), "utf8");
- expect(txt).toContain("- openclaw-main: primary agent on this server");
- expect(txt).not.toContain(AGENTS_PLACEHOLDER);
- });
-
- test("without agent_name keeps placeholder", () => {
- bootstrapVault(tmp, { name: "Test" });
- const txt = readFileSync(join(tmp, "AI Wiki", "identity", "agents.md"), "utf8");
- expect(txt).toContain(AGENTS_PLACEHOLDER);
- });
-
- test("registers a second agent under existing one (multi-runtime install)", () => {
- bootstrapVault(tmp, { name: "Test", agentName: "hermes-vps-agent" });
- const agentsPath = join(tmp, "AI Wiki", "identity", "agents.md");
- expect(readFileSync(agentsPath, "utf8")).toContain(
- "- hermes-vps-agent: primary agent on this server",
- );
-
- const second = bootstrapVault(tmp, { name: "Test", agentName: "codex-vps-agent" });
- expect(second).toContain(normalize("AI Wiki/identity/agents.md"));
-
- const text = readFileSync(agentsPath, "utf8");
- expect(text).toContain("- hermes-vps-agent: primary agent on this server");
- expect(text).toContain("- codex-vps-agent: primary agent on this server");
- expect(text.indexOf("hermes-vps-agent")).toBeLessThan(text.indexOf("codex-vps-agent"));
- expect(text).toContain("## Scopes");
- expect(text.indexOf("codex-vps-agent")).toBeLessThan(text.indexOf("## Scopes"));
-
- // Re-registering the same agent is a no-op.
- const third = bootstrapVault(tmp, { name: "Test", agentName: "codex-vps-agent" });
- expect(third).not.toContain(normalize("AI Wiki/identity/agents.md"));
- const after = readFileSync(agentsPath, "utf8");
- expect((after.match(/- codex-vps-agent: primary agent on this server/g) ?? []).length).toBe(1);
- });
-
- test("upgrades existing placeholder in place when agent_name added later", () => {
- bootstrapVault(tmp, { name: "Test" });
- const agentsPath = join(tmp, "AI Wiki", "identity", "agents.md");
- expect(readFileSync(agentsPath, "utf8")).toContain(AGENTS_PLACEHOLDER);
-
- const created = bootstrapVault(tmp, { name: "Test", agentName: "hermes-main" });
- expect(created).toContain(normalize("AI Wiki/identity/agents.md"));
- const text = readFileSync(agentsPath, "utf8");
- expect(text).toContain("- hermes-main: primary agent on this server");
- expect(text).not.toContain(AGENTS_PLACEHOLDER);
- });
-
- test("does not overwrite existing files by default", () => {
- mkdirSync(join(tmp, "AI Wiki"), { recursive: true });
- writeFileSync(join(tmp, "AI Wiki", "index.md"), "custom content");
- const created = bootstrapVault(tmp, { name: "Test" });
- expect(created).not.toContain(normalize("AI Wiki/index.md"));
- expect(readFileSync(join(tmp, "AI Wiki", "index.md"), "utf8")).toBe("custom content");
- });
-
- test("force overwrites", () => {
- mkdirSync(join(tmp, "AI Wiki"), { recursive: true });
- writeFileSync(join(tmp, "AI Wiki", "index.md"), "old");
- const created = bootstrapVault(tmp, { name: "Test", force: true });
- expect(created).toContain(normalize("AI Wiki/index.md"));
- expect(readFileSync(join(tmp, "AI Wiki", "index.md"), "utf8")).not.toBe("old");
- });
-});
diff --git a/tests/core/path-constants.test.ts b/tests/core/path-constants.test.ts
new file mode 100644
index 00000000..1a02d7df
--- /dev/null
+++ b/tests/core/path-constants.test.ts
@@ -0,0 +1,58 @@
+/**
+ * Canonical vault-relative path constants. Everywhere the codebase
+ * builds a path inside the vault, it imports a constant from this
+ * test's covered modules instead of repeating the literal. Future
+ * renames (Brain → Memory, Brain/payments → Payments, ...) are a
+ * one-line change in the constants module.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { posix } from "node:path";
+
+import { BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";
+import {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
+} from "../../src/core/pay-memory/paths.ts";
+
+describe("BRAIN_ROOT_REL", () => {
+ test("names the Brain-layer root directory", () => {
+ expect(BRAIN_ROOT_REL).toBe("Brain");
+ });
+});
+
+describe("PAY_MEMORY_*_REL constants", () => {
+ test("compose under BRAIN_ROOT_REL so a Brain rename cascades", () => {
+ expect(PAY_MEMORY_ROOT_REL).toBe(posix.join(BRAIN_ROOT_REL, "payments"));
+ expect(PAY_MEMORY_POLICIES_REL).toBe(
+ posix.join(PAY_MEMORY_ROOT_REL, "policies"),
+ );
+ expect(PAY_MEMORY_ASSETS_REL).toBe(
+ posix.join(PAY_MEMORY_ROOT_REL, "assets"),
+ );
+ expect(PAY_MEMORY_DRAFTS_REL).toBe(
+ posix.join(PAY_MEMORY_ROOT_REL, "drafts"),
+ );
+ expect(PAY_MEMORY_REPORTS_REL).toBe(
+ posix.join(PAY_MEMORY_ROOT_REL, "reports"),
+ );
+ expect(PAY_MEMORY_PENDING_REL).toBe(
+ posix.join(PAY_MEMORY_ROOT_REL, "_pending"),
+ );
+ });
+
+ test("spending policy file constants compose under policies", () => {
+ expect(PAY_MEMORY_SPENDING_MD_REL).toBe(
+ posix.join(PAY_MEMORY_POLICIES_REL, "spending.md"),
+ );
+ expect(PAY_MEMORY_SPENDING_JSON_REL).toBe(
+ posix.join(PAY_MEMORY_POLICIES_REL, "spending.json"),
+ );
+ });
+});
diff --git a/tests/core/path-safety.test.ts b/tests/core/path-safety.test.ts
index 63b7d251..60484e28 100644
--- a/tests/core/path-safety.test.ts
+++ b/tests/core/path-safety.test.ts
@@ -19,7 +19,7 @@ describe("ensureInsideVault", () => {
});
test("accepts descendants", () => {
- const target = join(VAULT, "AI Wiki", "notes", "x.md");
+ const target = join(VAULT, "Notes", "notes", "x.md");
expect(ensureInsideVault(target, VAULT)).toBe(target);
});
@@ -38,7 +38,7 @@ describe("ensureInsideVault", () => {
});
test("returns the resolved absolute path", () => {
- const target = join(VAULT, "AI Wiki", "x.md");
+ const target = join(VAULT, "Notes", "x.md");
expect(ensureInsideVault(target, VAULT)).toBe(target);
});
});
@@ -71,7 +71,7 @@ describe("ensureInsideVault — realpath / symlink escape", () => {
});
test("accepts a target inside a real subdirectory", () => {
- const sub = join(vault, "AI Wiki");
+ const sub = join(vault, "Notes");
mkdirSync(sub, { recursive: true });
expect(ensureInsideVault(join(sub, "x.md"), vault)).toBe(join(sub, "x.md"));
});
@@ -81,17 +81,17 @@ describe("ensureInsideVault — realpath / symlink escape", () => {
// protection should not crash on a path component that doesn't exist
// yet (the writer creates it after this check passes).
expect(
- ensureInsideVault(join(vault, "AI Wiki", "payments", "2026-05-10", "x.md"), vault),
- ).toBe(join(vault, "AI Wiki", "payments", "2026-05-10", "x.md"));
+ ensureInsideVault(join(vault, "Notes", "payments", "2026-05-10", "x.md"), vault),
+ ).toBe(join(vault, "Notes", "payments", "2026-05-10", "x.md"));
});
});
describe("vaultRelative", () => {
test("renders descendant paths with forward slashes", () => {
- const target = join(VAULT, "AI Wiki", "notes", "x.md");
+ const target = join(VAULT, "Notes", "notes", "x.md");
// The renderer always emits forward slashes, even when the host
// separator is `\`, so wikilinks/Obsidian behave consistently.
- expect(vaultRelative(target, VAULT)).toBe("AI Wiki/notes/x.md");
+ expect(vaultRelative(target, VAULT)).toBe("Notes/notes/x.md");
});
test("returns empty string for the vault root itself", () => {
diff --git a/tests/core/pay-memory.approval.test.ts b/tests/core/pay-memory.approval.test.ts
index ad9cd222..43777d58 100644
--- a/tests/core/pay-memory.approval.test.ts
+++ b/tests/core/pay-memory.approval.test.ts
@@ -14,6 +14,17 @@ import {
} from "../../src/core/pay-memory/approval.ts";
import { policyJsonPath } from "../../src/core/pay-memory/policy-rules.ts";
+import {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
+} from "../../src/core/pay-memory/paths.ts";
+
let tmp: string;
beforeEach(() => {
@@ -36,7 +47,7 @@ describe("writePendingRequest", () => {
test("creates a pending-payment-request artifact with frontmatter and body", () => {
const out = writePendingRequest(tmp, baseInput);
expect(out.status).toBe("pending");
- expect(out.relativePath.startsWith("AI Wiki/payments/_pending/")).toBe(true);
+ expect(out.relativePath.startsWith(`${PAY_MEMORY_PENDING_REL}/`)).toBe(true);
expect(out.id.startsWith("req-2026-05-10-1000-fal-")).toBe(true);
expect(out.policyDecision.hasPolicy).toBe(false);
@@ -54,17 +65,17 @@ describe("writePendingRequest", () => {
currency: "USDC",
endpoint: "https://gateway.example/v1/fal",
expectedOutput: "PNG image, 1024×512",
- vaultFiles: ["AI Wiki/drafts/post.md", "AI Wiki/assets/header.md"],
+ vaultFiles: [`${PAY_MEMORY_DRAFTS_REL}/post.md`, `${PAY_MEMORY_ASSETS_REL}/header.md`],
});
const text = readFileSync(out.path, "utf8");
expect(text).toContain("expected_amount: 0.05");
expect(text).toContain("currency: USDC");
- expect(text).toContain("- `AI Wiki/drafts/post.md`");
+ expect(text).toContain(`- \`${PAY_MEMORY_DRAFTS_REL}/post.md\``);
expect(text).toContain("PNG image, 1024×512");
});
test("records the policy decision when policies/spending.json is present", () => {
- mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });
+ mkdirSync(join(tmp, PAY_MEMORY_POLICIES_REL), { recursive: true });
writeFileSync(
policyJsonPath(tmp),
JSON.stringify({ allowed_services: ["paysponge/fal"], require_approval_above: 0.04 }),
@@ -78,7 +89,7 @@ describe("writePendingRequest", () => {
});
test("enforcePolicy=true blocks creation when policy denies", () => {
- mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });
+ mkdirSync(join(tmp, PAY_MEMORY_POLICIES_REL), { recursive: true });
writeFileSync(
policyJsonPath(tmp),
JSON.stringify({ allowed_services: ["paysponge/fal"] }),
@@ -136,11 +147,11 @@ describe("state transitions", () => {
).rejects.toThrow(/cannot transition request t-3 from pending to consumed/);
await approvePendingRequest(tmp, "t-3", { approvedBy: "sergey" });
const out = await consumePendingRequest(tmp, "t-3", {
- receiptPath: "AI Wiki/payments/2026-05-10/x.md",
+ receiptPath: `${PAY_MEMORY_ROOT_REL}/2026-05-10/x.md`,
});
expect(out.status).toBe("consumed");
const reloaded = loadPendingRequest(tmp, "t-3")!;
- expect(reloaded.metadata["receipt"]).toBe("AI Wiki/payments/2026-05-10/x.md");
+ expect(reloaded.metadata["receipt"]).toBe(`${PAY_MEMORY_ROOT_REL}/2026-05-10/x.md`);
});
test("rejected and consumed are terminal", async () => {
diff --git a/tests/core/pay-memory.asset.test.ts b/tests/core/pay-memory.asset.test.ts
index 61a9221e..4bb0cbf3 100644
--- a/tests/core/pay-memory.asset.test.ts
+++ b/tests/core/pay-memory.asset.test.ts
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { parseFrontmatter } from "../../src/core/vault.ts";
import { writeAsset } from "../../src/core/pay-memory/asset.ts";
+
let tmp: string;
beforeEach(() => {
@@ -25,7 +26,7 @@ const base = {
describe("writeAsset", () => {
test("creates the note with derived slug and frontmatter", () => {
const out = writeAsset(tmp, base);
- expect(out.relativePath.startsWith("AI Wiki/assets/")).toBe(true);
+ expect(out.relativePath.startsWith("Brain/payments/assets/")).toBe(true);
expect(out.slug).toContain("blog-header");
const [meta, body] = parseFrontmatter(out.path);
@@ -40,13 +41,13 @@ describe("writeAsset", () => {
test("links to source receipt and used-in draft as wikilinks", () => {
const out = writeAsset(tmp, {
...base,
- sourceReceipt: "AI Wiki/payments/2026-05-10/fal-blog.md",
- usedIn: "AI Wiki/drafts/blog-post.md",
+ sourceReceipt: "Brain/payments/2026-05-10/fal-blog.md",
+ usedIn: "Brain/payments/drafts/blog-post.md",
prompt: "A recursive technical blog illustration\nNo logos\nNo text",
});
const text = readFileSync(out.path, "utf8");
- expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');
- expect(text).toContain('used_in: "[[AI Wiki/drafts/blog-post]]"');
+ expect(text).toContain('source_receipt: "[[Brain/payments/2026-05-10/fal-blog]]"');
+ expect(text).toContain('used_in: "[[Brain/payments/drafts/blog-post]]"');
expect(text).toContain("> A recursive technical blog illustration");
expect(text).toContain("> No logos");
});
@@ -72,11 +73,11 @@ describe("writeAsset", () => {
test("sanitizes brackets in source_receipt wikilink", () => {
const out = writeAsset(tmp, {
...base,
- sourceReceipt: "AI Wiki/payments/2026-05-10/fal[v2].md",
+ sourceReceipt: "Brain/payments/2026-05-10/fal[v2].md",
});
const text = readFileSync(out.path, "utf8");
- expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/falv2]]"');
- expect(text).toContain("Receipt: [[AI Wiki/payments/2026-05-10/falv2]]");
+ expect(text).toContain('source_receipt: "[[Brain/payments/2026-05-10/falv2]]"');
+ expect(text).toContain("Receipt: [[Brain/payments/2026-05-10/falv2]]");
});
test("escapes backticks in service name", () => {
diff --git a/tests/core/pay-memory.digest.test.ts b/tests/core/pay-memory.digest.test.ts
index 67aeaefb..c437aacd 100644
--- a/tests/core/pay-memory.digest.test.ts
+++ b/tests/core/pay-memory.digest.test.ts
@@ -10,6 +10,7 @@ import {
} from "../../src/core/pay-memory/digest.ts";
import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";
+
let tmp: string;
beforeEach(() => {
@@ -90,13 +91,13 @@ describe("renderPaymentDigestTelegram", () => {
receipts: 3,
totalAmount: 0.08,
currency: "USDC",
- reportPath: "AI Wiki/reports/payment-report-2026-05-10.md",
+ reportPath: "Brain/payments/reports/payment-report-2026-05-10.md",
});
expect(text).toContain("💳 Оплачено сервисов: **2**");
expect(text).toContain("💰 Сумма: **0.08 USDC**");
expect(text).toContain("📁 Файлы чеков: **3**");
expect(text).toContain(
- "🔗 Отчёт: `AI Wiki/reports/payment-report-2026-05-10.md`",
+ "🔗 Отчёт: `Brain/payments/reports/payment-report-2026-05-10.md`",
);
});
diff --git a/tests/core/pay-memory.paths.test.ts b/tests/core/pay-memory.paths.test.ts
index 536c5213..0039c3ee 100644
--- a/tests/core/pay-memory.paths.test.ts
+++ b/tests/core/pay-memory.paths.test.ts
@@ -6,6 +6,12 @@ import {
isoDateNow,
isoTimeNow,
isoTimestampZ,
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
payMemoryDirs,
paymentsDateDir,
policyPath,
@@ -17,27 +23,27 @@ import {
} from "../../src/core/pay-memory/paths.ts";
describe("payMemoryDirs", () => {
- test("composes the canonical AI Wiki layout", () => {
+ test("composes the canonical Brain/payments layout", () => {
const dirs = payMemoryDirs("/vault");
- expect(dirs.policies).toBe(join("/vault", "AI Wiki", "policies"));
- expect(dirs.payments).toBe(join("/vault", "AI Wiki", "payments"));
- expect(dirs.assets).toBe(join("/vault", "AI Wiki", "assets"));
- expect(dirs.drafts).toBe(join("/vault", "AI Wiki", "drafts"));
- expect(dirs.reports).toBe(join("/vault", "AI Wiki", "reports"));
+ expect(dirs.policies).toBe(join("/vault", PAY_MEMORY_POLICIES_REL));
+ expect(dirs.payments).toBe(join("/vault", PAY_MEMORY_ROOT_REL));
+ expect(dirs.assets).toBe(join("/vault", PAY_MEMORY_ASSETS_REL));
+ expect(dirs.drafts).toBe(join("/vault", PAY_MEMORY_DRAFTS_REL));
+ expect(dirs.reports).toBe(join("/vault", PAY_MEMORY_REPORTS_REL));
});
test("policyPath, receiptPath, assetPath, reportPath", () => {
- expect(policyPath("/v")).toBe(join("/v", "AI Wiki", "policies", "spending.md"));
+ expect(policyPath("/v")).toBe(join("/v", PAY_MEMORY_SPENDING_MD_REL));
expect(receiptPath("/v", "2026-05-10", "fal-x")).toBe(
- join("/v", "AI Wiki", "payments", "2026-05-10", "fal-x.md"),
+ join("/v", PAY_MEMORY_ROOT_REL, "2026-05-10", "fal-x.md"),
);
- expect(assetPath("/v", "header")).toBe(join("/v", "AI Wiki", "assets", "header.md"));
- expect(reportPath("/v", "demo")).toBe(join("/v", "AI Wiki", "reports", "demo.md"));
+ expect(assetPath("/v", "header")).toBe(join("/v", PAY_MEMORY_ASSETS_REL, "header.md"));
+ expect(reportPath("/v", "demo")).toBe(join("/v", PAY_MEMORY_REPORTS_REL, "demo.md"));
});
test("paymentsDateDir validates date", () => {
expect(paymentsDateDir("/v", "2026-05-10")).toBe(
- join("/v", "AI Wiki", "payments", "2026-05-10"),
+ join("/v", PAY_MEMORY_ROOT_REL, "2026-05-10"),
);
expect(() => paymentsDateDir("/v", "2026.05.10")).toThrow();
expect(() => paymentsDateDir("/v", "10-05-2026")).toThrow();
diff --git a/tests/core/pay-memory.policy-rules.test.ts b/tests/core/pay-memory.policy-rules.test.ts
index 88e8390d..67f4d1ca 100644
--- a/tests/core/pay-memory.policy-rules.test.ts
+++ b/tests/core/pay-memory.policy-rules.test.ts
@@ -11,6 +11,17 @@ import {
} from "../../src/core/pay-memory/policy-rules.ts";
import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";
+import {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
+} from "../../src/core/pay-memory/paths.ts";
+
let tmp: string;
beforeEach(() => {
@@ -23,7 +34,7 @@ afterEach(() => {
function writePolicy(rules: unknown) {
const path = policyJsonPath(tmp);
- mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });
+ mkdirSync(join(tmp, PAY_MEMORY_POLICIES_REL), { recursive: true });
writeFileSync(path, JSON.stringify(rules, null, 2), "utf8");
}
@@ -51,7 +62,7 @@ describe("loadPolicyRules", () => {
test("rejects malformed JSON", () => {
const path = policyJsonPath(tmp);
- mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });
+ mkdirSync(join(tmp, PAY_MEMORY_POLICIES_REL), { recursive: true });
writeFileSync(path, "{ not json", "utf8");
expect(() => loadPolicyRules(tmp)).toThrow(/not valid JSON/);
});
diff --git a/tests/core/pay-memory.policy.test.ts b/tests/core/pay-memory.policy.test.ts
index 2675e4c3..1791ca20 100644
--- a/tests/core/pay-memory.policy.test.ts
+++ b/tests/core/pay-memory.policy.test.ts
@@ -71,6 +71,6 @@ describe("DEFAULT_POLICY_TEMPLATE", () => {
test("documents the post-call evidence the agent must save", () => {
expect(DEFAULT_POLICY_TEMPLATE).toContain("raw payment-tool output");
- expect(DEFAULT_POLICY_TEMPLATE).toContain("AI Wiki/payments/<date>/");
+ expect(DEFAULT_POLICY_TEMPLATE).toContain("Brain/payments/<date>/");
});
});
diff --git a/tests/core/pay-memory.receipt.test.ts b/tests/core/pay-memory.receipt.test.ts
index 746046ad..b454de41 100644
--- a/tests/core/pay-memory.receipt.test.ts
+++ b/tests/core/pay-memory.receipt.test.ts
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { parseFrontmatter } from "../../src/core/vault.ts";
import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";
+
let tmp: string;
beforeEach(() => {
@@ -31,7 +32,7 @@ describe("writeReceipt", () => {
expect(out.date).toBe("2026-05-10");
expect(out.created).toBe("2026-05-10T17:20:00Z");
expect(out.slug.startsWith("fal-")).toBe(true);
- expect(out.relativePath.startsWith("AI Wiki/payments/2026-05-10/")).toBe(true);
+ expect(out.relativePath.startsWith("Brain/payments/2026-05-10/")).toBe(true);
const [meta, body] = parseFrontmatter(out.path);
expect(meta["type"]).toBe("agent-payment-receipt");
@@ -42,7 +43,7 @@ describe("writeReceipt", () => {
expect(meta["network"]).toBe("solana");
expect(meta["created"]).toBe("2026-05-10T17:20:00Z");
expect(body).toContain("# Payment Receipt: Generate one original blog header image");
- expect(body).toContain("[[AI Wiki/policies/spending]]");
+ expect(body).toContain("[[Brain/payments/policies/spending]]");
});
test("respects an explicit slug", () => {
@@ -68,7 +69,7 @@ describe("writeReceipt", () => {
currency: "USDC",
paymentProof: "5G3...sig",
resultRef: "https://fal-cdn.example/abc.png",
- resultNote: "AI Wiki/assets/blog-header.md",
+ resultNote: "Brain/payments/assets/blog-header.md",
rawOutput: "{\"ok\": true}",
});
const [meta, body] = parseFrontmatter(out.path);
@@ -79,8 +80,8 @@ describe("writeReceipt", () => {
expect(meta["currency"]).toBe("USDC");
expect(meta["payment_proof"]).toBe("5G3...sig");
expect(meta["result_ref"]).toBe("https://fal-cdn.example/abc.png");
- expect(meta["result_note"]).toBe("AI Wiki/assets/blog-header.md");
- expect(body).toContain("[[AI Wiki/assets/blog-header]]");
+ expect(meta["result_note"]).toBe("Brain/payments/assets/blog-header.md");
+ expect(body).toContain("[[Brain/payments/assets/blog-header]]");
expect(body).toContain("`USDC`");
expect(body).not.toContain("_(not provided)_");
});
@@ -117,10 +118,10 @@ describe("writeReceipt", () => {
test("sanitizes brackets in resultNote wikilink", () => {
const out = writeReceipt(tmp, {
...baseInput,
- resultNote: "AI Wiki/assets/blog [draft].md",
+ resultNote: "Brain/payments/assets/blog [draft].md",
});
const text = readFileSync(out.path, "utf8");
- expect(text).toContain("[[AI Wiki/assets/blog draft]]");
+ expect(text).toContain("[[Brain/payments/assets/blog draft]]");
expect(text).not.toContain("[draft]]]");
});
@@ -176,7 +177,7 @@ describe("writeReceipt", () => {
expect(body).toContain("Policy returned `approval_required`");
expect(body).toContain("Rule fired: `max_single_call`");
expect(body).toContain("expected amount 0.10 USDC exceeds max_single_call 0.07 USDC");
- expect(body).toContain("[[AI Wiki/payments/_pending/req-2026-05-10-fal]]");
+ expect(body).toContain("[[Brain/payments/_pending/req-2026-05-10-fal]]");
expect(body).toContain("Approved by: sergey");
});
diff --git a/tests/core/pay-memory.report.test.ts b/tests/core/pay-memory.report.test.ts
index 526409c4..70cdeb5f 100644
--- a/tests/core/pay-memory.report.test.ts
+++ b/tests/core/pay-memory.report.test.ts
@@ -10,6 +10,7 @@ import {
} from "../../src/core/pay-memory/report.ts";
import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";
+
let tmp: string;
beforeEach(() => {
@@ -41,7 +42,7 @@ describe("aggregateReceipts", () => {
actualAmount: "0.05",
currency: "USDC",
resultRef: "https://fal/img1",
- resultNote: "AI Wiki/assets/img1.md",
+ resultNote: "Brain/payments/assets/img1.md",
});
writeReceipt(tmp, {
...baseReceipt,
@@ -57,12 +58,12 @@ describe("aggregateReceipts", () => {
expect(summaries[1]!.service).toBe("paysponge/fal");
expect(summaries[1]!.actualAmount).toBe("0.05");
expect(summaries[1]!.resultRef).toBe("https://fal/img1");
- expect(summaries[1]!.resultNote).toBe("AI Wiki/assets/img1.md");
+ expect(summaries[1]!.resultNote).toBe("Brain/payments/assets/img1.md");
});
test("ignores files without the receipt frontmatter type", () => {
writeReceipt(tmp, { ...baseReceipt, slug: "real-1" });
- const dir = join(tmp, "AI Wiki", "payments", "2026-05-10");
+ const dir = join(tmp, "Brain", "payments", "2026-05-10");
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "stray.md"),
@@ -84,7 +85,7 @@ describe("writeReport", () => {
actualAmount: "0.05",
currency: "USDC",
resultRef: "https://fal/img1",
- resultNote: "AI Wiki/assets/img1.md",
+ resultNote: "Brain/payments/assets/img1.md",
});
const out = writeReport(tmp, {
date: "2026-05-10",
@@ -92,7 +93,7 @@ describe("writeReport", () => {
task: "Blog post about Pay Memory",
});
expect(out.receiptsUsed).toBe(1);
- expect(out.relativePath.startsWith("AI Wiki/reports/")).toBe(true);
+ expect(out.relativePath.startsWith("Brain/payments/reports/")).toBe(true);
const [meta, body] = parseFrontmatter(out.path);
expect(meta["type"]).toBe("payment-report");
@@ -102,8 +103,8 @@ describe("writeReport", () => {
expect(meta["task"]).toBe("Blog post about Pay Memory");
expect(body).toContain("### paysponge/fal");
expect(body).toContain("Amount: `0.05 USDC`");
- expect(body).toContain("[[AI Wiki/payments/2026-05-10/fal-1]]");
- expect(body).toContain("[[AI Wiki/assets/img1]]");
+ expect(body).toContain("[[Brain/payments/2026-05-10/fal-1]]");
+ expect(body).toContain("[[Brain/payments/assets/img1]]");
});
test("renders gracefully when there are no receipts", () => {
diff --git a/tests/e2e/brain-capture-and-fields.test.ts b/tests/e2e/brain-capture-and-fields.test.ts
index da77481c..d23c4fec 100644
--- a/tests/e2e/brain-capture-and-fields.test.ts
+++ b/tests/e2e/brain-capture-and-fields.test.ts
@@ -1,24 +1,19 @@
/**
- * End-to-end scenario for the capture extensions + frontmatter migration.
+ * End-to-end scenario for the capture extensions.
*
- * Exercises the full chain across CLI invocations:
+ * Exercises the chain across CLI invocations:
* 1. `o2b init` + `o2b brain init` bootstrap a fresh vault.
* 2. A Daily note with an `@osb` marker is dropped on disk.
* 3. `o2b brain scan-inline` captures the marker into Brain/inbox/
- * and annotates the Daily note with `@osb✓ [[sig-...]]`.
+ * and annotates the source note with `@osb✓ [[sig-...]]`.
* 4. The session import path picks up the same marker shape from a
* transcript fixture (different topic to confirm independence).
- * 5. `o2b brain migrate-frontmatter --apply --yes` rewrites a
- * hand-crafted legacy-shape pref file into the `_`-prefixed
- * form and lands a snapshot under Brain/.snapshots/.
- * 6. `o2b brain rollback <run_id>` restores the pre-migration shape.
*
* If any step fails, the chain breaks and we see which seam is broken.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
- existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -82,7 +77,7 @@ describe("capture + migration end-to-end", () => {
);
// Step 3: scan-inline captures + rewrites
- r = await runCli(["brain", "scan-inline", "--vault", vault], {
+ r = await runCli(["brain", "scan-inline", "--vault", vault, "--path", "Daily"], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
});
expect(r.returncode).toBe(0);
@@ -109,67 +104,5 @@ describe("capture + migration end-to-end", () => {
const sigsAfterImport = readdirSync(inbox).filter((n) => n.startsWith("sig-"));
expect(sigsAfterImport.length).toBeGreaterThan(inlineSigs.length);
- // Step 5: hand-write a legacy-shape preference, then migrate.
- const legacyPrefPath = join(vault, "Brain", "preferences", "pref-legacy-e2e.md");
- writeFileSync(
- legacyPrefPath,
- [
- "---",
- "kind: brain-preference",
- "id: pref-legacy-e2e",
- "created_at: 2026-05-14T10:42:00Z",
- "unconfirmed_until: 2026-05-28T10:42:00Z",
- "tags: [brain, brain/preference, brain/topic/legacy-e2e]",
- "topic: legacy-e2e",
- "principle: Some rule",
- "pinned: false",
- "status: confirmed",
- "confirmed_at: 2026-05-15T10:00:00Z",
- "evidenced_by: []",
- "applied_count: 1",
- "violated_count: 0",
- "last_evidence_at: null",
- "confidence: low",
- "---",
- "",
- ].join("\n"),
- "utf8",
- );
- r = await runCli(
- ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- const afterMigrate = readFileSync(legacyPrefPath, "utf8");
- expect(afterMigrate).toMatch(/^_status: confirmed$/m);
- expect(afterMigrate).not.toMatch(/^status: confirmed$/m);
-
- const snapDir = join(vault, "Brain", ".snapshots");
- const snaps = readdirSync(snapDir).filter(
- (n) => n.startsWith("migrate-") && n.endsWith(".tar.zst"),
- );
- expect(snaps.length).toBe(1);
-
- // Step 6: rollback restores the legacy shape. The migration
- // intentionally drifted the live tree from the snapshot moment,
- // so v0.10.6 rollback requires `--force-rollback` to overwrite.
- const runId = snaps[0]!.replace(/\.tar\.zst$/, "");
- r = await runCli(
- [
- "brain",
- "rollback",
- runId,
- "--vault",
- vault,
- "--yes",
- "--force-rollback",
- ],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- expect(existsSync(legacyPrefPath)).toBe(true);
- const afterRollback = readFileSync(legacyPrefPath, "utf8");
- expect(afterRollback).toMatch(/^status: confirmed$/m);
- expect(afterRollback).not.toMatch(/^_status: confirmed$/m);
}, 60_000);
});
diff --git a/tests/e2e/pay-memory-factchecktools.sh b/tests/e2e/pay-memory-factchecktools.sh
index dc029be9..51c4171d 100755
--- a/tests/e2e/pay-memory-factchecktools.sh
+++ b/tests/e2e/pay-memory-factchecktools.sh
@@ -110,7 +110,7 @@ bun run "$ROOT/src/cli/main.ts" capture-asset \
--title "Fact-check claims: $QUERY" \
--service "solana-foundation/google/factchecktools" \
--result-url "${RESULT_URL:-https://factchecktools.google.com/}" \
- --source-receipt "AI Wiki/payments/$DATE/factcheck-${ENCODED_QUERY//+/-}.md" \
+ --source-receipt "Brain/payments/$DATE/factcheck-${ENCODED_QUERY//+/-}.md" \
--slug "factcheck-${ENCODED_QUERY//+/-}"
echo
@@ -123,7 +123,7 @@ bun run "$ROOT/src/cli/main.ts" payment-report \
echo
echo "==> generated files"
-find "$VAULT/AI Wiki" -type f | sort
+find "$VAULT/Brain/payments" -type f | sort
echo
echo "==> done: vault preserved at $VAULT"
diff --git a/tests/e2e/pay-memory-mainnet-places.sh b/tests/e2e/pay-memory-mainnet-places.sh
index fbc82c50..802650e7 100755
--- a/tests/e2e/pay-memory-mainnet-places.sh
+++ b/tests/e2e/pay-memory-mainnet-places.sh
@@ -153,7 +153,7 @@ bun run "$ROOT/src/cli/main.ts" capture-asset \
--title "Places searchText: $QUERY" \
--service "solana-foundation/google/places" \
--result-url "${ENDPOINT}" \
- --source-receipt "AI Wiki/payments/$DATE/$SLUG.md" \
+ --source-receipt "Brain/payments/$DATE/$SLUG.md" \
--slug "$SLUG"
echo
@@ -166,7 +166,7 @@ bun run "$ROOT/src/cli/main.ts" payment-report \
echo
echo "==> generated files"
-find "$VAULT/AI Wiki" -type f | sort
+find "$VAULT/Brain/payments" -type f | sort
echo
echo "==> done: vault preserved at $VAULT"
diff --git a/tests/e2e/pay-memory-sandbox.sh b/tests/e2e/pay-memory-sandbox.sh
index 8f93dda5..eb87310d 100755
--- a/tests/e2e/pay-memory-sandbox.sh
+++ b/tests/e2e/pay-memory-sandbox.sh
@@ -97,7 +97,7 @@ bun run "$ROOT/src/cli/main.ts" capture-asset \
--title "AAPL Quote (sandbox)" \
--service "debugger.pay.sh/mpp" \
--result-url "https://debugger.pay.sh/mpp/quote/AAPL" \
- --source-receipt "AI Wiki/payments/$DATE/aapl-quote-sandbox.md" \
+ --source-receipt "Brain/payments/$DATE/aapl-quote-sandbox.md" \
--slug "aapl-quote-sandbox"
echo
@@ -110,7 +110,7 @@ bun run "$ROOT/src/cli/main.ts" payment-report \
echo
echo "==> generated files"
-find "$VAULT/AI Wiki" -type f | sort
+find "$VAULT/Brain/payments" -type f | sort
echo
echo "==> done: vault preserved at $VAULT"
diff --git a/tests/helpers/concurrent-append-runner.ts b/tests/helpers/concurrent-append-runner.ts
deleted file mode 100644
index 6c3308a4..00000000
--- a/tests/helpers/concurrent-append-runner.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Test helper: append a single event from a subprocess. Used by the
- * concurrent-append test to exercise cross-process locking. Argv:
- * <vault> <index>
- */
-
-import { appendEvent } from "../../src/core/event-log.ts";
-
-const [, , vault, indexStr] = process.argv;
-if (!vault || indexStr === undefined) {
- process.stderr.write("usage: <vault> <index>\n");
- process.exit(2);
-}
-const index = Number.parseInt(indexStr, 10);
-if (!Number.isFinite(index)) {
- process.stderr.write(`error: <index> must be a finite number, got ${JSON.stringify(indexStr)}\n`);
- process.exit(2);
-}
-const time = `10:${String(index).padStart(2, "0")}`;
-
-await appendEvent(vault, "worker", `entry ${index}`, { date: "2026.05.06", time });
diff --git a/tests/helpers/fixtures.ts b/tests/helpers/fixtures.ts
index fe60c969..f4c94867 100644
--- a/tests/helpers/fixtures.ts
+++ b/tests/helpers/fixtures.ts
@@ -6,16 +6,20 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
+import {
+ BRAIN_MANUAL_FILE,
+ BRAIN_ROOT_REL,
+} from "../../src/core/brain/paths.ts";
+
export function createSandboxVault(root: string, name = "Sandbox Brain"): string {
const vault = join(root, "sandbox-vault");
- mkdirSync(join(vault, "AI Wiki"), { recursive: true });
- mkdirSync(join(vault, "Daily"), { recursive: true });
+ mkdirSync(join(vault, BRAIN_ROOT_REL), { recursive: true });
writeFileSync(
- join(vault, "AI Wiki", "_OPEN_SECOND_BRAIN.md"),
+ join(vault, BRAIN_ROOT_REL, BRAIN_MANUAL_FILE),
`---\ntitle: ${name}\ntype: operating-manual\n---\n\n# ${name}\n`,
);
writeFileSync(
- join(vault, "AI Wiki", "Concept.md"),
+ join(vault, "Concept.md"),
"---\ntitle: Sandbox Concept\n---\n\nLinked to [[Other]].\n",
);
writeFileSync(join(vault, "Other.md"), "# Other\n");
diff --git a/tests/mcp/link-graph-mcp-fields.test.ts b/tests/mcp/link-graph-mcp-fields.test.ts
index 97fd5889..cccd20bc 100644
--- a/tests/mcp/link-graph-mcp-fields.test.ts
+++ b/tests/mcp/link-graph-mcp-fields.test.ts
@@ -95,13 +95,29 @@ async function callTool(
}) as Promise<{ result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: { code: number; message: string } }>;
}
+const DERIVED_KEYS = new Set([
+ "status",
+ "applied_count",
+ "violated_count",
+ "last_evidence_at",
+ "confidence",
+ "confidence_value",
+ "evidenced_by",
+ "contradicted_by",
+ "lifecycle",
+ "confirmed_at",
+]);
+
function writePref(
slug: string,
frontmatter: Record<string, string>,
body = "",
): void {
const lines = ["---"];
- for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);
+ for (const [k, v] of Object.entries(frontmatter)) {
+ const key = DERIVED_KEYS.has(k) ? `_${k}` : k;
+ lines.push(`${key}: ${v}`);
+ }
lines.push("---", "", body);
writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), lines.join("\n"));
}
diff --git a/tests/mcp/pay-memory.test.ts b/tests/mcp/pay-memory.test.ts
index 6cfa3386..7ca82f51 100644
--- a/tests/mcp/pay-memory.test.ts
+++ b/tests/mcp/pay-memory.test.ts
@@ -5,6 +5,17 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import {
+ PAY_MEMORY_ASSETS_REL,
+ PAY_MEMORY_DRAFTS_REL,
+ PAY_MEMORY_PENDING_REL,
+ PAY_MEMORY_POLICIES_REL,
+ PAY_MEMORY_REPORTS_REL,
+ PAY_MEMORY_ROOT_REL,
+ PAY_MEMORY_SPENDING_JSON_REL,
+ PAY_MEMORY_SPENDING_MD_REL,
+} from "../../src/core/pay-memory/paths.ts";
+
let tmp: string;
let vault: string;
const savedEnv: Record<string, string | undefined> = {};
@@ -57,11 +68,13 @@ describe("payment_memory_init", () => {
const r = await call(server, "payment_memory_init");
expect(r.result.isError).toBe(false);
const s = r.result.structuredContent;
- expect(s.policy_path).toBe("AI Wiki/policies/spending.md");
+ expect(s.policy_path).toBe("Brain/payments/policies/spending.md");
expect(s.policy_status).toBe("created");
- expect(s.created).toContain("AI Wiki/policies");
- for (const sub of ["policies", "payments", "assets", "drafts", "reports"]) {
- expect(existsSync(join(vault, "AI Wiki", sub))).toBe(true);
+ expect(s.created).toContain("Brain/payments/policies");
+ // Receipts go DIRECTLY under Brain/payments/ (no nested payments subdir).
+ expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL))).toBe(true);
+ for (const sub of ["policies", "assets", "drafts", "reports"]) {
+ expect(existsSync(join(vault, "Brain", "payments", sub))).toBe(true);
}
});
@@ -95,14 +108,14 @@ describe("payment_receipt_append", () => {
actual_amount: "0.05",
currency: "USDC",
result_ref: "https://fal-cdn.example/img.png",
- result_note: "AI Wiki/assets/blog-header.md",
+ result_note: "Brain/payments/assets/blog-header.md",
raw_output: 'Authorization: Bearer SECRET\n{"api_key": "sk_live_abc"}',
date: "2026-05-10",
time: "17:20",
});
expect(r.result.isError).toBe(false);
const s = r.result.structuredContent;
- expect(s.path.startsWith("AI Wiki/payments/2026-05-10/")).toBe(true);
+ expect(s.path.startsWith("Brain/payments/2026-05-10/")).toBe(true);
expect(s.date).toBe("2026-05-10");
expect(s.created).toBe("2026-05-10T17:20:00Z");
const text = readFileSync(join(vault, s.path), "utf8");
@@ -155,15 +168,15 @@ describe("asset_capture", () => {
title: "Blog Header: Pay Memory",
service: "paysponge/fal",
result_url: "https://fal-cdn.example/img.png",
- source_receipt: "AI Wiki/payments/2026-05-10/fal-blog.md",
+ source_receipt: "Brain/payments/2026-05-10/fal-blog.md",
prompt: "A recursive technical illustration",
- used_in: "AI Wiki/drafts/blog-post.md",
+ used_in: "Brain/payments/drafts/blog-post.md",
});
expect(r.result.isError).toBe(false);
const s = r.result.structuredContent;
const text = readFileSync(join(vault, s.path), "utf8");
expect(text).toContain("# Blog Header: Pay Memory");
- expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');
+ expect(text).toContain('source_receipt: "[[Brain/payments/2026-05-10/fal-blog]]"');
expect(text).toContain("> A recursive technical illustration");
});
});
@@ -228,7 +241,7 @@ describe("payment_policy_check", () => {
await call(server, "payment_memory_init");
const { writeFileSync } = await import("node:fs");
writeFileSync(
- join(vault, "AI Wiki", "policies", "spending.json"),
+ join(vault, PAY_MEMORY_SPENDING_JSON_REL),
JSON.stringify({ allowed_services: ["paysponge/fal"] }),
"utf8",
);
@@ -279,7 +292,7 @@ describe("approval workflow MCP tools", () => {
const s = r.result.structuredContent;
expect(s.id).toBe("mcp-1");
expect(s.status).toBe("pending");
- expect(s.path).toBe("AI Wiki/payments/_pending/mcp-1.md");
+ expect(s.path).toBe("Brain/payments/_pending/mcp-1.md");
});
test("payment_request_status surfaces metadata", async () => {
@@ -309,7 +322,7 @@ describe("approval workflow MCP tools", () => {
});
const r = await call(server, "payment_request_consume", {
id: "mcp-3",
- receipt: "AI Wiki/payments/2026-05-10/x.md",
+ receipt: "Brain/payments/2026-05-10/x.md",
});
expect(r.result.isError).toBe(true);
expect((r.result.content[0] as { text: string }).text).toContain("cannot transition");
diff --git a/tests/mcp/resources.test.ts b/tests/mcp/resources.test.ts
index e13db859..114b2533 100644
--- a/tests/mcp/resources.test.ts
+++ b/tests/mcp/resources.test.ts
@@ -248,7 +248,7 @@ describe("MCP resources — read osb://preference/{id}", () => {
`---
kind: brain-retired
id: ret-old-thing
-status: retired
+_status: retired
retired_at: 2026-05-10T00:00:00Z
retired_reason: rebutted
retired_by: "[[Brain/log/2026-05-10]]"
@@ -256,11 +256,11 @@ created_at: 2026-05-01T00:00:00Z
tags: [brain, brain/retired]
topic: old-thing
principle: A stale rule
-evidenced_by: []
-applied_count: 0
-violated_count: 0
-last_evidence_at: null
-confidence: low
+_evidenced_by: []
+_applied_count: 0
+_violated_count: 0
+_last_evidence_at: null
+_confidence: low
pinned: false
---
@@ -376,41 +376,6 @@ describe("MCP resources — read osb://status", () => {
expect(text).toContain("## Activity");
});
- test("file with both 'status:' and '_status:' counts as unknown (collision policy)", async () => {
- // Hand-write a file carrying both shapes — same collision policy
- // as parsePreference / brain_doctor, so the status reader must
- // not silently pick one and hide the corruption.
- const path = `${vault}/Brain/preferences/pref-double-shape.md`;
- const { writeFileSync } = await import("node:fs");
- writeFileSync(
- path,
- [
- "---",
- "kind: brain-preference",
- "id: pref-double-shape",
- "created_at: 2026-05-01T00:00:00Z",
- "unconfirmed_until: 2026-05-30T00:00:00Z",
- "tags: [brain, brain/preference, brain/topic/double]",
- "topic: double",
- "principle: Rule",
- "pinned: false",
- "status: confirmed",
- "_status: confirmed",
- "evidenced_by: []",
- "---",
- "",
- ].join("\n"),
- "utf8",
- );
-
- const server = makeServer();
- await initialize(server);
- const r = await read(server, "osb://status");
- const text = r.result.contents[0].text as string;
- expect(text).toContain("preferences: 1");
- expect(text).toContain("unknown: 1");
- expect(text).not.toContain("confirmed: 1");
- });
});
describe("MCP resources — read osb://backlinks/{id}", () => {