Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

v0.10.4: Brain onboarding quality β€” protect, per-runtime identity templates, starter bundle

Sol Aitken2056c4ade718
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index b79bc035..bb8deadc 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.3",
+ "version": "0.10.4",
"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 95b6d136..d4ca5b55 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.3",
+ "version": "0.10.4",
"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 eb60a9ce..9712ee7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,59 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.10.4] - 2026-05-17
+
+Brings the v0.10.4 "Brain onboarding quality" cluster from
+`Projects/OpenSecondBrain/Features/_summary`: Β§18 machine-enforced
+write protection for `Brain/`, Β§4 partial (per-runtime identity
+reminder templates for the two runtimes that actually call
+`buildReminder` per-turn / per-action), and Β§15 partial (bundled
+starter set behind `o2b brain init --starter`).
+
+No vault migration is required. Existing vaults are unaffected
+until the operator opts in by running `o2b brain protect`,
+appending `--starter` to a fresh `o2b brain init`, or setting
+`O2B_TARGET=hermes` or `O2B_TARGET=openclaw` in the MCP server's
+env block. The common identity reminder template is unchanged.
+
+### Added
+
+- Β§18 β€” `o2b brain protect --target {claudecode|codex}` writes a
+ managed, idempotent block into the runtime's native permissions
+ config that denies writes to `Brain/preferences/`, `retired/`,
+ `log/`, `.snapshots/`, and `_brain.yaml` while leaving
+ `Brain/inbox/` writable. `--print` (default) emits the snippet
+ to stdout; `--apply` writes the file and saves a `.bak.<ts>`
+ beside it. Pair `o2b brain unprotect` removes only the OSB-owned
+ entries (tracked via the sidecar manifest
+ `<vault>/.open-second-brain/protect.lock.json`).
+- Β§4 (partial) β€” per-runtime identity reminder templates at
+ `templates/identity-reminder.{hermes,openclaw}.txt`. The resolver
+ in `buildReminder` accepts an explicit `target`, falls back to
+ `O2B_TARGET`, and finally to the common template. Hermes Python
+ shim has byte-level parity with the TypeScript resolver through
+ a shared fixture. The common `identity-reminder.txt` is
+ unchanged. Claude Code and Codex steer through
+ `hooks/lib/messages.ts`, which is a different mechanism not
+ addressed here β€” tracked under design doc D5.
+- Β§15 (partial) β€” `o2b brain init --starter` drops a bundled
+ example set (8 preferences, 3 retired, 1 inbox signal, 6 log
+ days) into a fresh Brain. The bundle is regenerated through the
+ canonical writers (`writePreference`, `appendApplyEvidence`,
+ `moveToRetired`, `dream`) so its shape never drifts from real
+ vault output. Doctor-clean and a no-op under
+ `o2b brain dream`. Refuses to run on a non-empty Brain.
+
+### Deferred
+
+Full multi-runtime `o2b install` orchestrator (Β§4 second half),
+interactive `o2b init --interactive` wizard (Β§15 second half),
+per-runtime steering text for Claude Code / Codex in
+`hooks/lib/messages.ts`, and the `brain-memory` SKILL "good-vs-bad"
+examples section. Triggers to revisit are recorded in the vault
+summary's "Deferred work" section
+(`Projects/OpenSecondBrain/Features/_summary.md`).
+
## [0.10.3] - 2026-05-17
Brings four Tier-A items from
@@ -1521,6 +1574,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.10.4]: https://github.com/itechmeat/open-second-brain/compare/v0.10.3...v0.10.4
[0.10.3]: https://github.com/itechmeat/open-second-brain/compare/v0.10.2...v0.10.3
[0.10.2]: https://github.com/itechmeat/open-second-brain/compare/v0.10.1...v0.10.2
[0.10.1]: https://github.com/itechmeat/open-second-brain/compare/v0.10.0...v0.10.1
diff --git a/README.md b/README.md
index 6f168938..b0312f28 100644
--- a/README.md
+++ b/README.md
@@ -116,16 +116,18 @@ 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
-# Brain (observing memory β€” 14 verbs)
-o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md
+# 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 digest Render a Markdown or JSON summary of recent Brain transitions
o2b brain query Read helper: by preference, by topic, or by log timestamp
-o2b brain reject (CLI-only) Move a preference to retired/ with reason: user-rejected
+o2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.
o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)
o2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain/_brain.yaml (--clear)
+o2b brain protect (CLI-only) Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
+o2b brain unprotect (CLI-only) Remove the OSB-managed deny rules for the chosen target
o2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/
o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot (--dry-run previews)
o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, …)
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 6cd4f3a2..e5afce45 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -356,8 +356,9 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic |
| Manage search index | `o2b search index \| reindex \| status \| check` | β€” (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite` |
| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |
-| Retire manually | `o2b brain reject` | β€” (CLI-only) | moves pref β†’ retired/ |
+| Retire manually | `o2b brain reject` | β€” (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |
| Toggle pin | `o2b brain pin / unpin` | β€” (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |
+| Protect Brain/ | `o2b brain protect / unprotect` | β€” (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |
| Restore snapshot | `o2b brain rollback` | β€” (CLI-only) | overwrites Brain/ from snapshot |
Operations that change the **protected set** (`pin`, `unpin`,
diff --git a/docs/plans/2026-05-17-brain-onboarding-quality-design.md b/docs/plans/2026-05-17-brain-onboarding-quality-design.md
new file mode 100644
index 00000000..804bc546
--- /dev/null
+++ b/docs/plans/2026-05-17-brain-onboarding-quality-design.md
@@ -0,0 +1,306 @@
+# v0.10.4 β€” Brain onboarding quality
+
+Status: draft
+Owners: TBD
+Source: `/root/vault/Projects/OpenSecondBrain/Features/_summary.md` Β§4 (partial), Β§15 (partial), Β§18
+
+## Context
+
+The Open Second Brain features summary identifies an "onboarding quality" cluster of work that lowers the cost of bringing a new vault, a new runtime, or a new contributor online. This design covers three items from that cluster β€” the protect-Brain mechanic (Β§18) and the first halves of the per-target identity reminder family (Β§4) and the starter-bundle (Β§15). The second halves of Β§4 (full multi-runtime installer with config autodetect and steering shims) and Β§15 (interactive `o2b init` wizard) are intentionally **deferred** β€” see *Goals / non-goals* below for why.
+
+The three items ship in **one PR**, under a single `v0.10.4` CHANGELOG entry. They share the same surface (runtime adapters), the same documentation pages (`install.md` branches), and the same review concerns (idempotency, no-LLM, no-network). Splitting them into three PRs would triple `install.md` churn for no engineering gain.
+
+## Goals
+
+- **G1.** Machine-enforced write protection for `Brain/preferences/`, `Brain/retired/`, `Brain/log/`, `Brain/.snapshots/` against Claude Code and Codex agents, via each runtime's native permission mechanism. `Brain/inbox/` stays writable (agents legitimately drop signals there through `brain_feedback`).
+- **G2.** Per-runtime identity reminder templates for the two runtimes that actually call `buildReminder` per-turn / per-action: **Hermes** (Python shim, per `pre_llm_call` hook) and **OpenClaw** (native JS plugin, per `before_prompt_build` hook). The current common template stays as a fallback β€” back-compat is unconditional. Claude Code and Codex are explicitly **out of scope here** β€” their per-tool-call steering lives in `hooks/lib/messages.ts:postWriteReminder`, which is a different mechanism (post-write hook reminder, not per-turn identity injection). Adding per-target text for those two requires touching `hooks/lib/messages.ts` and is tracked under deferred work.
+- **G3.** A bundled starter pack β€” 8 confirmed preferences (mixed confidence, scope, pinned), 3 retired (mixed retire reasons), 1 inbox signal, 6 log days β€” that `o2b brain init --starter` drops into a fresh vault. The pack doubles as a "this is how a healthy Brain looks" reference for both humans and onboarding agents.
+
+## Non-goals (explicitly deferred)
+
+- **D1 β€” full `o2b install` orchestrator.** The single-command, autodetect-the-config, idempotent-managed-block, parsed-back-out-by-uninstall, supports-all-known-runtimes installer that Β§4 envisions is *not* part of this design. Trigger to revisit: β‰₯3 onboarding complaints from non-primary users, OR a request for a runtime not in {hermes, claudecode, codex, openclaw}.
+- **D2 β€” multi-tool steering shims.** Per-target shim files in `~/.cursor/skills/`, `~/.kiro/`, `~/.aider/`, etc., that point at the canonical `brain-memory` skill (Β§4, [[memoria]]). Deferred behind D1 β€” the shim infrastructure is a sub-feature of the installer.
+- **D3 β€” interactive `o2b init --interactive` wizard.** The wizard logically wraps the installer (it has to register runtime configs to be useful); building it before D1 produces a survey with no follow-through. Trigger to revisit: after D1 ships.
+- **D4 β€” "good vs bad" SKILL section.** The contrastive 3–5 pairs of well-/poorly-formed `principle` / `topic` / `note` examples (Β§15, [[megamemory]] Β§3). The starter-bundle files themselves are reference material; we add the SKILL section if onboarding feedback shows the starter pack alone is insufficient.
+- **D5 β€” per-runtime hook reminder text for Claude Code and Codex.** Both runtimes deliver their post-Write steering through `hooks/lib/messages.ts:postWriteReminder` (single universal string today), not through `buildReminder`. Adding per-runtime cadence text there is a separate mechanism with separate test coverage. Trigger to revisit: observable difference in how Claude Code vs Codex sessions miss `brain_feedback` calls, OR a request to differentiate the post-write nudge per runtime.
+
+The deferred items are also recorded in the vault summary under a new "Deferred work" section so they survive across planning sessions.
+
+## Β§18 β€” `o2b brain protect` / `o2b brain unprotect`
+
+### Surface
+
+```
+o2b brain protect --target {claudecode|codex} [--vault <path>] [--apply | --print]
+o2b brain unprotect --target {claudecode|codex} [--vault <path>]
+```
+
+- `--print` (default) writes the rendered snippet to stdout and exits 0. No filesystem writes.
+- `--apply` idempotently patches the target's config file. Re-running is a no-op if the managed block is already current; if the OSB-managed block is present but stale, it is replaced in place. User-authored content outside the block is preserved byte-for-byte.
+- `unprotect` removes the managed block (`--print` shows what would be removed; `--apply` removes it). If the block is absent, exits 0 with a one-line "not present" notice.
+- `--vault <path>` overrides the configured vault (the machine config is the default source).
+
+### Targets and their native mechanisms
+
+| Target | Config file | Mechanism |
+|---|---|---|
+| `claudecode` | `<vault>/.claude/settings.json` (project scope) | `permissions.deny: ["Write(<vault>/Brain/preferences/**)", "Edit(<vault>/Brain/preferences/**)", … ]` |
+| `codex` | `~/.codex/config.toml` (user scope) | `[permissions.osb_protected.filesystem]` block with `":project_roots" = { "Brain/preferences/**" = "none", … }` plus `default_permissions = "osb_protected"` |
+
+Project-scope `.claude/settings.json` is chosen over user-scope `~/.claude/settings.json` because the vault is unique per host; a user-scope deny would forbid writes globally and break work in other projects. Project scope applies only when Claude Code runs from inside the vault.
+
+Codex does not support a project-scope `.codex/config.toml` matching the Claude Code shape, so `osb_protected` lives at user scope. The glob patterns are vault-relative; if the user has multiple vaults, each vault adds its own entries to the same profile (the patterns simply accumulate β€” Codex evaluates them all).
+
+### Managed-block markers
+
+The patch is fenced so `unprotect` can remove exactly what `protect` added, and re-runs of `--apply` are byte-identical (idempotency).
+
+- **TOML (Codex):** standard `# >>> open-second-brain managed >>>` and `# <<< open-second-brain managed <<<` line comments enclosing the OSB block. Outside-block content is untouched on re-run; inside-block content is regenerated each `--apply`.
+- **JSON (Claude Code):** `settings.json` rejects line comments, so the line-comment fence used for TOML does not transfer. Instead, a sidecar manifest `<vault>/.open-second-brain/protect.lock.json` lists the `permissions.deny` / `permissions.allow` entries OSB owns. `unprotect` consults the manifest to know which entries to remove; the manifest is rebuilt on every `--apply`. The user can read the manifest to see what we changed.
+
+### Rule set (both targets)
+
+The same six logical rules, rendered into each target's syntax:
+
+1. Deny `Write` / `Edit` under `<vault>/Brain/preferences/**`.
+2. Deny `Write` / `Edit` under `<vault>/Brain/retired/**`.
+3. Deny `Write` / `Edit` under `<vault>/Brain/log/**`.
+4. Deny `Write` / `Edit` under `<vault>/Brain/.snapshots/**`.
+5. Deny `Write` / `Edit` on `<vault>/Brain/_brain.yaml`.
+6. Allow `Write` under `<vault>/Brain/inbox/**` (explicit allow to override any broader deny the user may have).
+
+For Codex, the same six rules are expressed as `"<path-glob>" = "none"` (for denies) and `"Brain/inbox/**" = "write"`. The leading `":project_roots"` block tells Codex the patterns are vault-relative.
+
+### Pre-apply safety
+
+- `--apply` refuses to overwrite a target config that has an OSB-managed block from a *newer* schema than the current binary knows about. The block carries a `schema_version` line; mismatch on `--apply` exits with an error suggesting `o2b update` or `--print` (so the user can compare).
+- `--apply` writes a sibling backup `<file>.bak.<unix-ts>` before mutating. Backups are not pruned automatically β€” the user owns config history.
+- The vault must be initialised (`<vault>/Brain/` must exist). `protect` against an unbootstrapped vault exits with an error pointing at `o2b brain init`.
+
+### Tests
+
+- Unit: rule renderer produces stable byte output for both targets, given a fixed vault path.
+- Unit: marker parser correctly extracts an existing managed block (both TOML line-comment and JSON-via-manifest), preserves outside-block content on re-render.
+- Integration: round-trip `protect --apply` β†’ `unprotect --apply` β†’ `protect --apply` leaves the config bytewise equal to the first `--apply` result.
+- Integration: `--print` and `--apply` produce the same logical content (`--apply` then `diff` against `--print` stripped of file headers).
+- E2E (skipped on CI, manual): on a real Claude Code project, `protect --apply` followed by an attempt to `Edit Brain/preferences/pref-X.md` from inside Claude Code is blocked by the runtime's permission check.
+
+### Files touched
+
+- New: `src/core/brain/protect.ts` (rule renderer + apply/unprotect for both targets + manifest read/write).
+- New: `src/cli/brain-protect.ts` (CLI surface; argparse glue).
+- Modify: `src/cli/brain.ts` (wire the two new subcommands).
+- New: `tests/core/brain/protect.test.ts`, `tests/cli/brain-protect.test.ts`.
+- Modify: `install.md` (add a "Step 5b β€” optional `o2b brain protect`" note to branches A, C, D, E β€” i.e. all branches whose runtime is one of the two supported targets, plus generic).
+
+## Β§4 (partial) β€” per-runtime identity reminder templates
+
+### Scope correction
+
+The first draft of this section listed four targets (`hermes`, `claudecode`, `codex`, `openclaw`). Cross-checking call sites of `buildReminder` shows it is exercised on a per-turn / per-action basis by only two runtimes:
+
+- **OpenClaw** β€” native JS plugin, calls `buildReminder` from `src/openclaw/index.ts` inside the `before_prompt_build` hook.
+- **Hermes** β€” Python shim (`plugins/hermes/__init__.py`) reads `templates/identity-reminder.txt` directly inside the `pre_llm_call` hook.
+
+For **Claude Code** and **Codex**, the per-tool-call steering text is owned by `hooks/lib/messages.ts:postWriteReminder` and ships as a single universal string. Adding per-runtime cadence text for those two means editing `messages.ts`, which is a different mechanism (post-write reminder) with different tests. Shipping `identity-reminder.claudecode.txt` and `identity-reminder.codex.txt` files that no runtime currently reads would be a misleading fallback β€” an inspector would find their target's filename in `templates/` and assume the runtime uses it. Excluded here, tracked in D5.
+
+### File layout
+
+```
+templates/
+ identity-reminder.txt # common fallback (existing, unchanged)
+ identity-reminder.hermes.txt # NEW β€” short multi-turn
+ identity-reminder.openclaw.txt # NEW β€” in-process plugin
+```
+
+Each file is plain text with a single `{agent}` placeholder, matching the current contract. No new template syntax β€” the renderer remains `replace(/\{agent\}/g, …)`.
+
+### Resolver
+
+`src/core/identity-reminder.ts` gains:
+
+```ts
+export const KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"] as const;
+export type RuntimeTarget = (typeof KNOWN_RUNTIME_TARGETS)[number];
+
+export function buildReminder(agent: string, target?: RuntimeTarget): string;
+```
+
+Resolution order:
+
+1. Explicit `target` parameter β†’ `identity-reminder.<target>.txt` if present, else common fallback.
+2. `target` omitted β†’ `process.env.O2B_TARGET` (if it is one of the known values) β†’ same lookup.
+3. Neither β†’ common `identity-reminder.txt` (current behaviour, preserves call sites that have not been updated).
+
+Unknown / malformed env value: logged once to stderr, treated as `undefined`. We do not silently coerce β€” an unknown target points at either a typo or a missing template, both of which a future contributor should see.
+
+### Template content (drafts)
+
+Both templates target ~5–7 lines, share the leading clause from the common template, and add a runtime-specific cadence note.
+
+- **hermes.txt:** "Identity: @{agent}. After every durable artifact this turn β€” call `event_log_append`. Hermes turns are short; do not batch the log calls across turns."
+- **openclaw.txt:** "Identity: @{agent}. After every durable in-process action β€” call `event_log_append`. OpenClaw has no session boundary; log immediately."
+
+Each adds the same "Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact." closing line from the common template, so the *what counts as durable* contract is identical across targets.
+
+Finalised text lands in the PR; the drafts above are the design-time skeleton.
+
+### Wiring
+
+- `src/openclaw/index.ts` β€” passes `target: "openclaw"` to `buildReminder`. No env dependency.
+- `plugins/hermes/__init__.py` β€” Python shim mirrors the TS resolver: reads `templates/identity-reminder.hermes.txt` when the file exists, otherwise falls back to `identity-reminder.txt`. The Python and TS resolvers must produce identical text given the same inputs; a fixture test pinned across both languages enforces this.
+
+The MCP server (`src/mcp/instructions.ts`) does **not** route through `buildReminder` β€” its `initialize.instructions` payload is independent prose describing the Brain tool surface. No changes there.
+
+### Tests
+
+- Unit (TS): both `RuntimeTarget` values resolve to the correct file; explicit param beats env; unknown env value warns + falls back; missing per-target file falls back without warning (file-not-present is a valid state for a partially-deployed template set).
+- Unit (Python): hermes-only matrix on the shim.
+- Fixture parity: `tests/fixtures/identity-reminder/{hermes,openclaw}.txt` records the expected output for `agent="test-agent"`; the TS test asserts both and the Python test asserts hermes against the same fixture bytes.
+
+### Files touched
+
+- New: `templates/identity-reminder.{hermes,openclaw}.txt`.
+- Modify: `src/core/identity-reminder.ts` (resolver + `RuntimeTarget` type).
+- Modify: `src/openclaw/index.ts` (call site).
+- Modify: `plugins/hermes/__init__.py` (Python parity).
+- New: `tests/fixtures/identity-reminder/{hermes,openclaw}.txt`.
+- Modify: `tests/core/identity-reminder.test.ts`, `tests/python/test_hermes_plugin.py`.
+
+`install.md` is **not** touched by Β§4 β€” the new templates plug into Hermes and OpenClaw automatically (Hermes shim auto-detects via the constant target, OpenClaw call site is hard-coded).
+
+## Β§15 (partial) β€” starter bundle
+
+### Bundle layout (in repo)
+
+```
+templates/
+ brain-starter/
+ preferences/
+ pref-imperative-commit-messages.md # confirmed, high, scope=process
+ pref-no-unexplained-abbreviations.md # confirmed, high, scope=writing, pinned
+ pref-prefer-typed-errors.md # confirmed, medium, scope=coding
+ pref-explicit-imports-only.md # confirmed, medium, scope=coding
+ pref-changelog-every-release.md # confirmed, high, scope=process
+ pref-russian-in-chat.md # confirmed, low, scope=writing
+ pref-test-before-refactor.md # unconfirmed (trial window open), scope=coding
+ pref-prefer-bun-over-npx.md # confirmed, low, scope=infra
+ retired/
+ ret-tabs-over-spaces.md # user_rejected_reason: "mixed allowed"
+ ret-no-emojis-in-code.md # rebutted: 5 contradictory signals
+ ret-prefer-curl-over-wget.md # stale-no-evidence (60 days)
+ inbox/
+ sig-2026-05-10-strict-types.md # one pending signal
+ log/
+ 2026-05-12.md # apply-evidence events (multiple)
+ 2026-05-13.md # apply-evidence events
+ 2026-05-14.md # apply-evidence events
+ 2026-05-15.md # apply-evidence events + retire events
+ 2026-05-16.md # apply-evidence events + retire event
+ 2026-05-17.md # dream summary at the bundle's fixed `now`
+```
+
+Each file is produced through the canonical writers (`writePreference`, `appendApplyEvidence`, `moveToRetired`, `dream`) by a one-off generator run, then committed verbatim. The bundle ships in the post-dream steady state at a fixed `now = 2026-05-17T12:00:00Z`, so a second `dream` run at the same `now` is a byte-identical no-op. Files reference each other through stable wikilinks (signals β†’ preferences, retired β†’ preferences via `supersedes:`, log entries β†’ preferences); the doctor lint pass on the assembled bundle must be clean.
+
+Apply-evidence headings within one log day are spaced 5 minutes apart through a shared per-day counter, so each `## HH:MM:SSZ β€” apply-evidence` heading is unique (markdownlint MD024).
+
+Frontmatter dates are baked at template-author time β€” they do not move forward, because the bundle is a *demonstration*, not a *live state*. The unconfirmed preference is dated so its `unconfirmed_until` is in the future relative to the fixed `now`; the user will see `unconfirmed_until: 2026-05-25` and understand the trial window concept by inspection.
+
+### CLI
+
+```
+o2b brain init [--starter] [--starter-path <dir>]
+```
+
+- Without `--starter` β€” existing behaviour (directories, `_brain.yaml`, `_BRAIN.md`, legacy overview).
+- With `--starter` β€” after the existing init steps run successfully, copy `templates/brain-starter/**` into `<vault>/Brain/`.
+- `--starter-path <dir>` β€” override the source directory. Defers user-authored starter packs without committing to a starter registry / marketplace. Useful for teams who want a house style starter.
+
+### Collision policy
+
+`--starter` refuses to copy if any of `Brain/preferences/`, `Brain/retired/`, `Brain/inbox/`, `Brain/log/` is non-empty. The check runs before any file is written; if it fails, exit code is 2 (vs 1 for a generic init failure), and the message is:
+
+```
+Brain/ already has content β€” `--starter` is intended for fresh vaults.
+Inspect the bundle at <repo>/templates/brain-starter/ and copy individual
+files manually if you want to backfill a non-empty Brain.
+```
+
+The check is symmetric across all four subdirs: a non-empty `log/` is as much a "this Brain is in use" signal as a non-empty `preferences/`, and we refuse on either.
+
+### Tests
+
+- Unit: starter copy on an empty Brain produces exactly the manifest listed above.
+- Unit: starter on a Brain with one preference file exits with code 2 and the message above; no files are written.
+- Smoke: `o2b brain doctor` on the assembled starter passes with no warnings. This is also a CI gate β€” the starter must never contain a malformed link or out-of-range value (treating the starter as a frozen test fixture).
+- Smoke: `o2b brain dream --now 2026-05-17T12:00:00Z` on the starter is a no-op (the one unconfirmed preference's trial window has not expired at the pinned `--now`, and no apply-evidence is recent enough to refresh counters past their starter values).
+
+### Files touched
+
+- New: `templates/brain-starter/**` (18 bundled Markdown files β€” 8 preferences, 3 retired, 1 inbox signal, 6 log days produced by an authentic dream-pass over the seed data).
+- Modify: `src/core/brain/init.ts` β€” add `starter: boolean` and `starterPath?: string` options; new helper `copyStarterBundle`.
+- Modify: `src/cli/brain.ts` β€” surface the two flags.
+- New: `tests/core/brain/starter.test.ts`.
+- Modify: `install.md` β€” `o2b brain init` step description in all five branches gets a one-line "or `o2b brain init --starter` if you want example preferences to learn the shape" addition.
+
+## Test plan summary
+
+Cross-feature checks beyond the per-feature tests above:
+
+- **Doctor cleanliness.** A fresh vault with `o2b brain init --starter` followed by `o2b brain protect --target claudecode --apply` followed by `o2b brain protect --target codex --apply` passes `o2b brain doctor` and `o2b doctor --repo` (the latter validates that the new templates and the new starter files are well-formed).
+- **Idempotency loops.**
+ - `protect --apply` Γ— 3 β†’ final state byte-identical to first.
+ - `init --starter` on already-populated Brain β†’ no writes, exit 2.
+ - `unprotect --apply` immediately after `protect --apply` β†’ config bytes identical to pre-protect.
+- **No-network invariant.** All three features run with no network calls (verified by running tests with `NODE_OPTIONS=--no-network`-style guard, or β€” failing that β€” by a code-level assertion that none of the new modules import `node:net`, `node:https`, `node:http`, `fetch`, or `node-fetch`).
+- **Cross-language parity (identity reminders only).** TS and Python resolvers produce the same bytes for every (agent, target) pair represented in `tests/fixtures/identity-reminder/`.
+
+## Open questions
+
+1. **Backup file lifecycle for `protect --apply`.** The current proposal writes `<file>.bak.<unix-ts>` and never prunes. Should `protect` accept `--no-backup` for users who pipe these into source control and don't want clutter? Default-on / opt-out is the safer call; flagging here for explicit decision at impl time.
+2. **Codex managed-block uniqueness.** `~/.codex/config.toml` is user-scope. If a user runs `protect --target codex` against vault A and later against vault B, the second run extends the same `[permissions.osb_protected.filesystem]` block with vault-B-relative globs. Question: do we keep one block per host (current proposal), or one block per vault (would require dynamic profile names like `osb_protected_<vault-hash>`)? Recommended answer: one block per host, names of vaults stored as comments in the managed fence. Surface this for review.
+3. **Starter pack i18n.** The bundled preferences mix English and a Russian-language pref (`pref-russian-in-chat`). Question: do we want a `--starter-lang ru` switch that swaps the english-language sample principles for Russian phrasings? Recommended: not in v0.10.4 β€” the user's *real* preferences will land in the language of their actual sessions; starter mixes both intentionally to demonstrate the language-policy from the `brain-memory` skill.
+
+## CHANGELOG entry (draft)
+
+```markdown
+## v0.10.4 β€” Brain onboarding quality
+
+- Β§18 β€” `o2b brain protect --target {claudecode|codex}` writes a managed,
+ idempotent block into the runtime's native permissions config that
+ denies writes to `Brain/preferences/`, `retired/`, `log/`,
+ `.snapshots/`, and `_brain.yaml` while leaving `Brain/inbox/`
+ writable. Pair `o2b brain unprotect` removes the block. `--print`
+ outputs the snippet without touching disk; `--apply` writes and
+ backs up the prior config.
+- Β§4 (partial) β€” per-runtime identity reminder templates for the two
+ runtimes that call `buildReminder` per-turn / per-action:
+ `templates/identity-reminder.{hermes,openclaw}.txt`. Resolver in
+ `buildReminder` accepts an explicit `target`, falls back to
+ `O2B_TARGET`, and finally to the common template. Hermes Python
+ shim has parity. Common `identity-reminder.txt` is unchanged.
+ Claude Code and Codex steer through `hooks/lib/messages.ts`, which
+ is a separate mechanism not addressed here.
+- Β§15 (partial) β€” `o2b brain init --starter` drops a curated bundle of
+ 8 confirmed preferences, 3 retired, 1 inbox signal, and 6 log days
+ into a fresh Brain. The bundle passes `o2b brain doctor` cleanly and
+ is a no-op under `o2b brain dream` at install time. Refuses to run
+ on a non-empty Brain.
+- Deferred: full multi-runtime `o2b install` orchestrator (Β§4 second
+ half), interactive `o2b init --interactive` wizard (Β§15 second
+ half), `brain-memory` SKILL "good-vs-bad" examples section. See
+ vault `Projects/OpenSecondBrain/Features/_summary.md` Deferred work
+ section for triggers to revisit.
+```
+
+## References
+
+- Vault summary: `Projects/OpenSecondBrain/Features/_summary.md` (Β§4, Β§15, Β§18).
+- Claude Code permissions: `permissions.deny` / `permissions.allow` in `settings.json`.
+- Codex permissions: `[permissions.<name>.filesystem]` and `default_permissions` keys, documented at <https://developers.openai.com/codex/config-advanced>.
+- Prior Brain plans for structural reference:
+ `docs/plans/2026-05-17-tier-a-snapshot-confidence-pointer-design.md`,
+ `docs/plans/2026-05-16-brain-search-design.md`.
+- Current identity-reminder source of truth: `templates/identity-reminder.txt`, `src/core/identity-reminder.ts`, `plugins/hermes/__init__.py`.
+- Current init source of truth: `src/core/brain/init.ts`,
+ `src/core/brain/templates/_BRAIN.md.tpl`.
diff --git a/docs/plans/2026-05-17-brain-onboarding-quality-impl.md b/docs/plans/2026-05-17-brain-onboarding-quality-impl.md
new file mode 100644
index 00000000..cafdd7f6
--- /dev/null
+++ b/docs/plans/2026-05-17-brain-onboarding-quality-impl.md
@@ -0,0 +1,2480 @@
+# v0.10.4 Brain onboarding quality β€” Implementation Plan
+
+> **For agentic workers:** Use `superpowers:executing-plans` (or
+> `superpowers:subagent-driven-development` for fresh-context-per-task
+> dispatch) to walk this plan task-by-task. Steps use checkbox
+> (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship Β§18 (`o2b brain protect`), Β§4-partial (per-runtime
+identity-reminder templates) and Β§15-partial (`o2b brain init --starter`)
+from `Projects/OpenSecondBrain/Features/_summary` in one PR.
+
+**Architecture:** Three independent slices land in dependency order.
+Β§4 lands first because its `RuntimeTarget` resolver introduces the
+runtime-naming union that Β§18 reuses (renamed `ProtectTarget` β€” narrower
+membership). Β§18 lands second because it is the largest slice and
+benefits from Β§4 already being on disk for tests that exercise both.
+Β§15 lands last because its starter bundle gates on `o2b brain doctor`
+being green, which means every prior change must be settled.
+
+- **Β§4** lives in `src/core/identity-reminder.ts` (resolver), two new
+ `templates/identity-reminder.<target>.txt` files for the two
+ runtimes that call `buildReminder` (`hermes`, `openclaw`), two
+ call-site sweeps (`src/openclaw/index.ts`, `plugins/hermes/__init__.py`),
+ plus fixtures for TS↔Python parity. Claude Code / Codex per-runtime
+ steering lives in `hooks/lib/messages.ts` (different mechanism)
+ and is deferred β€” see design doc D5.
+- **Β§18** lives entirely in a new module `src/core/brain/protect.ts`
+ plus a CLI surface in `src/cli/brain.ts`. The manifest file
+ (`<vault>/.open-second-brain/protect.lock.json`) is owned by this
+ module and never touched by any other writer.
+- **Β§15** drops a `templates/brain-starter/` tree (18 files β€” 8 prefs, 3 retired, 1 inbox signal, 6 log days), adds a
+ `copyStarterBundle` helper to `src/core/brain/init.ts`, and surfaces
+ two new flags on `o2b brain init`.
+
+**Tech Stack:** TypeScript on Bun. No new external dependencies.
+Re-uses `fs-atomic.ts`, `proper-lockfile` (already in deps),
+`bun:test`, `tsc --noEmit`.
+
+**Source of truth for behaviour:**
+[`docs/plans/2026-05-17-brain-onboarding-quality-design.md`](./2026-05-17-brain-onboarding-quality-design.md).
+Every task below implements a slice of that spec β€” on conflict the
+spec wins and this plan is amended.
+
+---
+
+## Plan-wide conventions
+
+These apply to every task; do not re-state per step.
+
+- **Imports.** Production code uses `node:`-prefixed builtins
+ (`node:fs`, `node:os`, `node:path`). Tests use
+ `import { test, expect, describe, beforeEach, afterEach } from "bun:test"`.
+ Always `.ts` extensions in cross-module imports.
+- **Result shape.** New public-API return values are `Object.freeze`-d
+ at the producing call site (project convention, mirrors
+ `src/core/brain/query.ts`).
+- **Errors.** Reuse existing typed errors when the failure mode
+ matches; create one new typed error `BrainProtectError` for Β§18
+ because its failure shape (target / vault / manifest mismatch) is
+ distinct enough to warrant separate catch handling.
+- **No git from this plan.** Each task ends with **Pause for review
+ (no commit).** Active git is reserved for the user β€” see vault
+ memory `project_o2b_no_active_git`.
+- **No misleading fallbacks.** New CLI flags exit 2 with an explicit
+ message rather than silently fall through. Unknown
+ `RuntimeTarget` env value warns to stderr once and uses common
+ template; it does not silently coerce.
+- **Atomic writes** via `src/core/fs-atomic.ts:atomicWriteFileSync`.
+ Manifest writes (Β§18) hold `proper-lockfile.lock(path, { retries: 3,
+ factor: 2 })` to prevent torn state under concurrent `--apply`.
+- **Style preferences (Brain active):**
+ - `pref-no-exclamation-marks-in-docs` β€” no exclamation marks in
+ prose strings (rendered text, error messages, comments).
+ - `pref-no-simply-word` β€” the word "simply" is forbidden in any
+ written artifact (docs, comments, log strings, tests).
+- **Verification.** Every task ends with a targeted `bun test
+ tests/path/to/file.test.ts` and an expected pass count. End of
+ every Phase: full `bun test` + `bun run typecheck` green.
+- **CHANGELOG.** Touched exactly once, in Phase 4. Do not bump in
+ mid-PR β€” per vault memory `feedback_one_pr_one_version`.
+
+---
+
+## File map
+
+New files (count: 21):
+
+```
+docs/plans/2026-05-17-brain-onboarding-quality-impl.md # this file
+src/core/brain/protect.ts # Β§18 module
+src/cli/brain-protect.ts # Β§18 CLI verb
+templates/identity-reminder.hermes.txt # Β§4
+templates/identity-reminder.openclaw.txt # Β§4
+templates/brain-starter/preferences/pref-imperative-commit-messages.md # Β§15
+templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md
+templates/brain-starter/preferences/pref-prefer-typed-errors.md
+templates/brain-starter/preferences/pref-explicit-imports-only.md
+templates/brain-starter/preferences/pref-changelog-every-release.md
+templates/brain-starter/preferences/pref-russian-in-chat.md
+templates/brain-starter/preferences/pref-test-before-refactor.md
+templates/brain-starter/preferences/pref-prefer-bun-over-npx.md
+templates/brain-starter/retired/ret-tabs-over-spaces.md
+templates/brain-starter/retired/ret-no-emojis-in-code.md
+templates/brain-starter/retired/ret-prefer-curl-over-wget.md
+templates/brain-starter/inbox/sig-2026-05-10-strict-types.md
+templates/brain-starter/log/2026-05-15.md
+templates/brain-starter/log/2026-05-16.md
+tests/core/brain/protect.test.ts
+tests/cli/brain-protect.test.ts
+tests/core/brain/starter.test.ts
+tests/fixtures/identity-reminder/hermes.txt
+tests/fixtures/identity-reminder/openclaw.txt
+```
+
+Modified files (count: 10):
+
+```
+src/core/identity-reminder.ts # Β§4 resolver
+src/core/brain/init.ts # Β§15 helper
+src/cli/brain.ts # Β§18 + Β§15 wiring
+src/openclaw/index.ts # Β§4 call site
+plugins/hermes/__init__.py # Β§4 Python parity
+tests/core/identity-reminder.test.ts # Β§4 unit
+tests/python/test_hermes_plugin.py # Β§4 Python unit
+install.md # all three notes
+CHANGELOG.md # Phase 4 only
+package.json # version bump Phase 4
+```
+
+Version-mirror files (touched once in Phase 4):
+
+```
+.claude-plugin/plugin.json
+.codex-plugin/plugin.json
+plugins/codex/.codex-plugin/plugin.json
+plugins/hermes/plugin.yaml
+plugin.yaml
+openclaw.plugin.json
+__init__.py
+```
+
+`bun run sync-version` rewrites these from `package.json`; do not
+hand-edit.
+
+---
+
+## Phase 1 β€” Β§4-partial Per-runtime identity-reminder templates
+
+Smallest blast radius. Lays the `RuntimeTarget` type that Β§18 reuses
+under a narrower name.
+
+### Task 1: Add `RuntimeTarget` type and known-target set
+
+**Objective:** Introduce the closed union of runtime names without
+yet changing resolver behaviour. Pure type addition.
+
+**Files:**
+
+- Modify: `src/core/identity-reminder.ts`
+
+**Step 1: Read current state**
+
+Run: `wc -l src/core/identity-reminder.ts` β€” expected 46.
+
+**Step 2: Add the type and the const set**
+
+Append to `src/core/identity-reminder.ts` (above
+`loadReminderTemplate`):
+
+```ts
+/**
+ * Closed enumeration of runtime targets the resolver knows about.
+ * Adding a target is a PR-change (new template file + new union
+ * member), not a runtime decision β€” the project deliberately ships
+ * a fixed list rather than a dynamic registry. The list contains
+ * exactly the runtimes that call `buildReminder` per-turn /
+ * per-action; Claude Code and Codex steer through a different
+ * mechanism (`hooks/lib/messages.ts`) and are intentionally not
+ * here.
+ */
+export const KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"] as const;
+
+export type RuntimeTarget = (typeof KNOWN_RUNTIME_TARGETS)[number];
+
+export function isRuntimeTarget(value: string | undefined): value is RuntimeTarget {
+ return (
+ typeof value === "string"
+ && (KNOWN_RUNTIME_TARGETS as readonly string[]).includes(value)
+ );
+}
+```
+
+**Step 3: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 4: Pause for review (no commit)**
+
+### Task 2: Test the per-target template lookup
+
+**Objective:** Express the expected resolver behaviour as failing
+tests; lock in the contract before writing the resolver.
+
+**Files:**
+
+- Modify: `tests/core/identity-reminder.test.ts`
+
+**Step 1: Add fixture loader helper at top of file**
+
+```ts
+import { readFileSync } from "node:fs";
+import { resolve, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const FIXTURE_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "fixtures",
+ "identity-reminder",
+);
+
+function readFixture(target: string): string {
+ return readFileSync(resolve(FIXTURE_DIR, `${target}.txt`), "utf8").trimEnd();
+}
+```
+
+(The fixture files do not exist yet β€” tests will fail with ENOENT
+until Task 6 lands. That is expected.)
+
+**Step 2: Add a describe block for per-target resolution**
+
+```ts
+describe("buildReminder per-target resolution", () => {
+ test("explicit target=hermes returns hermes template body", () => {
+ const out = buildReminder("test-agent", "hermes");
+ expect(out).toContain("Identity: @test-agent");
+ expect(out).toContain("Hermes turns are short");
+ });
+
+ test("explicit target=openclaw returns openclaw template body", () => {
+ const out = buildReminder("test-agent", "openclaw");
+ expect(out).toContain("OpenClaw has no session boundary");
+ });
+
+ test("no target falls back to common template", () => {
+ const out = buildReminder("test-agent");
+ expect(out).toContain("Identity: @test-agent");
+ expect(out).not.toContain("Hermes turns are short");
+ expect(out).not.toContain("OpenClaw has no session boundary");
+ });
+});
+```
+
+**Step 3: Run tests**
+
+Run: `bun test tests/core/identity-reminder.test.ts`
+Expected: 3 failures (signature mismatch on `buildReminder` plus
+missing fixtures).
+
+**Step 4: Pause for review (no commit)**
+
+### Task 3: Extend `buildReminder` with target overload
+
+**Objective:** Resolver β€” explicit `target` first, env second, common
+fallback last. Missing per-target file falls back without warning;
+unknown env value warns once and falls back.
+
+**Files:**
+
+- Modify: `src/core/identity-reminder.ts`
+
+**Step 1: Replace `buildReminder` signature**
+
+Replace the existing `buildReminder` block with:
+
+```ts
+const PER_TARGET_PATH = (target: RuntimeTarget): string =>
+ resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "templates",
+ `identity-reminder.${target}.txt`,
+ );
+
+function tryReadTargetTemplate(target: RuntimeTarget): string | null {
+ try {
+ return readFileSync(PER_TARGET_PATH(target), "utf8").trimEnd();
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw err;
+ }
+}
+
+let envWarnedOnce = false;
+function resolveTargetFromEnv(): RuntimeTarget | undefined {
+ const raw = process.env.O2B_TARGET;
+ if (raw === undefined || raw === "") return undefined;
+ if (isRuntimeTarget(raw)) return raw;
+ if (!envWarnedOnce) {
+ envWarnedOnce = true;
+ process.stderr.write(
+ `open-second-brain: unknown O2B_TARGET='${raw}', using common identity template\n`,
+ );
+ }
+ return undefined;
+}
+
+export function buildReminder(agent: string, target?: RuntimeTarget): string {
+ const effective = target ?? resolveTargetFromEnv();
+ if (effective !== undefined) {
+ const tpl = tryReadTargetTemplate(effective);
+ if (tpl !== null) return tpl.replace(/\{agent\}/g, agent);
+ }
+ return loadReminderTemplate().replace(/\{agent\}/g, agent);
+}
+```
+
+**Step 2: Reset the env-warned flag (test-only export)**
+
+Append:
+
+```ts
+/** Test-only: reset internal warn-once latch. */
+export function __resetEnvWarnedOnceForTests(): void {
+ envWarnedOnce = false;
+}
+```
+
+**Step 3: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 4: Run resolver tests**
+
+Run: `bun test tests/core/identity-reminder.test.ts`
+Expected: 3 failures (fixtures still missing β€” error now is
+`ENOENT` on the per-target template files). The resolver code is
+correct; the failure mode confirms it reached the template-read
+path.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 4: Create the two per-target template files
+
+**Objective:** Final text content per the design doc Β§4-partial
+section. Each file is plain text, 5–7 lines, single `{agent}`
+placeholder. Claude Code and Codex template files are intentionally
+**not** created β€” their steering goes through `hooks/lib/messages.ts`,
+which is a separate mechanism tracked under design doc D5.
+
+**Files:**
+
+- Create: `templates/identity-reminder.hermes.txt`
+- Create: `templates/identity-reminder.openclaw.txt`
+
+**Step 1: Write `identity-reminder.hermes.txt`**
+
+```text
+[open-second-brain] Identity: @{agent}. After every durable artifact this turn β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. Hermes turns are short; do not batch the log calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+```
+
+**Step 2: Write `identity-reminder.openclaw.txt`**
+
+```text
+[open-second-brain] Identity: @{agent}. After every durable in-process action β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+```
+
+**Step 3: Pause for review (no commit)**
+
+### Task 5: Write parity fixtures and confirm tests pass
+
+**Objective:** Pin the expected output per (agent, target) so TS and
+Python diverging is caught by tests on both sides.
+
+**Files:**
+
+- Create: `tests/fixtures/identity-reminder/hermes.txt`
+- Create: `tests/fixtures/identity-reminder/openclaw.txt`
+
+**Step 1: Generate each fixture from the matching template**
+
+For each `<target>` in `hermes`, `openclaw`, copy
+`templates/identity-reminder.<target>.txt` to
+`tests/fixtures/identity-reminder/<target>.txt` and substitute
+`{agent}` β†’ `test-agent`.
+
+**Step 2: Add fixture-parity tests**
+
+Append to `tests/core/identity-reminder.test.ts`:
+
+```ts
+describe("buildReminder fixture parity", () => {
+ for (const target of KNOWN_RUNTIME_TARGETS) {
+ test(`agent=test-agent target=${target} matches fixture`, () => {
+ const expected = readFixture(target);
+ const actual = buildReminder("test-agent", target);
+ expect(actual).toBe(expected);
+ });
+ }
+});
+```
+
+Add the matching import at the top:
+
+```ts
+import { buildReminder, KNOWN_RUNTIME_TARGETS } from "../../src/core/identity-reminder.ts";
+```
+
+**Step 3: Run targeted tests**
+
+Run: `bun test tests/core/identity-reminder.test.ts`
+Expected: 5 tests pass (3 from Task 2 + 2 parity).
+
+**Step 4: Pause for review (no commit)**
+
+### Task 6: Test env-based resolution
+
+**Objective:** Cover `O2B_TARGET` env path and unknown-value warn.
+
+**Files:**
+
+- Modify: `tests/core/identity-reminder.test.ts`
+
+**Step 1: Add env-resolution tests**
+
+```ts
+describe("buildReminder env-based resolution", () => {
+ let savedEnv: string | undefined;
+
+ beforeEach(() => {
+ savedEnv = process.env.O2B_TARGET;
+ __resetEnvWarnedOnceForTests();
+ });
+
+ afterEach(() => {
+ if (savedEnv === undefined) delete process.env.O2B_TARGET;
+ else process.env.O2B_TARGET = savedEnv;
+ });
+
+ test("env O2B_TARGET=openclaw resolves to openclaw template", () => {
+ process.env.O2B_TARGET = "openclaw";
+ expect(buildReminder("test-agent")).toContain("OpenClaw has no session boundary");
+ });
+
+ test("explicit target beats env", () => {
+ process.env.O2B_TARGET = "openclaw";
+ expect(buildReminder("test-agent", "hermes")).toContain(
+ "Hermes turns are short",
+ );
+ });
+
+ test("unknown env value falls back to common template", () => {
+ process.env.O2B_TARGET = "nonsense";
+ const out = buildReminder("test-agent");
+ expect(out).not.toContain("Hermes turns are short");
+ expect(out).not.toContain("OpenClaw has no session boundary");
+ });
+});
+```
+
+Add the matching import:
+
+```ts
+import {
+ buildReminder,
+ KNOWN_RUNTIME_TARGETS,
+ __resetEnvWarnedOnceForTests,
+} from "../../src/core/identity-reminder.ts";
+```
+
+**Step 2: Run targeted tests**
+
+Run: `bun test tests/core/identity-reminder.test.ts`
+Expected: 8 tests pass.
+
+**Step 3: Pause for review (no commit)**
+
+### Task 7: Wire OpenClaw call site
+
+**Objective:** OpenClaw passes `target: "openclaw"` explicitly; no
+env dependency in-process.
+
+**Files:**
+
+- Modify: `src/openclaw/index.ts`
+
+**Step 1: Locate the `buildReminder` call**
+
+Run: `grep -n "buildReminder" src/openclaw/index.ts`
+
+**Step 2: Pass the target argument**
+
+Change `buildReminder(agent)` to `buildReminder(agent, "openclaw")`.
+Import the type if not already imported.
+
+**Step 3: Build OpenClaw bundle**
+
+Run: `bun run build:openclaw`
+Expected: success, `openclaw/index.js` rebuilt.
+
+**Step 4: Run OpenClaw tests**
+
+Run: `bun test tests/openclaw/`
+Expected: all pre-existing tests still pass; one of them (whichever
+asserts the reminder body) now matches the openclaw-specific text.
+If a test asserts a substring like "Hermes turns are short" or
+similar runtime-specific text from the common template, update it
+to assert the OpenClaw substring "OpenClaw has no session boundary".
+
+**Step 5: Pause for review (no commit)**
+
+### Task 8: Verify MCP instructions are out of scope
+
+**Objective:** Confirm by re-grep that `src/mcp/instructions.ts` and
+the rest of `src/mcp/` do not call `buildReminder` β€” so they are
+correctly out of scope for Β§4-partial. No code change.
+
+The MCP `initialize.instructions` field describes the Brain tool
+surface (`brain_feedback`, `brain_apply_evidence`, …) and is
+independent prose, not the per-turn identity reminder. Per-runtime
+text for Claude Code / Codex is deferred (design doc D5) because it
+lives in `hooks/lib/messages.ts:postWriteReminder`, which is a
+post-tool-call mechanism, not a per-turn injection.
+
+**Step 1: Confirm the grep returns no MCP hits**
+
+Run: `grep -rn "buildReminder" src/mcp/`
+Expected: no output (zero matches).
+
+**Step 2: If the grep returns hits, stop and escalate**
+
+A non-empty result means the assumption underlying this
+narrow-scope decision has changed. Stop and re-discuss with the
+user before proceeding.
+
+**Step 3: Pause for review (no commit)**
+
+### Task 9: Python shim parity β€” Hermes plugin
+
+**Objective:** `plugins/hermes/__init__.py` mirrors the TS resolver:
+read `templates/identity-reminder.hermes.txt` when present, fall
+back to `templates/identity-reminder.txt`.
+
+**Files:**
+
+- Modify: `plugins/hermes/__init__.py`
+
+**Step 1: Locate the reminder-loading code**
+
+Run: `grep -n "identity-reminder" plugins/hermes/__init__.py`
+
+**Step 2: Add target resolver helper**
+
+Insert near the top:
+
+```python
+_KNOWN_TARGETS = frozenset({"hermes", "claudecode", "codex", "openclaw"})
+
+
+def _resolve_target() -> str | None:
+ """Mirror src/core/identity-reminder.ts:resolveTargetFromEnv."""
+ import os
+ raw = os.environ.get("O2B_TARGET")
+ if raw and raw in _KNOWN_TARGETS:
+ return raw
+ return None
+```
+
+**Step 3: Update the template-loading function**
+
+Wrap the existing common-template `Path(...) / "identity-reminder.txt"`
+read with a per-target check. The Hermes shim runs inside Hermes
+itself; pass `target="hermes"` explicitly rather than via env so
+the behaviour is deterministic regardless of how Hermes invokes
+plugins.
+
+```python
+def _load_reminder_template() -> str:
+ target = "hermes" # always; this plugin runs inside Hermes
+ target_path = TEMPLATES_DIR / f"identity-reminder.{target}.txt"
+ if target_path.is_file():
+ return target_path.read_text(encoding="utf-8").rstrip()
+ return COMMON_TEMPLATE_PATH.read_text(encoding="utf-8").rstrip()
+```
+
+(Variable names depend on the existing file; preserve them.)
+
+**Step 4: Pause for review (no commit)**
+
+### Task 10: Python shim test
+
+**Objective:** Pin the Python output against the same fixture as TS,
+so divergence breaks both languages' CI.
+
+**Files:**
+
+- Modify: `tests/python/test_hermes_plugin.py`
+
+**Step 1: Add a fixture-parity test**
+
+```python
+def test_reminder_matches_typescript_fixture():
+ from pathlib import Path
+ from plugins.hermes import _load_reminder_template
+
+ raw = _load_reminder_template().replace("{agent}", "test-agent")
+ fixture = (
+ Path(__file__).resolve().parents[1]
+ / "fixtures"
+ / "identity-reminder"
+ / "hermes.txt"
+ ).read_text(encoding="utf-8").rstrip()
+ assert raw == fixture
+```
+
+(Adapt the import path to wherever `_load_reminder_template` is
+exposed β€” it may need a small re-export from `plugins/hermes/__init__.py`.)
+
+**Step 2: Run Python tests**
+
+Run: `python3 -m unittest tests.python.test_hermes_plugin`
+Expected: all tests pass, including the new parity one.
+
+**Step 3: Pause for review (no commit)**
+
+### Task 11: Phase 1 close β€” full green
+
+**Step 1: Run the full TS test suite**
+
+Run: `bun test`
+Expected: every test passes.
+
+**Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 3: Python tests**
+
+Run: `python3 -m unittest discover tests/python/`
+Expected: all pass.
+
+**Step 4: Pause for review (no commit)**
+
+---
+
+## Phase 2 β€” Β§18 `o2b brain protect`
+
+Largest slice. Pure renderer first (no IO), then IO surfaces, then
+CLI wiring.
+
+### Task 12: Skeleton β€” types and `BrainProtectError`
+
+**Objective:** Define the public surface of `src/core/brain/protect.ts`
+without behaviour. Compilable, importable, no tests yet.
+
+**Files:**
+
+- Create: `src/core/brain/protect.ts`
+
+**Step 1: Author the skeleton**
+
+```ts
+/**
+ * Β§18 of the OSB features summary: machine-enforced write protection
+ * for Brain/preferences/, retired/, log/, .snapshots/ and
+ * Brain/_brain.yaml against runtimes whose native config supports
+ * path-level deny rules. Brain/inbox/ stays writable.
+ */
+
+export const PROTECT_TARGETS = ["claudecode", "codex"] as const;
+export type ProtectTarget = (typeof PROTECT_TARGETS)[number];
+
+export class BrainProtectError extends Error {
+ constructor(
+ message: string,
+ readonly cause?: { code: string; detail?: unknown },
+ ) {
+ super(message);
+ this.name = "BrainProtectError";
+ }
+}
+
+export interface ProtectRule {
+ readonly kind: "deny" | "allow";
+ readonly action: "Write" | "Edit";
+ readonly path: string;
+}
+
+export interface RenderedSnippet {
+ readonly target: ProtectTarget;
+ readonly body: string;
+ readonly destination: string;
+}
+
+export interface ApplyResult {
+ readonly target: ProtectTarget;
+ readonly destination: string;
+ readonly backupPath: string;
+ readonly changed: boolean;
+}
+
+export const PROTECT_SCHEMA_VERSION = 1;
+```
+
+**Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 3: Pause for review (no commit)**
+
+### Task 13: Pure rule set β€” `buildProtectRules(vault)`
+
+**Objective:** Vault β†’ 6 deterministic rules. Pure, no IO.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Create: `tests/core/brain/protect.test.ts`
+
+**Step 1: Write the failing test**
+
+```ts
+import { test, expect, describe } from "bun:test";
+import { buildProtectRules } from "../../../src/core/brain/protect.ts";
+
+describe("buildProtectRules", () => {
+ test("returns 6 rules in stable order for a given vault", () => {
+ const rules = buildProtectRules("/vault");
+ expect(rules).toHaveLength(11); // 5 deny paths Γ— 2 actions + 1 allow
+ expect(rules[0]).toEqual({
+ kind: "deny",
+ action: "Write",
+ path: "/vault/Brain/preferences/**",
+ });
+ const last = rules[rules.length - 1];
+ expect(last).toEqual({
+ kind: "allow",
+ action: "Write",
+ path: "/vault/Brain/inbox/**",
+ });
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: FAIL β€” `buildProtectRules is not exported`.
+
+**Step 3: Implement**
+
+Append to `src/core/brain/protect.ts`:
+
+```ts
+import { join } from "node:path";
+
+const DENY_PATHS = [
+ "Brain/preferences/**",
+ "Brain/retired/**",
+ "Brain/log/**",
+ "Brain/.snapshots/**",
+ "Brain/_brain.yaml",
+] as const;
+
+const ALLOW_PATHS = ["Brain/inbox/**"] as const;
+
+export function buildProtectRules(vault: string): ReadonlyArray<ProtectRule> {
+ const rules: ProtectRule[] = [];
+ for (const rel of DENY_PATHS) {
+ for (const action of ["Write", "Edit"] as const) {
+ rules.push({ kind: "deny", action, path: join(vault, rel) });
+ }
+ }
+ for (const rel of ALLOW_PATHS) {
+ rules.push({ kind: "allow", action: "Write", path: join(vault, rel) });
+ }
+ return Object.freeze(rules);
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 1 pass.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 14: Renderer for Claude Code
+
+**Objective:** Pure function: rules β†’ JSON snippet shape that
+`<vault>/.claude/settings.json` would receive. Includes the managed
+manifest payload separately.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Write the failing test**
+
+```ts
+import { renderClaudeCode } from "../../../src/core/brain/protect.ts";
+
+describe("renderClaudeCode", () => {
+ test("emits a snippet with deny + allow arrays and a manifest", () => {
+ const rules = buildProtectRules("/vault");
+ const out = renderClaudeCode(rules);
+ expect(out.snippet).toEqual({
+ permissions: {
+ deny: expect.arrayContaining([
+ "Write(/vault/Brain/preferences/**)",
+ "Edit(/vault/Brain/preferences/**)",
+ ]),
+ allow: ["Write(/vault/Brain/inbox/**)"],
+ },
+ });
+ expect(out.manifest).toEqual({
+ schema_version: 1,
+ target: "claudecode",
+ vault: "/vault",
+ owned_deny: expect.any(Array),
+ owned_allow: ["Write(/vault/Brain/inbox/**)"],
+ });
+ expect(out.manifest.owned_deny).toHaveLength(10);
+ });
+});
+```
+
+**Step 2: Run β€” expect failure (import error)**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: FAIL.
+
+**Step 3: Implement**
+
+```ts
+export interface ClaudeCodeRender {
+ readonly snippet: {
+ permissions: { deny: string[]; allow: string[] };
+ };
+ readonly manifest: {
+ schema_version: number;
+ target: "claudecode";
+ vault: string;
+ owned_deny: string[];
+ owned_allow: string[];
+ };
+}
+
+export function renderClaudeCode(
+ rules: ReadonlyArray<ProtectRule>,
+ vault: string = inferVault(rules),
+): ClaudeCodeRender {
+ const deny = rules
+ .filter((r) => r.kind === "deny")
+ .map((r) => `${r.action}(${r.path})`);
+ const allow = rules
+ .filter((r) => r.kind === "allow")
+ .map((r) => `${r.action}(${r.path})`);
+ return Object.freeze({
+ snippet: { permissions: { deny, allow } },
+ manifest: {
+ schema_version: PROTECT_SCHEMA_VERSION,
+ target: "claudecode" as const,
+ vault,
+ owned_deny: deny,
+ owned_allow: allow,
+ },
+ });
+}
+
+function inferVault(rules: ReadonlyArray<ProtectRule>): string {
+ const first = rules[0];
+ if (!first) {
+ throw new BrainProtectError("renderClaudeCode requires at least one rule");
+ }
+ return first.path.split("/Brain/")[0]!;
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 2 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 15: Renderer for Codex
+
+**Objective:** Pure function: rules β†’ TOML body wrapped in the
+managed-block fence. Includes `[permissions.osb_protected.filesystem]`
+plus `default_permissions = "osb_protected"`.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Write failing test**
+
+```ts
+import { renderCodex } from "../../../src/core/brain/protect.ts";
+
+describe("renderCodex", () => {
+ test("emits TOML wrapped in osb fence with right keys", () => {
+ const rules = buildProtectRules("/vault");
+ const out = renderCodex(rules);
+ expect(out.body).toContain("# >>> open-second-brain managed >>>");
+ expect(out.body).toContain("# <<< open-second-brain managed <<<");
+ expect(out.body).toContain("[permissions.osb_protected.filesystem]");
+ expect(out.body).toContain('"/vault/Brain/preferences/**" = "none"');
+ expect(out.body).toContain('"/vault/Brain/inbox/**" = "write"');
+ expect(out.body).toContain('default_permissions = "osb_protected"');
+ expect(out.body).toContain(`schema_version = ${PROTECT_SCHEMA_VERSION}`);
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: FAIL.
+
+**Step 3: Implement**
+
+```ts
+const FENCE_OPEN = "# >>> open-second-brain managed >>>";
+const FENCE_CLOSE = "# <<< open-second-brain managed <<<";
+
+export interface CodexRender {
+ readonly body: string;
+}
+
+export function renderCodex(rules: ReadonlyArray<ProtectRule>): CodexRender {
+ const lines: string[] = [
+ FENCE_OPEN,
+ `# schema_version = ${PROTECT_SCHEMA_VERSION}`,
+ `default_permissions = "osb_protected"`,
+ "",
+ "[permissions.osb_protected.filesystem]",
+ ];
+ for (const r of rules) {
+ const value = r.kind === "deny" ? "none" : "write";
+ lines.push(`"${r.path}" = "${value}"`);
+ }
+ lines.push(FENCE_CLOSE);
+ return Object.freeze({ body: lines.join("\n") + "\n" });
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 3 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 16: Manifest read / write helpers
+
+**Objective:** Read and write `<vault>/.open-second-brain/protect.lock.json`
+atomically; reject malformed manifests.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Write failing tests**
+
+```ts
+import { mkdtempSync } from "node:fs";
+import { join, tmpdir } from "node:os"; // adjust to "node:path"
+import { readManifest, writeManifest } from "../../../src/core/brain/protect.ts";
+
+describe("manifest", () => {
+ test("round-trip claudecode manifest", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ const m = {
+ schema_version: 1,
+ target: "claudecode" as const,
+ vault: dir,
+ owned_deny: ["Write(/v/Brain/preferences/**)"],
+ owned_allow: ["Write(/v/Brain/inbox/**)"],
+ };
+ writeManifest(dir, m);
+ expect(readManifest(dir, "claudecode")).toEqual(m);
+ });
+
+ test("reading absent manifest returns null", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ expect(readManifest(dir, "claudecode")).toBeNull();
+ });
+
+ test("higher schema_version on disk throws", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ writeManifest(dir, {
+ schema_version: 999,
+ target: "claudecode",
+ vault: dir,
+ owned_deny: [],
+ owned_allow: [],
+ });
+ expect(() => readManifest(dir, "claudecode")).toThrow(BrainProtectError);
+ });
+});
+```
+
+(Adjust the `node:os` / `node:path` import as needed.)
+
+**Step 2: Run β€” expect failure**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+
+**Step 3: Implement**
+
+```ts
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { atomicWriteFileSync } from "./../fs-atomic.ts";
+
+const MANIFEST_DIR = ".open-second-brain";
+const MANIFEST_FILE = "protect.lock.json";
+
+function manifestPath(vault: string): string {
+ return join(vault, MANIFEST_DIR, MANIFEST_FILE);
+}
+
+interface ManifestRecordClaudeCode {
+ schema_version: number;
+ target: "claudecode";
+ vault: string;
+ owned_deny: string[];
+ owned_allow: string[];
+}
+
+interface ManifestRecordCodex {
+ schema_version: number;
+ target: "codex";
+ vault: string;
+ // For Codex, the fence is enough; we keep target presence for
+ // symmetry but do not need owned_* fields.
+}
+
+type ManifestRecord = ManifestRecordClaudeCode | ManifestRecordCodex;
+
+export function readManifest(
+ vault: string,
+ target: ProtectTarget,
+): ManifestRecord | null {
+ const path = manifestPath(vault);
+ if (!existsSync(path)) return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(readFileSync(path, "utf8"));
+ } catch (err) {
+ throw new BrainProtectError(`malformed manifest at ${path}`, {
+ code: "MANIFEST_MALFORMED",
+ detail: err,
+ });
+ }
+ const all = parsed as { entries?: ManifestRecord[] } | undefined;
+ const entry = all?.entries?.find((e) => e.target === target);
+ if (!entry) return null;
+ if (entry.schema_version > PROTECT_SCHEMA_VERSION) {
+ throw new BrainProtectError(
+ `manifest schema_version ${entry.schema_version} is newer than this binary (${PROTECT_SCHEMA_VERSION}); run \`o2b update\``,
+ { code: "MANIFEST_NEWER_SCHEMA" },
+ );
+ }
+ return entry;
+}
+
+export function writeManifest(vault: string, entry: ManifestRecord): void {
+ const path = manifestPath(vault);
+ mkdirSync(join(vault, MANIFEST_DIR), { recursive: true });
+ const existing: { entries: ManifestRecord[] } = existsSync(path)
+ ? JSON.parse(readFileSync(path, "utf8"))
+ : { entries: [] };
+ const others = existing.entries.filter((e) => e.target !== entry.target);
+ const next = { entries: [...others, entry] };
+ atomicWriteFileSync(path, JSON.stringify(next, null, 2) + "\n");
+}
+
+export function removeManifestEntry(vault: string, target: ProtectTarget): void {
+ const path = manifestPath(vault);
+ if (!existsSync(path)) return;
+ const existing: { entries: ManifestRecord[] } = JSON.parse(
+ readFileSync(path, "utf8"),
+ );
+ const next = { entries: existing.entries.filter((e) => e.target !== target) };
+ atomicWriteFileSync(path, JSON.stringify(next, null, 2) + "\n");
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 6 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 17: `applyClaudeCode` β€” write settings.json + manifest
+
+**Objective:** Idempotent `--apply` for Claude Code. Reads existing
+`<vault>/.claude/settings.json`, merges OSB-owned entries (replacing
+any owned-by-prior-manifest), writes manifest, backs up old file.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Write failing tests**
+
+```ts
+import { readFileSync, writeFileSync } from "node:fs";
+import { applyProtect, unprotect } from "../../../src/core/brain/protect.ts";
+
+describe("applyProtect claudecode", () => {
+ test("creates settings.json + manifest on a fresh vault", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ const res = applyProtect({ target: "claudecode", vault: dir });
+ expect(res.changed).toBe(true);
+ const settings = JSON.parse(
+ readFileSync(join(dir, ".claude", "settings.json"), "utf8"),
+ );
+ expect(settings.permissions.deny).toContain(
+ `Write(${dir}/Brain/preferences/**)`,
+ );
+ });
+
+ test("idempotent: second apply produces byte-identical settings", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ applyProtect({ target: "claudecode", vault: dir });
+ const first = readFileSync(join(dir, ".claude", "settings.json"), "utf8");
+ applyProtect({ target: "claudecode", vault: dir });
+ const second = readFileSync(join(dir, ".claude", "settings.json"), "utf8");
+ expect(second).toBe(first);
+ });
+
+ test("preserves user-authored permissions on apply", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, ".claude"), { recursive: true });
+ writeFileSync(
+ join(dir, ".claude", "settings.json"),
+ JSON.stringify({
+ permissions: { deny: ["Bash(rm -rf /)"], allow: [] },
+ }),
+ );
+ applyProtect({ target: "claudecode", vault: dir });
+ const settings = JSON.parse(
+ readFileSync(join(dir, ".claude", "settings.json"), "utf8"),
+ );
+ expect(settings.permissions.deny).toContain("Bash(rm -rf /)");
+ expect(settings.permissions.deny).toContain(
+ `Write(${dir}/Brain/preferences/**)`,
+ );
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+
+**Step 3: Implement**
+
+```ts
+export interface ApplyOptions {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+}
+
+export function applyProtect(opts: ApplyOptions): ApplyResult {
+ switch (opts.target) {
+ case "claudecode": return applyClaudeCode(opts.vault);
+ case "codex": return applyCodex(opts.vault);
+ }
+}
+
+function applyClaudeCode(vault: string): ApplyResult {
+ ensureVaultBootstrapped(vault);
+ const rules = buildProtectRules(vault);
+ const rendered = renderClaudeCode(rules, vault);
+ const dest = join(vault, ".claude", "settings.json");
+ mkdirSync(join(vault, ".claude"), { recursive: true });
+
+ const prev = readManifest(vault, "claudecode") as ManifestRecordClaudeCode | null;
+ const before = existsSync(dest) ? readFileSync(dest, "utf8") : "{}";
+ const settings = JSON.parse(before);
+ settings.permissions ??= { deny: [], allow: [] };
+ settings.permissions.deny ??= [];
+ settings.permissions.allow ??= [];
+
+ // Remove prior owned entries.
+ const priorDeny = prev?.owned_deny ?? [];
+ const priorAllow = prev?.owned_allow ?? [];
+ settings.permissions.deny = settings.permissions.deny.filter(
+ (e: string) => !priorDeny.includes(e),
+ );
+ settings.permissions.allow = settings.permissions.allow.filter(
+ (e: string) => !priorAllow.includes(e),
+ );
+
+ // Add new owned entries, deduping against user-authored same-string.
+ for (const e of rendered.snippet.permissions.deny) {
+ if (!settings.permissions.deny.includes(e)) {
+ settings.permissions.deny.push(e);
+ }
+ }
+ for (const e of rendered.snippet.permissions.allow) {
+ if (!settings.permissions.allow.includes(e)) {
+ settings.permissions.allow.push(e);
+ }
+ }
+
+ const after = JSON.stringify(settings, null, 2) + "\n";
+ const changed = after !== before;
+ const backupPath = `${dest}.bak.${Date.now()}`;
+ if (changed && existsSync(dest)) {
+ writeFileSync(backupPath, before);
+ }
+ atomicWriteFileSync(dest, after);
+ writeManifest(vault, rendered.manifest);
+ return Object.freeze({
+ target: "claudecode",
+ destination: dest,
+ backupPath: changed ? backupPath : "",
+ changed,
+ });
+}
+
+function ensureVaultBootstrapped(vault: string): void {
+ if (!existsSync(join(vault, "Brain"))) {
+ throw new BrainProtectError(
+ `vault at ${vault} has no Brain/ directory; run \`o2b brain init\` first`,
+ { code: "VAULT_NOT_BOOTSTRAPPED" },
+ );
+ }
+}
+```
+
+Note: tests need to `mkdirSync(join(vault, "Brain"), { recursive: true })`
+before calling `applyProtect` because of the bootstrap check. Update
+the failing tests in Step 1 accordingly before Step 3.
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 9 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 18: `unprotect` for Claude Code
+
+**Objective:** Round-trip: protect β†’ unprotect β†’ byte-equal pre-protect
+state (modulo backup files).
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Failing test**
+
+```ts
+describe("unprotect claudecode", () => {
+ test("round-trip restores settings.json to pre-protect content", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ mkdirSync(join(dir, ".claude"), { recursive: true });
+ const userSettings = JSON.stringify(
+ { permissions: { deny: ["Bash(rm -rf /)"], allow: [] } },
+ null,
+ 2,
+ ) + "\n";
+ writeFileSync(join(dir, ".claude", "settings.json"), userSettings);
+
+ applyProtect({ target: "claudecode", vault: dir });
+ unprotect({ target: "claudecode", vault: dir });
+
+ const after = readFileSync(join(dir, ".claude", "settings.json"), "utf8");
+ expect(after).toBe(userSettings);
+ });
+
+ test("unprotect on absent manifest exits without throwing", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ expect(() => unprotect({ target: "claudecode", vault: dir })).not.toThrow();
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+**Step 3: Implement**
+
+```ts
+export interface UnprotectOptions {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+}
+
+export function unprotect(opts: UnprotectOptions): void {
+ switch (opts.target) {
+ case "claudecode": return unprotectClaudeCode(opts.vault);
+ case "codex": return unprotectCodex(opts.vault);
+ }
+}
+
+function unprotectClaudeCode(vault: string): void {
+ const dest = join(vault, ".claude", "settings.json");
+ const prev = readManifest(vault, "claudecode") as
+ | ManifestRecordClaudeCode
+ | null;
+ if (!prev || !existsSync(dest)) return;
+
+ const raw = readFileSync(dest, "utf8");
+ const parsed = JSON.parse(raw);
+ if (parsed?.permissions?.deny) {
+ parsed.permissions.deny = parsed.permissions.deny.filter(
+ (e: string) => !prev.owned_deny.includes(e),
+ );
+ }
+ if (parsed?.permissions?.allow) {
+ parsed.permissions.allow = parsed.permissions.allow.filter(
+ (e: string) => !prev.owned_allow.includes(e),
+ );
+ }
+ // If permissions is now { deny: [], allow: [] }, leave it β€” that
+ // matches what the user's settings.json would look like after they
+ // remove all rules manually. Do not delete the key.
+
+ const after = JSON.stringify(parsed, null, 2) + "\n";
+ atomicWriteFileSync(dest, after);
+ removeManifestEntry(vault, "claudecode");
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 11 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 19: `applyCodex` β€” patch `~/.codex/config.toml` fence
+
+**Objective:** Locate (or create) `~/.codex/config.toml`, inject the
+managed fence emitted by `renderCodex`. Re-apply replaces the fence
+content; outside-fence content untouched.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Failing test**
+
+```ts
+describe("applyProtect codex", () => {
+ test("creates config.toml with the managed fence on a fresh user home", () => {
+ const home = mkdtempSync(join(tmpdir(), "osb-codex-home-"));
+ const vault = mkdtempSync(join(tmpdir(), "osb-codex-vault-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const res = applyProtect({
+ target: "codex",
+ vault,
+ __homeOverride: home, // test seam
+ } as ApplyOptions & { __homeOverride?: string });
+ expect(res.changed).toBe(true);
+ const config = readFileSync(join(home, ".codex", "config.toml"), "utf8");
+ expect(config).toContain("# >>> open-second-brain managed >>>");
+ expect(config).toContain("[permissions.osb_protected.filesystem]");
+ });
+
+ test("idempotent on Codex too", () => {
+ const home = mkdtempSync(join(tmpdir(), "osb-codex-home-"));
+ const vault = mkdtempSync(join(tmpdir(), "osb-codex-vault-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ applyProtect({ target: "codex", vault, __homeOverride: home } as ApplyOptions & { __homeOverride?: string });
+ const first = readFileSync(join(home, ".codex", "config.toml"), "utf8");
+ applyProtect({ target: "codex", vault, __homeOverride: home } as ApplyOptions & { __homeOverride?: string });
+ const second = readFileSync(join(home, ".codex", "config.toml"), "utf8");
+ expect(second).toBe(first);
+ });
+
+ test("preserves user content outside the fence", () => {
+ const home = mkdtempSync(join(tmpdir(), "osb-codex-home-"));
+ const vault = mkdtempSync(join(tmpdir(), "osb-codex-vault-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ const userToml = '# user content\nmodel = "gpt-5.5"\n';
+ writeFileSync(join(home, ".codex", "config.toml"), userToml);
+ applyProtect({ target: "codex", vault, __homeOverride: home } as ApplyOptions & { __homeOverride?: string });
+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");
+ expect(after.startsWith(userToml)).toBe(true);
+ expect(after).toContain("# >>> open-second-brain managed >>>");
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+**Step 3: Implement**
+
+Extend `ApplyOptions` to support a test seam:
+
+```ts
+export interface ApplyOptions {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+ /** Test-only: override $HOME for Codex config path resolution. */
+ readonly __homeOverride?: string;
+}
+
+import { homedir } from "node:os";
+
+function applyCodex(vault: string, homeOverride?: string): ApplyResult {
+ ensureVaultBootstrapped(vault);
+ const home = homeOverride ?? homedir();
+ const dest = join(home, ".codex", "config.toml");
+ mkdirSync(join(home, ".codex"), { recursive: true });
+
+ const before = existsSync(dest) ? readFileSync(dest, "utf8") : "";
+ const rules = buildProtectRules(vault);
+ const fence = renderCodex(rules).body;
+
+ const FENCE_RE = new RegExp(
+ `${escapeRe(FENCE_OPEN)}[\\s\\S]*?${escapeRe(FENCE_CLOSE)}\\n?`,
+ "m",
+ );
+ const stripped = before.replace(FENCE_RE, "");
+ const sep = stripped.length === 0 || stripped.endsWith("\n") ? "" : "\n";
+ const after = stripped + sep + fence;
+ const changed = after !== before;
+ const backupPath = `${dest}.bak.${Date.now()}`;
+ if (changed && existsSync(dest)) {
+ writeFileSync(backupPath, before);
+ }
+ atomicWriteFileSync(dest, after);
+ writeManifest(vault, {
+ schema_version: PROTECT_SCHEMA_VERSION,
+ target: "codex",
+ vault,
+ });
+ return Object.freeze({
+ target: "codex",
+ destination: dest,
+ backupPath: changed ? backupPath : "",
+ changed,
+ });
+}
+
+function escapeRe(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+```
+
+Update `applyProtect`'s switch to pass `opts.__homeOverride` to
+`applyCodex`.
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 14 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 20: `unprotect` for Codex + round-trip test
+
+**Objective:** Remove the fence block. Round-trip yields byte-identical
+pre-protect content.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Failing test**
+
+```ts
+describe("unprotect codex", () => {
+ test("round-trip on Codex restores pre-protect content", () => {
+ const home = mkdtempSync(join(tmpdir(), "osb-codex-home-"));
+ const vault = mkdtempSync(join(tmpdir(), "osb-codex-vault-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ const userToml = '# user content\nmodel = "gpt-5.5"\n';
+ writeFileSync(join(home, ".codex", "config.toml"), userToml);
+ applyProtect({ target: "codex", vault, __homeOverride: home } as ApplyOptions & { __homeOverride?: string });
+ unprotect({ target: "codex", vault, __homeOverride: home } as UnprotectOptions & { __homeOverride?: string });
+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");
+ expect(after).toBe(userToml);
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+**Step 3: Implement**
+
+Add `__homeOverride` to `UnprotectOptions`. Implement:
+
+```ts
+function unprotectCodex(vault: string, homeOverride?: string): void {
+ const home = homeOverride ?? homedir();
+ const dest = join(home, ".codex", "config.toml");
+ if (!existsSync(dest)) return;
+ const raw = readFileSync(dest, "utf8");
+ const FENCE_RE = new RegExp(
+ `\\n?${escapeRe(FENCE_OPEN)}[\\s\\S]*?${escapeRe(FENCE_CLOSE)}\\n?`,
+ "m",
+ );
+ const stripped = raw.replace(FENCE_RE, "");
+ atomicWriteFileSync(dest, stripped);
+ removeManifestEntry(vault, "codex");
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 15 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 21: `printSnippet` β€” `--print` mode
+
+**Objective:** Render to stdout-friendly string without touching the
+filesystem. Same content as `--apply` would produce, minus the user's
+existing config.
+
+**Files:**
+
+- Modify: `src/core/brain/protect.ts`
+- Modify: `tests/core/brain/protect.test.ts`
+
+**Step 1: Failing test**
+
+```ts
+import { printSnippet } from "../../../src/core/brain/protect.ts";
+
+describe("printSnippet", () => {
+ test("claudecode prints the JSON shape only (no manifest)", () => {
+ const out = printSnippet({ target: "claudecode", vault: "/v" });
+ expect(out.body).toContain('"Write(/v/Brain/preferences/**)"');
+ expect(out.body).toContain("permissions");
+ expect(out.body).not.toContain("schema_version"); // manifest stays internal
+ });
+
+ test("codex prints the fenced TOML block", () => {
+ const out = printSnippet({ target: "codex", vault: "/v" });
+ expect(out.body).toContain("# >>> open-second-brain managed >>>");
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+**Step 3: Implement**
+
+```ts
+export function printSnippet(opts: {
+ target: ProtectTarget;
+ vault: string;
+}): RenderedSnippet {
+ const rules = buildProtectRules(opts.vault);
+ switch (opts.target) {
+ case "claudecode": {
+ const r = renderClaudeCode(rules, opts.vault);
+ return Object.freeze({
+ target: "claudecode" as const,
+ body: JSON.stringify(r.snippet, null, 2) + "\n",
+ destination: join(opts.vault, ".claude", "settings.json"),
+ });
+ }
+ case "codex": {
+ const r = renderCodex(rules);
+ return Object.freeze({
+ target: "codex" as const,
+ body: r.body,
+ destination: join(homedir(), ".codex", "config.toml"),
+ });
+ }
+ }
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/protect.test.ts`
+Expected: 17 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 22: CLI surface β€” `o2b brain protect` and `o2b brain unprotect`
+
+**Objective:** Wire the verbs in `src/cli/brain.ts` (or a sibling
+`src/cli/brain-protect.ts`, depending on existing patterns; mirror how
+`brain set-primary` is wired).
+
+**Files:**
+
+- Create: `src/cli/brain-protect.ts`
+- Modify: `src/cli/brain.ts`
+
+**Step 1: Inspect existing CLI dispatch**
+
+Run: `grep -n "set-primary\|cmdBrain" src/cli/brain.ts`
+
+**Step 2: Implement `src/cli/brain-protect.ts`**
+
+```ts
+import {
+ applyProtect,
+ printSnippet,
+ unprotect,
+ PROTECT_TARGETS,
+ type ProtectTarget,
+} from "../core/brain/protect.ts";
+
+export interface CmdResult {
+ readonly stdout: string;
+ readonly stderr: string;
+ readonly exitCode: number;
+}
+
+export function cmdBrainProtect(argv: string[]): CmdResult {
+ const args = parseArgs(argv);
+ if (!isProtectTarget(args.target)) {
+ return {
+ stdout: "",
+ stderr: `unknown --target='${args.target}', supported: ${PROTECT_TARGETS.join(", ")}\n`,
+ exitCode: 2,
+ };
+ }
+ if (args.apply) {
+ const r = applyProtect({ target: args.target, vault: args.vault });
+ const note = r.changed ? `applied to ${r.destination}` : "no changes";
+ return {
+ stdout: `${note}\n${r.backupPath ? `backup: ${r.backupPath}\n` : ""}`,
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ const s = printSnippet({ target: args.target, vault: args.vault });
+ return { stdout: s.body, stderr: "", exitCode: 0 };
+}
+
+export function cmdBrainUnprotect(argv: string[]): CmdResult {
+ const args = parseArgs(argv);
+ if (!isProtectTarget(args.target)) {
+ return {
+ stdout: "",
+ stderr: `unknown --target='${args.target}'\n`,
+ exitCode: 2,
+ };
+ }
+ unprotect({ target: args.target, vault: args.vault });
+ return { stdout: "unprotect complete\n", stderr: "", exitCode: 0 };
+}
+
+interface ParsedArgs {
+ target: string;
+ vault: string;
+ apply: boolean;
+}
+
+function parseArgs(argv: string[]): ParsedArgs {
+ // Reuse existing arg-parsing helpers from src/cli/argparse.ts.
+ // ... implementation depends on what argparse exports.
+ throw new Error("not implemented");
+}
+
+function isProtectTarget(s: string): s is ProtectTarget {
+ return (PROTECT_TARGETS as readonly string[]).includes(s);
+}
+```
+
+Replace the `parseArgs` stub with the actual pattern used in
+`src/cli/brain.ts` for `set-primary`. The contract: `--target <name>`
+(required), `--vault <path>` (default from `defaultConfigPath()`),
+`--apply` (boolean flag, default false).
+
+**Step 3: Dispatch in `src/cli/brain.ts`**
+
+Add two cases to the existing brain-subcommand dispatch table:
+
+```ts
+case "protect": return cmdBrainProtect(rest);
+case "unprotect": return cmdBrainUnprotect(rest);
+```
+
+**Step 4: CLI tests**
+
+Create `tests/cli/brain-protect.test.ts`:
+
+```ts
+import { test, expect, describe } from "bun:test";
+import { mkdtempSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { cmdBrainProtect, cmdBrainUnprotect } from "../../src/cli/brain-protect.ts";
+
+describe("o2b brain protect CLI", () => {
+ test("--target claudecode --print returns JSON body, exit 0", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ const r = cmdBrainProtect(["--target", "claudecode", "--vault", dir]);
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain("Write(");
+ });
+
+ test("unknown target exits 2", () => {
+ const r = cmdBrainProtect(["--target", "vim"]);
+ expect(r.exitCode).toBe(2);
+ expect(r.stderr).toContain("unknown --target");
+ });
+
+ test("apply + unprotect round-trip works", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ expect(
+ cmdBrainProtect(["--target", "claudecode", "--vault", dir, "--apply"])
+ .exitCode,
+ ).toBe(0);
+ expect(
+ cmdBrainUnprotect(["--target", "claudecode", "--vault", dir]).exitCode,
+ ).toBe(0);
+ });
+});
+```
+
+**Step 5: Run CLI tests**
+
+Run: `bun test tests/cli/brain-protect.test.ts`
+Expected: 3 passes.
+
+**Step 6: Pause for review (no commit)**
+
+### Task 23: install.md addendum for Β§18
+
+**Objective:** Add a step "5c β€” Optional: machine-enforced Brain
+protection" to Claude Code (Branch D) and Codex (Branch C) branches.
+Branches A and B and E mention `o2b brain protect` is not yet
+available for their target.
+
+**Files:**
+
+- Modify: `install.md`
+
+**Step 1: Locate the right anchor in branches C and D**
+
+Run:
+`grep -n "### 6. Verify the installation" install.md`
+
+**Step 2: Insert the protect note**
+
+For each branch (C and D), after step 5 (or 5b) and before step 6,
+add:
+
+```markdown
+### 5c. Optional β€” machine-enforce write protection on `Brain/`
+
+OSB defends `Brain/preferences/`, `retired/`, `log/`, `.snapshots/`,
+and `Brain/_brain.yaml` against accidental writes by the running
+agent through the runtime's native permissions mechanism. `Brain/inbox/`
+stays writable β€” that's where `brain_feedback` legitimately drops
+signals.
+
+Preview the snippet first:
+
+```bash
+o2b brain protect --target <claudecode|codex>
+```
+
+Apply when you are satisfied:
+
+```bash
+o2b brain protect --target <claudecode|codex> --apply
+```
+
+`o2b brain unprotect --target <claudecode|codex>` removes the OSB-owned
+entries. A sidecar manifest at `<vault>/.open-second-brain/protect.lock.json`
+records what `protect` added, so `unprotect` removes exactly that
+and never touches user-authored rules.
+```
+
+For branches A, B, E, add a short note in the closing section:
+"`o2b brain protect` currently supports `claudecode` and `codex`
+targets; the convention-only `_BRAIN.md` instructions are the only
+mechanism available for other runtimes."
+
+**Step 3: Pause for review (no commit)**
+
+### Task 24: Phase 2 close
+
+**Step 1: Full test**
+
+Run: `bun test`
+Expected: every test passes.
+
+**Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 3: Pause for review (no commit)**
+
+---
+
+## Phase 3 β€” Β§15-partial `o2b brain init --starter`
+
+### Task 25: Author the 8 starter preference files
+
+**Objective:** Hand-author 8 markdown files matching the v0.10.x
+preference schema. Mixed confidence, scope, pinned flags.
+
+**Files:**
+
+- Create: `templates/brain-starter/preferences/pref-imperative-commit-messages.md`
+- Create: `templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md`
+- Create: `templates/brain-starter/preferences/pref-prefer-typed-errors.md`
+- Create: `templates/brain-starter/preferences/pref-explicit-imports-only.md`
+- Create: `templates/brain-starter/preferences/pref-changelog-every-release.md`
+- Create: `templates/brain-starter/preferences/pref-russian-in-chat.md`
+- Create: `templates/brain-starter/preferences/pref-test-before-refactor.md`
+- Create: `templates/brain-starter/preferences/pref-prefer-bun-over-npx.md`
+
+**Step 1: For each file, follow this template**
+
+Read `src/core/brain/preference.ts` and `docs/how-it-works.md` Β§
+"A preference's lifecycle" for the canonical frontmatter shape.
+
+A confirmed entry example (`pref-imperative-commit-messages.md`):
+
+```markdown
+---
+id: pref-imperative-commit-messages
+topic: imperative-commit-messages
+principle: Use imperative voice in commit messages β€” "Add", "Fix", "Refactor", not "Added" / "Fixes" / "Refactored".
+scope: process
+signal: positive
+_status: confirmed
+_created_at: 2026-04-01T10:00:00Z
+_confirmed_at: 2026-04-15T10:00:00Z
+_applied_count: 6
+_violated_count: 0
+_confidence: high
+_confidence_value: 0.72
+_last_evidence_at: 2026-05-10T14:00:00Z
+pinned: false
+evidenced_by:
+ - "[[Brain/log/2026-05-15]]"
+ - "[[Brain/log/2026-05-16]]"
+---
+
+# {{principle}}
+
+## Why
+
+Commit titles read as instructions the reader executes mentally. Imperative voice mirrors how git itself describes its operations.
+
+## Origin
+
+Three signals across 14 days in early starter usage.
+```
+
+Repeat per the table below. Vary `_confidence` (high/medium/low),
+`_applied_count`, `scope`, and `pinned` to demonstrate the range.
+One entry must be `_status: unconfirmed` with `unconfirmed_until`
+set so the field's purpose is visible.
+
+| Slug | Scope | Confidence | Pinned | Status |
+|---|---|---|---|---|
+| pref-imperative-commit-messages | process | high | false | confirmed |
+| pref-no-unexplained-abbreviations | writing | high | **true** | confirmed |
+| pref-prefer-typed-errors | coding | medium | false | confirmed |
+| pref-explicit-imports-only | coding | medium | false | confirmed |
+| pref-changelog-every-release | process | high | false | confirmed |
+| pref-russian-in-chat | writing | low | false | confirmed |
+| pref-test-before-refactor | coding | β€” | false | **unconfirmed** |
+| pref-prefer-bun-over-npx | infra | low | false | confirmed |
+
+**Step 2: Pause for review (no commit)**
+
+### Task 26: Author the 3 retired files
+
+**Objective:** Three retire reasons β€” `user-rejected`, `rebutted`,
+`stale-no-evidence` β€” to show the doctor lint surface and the
+retired-pref shape.
+
+**Files:**
+
+- Create: `templates/brain-starter/retired/ret-tabs-over-spaces.md`
+- Create: `templates/brain-starter/retired/ret-no-emojis-in-code.md`
+- Create: `templates/brain-starter/retired/ret-prefer-curl-over-wget.md`
+
+**Step 1: For each file, follow the retired schema**
+
+Reference `src/core/brain/preference.ts:moveToRetired` and `docs/how-it-works.md`
+for the retired frontmatter shape. Example (`ret-tabs-over-spaces.md`):
+
+```markdown
+---
+id: ret-tabs-over-spaces
+topic: tabs-over-spaces
+principle: Use tabs for indentation, not spaces.
+_retired_at: 2026-04-20T09:00:00Z
+_retired_reason: user-rejected
+user_rejected_reason: "Mixed indentation is acceptable in this codebase β€” different repos have different conventions and a single rule can't capture that."
+scope: coding
+_original_status: confirmed
+_applied_count: 2
+_violated_count: 0
+---
+
+# {{principle}}
+
+## Why retired
+
+User rejected the rule explicitly. Reason recorded above.
+```
+
+**Step 2: Pause for review (no commit)**
+
+### Task 27: Author the inbox signal and 6 log days
+
+**Objective:** One pending signal showing the inbox shape; six
+log-day files showing apply-evidence and a retire entry.
+
+**Files:**
+
+- Create: `templates/brain-starter/inbox/sig-2026-05-10-strict-types.md`
+- Create: `templates/brain-starter/log/2026-05-15.md`
+- Create: `templates/brain-starter/log/2026-05-16.md`
+
+**Step 1: Author the signal file**
+
+Schema from `src/core/brain/types.ts:BrainSignal`. Sample:
+
+```markdown
+---
+id: sig-2026-05-10-strict-types
+topic: strict-types-in-public-api
+signal: positive
+principle: Public-API function signatures should be fully typed β€” no implicit any in exports.
+scope: coding
+created_at: 2026-05-10T15:30:00Z
+agent: starter-author
+source: ["[[Daily/2026.05.10]]"]
+source_type: live
+---
+
+## Raw
+
+"Public functions should never accept implicit any β€” readers reading the type signature get the whole contract."
+```
+
+**Step 2: Author the log days**
+
+Sample `2026-05-15.md`:
+
+```markdown
+---
+date: 2026-05-15
+---
+
+## 2026-05-15T14:00:00Z apply-evidence
+- pref: [[pref-imperative-commit-messages]]
+- artifact: [[Brain/log/2026-05-15#example-commit]]
+- result: applied
+- agent: starter-author
+
+## 2026-05-15T15:10:00Z apply-evidence
+- pref: [[pref-no-unexplained-abbreviations]]
+- artifact: [[docs/example-doc.md]]
+- result: applied
+- agent: starter-author
+```
+
+Sample `2026-05-16.md`:
+
+```markdown
+---
+date: 2026-05-16
+---
+
+## 2026-05-16T09:30:00Z apply-evidence
+- pref: [[pref-prefer-typed-errors]]
+- artifact: [[src/example.ts:42-60]]
+- result: applied
+- agent: starter-author
+
+## 2026-05-16T11:00:00Z retire
+- pref: [[ret-tabs-over-spaces]]
+- reason: user-rejected
+- agent: starter-author
+```
+
+**Step 3: Pause for review (no commit)**
+
+### Task 28: `copyStarterBundle` helper
+
+**Objective:** Pure copy helper. Refuses if any of `Brain/preferences/`,
+`retired/`, `inbox/`, `log/` is non-empty. Returns a manifest of what
+was copied.
+
+**Files:**
+
+- Modify: `src/core/brain/init.ts`
+- Create: `tests/core/brain/starter.test.ts`
+
+**Step 1: Failing tests**
+
+```ts
+import { test, expect, describe } from "bun:test";
+import { mkdtempSync, mkdirSync, writeFileSync, readdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { copyStarterBundle } from "../../../src/core/brain/init.ts";
+
+describe("copyStarterBundle", () => {
+ test("copies the 18 starter files into an empty Brain", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-starter-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ const result = copyStarterBundle(vault);
+ expect(result.copied).toHaveLength(14);
+ expect(readdirSync(join(vault, "Brain", "preferences"))).toHaveLength(8);
+ expect(readdirSync(join(vault, "Brain", "retired"))).toHaveLength(3);
+ expect(readdirSync(join(vault, "Brain", "inbox"))).toHaveLength(1);
+ expect(readdirSync(join(vault, "Brain", "log"))).toHaveLength(2);
+ });
+
+ test("refuses to copy when preferences/ already has a file", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-starter-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-existing.md"),
+ "---\nid: pref-existing\n---\n",
+ );
+ expect(() => copyStarterBundle(vault)).toThrow(
+ /already has content/i,
+ );
+ });
+
+ test("custom --starter-path resolves relative to cwd", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-starter-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ const custom = mkdtempSync(join(tmpdir(), "osb-starter-src-"));
+ mkdirSync(join(custom, "preferences"), { recursive: true });
+ writeFileSync(
+ join(custom, "preferences", "pref-x.md"),
+ "---\nid: pref-x\n---\n",
+ );
+ const result = copyStarterBundle(vault, { starterPath: custom });
+ expect(result.copied).toHaveLength(1);
+ });
+});
+```
+
+**Step 2: Run β€” expect failure**
+
+Run: `bun test tests/core/brain/starter.test.ts`
+
+**Step 3: Implement**
+
+Add to `src/core/brain/init.ts`:
+
+```ts
+import { readdirSync, copyFileSync } from "node:fs";
+
+export interface StarterBundleResult {
+ readonly copied: ReadonlyArray<string>;
+}
+
+export interface CopyStarterOptions {
+ readonly starterPath?: string;
+}
+
+const DEFAULT_STARTER_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "..",
+ "templates",
+ "brain-starter",
+);
+
+const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;
+
+export function copyStarterBundle(
+ vault: string,
+ opts: CopyStarterOptions = {},
+): StarterBundleResult {
+ const src = opts.starterPath ?? DEFAULT_STARTER_DIR;
+ for (const sub of STARTER_TARGETS) {
+ const dir = join(vault, "Brain", sub);
+ if (!existsSync(dir)) {
+ throw new Error(
+ `Brain/${sub} does not exist β€” run \`o2b brain init\` without --starter first`,
+ );
+ }
+ const existing = readdirSync(dir).filter((n) => !n.startsWith("."));
+ if (existing.length > 0) {
+ throw new Error(
+ `Brain/${sub} already has content β€” --starter is intended for fresh vaults. ` +
+ `Inspect the bundle at ${src} and copy individual files manually if needed.`,
+ );
+ }
+ }
+ const copied: string[] = [];
+ for (const sub of STARTER_TARGETS) {
+ const srcDir = join(src, sub);
+ if (!existsSync(srcDir)) continue;
+ for (const name of readdirSync(srcDir)) {
+ const from = join(srcDir, name);
+ const to = join(vault, "Brain", sub, name);
+ copyFileSync(from, to);
+ copied.push(join("Brain", sub, name));
+ }
+ }
+ return Object.freeze({ copied });
+}
+```
+
+**Step 4: Run β€” expect pass**
+
+Run: `bun test tests/core/brain/starter.test.ts`
+Expected: 3 passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 29: Wire `--starter` and `--starter-path` flags
+
+**Objective:** `o2b brain init [--starter] [--starter-path <dir>]`
+calls `copyStarterBundle` after the existing init succeeds.
+
+**Files:**
+
+- Modify: `src/cli/brain.ts`
+- Modify: `src/core/brain/init.ts` (option threading on `bootstrapBrain`)
+
+**Step 1: Extend `BootstrapBrainOptions`**
+
+```ts
+export interface BootstrapBrainOptions {
+ // ... existing fields ...
+ readonly starter?: boolean;
+ readonly starterPath?: string;
+}
+```
+
+In `bootstrapBrain`, after the existing logic, if `opts.starter`:
+
+```ts
+const starterResult = copyStarterBundle(vault, {
+ starterPath: opts.starterPath,
+});
+created.push(...starterResult.copied);
+```
+
+**Step 2: Surface in CLI**
+
+In `src/cli/brain.ts`, locate the existing `init` parser. Add
+`--starter` (boolean) and `--starter-path <path>` (string).
+
+**Step 3: CLI test**
+
+Add to an existing CLI test file (or new `tests/cli/brain-init-starter.test.ts`):
+
+```ts
+import { test, expect } from "bun:test";
+// ... setup ...
+
+test("o2b brain init --starter copies 18 files", () => {
+ // construct config + vault, run cmdBrainInit with ["--starter"],
+ // assert the four Brain/ subdirs have the expected counts.
+});
+```
+
+**Step 4: Run tests**
+
+Run: `bun test tests/cli/`
+Expected: existing passes + new starter test passes.
+
+**Step 5: Pause for review (no commit)**
+
+### Task 30: Doctor cleanliness gate
+
+**Objective:** A fresh vault initialised with `--starter` passes
+`o2b brain doctor` with zero warnings. This is a CI gate β€” the
+starter must remain doctor-clean as the project evolves.
+
+**Files:**
+
+- Modify: `tests/core/brain/starter.test.ts`
+
+**Step 1: Add the smoke test**
+
+```ts
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+
+test("doctor is clean after init --starter on a fresh vault", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-starter-doctor-"));
+ // Write a minimal machine config first; bootstrapBrain refuses
+ // without it.
+ // ... setup machine config ...
+ bootstrapBrain(vault, { starter: true });
+ const result = runDoctor(vault);
+ expect(result.warnings).toEqual([]);
+ expect(result.errors).toEqual([]);
+});
+```
+
+Adjust `runDoctor` import to the actual exported name.
+
+**Step 2: Run**
+
+Run: `bun test tests/core/brain/starter.test.ts`
+Expected: 4 passes (the existing 3 plus doctor smoke).
+
+If doctor flags any issue, fix the offending starter file (not the
+doctor β€” doctor's pass/fail is the gate).
+
+**Step 3: Pause for review (no commit)**
+
+### Task 31: Dream no-op gate
+
+**Objective:** A fresh vault initialised with `--starter` is a no-op
+under `o2b brain dream --now <fixed-time>`.
+
+**Files:**
+
+- Modify: `tests/core/brain/starter.test.ts`
+
+**Step 1: Add the dream no-op test**
+
+```ts
+import { dream } from "../../../src/core/brain/dream.ts";
+
+test("dream is no-op on the fresh --starter vault", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-starter-dream-"));
+ // ... setup as in the doctor smoke test ...
+ bootstrapBrain(vault, { starter: true });
+ const result = dream(vault, {
+ now: new Date("2026-05-17T12:00:00Z"),
+ dryRun: true,
+ });
+ expect(result.changed).toBe(false);
+});
+```
+
+**Step 2: Run**
+
+Run: `bun test tests/core/brain/starter.test.ts`
+Expected: 5 passes.
+
+If dream reports `changed: true`, audit the starter content: the
+unconfirmed preference's `unconfirmed_until` must be after the fixed
+`--now` so the trial-window-expired path does not fire; no log
+entries should be old enough to flip a counter.
+
+**Step 3: Pause for review (no commit)**
+
+### Task 32: install.md addendum for Β§15
+
+**Objective:** Append a one-line "or `o2b brain init --starter` if you
+want example preferences" to the init step in each install branch.
+
+**Files:**
+
+- Modify: `install.md`
+
+**Step 1: Locate each branch's init step**
+
+Run:
+`grep -n "### 4. Initialize the vault" install.md`
+
+**Step 2: Append the note**
+
+After the existing `o2b init` invocation paragraph in each of branches
+A, B, C, D, E, add:
+
+```markdown
+Optionally append `--starter` to drop a bundled example set of 8
+preferences, 3 retired entries, 1 inbox signal, and 6 log days. The
+bundle passes `o2b brain doctor` cleanly and is a no-op under
+`o2b brain dream`. The starter refuses to run on a non-empty Brain.
+```
+
+**Step 3: Pause for review (no commit)**
+
+### Task 33: Phase 3 close
+
+**Step 1: Full test**
+
+Run: `bun test`
+Expected: every test passes.
+
+**Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 3: Pause for review (no commit)**
+
+---
+
+## Phase 4 β€” Release housekeeping
+
+### Task 34: CHANGELOG entry
+
+**Objective:** Single v0.10.4 block under the next version anchor;
+no `[Unreleased]` (per memory `feedback_no_unreleased_section`).
+
+**Files:**
+
+- Modify: `CHANGELOG.md`
+
+**Step 1: Read the current top of CHANGELOG**
+
+Run: `head -40 CHANGELOG.md`
+
+**Step 2: Insert the new entry directly under the H1**
+
+Use the draft from the design doc:
+
+```markdown
+## v0.10.4 β€” Brain onboarding quality
+
+### Added
+
+- Β§18 β€” `o2b brain protect --target {claudecode|codex}` writes a
+ managed, idempotent block into the runtime's native permissions
+ config that denies writes to `Brain/preferences/`, `retired/`,
+ `log/`, `.snapshots/`, and `_brain.yaml` while leaving
+ `Brain/inbox/` writable. Pair `o2b brain unprotect` removes the
+ block. `--print` outputs the snippet without touching disk;
+ `--apply` writes and backs up the prior config.
+- Β§4 (partial) β€” per-runtime identity-reminder templates for the
+ two runtimes that read `buildReminder` per-turn / per-action:
+ `templates/identity-reminder.{hermes,openclaw}.txt`. Resolver in
+ `buildReminder` accepts an explicit `target`, falls back to
+ `O2B_TARGET`, and finally to the common template. Hermes Python
+ shim has parity through a pinned fixture test. The common
+ `identity-reminder.txt` is unchanged. Claude Code and Codex steer
+ through `hooks/lib/messages.ts`, which is a separate mechanism not
+ touched here.
+- Β§15 (partial) β€” `o2b brain init --starter` drops a curated bundle
+ of 8 confirmed preferences, 3 retired, 1 inbox signal, and 6 log
+ days into a fresh Brain. The bundle passes `o2b brain doctor`
+ cleanly and is a no-op under `o2b brain dream` at install time.
+ Refuses to run on a non-empty Brain.
+
+### Deferred
+
+Full multi-runtime `o2b install` orchestrator (Β§4 second half),
+interactive `o2b init --interactive` wizard (Β§15 second half), and
+`brain-memory` SKILL "good-vs-bad" examples section. Triggers to
+revisit are recorded in the vault summary's "Deferred work"
+section.
+```
+
+**Step 3: Pause for review (no commit)**
+
+### Task 35: Version bump and version-mirror sync
+
+**Objective:** Set `package.json` version to `0.10.4` and propagate
+to every mirror file via `sync-version`.
+
+**Files:**
+
+- Modify: `package.json`
+- Auto-modified by sync-version: `.claude-plugin/plugin.json`,
+ `.codex-plugin/plugin.json`, `plugins/codex/.codex-plugin/plugin.json`,
+ `plugins/hermes/plugin.yaml`, `plugin.yaml`, `openclaw.plugin.json`,
+ `__init__.py`
+
+**Step 1: Edit `package.json`**
+
+Change `"version": "0.10.3"` to `"version": "0.10.4"`.
+
+**Step 2: Run sync-version**
+
+Run: `bun run sync-version`
+Expected: all mirror files updated to `0.10.4`.
+
+**Step 3: Verify**
+
+Run: `bun run sync-version:check`
+Expected: exit 0 ("all in sync").
+
+**Step 4: Pause for review (no commit)**
+
+### Task 36: Final green gate
+
+**Step 1: Full TS test**
+
+Run: `bun test`
+Expected: every test passes.
+
+**Step 2: Typecheck**
+
+Run: `bun run typecheck`
+Expected: 0 errors.
+
+**Step 3: Python tests**
+
+Run: `python3 -m unittest discover tests/python/`
+Expected: all pass.
+
+**Step 4: Optional β€” OpenClaw build**
+
+Run: `bun run build:openclaw`
+Expected: success.
+
+**Step 5: Verify install.md and CHANGELOG render**
+
+Run:
+```bash
+grep -c "v0.10.4" CHANGELOG.md
+grep -c "o2b brain protect" install.md
+grep -c "o2b brain init --starter" install.md
+```
+
+Expected: `β‰₯1` for each.
+
+**Step 6: Pause for final review (no commit)**
+
+---
+
+## Open items left for impl-time decisions
+
+The design doc's three open questions are restated here so the
+implementer encounters them in context:
+
+1. **Backup file lifecycle for `protect --apply`.** Current plan
+ always writes a `.bak.<ts>` and never prunes. If the user
+ prefers opt-out behaviour, add `--no-backup` on the CLI surface
+ in Task 22.
+
+2. **Codex managed-block uniqueness across multiple vaults.** Current
+ plan: one fence per host (vault paths concatenate inside the same
+ `[permissions.osb_protected.filesystem]`). If multi-vault use
+ becomes common, the renderer in Task 15 will need per-vault
+ profile names (`osb_protected_<vault-hash>`).
+
+3. **Starter i18n.** No `--starter-lang` switch in v0.10.4. The
+ bundled `pref-russian-in-chat` plus all-English peers demonstrate
+ the mixed-language policy from `brain-memory` skill organically.
+
+---
+
+## References
+
+- Design doc: [`2026-05-17-brain-onboarding-quality-design.md`](./2026-05-17-brain-onboarding-quality-design.md)
+- Vault summary: `Projects/OpenSecondBrain/Features/_summary.md`
+ (Β§4, Β§15, Β§18, "Deferred work")
+- Codex permissions doc:
+ <https://developers.openai.com/codex/config-advanced>
+- Claude Code permissions: project's prior installer notes inside
+ `install.md` already reference `settings.json` structure.
+- Prior impl plan to mirror structurally:
+ [`2026-05-17-tier-a-snapshot-confidence-pointer-impl.md`](./2026-05-17-tier-a-snapshot-confidence-pointer-impl.md).
diff --git a/install.md b/install.md
index e9ed9b5d..4123f22a 100644
--- a/install.md
+++ b/install.md
@@ -186,6 +186,14 @@ o2b brain init --vault /path/to/vault \
--primary-agent "<chosen-agent-name>"
```
+**Optional β€” append `--starter` to bootstrap with a worked example
+set.** `o2b brain init --vault /path/to/vault --starter` drops a curated
+bundle (8 preferences, 3 retired entries, 1 inbox signal, 6 log days)
+into the fresh `Brain/`. The bundle is byte-stable, passes
+`o2b brain doctor` cleanly, and is a no-op under `o2b brain dream`
+at install time. The starter refuses to run on a non-empty Brain β€”
+it is for the first-init experience only.
+
`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md`
and persists `agent_name` into the plugin config
(`~/.config/open-second-brain/config.yaml`). `--timezone` validates the
@@ -458,6 +466,12 @@ o2b init --vault /path/to/vault --name "My Second Brain" \
o2b brain init --vault /path/to/vault
```
+Append `--starter` to drop the bundled example set (8 preferences,
+3 retired entries, 1 inbox signal, 6 log days) into the fresh
+`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a
+no-op under `o2b brain dream` at install time; it refuses to run
+on a non-empty Brain.
+
`--agent-name` writes the chosen name into `AI Wiki/identity/agents.md`
and persists `agent_name` into the plugin config
(`~/.config/open-second-brain/config.yaml`). `--timezone` validates the
@@ -702,6 +716,12 @@ o2b init --vault /path/to/vault --name "My Second Brain" \
o2b brain init --vault /path/to/vault
```
+Append `--starter` to drop the bundled example set (8 preferences,
+3 retired entries, 1 inbox signal, 6 log days) into the fresh
+`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a
+no-op under `o2b brain dream` at install time; it refuses to run
+on a non-empty Brain.
+
`--timezone` validates the IANA name via stdlib `zoneinfo` and persists
it to the plugin config. From this moment on, every Daily entry is
stamped in that timezone regardless of the host's clock.
@@ -766,6 +786,33 @@ The hook invokes `o2b-hook` from PATH. That CLI was symlinked into
`o2b-hook` is missing from PATH the hook fails closed (turn proceeds
normally with a stderr trace) β€” re-run step 3 to fix.
+### 6c. Optional β€” machine-enforce write protection on `Brain/`
+
+OSB defends `Brain/preferences/`, `retired/`, `log/`, `.snapshots/`,
+and `Brain/_brain.yaml` against accidental writes by the agent
+through Codex's native `[permissions.osb_protected.filesystem]`
+table. `Brain/inbox/` stays writable β€” that is where
+`brain_feedback` legitimately drops signals.
+
+Preview the snippet without touching disk:
+
+```bash
+o2b brain protect --target codex --vault /path/to/vault
+```
+
+Apply when satisfied:
+
+```bash
+o2b brain protect --target codex --vault /path/to/vault --apply
+```
+
+`o2b brain unprotect --target codex --vault /path/to/vault` removes
+the OSB-managed block (a `# >>> open-second-brain managed >>>`
+fence in `~/.codex/config.toml`). A sidecar manifest at
+`<vault>/.open-second-brain/protect.lock.json` records what was
+added, so `unprotect` removes exactly the OSB rules and never
+touches user-authored config.
+
### 7. Update
```bash
@@ -937,6 +984,12 @@ o2b init --vault /path/to/vault --name "My Second Brain" \
o2b brain init --vault /path/to/vault
```
+Append `--starter` to drop the bundled example set (8 preferences,
+3 retired entries, 1 inbox signal, 6 log days) into the fresh
+`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a
+no-op under `o2b brain dream` at install time; it refuses to run
+on a non-empty Brain.
+
`o2b init` persists all three values (`vault`, `agent_name`, `timezone`)
into `~/.config/open-second-brain/config.yaml`. The `.mcp.json` that
Claude auto-registered is intentionally minimal β€” it points only at
@@ -983,6 +1036,34 @@ hook fire end-to-end use `--output-format=stream-json --verbose
--include-hook-events`; you should see `hook_started` /
`hook_response` events around each `Write` / `Edit`.
+### 6c. Optional β€” machine-enforce write protection on `Brain/`
+
+OSB defends `Brain/preferences/`, `retired/`, `log/`, `.snapshots/`,
+and `Brain/_brain.yaml` against accidental writes by the agent
+through Claude Code's native `permissions.deny` list. `Brain/inbox/`
+stays writable β€” that is where `brain_feedback` legitimately drops
+signals.
+
+Preview the snippet without touching disk:
+
+```bash
+o2b brain protect --target claudecode --vault /path/to/vault
+```
+
+Apply when satisfied:
+
+```bash
+o2b brain protect --target claudecode --vault /path/to/vault --apply
+```
+
+`o2b brain unprotect --target claudecode --vault /path/to/vault`
+removes the OSB-managed entries from `<vault>/.claude/settings.json`.
+A sidecar manifest at
+`<vault>/.open-second-brain/protect.lock.json` records exactly which
+`permissions.deny` / `permissions.allow` strings OSB owns, so
+`unprotect` removes only those and never touches user-authored
+rules.
+
### 7. Update
```bash
@@ -1084,6 +1165,12 @@ o2b init --vault /path/to/vault --name "My Second Brain" \
o2b brain init --vault /path/to/vault
```
+Append `--starter` to drop the bundled example set (8 preferences,
+3 retired entries, 1 inbox signal, 6 log days) into the fresh
+`Brain/`. The bundle passes `o2b brain doctor` cleanly and is a
+no-op under `o2b brain dream` at install time; it refuses to run
+on a non-empty Brain.
+
This is identical across runtimes β€” the values are persisted into
`~/.config/open-second-brain/config.yaml` and read back by the MCP
server with no further wiring required.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 81348a4f..befe76bd 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.3",
+ "version": "0.10.4",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index bbae069d..02f9548d 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -2158,15 +2158,64 @@ import { readFileSync as readFileSync4 } from "node:fs";
import { dirname as dirname3, resolve } from "node:path";
import { fileURLToPath } from "node:url";
var TEMPLATE_PATH = resolve(dirname3(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);
+}
+var commonTemplateCache;
function loadReminderTemplate() {
+ if (commonTemplateCache !== undefined)
+ return commonTemplateCache;
try {
- return readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();
+ commonTemplateCache = readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();
+ return commonTemplateCache;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`);
}
}
-function buildReminder(agent) {
+var TEMPLATES_DIR = resolve(dirname3(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`)
+])));
+var TEMPLATE_CACHE = new Map;
+function tryReadTargetTemplate(target) {
+ const cached = TEMPLATE_CACHE.get(target);
+ if (cached !== undefined)
+ return cached;
+ let body;
+ try {
+ body = readFileSync4(PER_TARGET_PATHS[target], "utf8").trimEnd();
+ } catch (err) {
+ if (err.code !== "ENOENT")
+ throw err;
+ body = null;
+ }
+ TEMPLATE_CACHE.set(target, body);
+ return body;
+}
+var envWarnedOnce = false;
+function resolveTargetFromEnv() {
+ const raw = process.env.O2B_TARGET;
+ if (raw === undefined || raw === "")
+ return;
+ if (isRuntimeTarget(raw))
+ return raw;
+ if (!envWarnedOnce) {
+ envWarnedOnce = true;
+ process.stderr.write(`open-second-brain: unknown O2B_TARGET='${raw}', using common identity template
+`);
+ }
+ return;
+}
+function buildReminder(agent, target) {
+ const effective = target ?? resolveTargetFromEnv();
+ if (effective !== undefined) {
+ const tpl = tryReadTargetTemplate(effective);
+ if (tpl !== null)
+ return tpl.replace(/\{agent\}/g, agent);
+ }
return loadReminderTemplate().replace(/\{agent\}/g, agent);
}
@@ -2342,12 +2391,12 @@ function tzOffsetMinutes(instantMs, tz) {
const localUtcMs = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
return Math.round((localUtcMs - instantMs) / 60000);
}
-// src/core/pay-memory/redactor.ts
+// src/core/redactor.ts
var PLACEHOLDER = "***REDACTED***";
var MAX_REDACTOR_INPUT = 256 * 1024;
var TRUNCATION_MARKER = `
-[…truncated for size; original exceeded 256 KB. Inspect \`pay\` raw output before sharing.]
+[…truncated for size; original exceeded 256 KB. Inspect raw output before sharing.]
`;
var SECRET_KEYS = [
"api_key",
@@ -3580,7 +3629,7 @@ var openclaw_default = definePluginEntry({
const agent = normalizeAgentArgument(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
if (agent === "agent")
return;
- return { prependContext: buildReminder(agent) };
+ return { prependContext: buildReminder(agent, "openclaw") };
});
api.registerTool({
name: "second_brain_status",
diff --git a/package.json b/package.json
index 1381f779..44d83301 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.3",
+ "version": "0.10.4",
"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 8076ba81..853c6587 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.3"
+version: "0.10.4"
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 dac071bd..45655561 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.3",
+ "version": "0.10.4",
"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/__init__.py b/plugins/hermes/__init__.py
index 5ab07aa9..60017f8c 100644
--- a/plugins/hermes/__init__.py
+++ b/plugins/hermes/__init__.py
@@ -26,19 +26,48 @@ from typing import Any
PLUGIN_NAME = "open-second-brain"
_REPO_ROOT = Path(__file__).resolve().parents[2]
-_TEMPLATE_PATH = _REPO_ROOT / "templates" / "identity-reminder.txt"
+_TEMPLATES_DIR = _REPO_ROOT / "templates"
+_COMMON_TEMPLATE_PATH = _TEMPLATES_DIR / "identity-reminder.txt"
+# This shim runs inside Hermes, so the target is fixed at the call site
+# rather than threaded through an env var β€” mirrors the TypeScript
+# behaviour where the OpenClaw plugin passes its own target literal.
+_TARGET = "hermes"
+_TARGET_TEMPLATE_PATH = _TEMPLATES_DIR / f"identity-reminder.{_TARGET}.txt"
_AGENT_LINE_RE = re.compile(r"^\s*(agent_name|agentName)\s*:\s*['\"]?([^'\"\n]+?)['\"]?\s*$", re.MULTILINE)
+_template_cache: str | None = None
-def _load_reminder_template() -> str:
- """Read the shared reminder template.
- The TypeScript core (`src/core/identity-reminder.ts`) reads the same
- file. Keeping one source on disk avoids manual mirroring of the wording
- between Python and TS. CI fails the build if the file is missing.
+def _load_reminder_template() -> str:
+ """Read the Hermes reminder template, falling back to the common file.
+
+ This shim is hermes-only β€” it does not honour ``O2B_TARGET``. The
+ TypeScript ``buildReminder`` has a three-step resolver (explicit
+ target -> env -> common); the Python equivalent collapses to
+ ``hermes`` -> common because Hermes always runs the Hermes target.
+ Both languages read the same templates on disk and a fixture-pinned
+ test catches text drift.
+
+ The body is cached after the first call. Hermes' ``pre_llm_call``
+ hook fires every turn; templates are installation-time artifacts
+ that do not change at runtime, so a single read per process is
+ enough. A gateway restart (every plugin update) flushes the cache.
"""
- return _TEMPLATE_PATH.read_text(encoding="utf-8").rstrip()
+ global _template_cache
+ if _template_cache is not None:
+ return _template_cache
+ if _TARGET_TEMPLATE_PATH.is_file():
+ _template_cache = _TARGET_TEMPLATE_PATH.read_text(encoding="utf-8").rstrip()
+ else:
+ _template_cache = _COMMON_TEMPLATE_PATH.read_text(encoding="utf-8").rstrip()
+ return _template_cache
+
+
+def _reset_template_cache_for_tests() -> None:
+ """Test-only: drop the cached body so a fixture rewrite is visible."""
+ global _template_cache
+ _template_cache = None
def _config_path() -> Path:
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index fe7c0981..4f56b8d2 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.3"
+version: "0.10.4"
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 d97865a4..9f78c996 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.3"
+version = "0.10.4"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index f03dafcf..7690b6c8 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -61,6 +61,14 @@ import {
import { renderDigest, type RenderDigestOptions } from "../core/brain/digest.ts";
import { runDoctor } from "../core/brain/doctor.ts";
import { setPinned } from "../core/brain/pin.ts";
+import {
+ applyProtect,
+ BrainProtectError,
+ isProtectTarget,
+ printSnippet,
+ PROTECT_TARGETS,
+ unprotect,
+} from "../core/brain/protect.ts";
import { setPrimaryAgent } from "../core/brain/set-primary.ts";
import { writeSignal } from "../core/brain/signal.ts";
import {
@@ -156,6 +164,8 @@ async function cmdBrainInit(argv: string[]): Promise<number> {
config: { type: "string" },
force: { type: "boolean" },
"primary-agent": { type: "string" },
+ starter: { type: "boolean" },
+ "starter-path": { type: "string" },
json: { type: "boolean" },
});
const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
@@ -176,12 +186,25 @@ async function cmdBrainInit(argv: string[]): Promise<number> {
primaryAgent = trimmed;
}
+ const starterPathFlag = flags["starter-path"];
+ let starterPath: string | undefined;
+ if (typeof starterPathFlag === "string") {
+ starterPath = starterPathFlag.trim();
+ if (starterPath.length === 0) {
+ return fail(
+ "brain init: --starter-path must be a non-empty path when provided",
+ );
+ }
+ }
+
let result;
try {
result = bootstrapBrain(vault, {
force: Boolean(flags["force"]),
configPath: config,
+ starter: Boolean(flags["starter"]),
...(primaryAgent !== undefined ? { primaryAgent } : {}),
+ ...(starterPath !== undefined ? { starterPath } : {}),
});
} catch (exc) {
return fail(`failed to initialize Brain: ${(exc as Error).message ?? exc}`);
@@ -874,6 +897,103 @@ async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
return 0;
}
+async function cmdBrainProtect(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ target: { type: "string", required: true },
+ vault: { type: "string" },
+ apply: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
+ if (!isProtectTarget(rawTarget)) {
+ return fail(
+ `brain protect --target='${flags["target"]}' is unknown; `
+ + `supported targets: ${PROTECT_TARGETS.join(", ")}`,
+ );
+ }
+ const target = rawTarget;
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+
+ try {
+ if (flags["apply"]) {
+ const result = applyProtect({ target, vault });
+ if (flags["json"]) {
+ okJson({
+ target: result.target,
+ destination: result.destination,
+ changed: result.changed,
+ backup: result.backupPath || null,
+ });
+ return 0;
+ }
+ const head = result.changed
+ ? `brain protect: applied to ${result.destination}`
+ : `brain protect: no changes (${result.destination} already current)`;
+ ok(head);
+ if (result.backupPath) ok(` backup: ${result.backupPath}`);
+ return 0;
+ }
+ // --print (default): emit the snippet body, no writes.
+ const snippet = printSnippet({ target, vault });
+ if (flags["json"]) {
+ okJson({
+ target: snippet.target,
+ destination: snippet.destination,
+ body: snippet.body,
+ });
+ return 0;
+ }
+ info(`# o2b brain protect --target ${target}`);
+ info(`# destination: ${snippet.destination}`);
+ info(`# preview only; re-run with --apply to write the file`);
+ process.stdout.write(snippet.body);
+ return 0;
+ } catch (exc) {
+ if (exc instanceof BrainProtectError) {
+ return fail(`brain protect failed: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
+async function cmdBrainUnprotect(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ target: { type: "string", required: true },
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
+ if (!isProtectTarget(rawTarget)) {
+ return fail(
+ `brain unprotect --target='${flags["target"]}' is unknown; `
+ + `supported targets: ${PROTECT_TARGETS.join(", ")}`,
+ );
+ }
+ const target = rawTarget;
+ const vault = resolveBrainVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
+
+ try {
+ unprotect({ target, vault });
+ } catch (exc) {
+ if (exc instanceof BrainProtectError) {
+ return fail(`brain unprotect failed: ${exc.message}`);
+ }
+ throw exc;
+ }
+ if (flags["json"]) {
+ okJson({ target, vault });
+ } else {
+ ok(`brain unprotect: removed OSB-managed rules for target=${target}`);
+ }
+ return 0;
+}
+
async function cmdBrainPin(argv: string[]): Promise<number> {
return await pinOrUnpin(argv, true);
}
@@ -1497,6 +1617,8 @@ Brain verbs (observing memory):
pin Mark a preference exempt from automatic retire (idempotent)
unpin Clear the pinned flag (idempotent)
set-primary Declare or clear primary_agent in _brain.yaml (--clear)
+ protect Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
+ unprotect Remove OSB-managed deny rules for the chosen target (--target)
snapshot diff Read-only diff between two snapshots, or snapshot vs live
rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
--dry-run previews via the same diff renderer)
@@ -1647,6 +1769,10 @@ export async function handleBrainSubcommand(
return await cmdBrainUnpin(rest);
case "set-primary":
return await cmdBrainSetPrimary(rest);
+ case "protect":
+ return await cmdBrainProtect(rest);
+ case "unprotect":
+ return await cmdBrainUnprotect(rest);
case "snapshot":
return await handleBrainSnapshotSubcommand(rest);
case "rollback":
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 32a544b2..88d778fb 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -28,12 +28,20 @@
* never a torn hybrid.
*/
-import { existsSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ statSync,
+} from "node:fs";
+import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { defaultConfigPath } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { escapeRegex } from "../strings.ts";
import {
brainConfigPath,
brainDirs,
@@ -47,6 +55,121 @@ import {
import type { BrainConfig } from "./types.ts";
import { DEFAULT_BRAIN_CONFIG } from "./policy.ts";
+const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;
+
+const DEFAULT_STARTER_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "..",
+ "templates",
+ "brain-starter",
+);
+
+export class BrainStarterError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "BrainStarterError";
+ }
+}
+
+export interface CopyStarterOptions {
+ /** Override the source directory; defaults to the bundled `templates/brain-starter/`. */
+ readonly starterPath?: string;
+}
+
+export interface StarterBundleResult {
+ /** Vault-relative paths newly written. */
+ readonly copied: ReadonlyArray<string>;
+}
+
+/**
+ * Copy the bundled starter set into `<vault>/Brain/`. Refuses when any
+ * of `preferences/`, `retired/`, `inbox/`, `log/` already contains a
+ * non-dotfile entry β€” the starter is for fresh vaults.
+ *
+ * Hidden files (those whose name starts with `.`) are ignored when
+ * checking emptiness so a `.gitkeep`-style placeholder does not block
+ * the copy.
+ */
+export function copyStarterBundle(
+ vault: string,
+ opts: CopyStarterOptions = {},
+): StarterBundleResult {
+ const src = opts.starterPath ?? DEFAULT_STARTER_DIR;
+ try {
+ if (!statSync(src).isDirectory()) {
+ throw new BrainStarterError(
+ `starter source is not a directory: ${src}`,
+ );
+ }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ throw new BrainStarterError(`starter source does not exist: ${src}`);
+ }
+ throw err;
+ }
+ for (const sub of STARTER_TARGETS) {
+ const dir = join(vault, "Brain", sub);
+ let entries;
+ try {
+ // `withFileTypes` returns Dirent objects so we avoid a `statSync`
+ // per child entry β€” one syscall per directory instead of N+1.
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ throw new BrainStarterError(
+ `Brain/${sub} does not exist β€” run \`o2b brain init\` (without --starter) first`,
+ );
+ }
+ throw err;
+ }
+ // "Non-empty" means anything the user (or a prior dream pass)
+ // could have left here. The only acceptable non-dotfile entry
+ // bootstrap places under a starter target is `inbox/processed/` β€”
+ // we whitelist that one explicitly so a freshly initialised vault
+ // does not trip the guard, but any other subdirectory (e.g. a
+ // user-created `preferences/custom/`) counts as content and
+ // refuses the starter.
+ const hasUserContent = entries.some((e) => {
+ if (e.name.startsWith(".")) return false;
+ if (sub === "inbox" && e.isDirectory() && e.name === "processed") {
+ return false;
+ }
+ return true;
+ });
+ if (hasUserContent) {
+ throw new BrainStarterError(
+ `Brain/${sub} already has content β€” \`--starter\` is intended for fresh vaults. `
+ + `Inspect the bundle at ${src} and copy individual files manually if needed.`,
+ );
+ }
+ }
+ const copied: string[] = [];
+ for (const sub of STARTER_TARGETS) {
+ const srcDir = join(src, sub);
+ if (!existsSync(srcDir)) continue;
+ const destDir = join(vault, "Brain", 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
+ // Brain content. The pre-check above already guarantees the
+ // destination is empty, so collisions are impossible.
+ cpSync(srcDir, destDir, {
+ recursive: true,
+ filter: (p) => !basename(p).startsWith("."),
+ });
+ // Report from the source listing β€” bootstrapBrain may have left
+ // sibling subdirs in the destination (e.g. `inbox/processed/`)
+ // 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));
+ }
+ }
+ return Object.freeze({ copied });
+}
+
// Resolve template paths relative to this source file. `import.meta.url`
// is stable under both `bun run` (TS source) and any future build that
// keeps the template files alongside the bundled JS.
@@ -88,6 +211,15 @@ export interface BootstrapBrainOptions {
* idempotent and won't disturb the rest of the file).
*/
readonly primaryAgent?: string;
+ /**
+ * Drop the bundled starter set (8 preferences, 3 retired, 1 inbox
+ * signal, 2 log days) into the freshly initialised `Brain/`.
+ * Refuses to run if any of those subdirectories is non-empty;
+ * `--starter` is for first-init only.
+ */
+ readonly starter?: boolean;
+ /** Override the starter source path (defaults to bundled). */
+ readonly starterPath?: string;
}
export interface BootstrapBrainResult {
@@ -204,6 +336,13 @@ export function bootstrapBrain(
created.push(overviewRel);
}
+ if (opts.starter === true) {
+ const starterResult = copyStarterBundle(vault, {
+ starterPath: opts.starterPath,
+ });
+ created.push(...starterResult.copied);
+ }
+
return { created, overwritten, skipped };
}
@@ -260,10 +399,6 @@ function renderTemplate(
return out;
}
-function escapeRegex(text: string): string {
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
/**
* Replace the `primary_agent: null` line in the default `_brain.yaml`
* body with the operator-supplied value, when provided. Trimmed,
diff --git a/src/core/brain/protect.ts b/src/core/brain/protect.ts
new file mode 100644
index 00000000..a8937646
--- /dev/null
+++ b/src/core/brain/protect.ts
@@ -0,0 +1,710 @@
+/**
+ * Β§18 of the OSB features summary β€” machine-enforced write protection
+ * for the `Brain/` subtree against the two runtimes whose native
+ * config supports path-level deny / allow rules.
+ *
+ * Protected paths (vault-relative):
+ * - `Brain/preferences/**` β€” deny Write / Edit
+ * - `Brain/retired/**` β€” deny Write / Edit
+ * - `Brain/log/**` β€” deny Write / Edit
+ * - `Brain/.snapshots/**` β€” deny Write / Edit
+ * - `Brain/_brain.yaml` β€” deny Write / Edit
+ * - `Brain/inbox/**` β€” explicit allow Write (the agent
+ * legitimately drops signals here through `brain_feedback`)
+ *
+ * Targets:
+ * - **claudecode** β€” patches `<vault>/.claude/settings.json` with a
+ * `permissions.deny` / `permissions.allow` array, tracking
+ * OSB-owned entries through a sidecar manifest at
+ * `<vault>/.open-second-brain/protect.lock.json`.
+ * - **codex** β€” patches `~/.codex/config.toml` with a managed
+ * fence (`# >>> open-second-brain managed >>>` ... `# <<<`)
+ * containing `[permissions.osb_protected.filesystem]` plus
+ * `default_permissions = "osb_protected"`.
+ *
+ * Both targets are fully idempotent: a second `applyProtect` on the
+ * same state is a byte-identical no-op, and `unprotect` removes
+ * exactly the entries the matching `applyProtect` added.
+ */
+
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+} from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { escapeRegex } from "../strings.ts";
+import { brainConfigPath, brainDirs } from "./paths.ts";
+
+/** Bumped on any structural change to manifest / fence layout. */
+export const PROTECT_SCHEMA_VERSION = 1;
+
+export const PROTECT_TARGETS = ["claudecode", "codex"] as const;
+export type ProtectTarget = (typeof PROTECT_TARGETS)[number];
+
+export function isProtectTarget(value: string | undefined): value is ProtectTarget {
+ return (
+ typeof value === "string"
+ && (PROTECT_TARGETS as readonly string[]).includes(value)
+ );
+}
+
+export class BrainProtectError extends Error {
+ readonly code: string;
+ readonly detail?: unknown;
+
+ constructor(message: string, info: { code: string; detail?: unknown } = { code: "BRAIN_PROTECT" }) {
+ super(message);
+ this.name = "BrainProtectError";
+ this.code = info.code;
+ if (info.detail !== undefined) this.detail = info.detail;
+ }
+}
+
+export interface ProtectRule {
+ readonly kind: "deny" | "allow";
+ readonly action: "Write" | "Edit";
+ readonly path: string;
+}
+
+export interface RenderedSnippet {
+ readonly target: ProtectTarget;
+ readonly body: string;
+ readonly destination: string;
+}
+
+export interface ApplyResult {
+ readonly target: ProtectTarget;
+ readonly destination: string;
+ /** Empty string when no backup was written (no prior content to save). */
+ readonly backupPath: string;
+ readonly changed: boolean;
+}
+
+export interface ApplyOptions {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+ /** Test seam: override `$HOME` when resolving the Codex config path. */
+ readonly __homeOverride?: string;
+}
+
+export interface UnprotectOptions {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+ readonly __homeOverride?: string;
+}
+
+// ─── Pure rule set (no IO) ────────────────────────────────────────────
+
+/**
+ * Pure vault-to-rules helper. The protected paths are derived from
+ * {@link brainDirs} and {@link brainConfigPath} so the protect rules
+ * stay in lockstep with the canonical Brain layout β€” if the layout
+ * ever moves, the rules follow without a parallel edit.
+ *
+ * The order of returned rules is stable β€” consumers (renderers,
+ * manifest) rely on it to keep output reproducible across runs on
+ * the same vault.
+ */
+export function buildProtectRules(vault: string): ReadonlyArray<ProtectRule> {
+ const dirs = brainDirs(vault);
+ const denyPaths = [
+ `${toPosix(dirs.preferences)}/**`,
+ `${toPosix(dirs.retired)}/**`,
+ `${toPosix(dirs.log)}/**`,
+ `${toPosix(dirs.snapshots)}/**`,
+ toPosix(brainConfigPath(vault)),
+ ];
+ const allowPaths = [`${toPosix(dirs.inbox)}/**`];
+
+ const rules: ProtectRule[] = [];
+ for (const path of denyPaths) {
+ for (const action of ["Write", "Edit"] as const) {
+ rules.push({ kind: "deny", action, path });
+ }
+ }
+ for (const path of allowPaths) {
+ rules.push({ kind: "allow", action: "Write", path });
+ }
+ return Object.freeze(rules);
+}
+
+/**
+ * Convert native separators to forward slashes. Both Claude Code and
+ * Codex permission matchers expect POSIX paths even on Windows;
+ * `brainDirs` returns paths joined with the native separator.
+ */
+function toPosix(p: string): string {
+ return p.replace(/\\/g, "/");
+}
+
+// ─── Claude Code rendering ────────────────────────────────────────────
+
+export interface ClaudeCodeRender {
+ readonly snippet: {
+ permissions: { deny: string[]; allow: string[] };
+ };
+ readonly manifest: ManifestRecordClaudeCode;
+}
+
+/**
+ * Render rules into the Claude Code shape. The `snippet` shape mirrors
+ * the projected `<vault>/.claude/settings.json` permissions block; the
+ * `manifest` is the authoritative record of which entries OSB owns,
+ * persisted separately so `unprotect` can remove exactly those without
+ * touching user-authored rules.
+ */
+export function renderClaudeCode(
+ rules: ReadonlyArray<ProtectRule>,
+ vault: string = inferVault(rules),
+): ClaudeCodeRender {
+ const deny = rules
+ .filter((r) => r.kind === "deny")
+ .map((r) => `${r.action}(${r.path})`);
+ const allow = rules
+ .filter((r) => r.kind === "allow")
+ .map((r) => `${r.action}(${r.path})`);
+ return Object.freeze({
+ snippet: { permissions: { deny, allow } },
+ manifest: {
+ schema_version: PROTECT_SCHEMA_VERSION,
+ target: "claudecode" as const,
+ vault,
+ owned_deny: deny,
+ owned_allow: allow,
+ },
+ });
+}
+
+function inferVault(rules: ReadonlyArray<ProtectRule>): string {
+ const first = rules[0];
+ if (!first) {
+ throw new BrainProtectError(
+ "renderClaudeCode requires at least one rule to infer the vault",
+ { code: "EMPTY_RULES" },
+ );
+ }
+ return first.path.split("/Brain/")[0]!;
+}
+
+// ─── Codex rendering ──────────────────────────────────────────────────
+
+const FENCE_OPEN = "# >>> open-second-brain managed >>>";
+const FENCE_CLOSE = "# <<< open-second-brain managed <<<";
+
+export interface CodexRender {
+ readonly body: string;
+}
+
+interface CodexFilesystemEntry {
+ readonly path: string;
+ readonly permission: "none" | "write";
+}
+
+/**
+ * Render rules into the Codex shape. The body is a self-contained
+ * managed block β€” including the `[permissions.osb_protected.filesystem]`
+ * table and `default_permissions = "osb_protected"` β€” wrapped in the
+ * line-comment fence used by `applyCodex` / `unprotectCodex` to locate
+ * the block on subsequent runs.
+ */
+export function renderCodex(rules: ReadonlyArray<ProtectRule>): CodexRender {
+ return renderCodexEntries(codexEntriesFromRules(rules));
+}
+
+function renderCodexEntries(
+ entries: ReadonlyArray<CodexFilesystemEntry>,
+): CodexRender {
+ const lines: string[] = [
+ FENCE_OPEN,
+ `# schema_version = ${PROTECT_SCHEMA_VERSION}`,
+ `default_permissions = "osb_protected"`,
+ "",
+ "[permissions.osb_protected.filesystem]",
+ ];
+ for (const entry of entries) {
+ lines.push(`${tomlString(entry.path)} = "${entry.permission}"`);
+ }
+ lines.push(FENCE_CLOSE);
+ return Object.freeze({ body: lines.join("\n") + "\n" });
+}
+
+function codexEntriesFromRules(
+ rules: ReadonlyArray<ProtectRule>,
+): ReadonlyArray<CodexFilesystemEntry> {
+ const entries: CodexFilesystemEntry[] = [];
+ const seen = new Set<string>();
+ for (const r of rules) {
+ if (seen.has(r.path)) continue;
+ seen.add(r.path);
+ entries.push({
+ path: r.path,
+ permission: r.kind === "deny" ? "none" : "write",
+ });
+ }
+ return Object.freeze(entries);
+}
+
+function tomlString(value: string): string {
+ return JSON.stringify(value);
+}
+
+// ─── Manifest (sidecar truth for what OSB owns) ───────────────────────
+
+const MANIFEST_DIR = ".open-second-brain";
+const MANIFEST_FILE = "protect.lock.json";
+
+interface ManifestRecordClaudeCode {
+ readonly schema_version: number;
+ readonly target: "claudecode";
+ readonly vault: string;
+ readonly owned_deny: ReadonlyArray<string>;
+ readonly owned_allow: ReadonlyArray<string>;
+}
+
+interface ManifestRecordCodex {
+ readonly schema_version: number;
+ readonly target: "codex";
+ readonly vault: string;
+ /**
+ * Vault-relative POSIX paths OSB owns inside the Codex fence. Kept
+ * separately from {@link buildProtectRules} so `unprotect` (and the
+ * apply-time stale-purge step) can remove exactly what a prior
+ * version added, even if the rule set drifts between releases. A
+ * v0.10.4 vault that upgrades to v0.10.5 with renamed sub-paths
+ * still finds its old entries via this list instead of leaking
+ * stale OSB permissions.
+ */
+ readonly owned_paths: ReadonlyArray<string>;
+}
+
+export type ManifestRecord = ManifestRecordClaudeCode | ManifestRecordCodex;
+
+interface ManifestFile {
+ entries: ManifestRecord[];
+}
+
+function manifestPath(vault: string): string {
+ return join(vault, MANIFEST_DIR, MANIFEST_FILE);
+}
+
+function parseManifestFile(raw: string, path: string): ManifestFile {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (err) {
+ throw new BrainProtectError(`malformed manifest at ${path}`, {
+ code: "MANIFEST_MALFORMED",
+ detail: err,
+ });
+ }
+ if (
+ parsed === null
+ || typeof parsed !== "object"
+ || !Array.isArray((parsed as { entries?: unknown }).entries)
+ ) {
+ throw new BrainProtectError(
+ `manifest at ${path} missing 'entries' array`,
+ { code: "MANIFEST_MALFORMED" },
+ );
+ }
+ return parsed as ManifestFile;
+}
+
+export function readManifest(
+ vault: string,
+ target: ProtectTarget,
+): ManifestRecord | null {
+ const path = manifestPath(vault);
+ if (!existsSync(path)) return null;
+ const file = parseManifestFile(readFileSync(path, "utf8"), path);
+ const entry = file.entries.find((e) => e.target === target);
+ if (entry === undefined) return null;
+ if (entry.schema_version > PROTECT_SCHEMA_VERSION) {
+ throw new BrainProtectError(
+ `manifest schema_version ${entry.schema_version} is newer than `
+ + `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,
+ { code: "MANIFEST_NEWER_SCHEMA" },
+ );
+ }
+ return entry;
+}
+
+export function writeManifest(vault: string, entry: ManifestRecord): void {
+ const path = manifestPath(vault);
+ mkdirSync(join(vault, MANIFEST_DIR), { recursive: true });
+ const file: ManifestFile = existsSync(path)
+ ? parseManifestFile(readFileSync(path, "utf8"), path)
+ : { entries: [] };
+ const others = file.entries.filter((e) => e.target !== entry.target);
+ const next: ManifestFile = { entries: [...others, entry] };
+ atomicWriteFileSync(path, JSON.stringify(next, null, 2) + "\n");
+}
+
+/**
+ * Idempotent variant of {@link writeManifest}: skips the write when
+ * the existing manifest entry is deep-equal to the new one. Avoids a
+ * spurious file rewrite on a no-op `applyProtect` call.
+ */
+function writeManifestIfChanged(vault: string, entry: ManifestRecord): void {
+ const existing = readManifest(vault, entry.target);
+ if (existing !== null && manifestEntriesEqual(existing, entry)) return;
+ writeManifest(vault, entry);
+}
+
+function manifestEntriesEqual(a: ManifestRecord, b: ManifestRecord): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+/**
+ * Read a file as UTF-8, returning the empty string when it does not
+ * exist. Avoids the `existsSync(p) ? readFileSync(p) : ""` TOCTOU
+ * pattern β€” one syscall on the happy path, and a race-free fallback
+ * on ENOENT.
+ */
+function readFileOrEmpty(path: string): string {
+ try {
+ return readFileSync(path, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return "";
+ throw err;
+ }
+}
+
+export function removeManifestEntry(
+ vault: string,
+ target: ProtectTarget,
+): void {
+ const path = manifestPath(vault);
+ if (!existsSync(path)) return;
+ const file = parseManifestFile(readFileSync(path, "utf8"), path);
+ const next: ManifestFile = {
+ entries: file.entries.filter((e) => e.target !== target),
+ };
+ atomicWriteFileSync(path, JSON.stringify(next, null, 2) + "\n");
+}
+
+// ─── Apply / unprotect ────────────────────────────────────────────────
+
+function ensureVaultBootstrapped(vault: string): void {
+ if (!existsSync(join(vault, "Brain"))) {
+ throw new BrainProtectError(
+ `vault at ${vault} has no Brain/ directory; run \`o2b brain init\` first`,
+ { code: "VAULT_NOT_BOOTSTRAPPED" },
+ );
+ }
+}
+
+/**
+ * Dispatch entry point. Delegates to the per-target implementation.
+ * Single-decision switch on `target` so adding a new target stays a
+ * one-place change (open/closed against future targets).
+ */
+export function applyProtect(opts: ApplyOptions): ApplyResult {
+ switch (opts.target) {
+ case "claudecode":
+ return applyClaudeCode(opts.vault);
+ case "codex":
+ return applyCodex(opts.vault, opts.__homeOverride);
+ }
+}
+
+export function unprotect(opts: UnprotectOptions): void {
+ switch (opts.target) {
+ case "claudecode":
+ return unprotectClaudeCode(opts.vault);
+ case "codex":
+ return unprotectCodex(opts.vault, opts.__homeOverride);
+ }
+}
+
+interface ClaudeSettings {
+ permissions?: {
+ deny?: string[];
+ allow?: string[];
+ };
+ [k: string]: unknown;
+}
+
+function readSettingsJson(path: string): { raw: string; parsed: ClaudeSettings } {
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ return { raw: "", parsed: {} };
+ }
+ throw err;
+ }
+ let parsed: ClaudeSettings;
+ try {
+ parsed = raw.trim() === "" ? {} : (JSON.parse(raw) as ClaudeSettings);
+ } catch (err) {
+ throw new BrainProtectError(`malformed settings.json at ${path}`, {
+ code: "SETTINGS_MALFORMED",
+ detail: err,
+ });
+ }
+ return { raw, parsed };
+}
+
+function applyClaudeCode(vault: string): ApplyResult {
+ ensureVaultBootstrapped(vault);
+ const rules = buildProtectRules(vault);
+ const rendered = renderClaudeCode(rules, vault);
+ const settingsDir = join(vault, ".claude");
+ const dest = join(settingsDir, "settings.json");
+ mkdirSync(settingsDir, { recursive: true });
+
+ const prev = readManifest(vault, "claudecode") as
+ | ManifestRecordClaudeCode
+ | null;
+ const { raw: before, parsed: settings } = readSettingsJson(dest);
+
+ settings.permissions ??= {};
+ settings.permissions.deny ??= [];
+ settings.permissions.allow ??= [];
+
+ // Remove prior OSB-owned entries so the result is independent of
+ // history (idempotency under repeated `--apply`).
+ const priorDeny = prev?.owned_deny ?? [];
+ const priorAllow = prev?.owned_allow ?? [];
+ settings.permissions.deny = settings.permissions.deny.filter(
+ (e) => !priorDeny.includes(e),
+ );
+ settings.permissions.allow = settings.permissions.allow.filter(
+ (e) => !priorAllow.includes(e),
+ );
+
+ for (const e of rendered.snippet.permissions.deny) {
+ if (!settings.permissions.deny.includes(e)) {
+ settings.permissions.deny.push(e);
+ }
+ }
+ for (const e of rendered.snippet.permissions.allow) {
+ if (!settings.permissions.allow.includes(e)) {
+ settings.permissions.allow.push(e);
+ }
+ }
+
+ const after = JSON.stringify(settings, null, 2) + "\n";
+ const changed = after !== before;
+ let backupPath = "";
+ if (changed && before !== "") {
+ backupPath = `${dest}.bak.${Date.now()}`;
+ atomicWriteFileSync(backupPath, before);
+ }
+ if (changed) atomicWriteFileSync(dest, after);
+ writeManifestIfChanged(vault, rendered.manifest);
+ return Object.freeze({
+ target: "claudecode" as const,
+ destination: dest,
+ backupPath,
+ changed,
+ });
+}
+
+function unprotectClaudeCode(vault: string): void {
+ const dest = join(vault, ".claude", "settings.json");
+ const prev = readManifest(vault, "claudecode") as
+ | ManifestRecordClaudeCode
+ | null;
+ if (prev === null || !existsSync(dest)) {
+ removeManifestEntry(vault, "claudecode");
+ return;
+ }
+ const { parsed: settings } = readSettingsJson(dest);
+ if (settings.permissions?.deny !== undefined) {
+ settings.permissions.deny = settings.permissions.deny.filter(
+ (e) => !prev.owned_deny.includes(e),
+ );
+ }
+ if (settings.permissions?.allow !== undefined) {
+ settings.permissions.allow = settings.permissions.allow.filter(
+ (e) => !prev.owned_allow.includes(e),
+ );
+ }
+ atomicWriteFileSync(dest, JSON.stringify(settings, null, 2) + "\n");
+ removeManifestEntry(vault, "claudecode");
+}
+
+// ─── Codex apply / unprotect ──────────────────────────────────────────
+
+function codexConfigPath(homeOverride: string | undefined): string {
+ const home = homeOverride ?? homedir();
+ return join(home, ".codex", "config.toml");
+}
+
+// The fence ends with its own trailing newline (renderCodex emits one),
+// so we consume it inside the match. We deliberately do NOT consume the
+// newline immediately before `FENCE_OPEN`: that one was either part of
+// the user's content or the synthetic separator `applyCodex` inserted
+// to keep the user's last line readable. Either way it belongs to the
+// non-managed half of the file.
+const CODEX_FENCE_RE = new RegExp(
+ `${escapeRegex(FENCE_OPEN)}[\\s\\S]*?${escapeRegex(FENCE_CLOSE)}\\n?`,
+ "m",
+);
+
+const CODEX_SCHEMA_RE = /#\s*schema_version\s*=\s*(\d+)/;
+const CODEX_ENTRY_RE = /^\s*"((?:\\.|[^"\\])*)"\s*=\s*"(none|write)"\s*$/;
+
+function parseCodexFence(raw: string): ReadonlyArray<CodexFilesystemEntry> {
+ const match = CODEX_FENCE_RE.exec(raw);
+ if (match === null) return [];
+ const block = match[0];
+ const schema = CODEX_SCHEMA_RE.exec(block);
+ if (schema !== null) {
+ const version = Number(schema[1]);
+ if (Number.isFinite(version) && version > PROTECT_SCHEMA_VERSION) {
+ throw new BrainProtectError(
+ `codex managed block schema_version ${version} is newer than `
+ + `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,
+ { code: "CODEX_FENCE_NEWER_SCHEMA" },
+ );
+ }
+ }
+
+ const entries: CodexFilesystemEntry[] = [];
+ const seen = new Set<string>();
+ for (const line of block.split(/\r?\n/)) {
+ const m = CODEX_ENTRY_RE.exec(line);
+ if (m === null) continue;
+ const path = parseTomlStringLiteral(m[1]!);
+ if (seen.has(path)) continue;
+ seen.add(path);
+ entries.push({ path, permission: m[2] as "none" | "write" });
+ }
+ return Object.freeze(entries);
+}
+
+function parseTomlStringLiteral(raw: string): string {
+ try {
+ return JSON.parse(`"${raw}"`) as string;
+ } catch {
+ throw new BrainProtectError(
+ "codex managed block contains an invalid quoted filesystem path",
+ { code: "CODEX_FENCE_MALFORMED" },
+ );
+ }
+}
+
+function replaceCodexFence(raw: string, fence: string | null): string {
+ const stripped = raw.replace(CODEX_FENCE_RE, "");
+ if (fence === null) return stripped;
+ return insertCodexFence(stripped, fence);
+}
+
+function insertCodexFence(raw: string, fence: string): string {
+ const firstTable = /^[ \t]*\[[^\]\r\n]+]\s*$/m.exec(raw);
+ if (firstTable === null) {
+ const sep = raw.length === 0 || raw.endsWith("\n") ? "" : "\n";
+ return raw + sep + fence;
+ }
+
+ const before = raw.slice(0, firstTable.index);
+ const after = raw.slice(firstTable.index);
+ const sep = before.length === 0 || before.endsWith("\n") ? "" : "\n";
+ return before + sep + fence + after;
+}
+
+function applyCodex(vault: string, homeOverride?: string): ApplyResult {
+ ensureVaultBootstrapped(vault);
+ const dest = codexConfigPath(homeOverride);
+ mkdirSync(join(dest, ".."), { recursive: true });
+
+ const before = readFileOrEmpty(dest);
+ const rules = buildProtectRules(vault);
+ const currentEntries = codexEntriesFromRules(rules);
+ const currentPaths = new Set(currentEntries.map((e) => e.path));
+ // Drop prior OSB-owned paths so an upgrade that renames or removes
+ // a protected glob does not leak stale managed entries. Falls back
+ // to current rules when no manifest exists yet (first apply, or a
+ // pre-v0.10.4 install bootstrapped without the `owned_paths` field).
+ const prev = readManifest(vault, "codex") as ManifestRecordCodex | null;
+ const ownedByPrior = new Set<string>(prev?.owned_paths ?? currentPaths);
+ const keptEntries = parseCodexFence(before).filter(
+ (e) => !ownedByPrior.has(e.path) && !currentPaths.has(e.path),
+ );
+ const fence = renderCodexEntries([...keptEntries, ...currentEntries]).body;
+ const after = replaceCodexFence(before, fence);
+ const changed = after !== before;
+ let backupPath = "";
+ if (changed && before !== "") {
+ backupPath = `${dest}.bak.${Date.now()}`;
+ atomicWriteFileSync(backupPath, before);
+ }
+ if (changed) atomicWriteFileSync(dest, after);
+ writeManifestIfChanged(vault, {
+ schema_version: PROTECT_SCHEMA_VERSION,
+ target: "codex",
+ vault,
+ owned_paths: currentEntries.map((e) => e.path),
+ });
+ return Object.freeze({
+ target: "codex" as const,
+ destination: dest,
+ backupPath,
+ changed,
+ });
+}
+
+function unprotectCodex(vault: string, homeOverride?: string): void {
+ const dest = codexConfigPath(homeOverride);
+ if (existsSync(dest)) {
+ const raw = readFileSync(dest, "utf8");
+ // Prefer the manifest's record of OSB-owned paths. Fall back to
+ // current rules only when no manifest is on disk β€” that handles
+ // a hand-edited fence whose manifest was deleted out-of-band.
+ const prev = readManifest(vault, "codex") as ManifestRecordCodex | null;
+ const ownedPaths = new Set<string>(
+ prev?.owned_paths
+ ?? codexEntriesFromRules(buildProtectRules(vault)).map((e) => e.path),
+ );
+ const remaining = parseCodexFence(raw).filter(
+ (e) => !ownedPaths.has(e.path),
+ );
+ const after = replaceCodexFence(
+ raw,
+ remaining.length > 0 ? renderCodexEntries(remaining).body : null,
+ );
+ if (after !== raw) atomicWriteFileSync(dest, after);
+ }
+ removeManifestEntry(vault, "codex");
+}
+
+// ─── Print mode (no IO mutation) ──────────────────────────────────────
+
+/**
+ * Render a snippet for stdout. Same content as `applyProtect` would
+ * inject, minus the user's existing config β€” so users can preview
+ * before committing.
+ */
+export function printSnippet(opts: {
+ readonly target: ProtectTarget;
+ readonly vault: string;
+ readonly __homeOverride?: string;
+}): RenderedSnippet {
+ const rules = buildProtectRules(opts.vault);
+ switch (opts.target) {
+ case "claudecode": {
+ const r = renderClaudeCode(rules, opts.vault);
+ return Object.freeze({
+ target: "claudecode" as const,
+ body: JSON.stringify(r.snippet, null, 2) + "\n",
+ destination: join(opts.vault, ".claude", "settings.json"),
+ });
+ }
+ case "codex": {
+ const r = renderCodex(rules);
+ return Object.freeze({
+ target: "codex" as const,
+ body: r.body,
+ destination: codexConfigPath(opts.__homeOverride),
+ });
+ }
+ }
+}
diff --git a/src/core/identity-reminder.ts b/src/core/identity-reminder.ts
index 3f1b4c0c..fa8ff807 100644
--- a/src/core/identity-reminder.ts
+++ b/src/core/identity-reminder.ts
@@ -26,10 +26,42 @@ const TEMPLATE_PATH = resolve(
"identity-reminder.txt",
);
-/** Read the template from disk. Caller substitutes `{agent}` via `buildReminder`. */
+/**
+ * Closed enumeration of runtime targets the resolver knows about.
+ * The list contains exactly the runtimes that call `buildReminder`
+ * per-turn / per-action: Hermes through its Python `pre_llm_call`
+ * shim, OpenClaw through its native `before_prompt_build` hook.
+ * Adding a target is a PR-change (new template file + new union
+ * member), not a runtime decision β€” the project deliberately ships
+ * a fixed list rather than a dynamic registry. Claude Code and
+ * Codex are intentionally absent; their post-tool-call steering is
+ * delivered by `hooks/lib/messages.ts:postWriteReminder`, which is
+ * a different mechanism.
+ */
+export const KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"] as const;
+
+export type RuntimeTarget = (typeof KNOWN_RUNTIME_TARGETS)[number];
+
+export function isRuntimeTarget(value: string | undefined): value is RuntimeTarget {
+ return (
+ typeof value === "string"
+ && (KNOWN_RUNTIME_TARGETS as readonly string[]).includes(value)
+ );
+}
+
+let commonTemplateCache: string | undefined;
+
+/**
+ * Read the common template from disk. Caller substitutes `{agent}`
+ * via {@link buildReminder}. Cached at first read β€” templates are
+ * installation-time artifacts that do not change at runtime, and the
+ * reminder is consulted on every LLM turn.
+ */
export function loadReminderTemplate(): string {
+ if (commonTemplateCache !== undefined) return commonTemplateCache;
try {
- return readFileSync(TEMPLATE_PATH, "utf8").trimEnd();
+ commonTemplateCache = readFileSync(TEMPLATE_PATH, "utf8").trimEnd();
+ return commonTemplateCache;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(
@@ -38,9 +70,92 @@ export function loadReminderTemplate(): string {
}
}
-/** Substitute `{agent}` and return the rendered reminder body. */
-export function buildReminder(agent: string): string {
+const TEMPLATES_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "templates",
+);
+
+const PER_TARGET_PATHS: Readonly<Record<RuntimeTarget, string>> = Object.freeze(
+ Object.fromEntries(
+ KNOWN_RUNTIME_TARGETS.map((t) => [
+ t,
+ resolve(TEMPLATES_DIR, `identity-reminder.${t}.txt`),
+ ]),
+ ),
+) as Readonly<Record<RuntimeTarget, string>>;
+
+/**
+ * Cache the per-target template body once per process. The reminder
+ * is read on every LLM turn through the OpenClaw / Hermes hooks; a
+ * disk read per turn shows up under heavy use. The cache stores both
+ * resolved bodies and a `null` sentinel for "file absent" so a
+ * partially deployed install keeps falling back without re-stating
+ * `ENOENT` against the filesystem every turn.
+ *
+ * Templates change only on install / upgrade; a process restart
+ * (which happens on every gateway restart and every CLI invocation)
+ * flushes the cache.
+ */
+const TEMPLATE_CACHE = new Map<RuntimeTarget, string | null>();
+
+function tryReadTargetTemplate(target: RuntimeTarget): string | null {
+ const cached = TEMPLATE_CACHE.get(target);
+ if (cached !== undefined) return cached;
+ let body: string | null;
+ try {
+ body = readFileSync(PER_TARGET_PATHS[target], "utf8").trimEnd();
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ body = null;
+ }
+ TEMPLATE_CACHE.set(target, body);
+ return body;
+}
+
+let envWarnedOnce = false;
+
+function resolveTargetFromEnv(): RuntimeTarget | undefined {
+ const raw = process.env.O2B_TARGET;
+ if (raw === undefined || raw === "") return undefined;
+ if (isRuntimeTarget(raw)) return raw;
+ if (!envWarnedOnce) {
+ envWarnedOnce = true;
+ process.stderr.write(
+ `open-second-brain: unknown O2B_TARGET='${raw}', using common identity template\n`,
+ );
+ }
+ return undefined;
+}
+
+/**
+ * Substitute `{agent}` and return the rendered reminder body.
+ *
+ * Resolution order for the template source:
+ * 1. Explicit `target` parameter, when its per-target file exists.
+ * 2. `process.env.O2B_TARGET`, when it names a known target and
+ * the per-target file exists.
+ * 3. Common `templates/identity-reminder.txt`.
+ *
+ * A missing per-target file silently falls back β€” that is a valid
+ * intermediate state during partial rollouts. An unknown env value
+ * warns to stderr once per process and falls back.
+ */
+export function buildReminder(agent: string, target?: RuntimeTarget): string {
+ const effective = target ?? resolveTargetFromEnv();
+ if (effective !== undefined) {
+ const tpl = tryReadTargetTemplate(effective);
+ if (tpl !== null) return tpl.replace(/\{agent\}/g, agent);
+ }
return loadReminderTemplate().replace(/\{agent\}/g, agent);
}
+/** Test-only: reset the warn-once latch and the template caches. */
+export function __resetEnvWarnedOnceForTests(): void {
+ envWarnedOnce = false;
+ commonTemplateCache = undefined;
+ TEMPLATE_CACHE.clear();
+}
+
export const __TEMPLATE_PATH_FOR_TESTS = TEMPLATE_PATH;
diff --git a/src/core/strings.ts b/src/core/strings.ts
new file mode 100644
index 00000000..adfb7c86
--- /dev/null
+++ b/src/core/strings.ts
@@ -0,0 +1,16 @@
+/**
+ * Small string-level utilities shared across `src/core/`.
+ *
+ * Kept here rather than inlined per call site so multiple modules
+ * (templates renderer, brain protect fence parser, future regex
+ * builders) stay consistent on the metachar set they escape.
+ */
+
+/**
+ * Escape every regex metacharacter in `text` so the result is safe
+ * to interpolate into a `RegExp` source string as a literal match.
+ * Mirrors the canonical MDN escape set.
+ */
+export function escapeRegex(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index c8ae6e68..0c7d4e72 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -140,7 +140,7 @@ export default definePluginEntry({
process.env["VAULT_AGENT_NAME"] ??
resolveAgentName();
if (agent === "agent") return undefined;
- return { prependContext: buildReminder(agent) };
+ return { prependContext: buildReminder(agent, "openclaw") };
});
api.registerTool(
diff --git a/templates/brain-starter/inbox/sig-2026-05-10-strict-types.md b/templates/brain-starter/inbox/sig-2026-05-10-strict-types.md
new file mode 100644
index 00000000..8751388f
--- /dev/null
+++ b/templates/brain-starter/inbox/sig-2026-05-10-strict-types.md
@@ -0,0 +1,16 @@
+---
+kind: brain-signal
+id: sig-2026-05-10-strict-types
+created_at: "2026-05-10T15:30:00Z"
+tags: [brain, brain/signal, brain/topic/strict-types-in-public-api, brain/scope/coding]
+topic: strict-types-in-public-api
+signal: positive
+agent: starter-author
+principle: "Public-API function signatures should be fully typed β€” no implicit any in exports."
+scope: coding
+source: ["[[Daily/2026.05.10]]"]
+---
+
+## Raw
+
+Public functions should never accept implicit any β€” readers reading the type signature get the whole contract.
diff --git a/templates/brain-starter/log/2026-05-12.md b/templates/brain-starter/log/2026-05-12.md
new file mode 100644
index 00000000..77b38808
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-12.md
@@ -0,0 +1,19 @@
+---
+kind: brain-log
+date: 2026-05-12
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-12
+
+## 10:00:00Z β€” apply-evidence
+- preference: [[pref-no-unexplained-abbreviations|Do not use internal abbreviations in user-facing copy without expanding them on…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:05:00Z β€” apply-evidence
+- preference: [[pref-changelog-every-release|Every released version gets a CHANGELOG entry under its concrete version header.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
diff --git a/templates/brain-starter/log/2026-05-13.md b/templates/brain-starter/log/2026-05-13.md
new file mode 100644
index 00000000..857c2bc5
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-13.md
@@ -0,0 +1,37 @@
+---
+kind: brain-log
+date: 2026-05-13
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-13
+
+## 10:00:00Z β€” apply-evidence
+- preference: [[pref-imperative-commit-messages|Use imperative voice in commit messages β€” `Add`, `Fix`, `Refactor`, not `Added`…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:05:00Z β€” apply-evidence
+- preference: [[pref-no-unexplained-abbreviations|Do not use internal abbreviations in user-facing copy without expanding them on…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:10:00Z β€” apply-evidence
+- preference: [[pref-explicit-imports-only|Use explicit imports β€” no wildcard star imports.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:15:00Z β€” apply-evidence
+- preference: [[pref-russian-in-chat|Reply in Russian when the user speaks Russian; repo artifacts stay English.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:20:00Z β€” apply-evidence
+- preference: [[pref-prefer-bun-over-npx|On this server, prefer `bun run` / `bunx` over `npx`; the project standardised…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
diff --git a/templates/brain-starter/log/2026-05-14.md b/templates/brain-starter/log/2026-05-14.md
new file mode 100644
index 00000000..ab92fd12
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-14.md
@@ -0,0 +1,43 @@
+---
+kind: brain-log
+date: 2026-05-14
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-14
+
+## 10:00:00Z β€” apply-evidence
+- preference: [[pref-imperative-commit-messages|Use imperative voice in commit messages β€” `Add`, `Fix`, `Refactor`, not `Added`…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:05:00Z β€” apply-evidence
+- preference: [[pref-no-unexplained-abbreviations|Do not use internal abbreviations in user-facing copy without expanding them on…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:10:00Z β€” apply-evidence
+- preference: [[pref-prefer-typed-errors|Throw typed error classes for distinct failure modes instead of bare Error with…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:15:00Z β€” apply-evidence
+- preference: [[pref-explicit-imports-only|Use explicit imports β€” no wildcard star imports.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:20:00Z β€” apply-evidence
+- preference: [[pref-changelog-every-release|Every released version gets a CHANGELOG entry under its concrete version header.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:25:00Z β€” apply-evidence
+- preference: [[pref-russian-in-chat|Reply in Russian when the user speaks Russian; repo artifacts stay English.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
diff --git a/templates/brain-starter/log/2026-05-15.md b/templates/brain-starter/log/2026-05-15.md
new file mode 100644
index 00000000..d7e854ff
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-15.md
@@ -0,0 +1,43 @@
+---
+kind: brain-log
+date: 2026-05-15
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-15
+
+## 10:00:00Z β€” apply-evidence
+- preference: [[pref-imperative-commit-messages|Use imperative voice in commit messages β€” `Add`, `Fix`, `Refactor`, not `Added`…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:05:00Z β€” apply-evidence
+- preference: [[pref-no-unexplained-abbreviations|Do not use internal abbreviations in user-facing copy without expanding them on…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:10:00Z β€” apply-evidence
+- preference: [[pref-prefer-typed-errors|Throw typed error classes for distinct failure modes instead of bare Error with…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:15:00Z β€” apply-evidence
+- preference: [[pref-explicit-imports-only|Use explicit imports β€” no wildcard star imports.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:20:00Z β€” apply-evidence
+- preference: [[pref-russian-in-chat|Reply in Russian when the user speaks Russian; repo artifacts stay English.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:25:00Z β€” apply-evidence
+- preference: [[pref-prefer-bun-over-npx|On this server, prefer `bun run` / `bunx` over `npx`; the project standardised…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
diff --git a/templates/brain-starter/log/2026-05-16.md b/templates/brain-starter/log/2026-05-16.md
new file mode 100644
index 00000000..048b10f4
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-16.md
@@ -0,0 +1,31 @@
+---
+kind: brain-log
+date: 2026-05-16
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-16
+
+## 10:00:00Z β€” apply-evidence
+- preference: [[pref-imperative-commit-messages|Use imperative voice in commit messages β€” `Add`, `Fix`, `Refactor`, not `Added`…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:05:00Z β€” apply-evidence
+- preference: [[pref-prefer-typed-errors|Throw typed error classes for distinct failure modes instead of bare Error with…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:10:00Z β€” apply-evidence
+- preference: [[pref-changelog-every-release|Every released version gets a CHANGELOG entry under its concrete version header.]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
+
+## 10:15:00Z β€” apply-evidence
+- preference: [[pref-prefer-bun-over-npx|On this server, prefer `bun run` / `bunx` over `npx`; the project standardised…]]
+- artifact: [[Brain/_BRAIN.md]]
+- agent: starter-author
+- result: applied
diff --git a/templates/brain-starter/log/2026-05-17.md b/templates/brain-starter/log/2026-05-17.md
new file mode 100644
index 00000000..1bbb6904
--- /dev/null
+++ b/templates/brain-starter/log/2026-05-17.md
@@ -0,0 +1,10 @@
+---
+kind: brain-log
+date: 2026-05-17
+tags: [brain, brain/log]
+---
+
+# Brain log β€” 2026-05-17
+
+## 12:00:00Z β€” dream
+- run_id: dream-2026-05-17-120000
diff --git a/templates/brain-starter/preferences/pref-changelog-every-release.md b/templates/brain-starter/preferences/pref-changelog-every-release.md
new file mode 100644
index 00000000..12e74b8d
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-changelog-every-release.md
@@ -0,0 +1,25 @@
+---
+kind: brain-preference
+id: pref-changelog-every-release
+created_at: "2026-03-15T12:00:00Z"
+_confirmed_at: "2026-03-29T12:00:00Z"
+unconfirmed_until: "2026-03-29T12:00:00Z"
+tags: [brain, brain/preference, brain/topic/changelog-every-release, brain/scope/process]
+topic: changelog-every-release
+_status: confirmed
+principle: Every released version gets a CHANGELOG entry under its concrete version header.
+_evidenced_by: []
+_applied_count: 3
+_violated_count: 0
+_last_evidence_at: "2026-05-16T10:10:00Z"
+_confidence: medium
+_confidence_value: 0.4332
+pinned: false
+scope: process
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-16T10:10:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:20:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-12T10:05:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-explicit-imports-only.md b/templates/brain-starter/preferences/pref-explicit-imports-only.md
new file mode 100644
index 00000000..34cd5623
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-explicit-imports-only.md
@@ -0,0 +1,25 @@
+---
+kind: brain-preference
+id: pref-explicit-imports-only
+created_at: "2026-04-05T08:00:00Z"
+_confirmed_at: "2026-04-19T08:00:00Z"
+unconfirmed_until: "2026-04-19T08:00:00Z"
+tags: [brain, brain/preference, brain/topic/explicit-imports-only, brain/scope/coding]
+topic: explicit-imports-only
+_status: confirmed
+principle: "Use explicit imports β€” no wildcard star imports."
+_evidenced_by: []
+_applied_count: 3
+_violated_count: 0
+_last_evidence_at: "2026-05-15T10:15:00Z"
+_confidence: medium
+_confidence_value: 0.4284
+pinned: false
+scope: coding
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:15:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:15:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-13T10:10:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-imperative-commit-messages.md b/templates/brain-starter/preferences/pref-imperative-commit-messages.md
new file mode 100644
index 00000000..48f82a02
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-imperative-commit-messages.md
@@ -0,0 +1,26 @@
+---
+kind: brain-preference
+id: pref-imperative-commit-messages
+created_at: "2026-04-01T10:00:00Z"
+_confirmed_at: "2026-04-15T10:00:00Z"
+unconfirmed_until: "2026-04-15T10:00:00Z"
+tags: [brain, brain/preference, brain/topic/imperative-commit-messages, brain/scope/process]
+topic: imperative-commit-messages
+_status: confirmed
+principle: "Use imperative voice in commit messages β€” `Add`, `Fix`, `Refactor`, not `Added` / `Fixes` / `Refactored`."
+_evidenced_by: []
+_applied_count: 4
+_violated_count: 0
+_last_evidence_at: "2026-05-16T10:00:00Z"
+_confidence: medium
+_confidence_value: 0.504
+pinned: false
+scope: process
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-16T10:00:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:00:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:00:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-13T10:00:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md b/templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md
new file mode 100644
index 00000000..815c73bd
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md
@@ -0,0 +1,26 @@
+---
+kind: brain-preference
+id: pref-no-unexplained-abbreviations
+created_at: "2026-03-20T09:00:00Z"
+_confirmed_at: "2026-04-03T09:00:00Z"
+unconfirmed_until: "2026-04-03T09:00:00Z"
+tags: [brain, brain/preference, brain/topic/no-unexplained-abbreviations, brain/scope/writing]
+topic: no-unexplained-abbreviations
+_status: confirmed
+principle: Do not use internal abbreviations in user-facing copy without expanding them on first use.
+_evidenced_by: []
+_applied_count: 4
+_violated_count: 0
+_last_evidence_at: "2026-05-15T10:05:00Z"
+_confidence: medium
+_confidence_value: 0.4983
+pinned: true
+scope: writing
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:05:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:05:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-13T10:05:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-12T10:00:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-prefer-bun-over-npx.md b/templates/brain-starter/preferences/pref-prefer-bun-over-npx.md
new file mode 100644
index 00000000..1730231d
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-prefer-bun-over-npx.md
@@ -0,0 +1,25 @@
+---
+kind: brain-preference
+id: pref-prefer-bun-over-npx
+created_at: "2026-04-12T10:00:00Z"
+_confirmed_at: "2026-04-26T10:00:00Z"
+unconfirmed_until: "2026-04-26T10:00:00Z"
+tags: [brain, brain/preference, brain/topic/prefer-bun-over-npx, brain/scope/infra]
+topic: prefer-bun-over-npx
+_status: confirmed
+principle: "On this server, prefer `bun run` / `bunx` over `npx`; the project standardised on Bun."
+_evidenced_by: []
+_applied_count: 3
+_violated_count: 0
+_last_evidence_at: "2026-05-16T10:15:00Z"
+_confidence: medium
+_confidence_value: 0.4333
+pinned: false
+scope: infra
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-16T10:15:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:25:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-13T10:20:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-prefer-typed-errors.md b/templates/brain-starter/preferences/pref-prefer-typed-errors.md
new file mode 100644
index 00000000..b4b30719
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-prefer-typed-errors.md
@@ -0,0 +1,25 @@
+---
+kind: brain-preference
+id: pref-prefer-typed-errors
+created_at: "2026-04-10T13:00:00Z"
+_confirmed_at: "2026-04-24T13:00:00Z"
+unconfirmed_until: "2026-04-24T13:00:00Z"
+tags: [brain, brain/preference, brain/topic/prefer-typed-errors, brain/scope/coding]
+topic: prefer-typed-errors
+_status: confirmed
+principle: Throw typed error classes for distinct failure modes instead of bare Error with a string message.
+_evidenced_by: []
+_applied_count: 3
+_violated_count: 0
+_last_evidence_at: "2026-05-16T10:05:00Z"
+_confidence: medium
+_confidence_value: 0.4332
+pinned: false
+scope: coding
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-16T10:05:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:10:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:10:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-russian-in-chat.md b/templates/brain-starter/preferences/pref-russian-in-chat.md
new file mode 100644
index 00000000..e417ecfc
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-russian-in-chat.md
@@ -0,0 +1,25 @@
+---
+kind: brain-preference
+id: pref-russian-in-chat
+created_at: "2026-04-20T14:00:00Z"
+_confirmed_at: "2026-05-02T10:00:00Z"
+unconfirmed_until: "2026-05-04T14:00:00Z"
+tags: [brain, brain/preference, brain/topic/russian-in-chat, brain/scope/writing]
+topic: russian-in-chat
+_status: confirmed
+principle: "Reply in Russian when the user speaks Russian; repo artifacts stay English."
+_evidenced_by: []
+_applied_count: 3
+_violated_count: 0
+_last_evidence_at: "2026-05-15T10:20:00Z"
+_confidence: medium
+_confidence_value: 0.4284
+pinned: false
+scope: writing
+---
+
+## Recent applications
+
+- [[Brain/_BRAIN.md]] β€” 2026-05-15T10:20:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-14T10:25:00Z (starter-author)
+- [[Brain/_BRAIN.md]] β€” 2026-05-13T10:15:00Z (starter-author)
diff --git a/templates/brain-starter/preferences/pref-test-before-refactor.md b/templates/brain-starter/preferences/pref-test-before-refactor.md
new file mode 100644
index 00000000..f2d951a7
--- /dev/null
+++ b/templates/brain-starter/preferences/pref-test-before-refactor.md
@@ -0,0 +1,19 @@
+---
+kind: brain-preference
+id: pref-test-before-refactor
+created_at: "2026-05-11T11:00:00Z"
+_confirmed_at: null
+unconfirmed_until: "2026-05-25T11:00:00Z"
+tags: [brain, brain/preference, brain/topic/test-before-refactor, brain/scope/coding]
+topic: test-before-refactor
+_status: unconfirmed
+principle: Add or update tests covering the behaviour to be refactored before changing implementation.
+_evidenced_by: []
+_applied_count: 0
+_violated_count: 0
+_last_evidence_at: null
+_confidence: low
+_confidence_value: 0
+pinned: false
+scope: coding
+---
diff --git a/templates/brain-starter/retired/ret-no-emojis-in-code.md b/templates/brain-starter/retired/ret-no-emojis-in-code.md
new file mode 100644
index 00000000..413dfc3a
--- /dev/null
+++ b/templates/brain-starter/retired/ret-no-emojis-in-code.md
@@ -0,0 +1,30 @@
+---
+created_at: "2026-03-05T10:00:00Z"
+tags: [brain, brain/retired, brain/topic/no-emojis-in-code, brain/scope/writing]
+topic: no-emojis-in-code
+principle: "Do not include emojis in source code, comments, or commit messages."
+_evidenced_by: []
+_applied_count: 1
+_violated_count: 5
+_last_evidence_at: "2026-03-05T10:00:00Z"
+_confidence: medium
+_confidence_value: 0.4
+pinned: false
+scope: writing
+kind: brain-retired
+id: ret-no-emojis-in-code
+status: retired
+retired_at: "2026-05-15T16:00:00.000Z"
+retired_reason: rebutted
+retired_by: "[[Brain/log/2026-05-15]]"
+aliases: [pref-no-emojis-in-code]
+---
+
+
+
+## Retired
+
+Reason: `rebutted`
+Retired at: 2026-05-15T16:00:00.000Z
+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
new file mode 100644
index 00000000..d304aa81
--- /dev/null
+++ b/templates/brain-starter/retired/ret-prefer-curl-over-wget.md
@@ -0,0 +1,30 @@
+---
+created_at: "2026-02-01T11:00:00Z"
+tags: [brain, brain/retired, brain/topic/prefer-curl-over-wget, brain/scope/infra]
+topic: prefer-curl-over-wget
+principle: "Use curl, not wget, for ad-hoc HTTP requests in shell scripts."
+_evidenced_by: []
+_applied_count: 1
+_violated_count: 0
+_last_evidence_at: "2026-02-01T11:00:00Z"
+_confidence: medium
+_confidence_value: 0.4
+pinned: false
+scope: infra
+kind: brain-retired
+id: ret-prefer-curl-over-wget
+status: retired
+retired_at: "2026-05-15T18:00:00.000Z"
+retired_reason: stale-no-evidence
+retired_by: "[[Brain/log/2026-05-15]]"
+aliases: [pref-prefer-curl-over-wget]
+---
+
+
+
+## Retired
+
+Reason: `stale-no-evidence`
+Retired at: 2026-05-15T18:00:00.000Z
+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
new file mode 100644
index 00000000..52664b06
--- /dev/null
+++ b/templates/brain-starter/retired/ret-tabs-over-spaces.md
@@ -0,0 +1,32 @@
+---
+created_at: "2026-03-01T09:00:00Z"
+tags: [brain, brain/retired, brain/topic/tabs-over-spaces, brain/scope/coding]
+topic: tabs-over-spaces
+principle: "Use tabs for indentation, not spaces."
+_evidenced_by: []
+_applied_count: 2
+_violated_count: 0
+_last_evidence_at: "2026-03-01T09:00:00Z"
+_confidence: medium
+_confidence_value: 0.4
+pinned: false
+scope: coding
+kind: brain-retired
+id: ret-tabs-over-spaces
+status: retired
+retired_at: "2026-05-16T11:00:00.000Z"
+retired_reason: user-rejected
+retired_by: "[[Brain/log/2026-05-16]]"
+user_rejected_reason: "Mixed indentation is acceptable in this codebase β€” different repos use different conventions and one global rule cannot capture that."
+aliases: [pref-tabs-over-spaces]
+---
+
+
+
+## Retired
+
+Reason: `user-rejected`
+Retired at: 2026-05-16T11:00:00.000Z
+Retired by: [[Brain/log/2026-05-16]]
+User reason: Mixed indentation is acceptable in this codebase β€” different repos use different conventions and one global rule cannot capture that.
+
diff --git a/templates/identity-reminder.hermes.txt b/templates/identity-reminder.hermes.txt
new file mode 100644
index 00000000..3b2f515a
--- /dev/null
+++ b/templates/identity-reminder.hermes.txt
@@ -0,0 +1 @@
+[open-second-brain] Identity: @{agent}. After every durable artifact this turn β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. Hermes turns are short; do not batch the log calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
diff --git a/templates/identity-reminder.openclaw.txt b/templates/identity-reminder.openclaw.txt
new file mode 100644
index 00000000..a75a1200
--- /dev/null
+++ b/templates/identity-reminder.openclaw.txt
@@ -0,0 +1 @@
+[open-second-brain] Identity: @{agent}. After every durable in-process action β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index d509610f..dc604d41 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -1296,3 +1296,106 @@ describe("brain migrate-frontmatter", () => {
expect(r.stderr).toMatch(/collision/i);
});
});
+
+describe("brain protect", () => {
+ test("--target claudecode --print returns the JSON shape, exit 0", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "protect", "--target", "claudecode", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("Write(");
+ expect(r.stdout).toContain("preview only");
+ expect(existsSync(join(vault, ".claude", "settings.json"))).toBe(false);
+ });
+
+ test("--target codex --print includes the managed fence", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "protect", "--target", "codex", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("# >>> open-second-brain managed >>>");
+ });
+
+ test("unknown --target exits 1 with a clear message", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["brain", "protect", "--target", "vim", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("unknown");
+ expect(r.stderr).toContain("claudecode");
+ });
+
+ test("--apply writes settings.json and is idempotent", async () => {
+ await bootstrap();
+ const first = await runCli(
+ [
+ "brain",
+ "protect",
+ "--target",
+ "claudecode",
+ "--vault",
+ vault,
+ "--apply",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(first.returncode).toBe(0);
+ expect(first.stdout).toContain("applied to");
+ const settingsPath = join(vault, ".claude", "settings.json");
+ const bytesAfterFirst = readFileSync(settingsPath, "utf8");
+ expect(bytesAfterFirst).toContain("Write(");
+
+ const second = await runCli(
+ [
+ "brain",
+ "protect",
+ "--target",
+ "claudecode",
+ "--vault",
+ vault,
+ "--apply",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(second.returncode).toBe(0);
+ expect(second.stdout).toContain("no changes");
+ expect(readFileSync(settingsPath, "utf8")).toBe(bytesAfterFirst);
+ });
+
+ test("apply + unprotect round-trip leaves no managed entries", async () => {
+ await bootstrap();
+ await runCli(
+ [
+ "brain",
+ "protect",
+ "--target",
+ "claudecode",
+ "--vault",
+ vault,
+ "--apply",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const r = await runCli(
+ ["brain", "unprotect", "--target", "claudecode", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("removed");
+ const parsed = JSON.parse(
+ readFileSync(join(vault, ".claude", "settings.json"), "utf8"),
+ );
+ // After unprotect, OSB-owned deny entries are gone. The keys may
+ // remain empty (user could have other rules) β€” assert via filter.
+ const ownedLeft = (parsed.permissions?.deny ?? []).filter((e: string) =>
+ e.includes("Brain/preferences"),
+ );
+ expect(ownedLeft).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/protect.test.ts b/tests/core/brain/protect.test.ts
new file mode 100644
index 00000000..8bf05d58
--- /dev/null
+++ b/tests/core/brain/protect.test.ts
@@ -0,0 +1,384 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ applyProtect,
+ BrainProtectError,
+ buildProtectRules,
+ printSnippet,
+ PROTECT_SCHEMA_VERSION,
+ readManifest,
+ renderClaudeCode,
+ renderCodex,
+ unprotect,
+ writeManifest,
+} from "../../../src/core/brain/protect.ts";
+
+const tmpRoots: string[] = [];
+
+function mkVault(): string {
+ const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ tmpRoots.push(dir);
+ return dir;
+}
+
+function mkHome(): string {
+ const dir = mkdtempSync(join(tmpdir(), "osb-codex-home-"));
+ tmpRoots.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const d of tmpRoots.splice(0)) {
+ try {
+ rmSync(d, { recursive: true, force: true });
+ } catch {
+ // tmp cleanup is best-effort
+ }
+ }
+});
+
+describe("buildProtectRules", () => {
+ test("returns 11 rules in stable order for a given vault", () => {
+ const rules = buildProtectRules("/vault");
+ // 5 deny paths Γ— 2 actions (Write+Edit) + 1 allow.
+ expect(rules).toHaveLength(11);
+ expect(rules[0]).toEqual({
+ kind: "deny",
+ action: "Write",
+ path: "/vault/Brain/preferences/**",
+ });
+ const last = rules[rules.length - 1];
+ expect(last).toEqual({
+ kind: "allow",
+ action: "Write",
+ path: "/vault/Brain/inbox/**",
+ });
+ });
+
+ test("denies cover the five protected sub-paths", () => {
+ const rules = buildProtectRules("/v");
+ const denyPaths = Array.from(
+ new Set(rules.filter((r) => r.kind === "deny").map((r) => r.path)),
+ ).sort();
+ expect(denyPaths).toEqual([
+ "/v/Brain/.snapshots/**",
+ "/v/Brain/_brain.yaml",
+ "/v/Brain/log/**",
+ "/v/Brain/preferences/**",
+ "/v/Brain/retired/**",
+ ]);
+ });
+});
+
+describe("renderClaudeCode", () => {
+ test("emits a snippet with deny + allow arrays and a manifest", () => {
+ const rules = buildProtectRules("/vault");
+ const out = renderClaudeCode(rules, "/vault");
+ expect(out.snippet.permissions.deny).toContain(
+ "Write(/vault/Brain/preferences/**)",
+ );
+ expect(out.snippet.permissions.deny).toContain(
+ "Edit(/vault/Brain/preferences/**)",
+ );
+ expect(out.snippet.permissions.allow).toEqual([
+ "Write(/vault/Brain/inbox/**)",
+ ]);
+ expect(out.manifest.schema_version).toBe(PROTECT_SCHEMA_VERSION);
+ expect(out.manifest.target).toBe("claudecode");
+ expect(out.manifest.vault).toBe("/vault");
+ expect(out.manifest.owned_deny).toHaveLength(10);
+ expect(out.manifest.owned_allow).toEqual([
+ "Write(/vault/Brain/inbox/**)",
+ ]);
+ });
+});
+
+describe("renderCodex", () => {
+ test("emits TOML wrapped in osb fence with right keys", () => {
+ const rules = buildProtectRules("/vault");
+ const out = renderCodex(rules);
+ expect(out.body).toContain("# >>> open-second-brain managed >>>");
+ expect(out.body).toContain("# <<< open-second-brain managed <<<");
+ expect(out.body).toContain("[permissions.osb_protected.filesystem]");
+ expect(out.body).toContain('"/vault/Brain/preferences/**" = "none"');
+ expect(out.body).toContain('"/vault/Brain/inbox/**" = "write"');
+ expect(out.body).toContain('default_permissions = "osb_protected"');
+ expect(out.body).toContain(`schema_version = ${PROTECT_SCHEMA_VERSION}`);
+ });
+
+ test("emits each filesystem path only once", () => {
+ const out = renderCodex(buildProtectRules("/vault"));
+ const keys = out.body
+ .split(/\r?\n/)
+ .map((line) => /^"([^"]+)"\s*=/.exec(line)?.[1])
+ .filter((path): path is string => path !== undefined);
+ expect(keys.length).toBe(new Set(keys).size);
+ expect(keys).toHaveLength(6);
+ });
+});
+
+describe("manifest read/write", () => {
+ test("round-trip claudecode manifest", () => {
+ const vault = mkVault();
+ const m = {
+ schema_version: PROTECT_SCHEMA_VERSION,
+ target: "claudecode" as const,
+ vault,
+ owned_deny: ["Write(/v/Brain/preferences/**)"],
+ owned_allow: ["Write(/v/Brain/inbox/**)"],
+ };
+ writeManifest(vault, m);
+ expect(readManifest(vault, "claudecode")).toEqual(m);
+ });
+
+ test("reading absent manifest returns null", () => {
+ const vault = mkVault();
+ expect(readManifest(vault, "claudecode")).toBeNull();
+ });
+
+ test("higher schema_version on disk throws", () => {
+ const vault = mkVault();
+ writeManifest(vault, {
+ schema_version: 999,
+ target: "claudecode",
+ vault,
+ owned_deny: [],
+ owned_allow: [],
+ });
+ expect(() => readManifest(vault, "claudecode")).toThrow(BrainProtectError);
+ });
+});
+
+describe("applyProtect claudecode", () => {
+ test("creates settings.json + manifest on a fresh vault", () => {
+ const vault = mkVault();
+ const r = applyProtect({ target: "claudecode", vault });
+ expect(r.changed).toBe(true);
+ const settings = JSON.parse(
+ readFileSync(join(vault, ".claude", "settings.json"), "utf8"),
+ );
+ expect(settings.permissions.deny).toContain(
+ `Write(${vault}/Brain/preferences/**)`,
+ );
+ });
+
+ test("idempotent: second apply produces byte-identical settings", () => {
+ const vault = mkVault();
+ applyProtect({ target: "claudecode", vault });
+ const first = readFileSync(
+ join(vault, ".claude", "settings.json"),
+ "utf8",
+ );
+ applyProtect({ target: "claudecode", vault });
+ const second = readFileSync(
+ join(vault, ".claude", "settings.json"),
+ "utf8",
+ );
+ expect(second).toBe(first);
+ });
+
+ test("preserves user-authored permissions on apply", () => {
+ const vault = mkVault();
+ mkdirSync(join(vault, ".claude"), { recursive: true });
+ writeFileSync(
+ join(vault, ".claude", "settings.json"),
+ JSON.stringify(
+ { permissions: { deny: ["Bash(rm -rf /)"], allow: [] } },
+ null,
+ 2,
+ ) + "\n",
+ );
+ applyProtect({ target: "claudecode", vault });
+ const settings = JSON.parse(
+ readFileSync(join(vault, ".claude", "settings.json"), "utf8"),
+ );
+ expect(settings.permissions.deny).toContain("Bash(rm -rf /)");
+ expect(settings.permissions.deny).toContain(
+ `Write(${vault}/Brain/preferences/**)`,
+ );
+ });
+
+ test("apply against unbootstrapped vault throws", () => {
+ const dir = mkdtempSync(join(tmpdir(), "osb-noinit-"));
+ tmpRoots.push(dir);
+ expect(() => applyProtect({ target: "claudecode", vault: dir }))
+ .toThrow(BrainProtectError);
+ });
+});
+
+describe("unprotect claudecode", () => {
+ test("round-trip restores settings.json to pre-protect content", () => {
+ const vault = mkVault();
+ mkdirSync(join(vault, ".claude"), { recursive: true });
+ const userSettings = JSON.stringify(
+ { permissions: { deny: ["Bash(rm -rf /)"], allow: [] } },
+ null,
+ 2,
+ ) + "\n";
+ writeFileSync(join(vault, ".claude", "settings.json"), userSettings);
+
+ applyProtect({ target: "claudecode", vault });
+ unprotect({ target: "claudecode", vault });
+
+ const after = readFileSync(
+ join(vault, ".claude", "settings.json"),
+ "utf8",
+ );
+ expect(after).toBe(userSettings);
+ });
+
+ test("unprotect on absent manifest exits without throwing", () => {
+ const vault = mkVault();
+ expect(() => unprotect({ target: "claudecode", vault })).not.toThrow();
+ });
+});
+
+describe("applyProtect codex", () => {
+ test("creates config.toml with the managed fence on a fresh user home", () => {
+ const home = mkHome();
+ const vault = mkVault();
+ const r = applyProtect({ target: "codex", vault, __homeOverride: home });
+ expect(r.changed).toBe(true);
+ const config = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(config).toContain("# >>> open-second-brain managed >>>");
+ expect(config).toContain("[permissions.osb_protected.filesystem]");
+ expect(config).toContain(`"${vault}/Brain/preferences/**" = "none"`);
+ });
+
+ test("idempotent on Codex too", () => {
+ const home = mkHome();
+ const vault = mkVault();
+ applyProtect({ target: "codex", vault, __homeOverride: home });
+ const first = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ applyProtect({ target: "codex", vault, __homeOverride: home });
+ const second = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(second).toBe(first);
+ });
+
+ test("preserves user content outside the fence", () => {
+ const home = mkHome();
+ const vault = mkVault();
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ const userToml = '# user content\nmodel = "gpt-5.5"\n';
+ writeFileSync(join(home, ".codex", "config.toml"), userToml);
+ applyProtect({ target: "codex", vault, __homeOverride: home });
+ const after = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(after.startsWith(userToml)).toBe(true);
+ expect(after).toContain("# >>> open-second-brain managed >>>");
+ });
+
+ test("inserts root-level default_permissions before the first TOML table", () => {
+ const home = mkHome();
+ const vault = mkVault();
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ writeFileSync(
+ join(home, ".codex", "config.toml"),
+ [
+ 'model = "gpt-5.5"',
+ "",
+ '[plugins."open-second-brain@open-second-brain"]',
+ "enabled = true",
+ "",
+ ].join("\n"),
+ );
+
+ applyProtect({ target: "codex", vault, __homeOverride: home });
+ const after = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(after.indexOf('default_permissions = "osb_protected"'))
+ .toBeLessThan(after.indexOf('[plugins."open-second-brain@open-second-brain"]'));
+ expect(after.indexOf("[permissions.osb_protected.filesystem]"))
+ .toBeLessThan(after.indexOf('[plugins."open-second-brain@open-second-brain"]'));
+ });
+
+ test("applying a second vault preserves the first vault's entries", () => {
+ const home = mkHome();
+ const vaultA = mkVault();
+ const vaultB = mkVault();
+ applyProtect({ target: "codex", vault: vaultA, __homeOverride: home });
+ applyProtect({ target: "codex", vault: vaultB, __homeOverride: home });
+
+ const config = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(config).toContain(`"${vaultA}/Brain/preferences/**" = "none"`);
+ expect(config).toContain(`"${vaultB}/Brain/preferences/**" = "none"`);
+ });
+});
+
+describe("unprotect codex", () => {
+ test("round-trip on Codex restores pre-protect content", () => {
+ const home = mkHome();
+ const vault = mkVault();
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ const userToml = '# user content\nmodel = "gpt-5.5"\n';
+ writeFileSync(join(home, ".codex", "config.toml"), userToml);
+ applyProtect({ target: "codex", vault, __homeOverride: home });
+ unprotect({ target: "codex", vault, __homeOverride: home });
+ const after = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(after).toBe(userToml);
+ });
+
+ test("removes only the selected vault from a shared managed fence", () => {
+ const home = mkHome();
+ const vaultA = mkVault();
+ const vaultB = mkVault();
+ applyProtect({ target: "codex", vault: vaultA, __homeOverride: home });
+ applyProtect({ target: "codex", vault: vaultB, __homeOverride: home });
+
+ unprotect({ target: "codex", vault: vaultA, __homeOverride: home });
+ const after = readFileSync(
+ join(home, ".codex", "config.toml"),
+ "utf8",
+ );
+ expect(after).not.toContain(`${vaultA}/Brain/preferences/**`);
+ expect(after).toContain(`${vaultB}/Brain/preferences/**`);
+ expect(after).toContain("# >>> open-second-brain managed >>>");
+ });
+});
+
+describe("printSnippet", () => {
+ test("claudecode prints the JSON shape (no manifest)", () => {
+ const out = printSnippet({ target: "claudecode", vault: "/v" });
+ expect(out.body).toContain('"Write(/v/Brain/preferences/**)"');
+ expect(out.body).toContain("permissions");
+ // Manifest fields stay internal β€” `--print` shows only the
+ // file-shaped snippet a user would paste.
+ expect(out.body).not.toContain("schema_version");
+ expect(out.body).not.toContain("owned_deny");
+ });
+
+ test("codex prints the fenced TOML block", () => {
+ const out = printSnippet({ target: "codex", vault: "/v" });
+ expect(out.body).toContain("# >>> open-second-brain managed >>>");
+ expect(out.body).toContain('[permissions.osb_protected.filesystem]');
+ });
+});
diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.ts
new file mode 100644
index 00000000..f96b9a8a
--- /dev/null
+++ b/tests/core/brain/starter.test.ts
@@ -0,0 +1,167 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import {
+ bootstrapBrain,
+ BrainStarterError,
+ copyStarterBundle,
+} from "../../../src/core/brain/init.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { dream } from "../../../src/core/brain/dream.ts";
+
+const tmpRoots: string[] = [];
+
+function mkVault(): string {
+ const dir = mkdtempSync(join(tmpdir(), "osb-starter-"));
+ tmpRoots.push(dir);
+ return dir;
+}
+
+function withRegisteredConfig(): { vault: string; config: string } {
+ const tmp = mkdtempSync(join(tmpdir(), "osb-starter-cfg-"));
+ tmpRoots.push(tmp);
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ mkdirSync(vault, { recursive: true });
+ writeFileSync(
+ config,
+ [
+ 'kind: open-second-brain-config',
+ 'schema_version: 1',
+ `vault: ${JSON.stringify(vault)}`,
+ 'agent_name: "starter-test-agent"',
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ return { vault, config };
+}
+
+afterEach(() => {
+ for (const d of tmpRoots.splice(0)) {
+ try {
+ rmSync(d, { recursive: true, force: true });
+ } catch {
+ // best-effort
+ }
+ }
+});
+
+describe("copyStarterBundle", () => {
+ test("copies the 18 starter files into an empty Brain", () => {
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ const result = copyStarterBundle(vault);
+ expect(result.copied).toHaveLength(18);
+ expect(readdirSync(join(vault, "Brain", "preferences"))).toHaveLength(8);
+ expect(readdirSync(join(vault, "Brain", "retired"))).toHaveLength(3);
+ expect(readdirSync(join(vault, "Brain", "inbox"))).toHaveLength(1);
+ expect(readdirSync(join(vault, "Brain", "log"))).toHaveLength(6);
+ });
+
+ test("refuses to copy when preferences/ already has a file", () => {
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-existing.md"),
+ "---\nkind: brain-preference\nid: pref-existing\n---\n",
+ );
+ expect(() => copyStarterBundle(vault)).toThrow(BrainStarterError);
+ // Refusal is total: no other directory was touched.
+ expect(readdirSync(join(vault, "Brain", "retired"))).toEqual([]);
+ expect(readdirSync(join(vault, "Brain", "inbox"))).toEqual([]);
+ expect(readdirSync(join(vault, "Brain", "log"))).toEqual([]);
+ });
+
+ test("refuses when log/ already has a file (symmetric across subdirs)", () => {
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ writeFileSync(
+ join(vault, "Brain", "log", "2026-05-01.md"),
+ "---\ndate: 2026-05-01\n---\n",
+ );
+ expect(() => copyStarterBundle(vault)).toThrow(BrainStarterError);
+ });
+
+ test("custom --starter-path resolves relative to cwd", () => {
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ const custom = mkdtempSync(join(tmpdir(), "osb-starter-src-"));
+ tmpRoots.push(custom);
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(custom, sub), { recursive: true });
+ }
+ writeFileSync(
+ join(custom, "preferences", "pref-x.md"),
+ "---\nkind: brain-preference\nid: pref-x\n---\n",
+ );
+ const result = copyStarterBundle(vault, { starterPath: custom });
+ expect(result.copied).toHaveLength(1);
+ expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual([
+ "pref-x.md",
+ ]);
+ });
+
+ test("rejects a starter path that does not exist", () => {
+ const vault = mkVault();
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+ expect(() =>
+ copyStarterBundle(vault, {
+ starterPath: "/definitely/not/a/real/path",
+ }),
+ ).toThrow(BrainStarterError);
+ });
+});
+
+describe("bootstrapBrain --starter", () => {
+ test("running through bootstrap drops the bundle and produces a doctor-clean Brain", () => {
+ const { vault, config } = withRegisteredConfig();
+ const r = bootstrapBrain(vault, {
+ configPath: config,
+ starter: true,
+ });
+ // 3 baseline file entries (_brain.yaml, _BRAIN.md, AI Wiki overview)
+ // plus 18 from the starter bundle.
+ const starterEntries = r.created.filter((p) =>
+ p.startsWith("Brain/preferences/")
+ || p.startsWith("Brain/retired/")
+ || p.startsWith("Brain/inbox/")
+ || p.startsWith("Brain/log/"),
+ );
+ expect(starterEntries).toHaveLength(18);
+
+ const doctor = runDoctor(vault);
+ expect(doctor.errors).toEqual([]);
+ // The starter must not raise lint warnings β€” drift would surface as
+ // broken-backlinks, low-evidence-confirmed, etc.
+ expect(doctor.warnings).toEqual([]);
+ });
+
+ test("dream is a no-op on the fresh starter at a fixed --now", () => {
+ const { vault, config } = withRegisteredConfig();
+ bootstrapBrain(vault, { configPath: config, starter: true });
+ const result = dream(vault, {
+ now: new Date("2026-05-17T12:00:00Z"),
+ dryRun: true,
+ });
+ expect(result.changed).toBe(false);
+ });
+});
diff --git a/tests/core/identity-reminder.test.ts b/tests/core/identity-reminder.test.ts
index 10dcd86a..ad84abd9 100644
--- a/tests/core/identity-reminder.test.ts
+++ b/tests/core/identity-reminder.test.ts
@@ -1,12 +1,27 @@
-import { describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
import {
__TEMPLATE_PATH_FOR_TESTS,
+ __resetEnvWarnedOnceForTests,
buildReminder,
+ KNOWN_RUNTIME_TARGETS,
loadReminderTemplate,
} from "../../src/core/identity-reminder.ts";
+const FIXTURE_DIR = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "fixtures",
+ "identity-reminder",
+);
+
+function readFixture(target: string): string {
+ return readFileSync(resolve(FIXTURE_DIR, `${target}.txt`), "utf8").trimEnd();
+}
+
describe("template", () => {
test("template file exists at the resolved path", () => {
expect(existsSync(__TEMPLATE_PATH_FOR_TESTS)).toBe(true);
@@ -48,3 +63,68 @@ describe("Python parity", () => {
expect(__TEMPLATE_PATH_FOR_TESTS).toContain("templates/identity-reminder.txt");
});
});
+
+describe("buildReminder per-target resolution", () => {
+ test("explicit target=hermes returns hermes template body", () => {
+ const out = buildReminder("test-agent", "hermes");
+ expect(out).toContain("Identity: @test-agent");
+ expect(out).toContain("Hermes turns are short");
+ });
+
+ test("explicit target=openclaw returns openclaw template body", () => {
+ const out = buildReminder("test-agent", "openclaw");
+ expect(out).toContain("OpenClaw has no session boundary");
+ });
+
+ test("no target falls back to common template", () => {
+ const out = buildReminder("test-agent");
+ expect(out).toContain("Identity: @test-agent");
+ expect(out).not.toContain("Hermes turns are short");
+ expect(out).not.toContain("OpenClaw has no session boundary");
+ });
+});
+
+describe("buildReminder fixture parity", () => {
+ for (const target of KNOWN_RUNTIME_TARGETS) {
+ test(`agent=test-agent target=${target} matches fixture`, () => {
+ const expected = readFixture(target);
+ const actual = buildReminder("test-agent", target);
+ expect(actual).toBe(expected);
+ });
+ }
+});
+
+describe("buildReminder env-based resolution", () => {
+ let savedEnv: string | undefined;
+
+ beforeEach(() => {
+ savedEnv = process.env.O2B_TARGET;
+ __resetEnvWarnedOnceForTests();
+ });
+
+ afterEach(() => {
+ if (savedEnv === undefined) delete process.env.O2B_TARGET;
+ else process.env.O2B_TARGET = savedEnv;
+ });
+
+ test("env O2B_TARGET=openclaw resolves to openclaw template", () => {
+ process.env.O2B_TARGET = "openclaw";
+ expect(buildReminder("test-agent")).toContain(
+ "OpenClaw has no session boundary",
+ );
+ });
+
+ test("explicit target beats env", () => {
+ process.env.O2B_TARGET = "openclaw";
+ expect(buildReminder("test-agent", "hermes")).toContain(
+ "Hermes turns are short",
+ );
+ });
+
+ test("unknown env value falls back to common template", () => {
+ process.env.O2B_TARGET = "nonsense";
+ const out = buildReminder("test-agent");
+ expect(out).not.toContain("Hermes turns are short");
+ expect(out).not.toContain("OpenClaw has no session boundary");
+ });
+});
diff --git a/tests/fixtures/identity-reminder/hermes.txt b/tests/fixtures/identity-reminder/hermes.txt
new file mode 100644
index 00000000..47ae5cf5
--- /dev/null
+++ b/tests/fixtures/identity-reminder/hermes.txt
@@ -0,0 +1 @@
+[open-second-brain] Identity: @test-agent. After every durable artifact this turn β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@test-agent` automatically, do not include them yourself. Hermes turns are short; do not batch the log calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
diff --git a/tests/fixtures/identity-reminder/openclaw.txt b/tests/fixtures/identity-reminder/openclaw.txt
new file mode 100644
index 00000000..d9698c8c
--- /dev/null
+++ b/tests/fixtures/identity-reminder/openclaw.txt
@@ -0,0 +1 @@
+[open-second-brain] Identity: @test-agent. After every durable in-process action β€” code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know β€” call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@test-agent` automatically, do not include them yourself. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
diff --git a/tests/python/test_hermes_plugin.py b/tests/python/test_hermes_plugin.py
index 6b9e3098..ad2e54b7 100644
--- a/tests/python/test_hermes_plugin.py
+++ b/tests/python/test_hermes_plugin.py
@@ -24,7 +24,13 @@ ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
-from plugins.hermes import check_health, health, on_pre_llm_call, register # noqa: E402
+from plugins.hermes import ( # noqa: E402
+ _load_reminder_template,
+ check_health,
+ health,
+ on_pre_llm_call,
+ register,
+)
PLUGIN_NAME = "open-second-brain"
@@ -188,5 +194,25 @@ class TemplateSourceOfTruthTests(unittest.TestCase):
self.assertNotIn("{agent}", result["context"])
+class PerTargetParityTests(unittest.TestCase):
+ """Python and TypeScript must produce the same bytes for the Hermes
+ target. The shared fixture at
+ ``tests/fixtures/identity-reminder/hermes.txt`` is asserted by the
+ TS resolver test; this test asserts the Python shim against the same
+ bytes. If the two drift, both languages' CI fails.
+ """
+
+ def test_hermes_template_matches_shared_fixture(self):
+ fixture = (
+ ROOT / "tests" / "fixtures" / "identity-reminder" / "hermes.txt"
+ ).read_text(encoding="utf-8").rstrip()
+ rendered = _load_reminder_template().replace("{agent}", "test-agent")
+ self.assertEqual(rendered, fixture)
+
+ def test_hermes_template_prefers_per_target_over_common(self):
+ body = _load_reminder_template()
+ self.assertIn("Hermes turns are short", body)
+
+
if __name__ == "__main__":
unittest.main()