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.2: Brain capture extensions β inline @osb markers, session-import, _field convention
Sol Aitken449bc54023a5
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex ad9db152..d59ddcec 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.1",+ "version": "0.10.2","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.jsonindex f47461fd..1cf05f66 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.1",+ "version": "0.10.2","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.mdindex 3242994d..7d82271b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,139 @@ 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.2] - 2026-05-16++Adds three Tier-A capture and hygiene items from+`Projects/OpenSecondBrain/Features/_summary`: Β§9 inline `@osb`+markers, Β§16 session-import, and Β§24 `_field` prefix convention+for derived frontmatter keys. The Brain layer now has three+capture surfaces (live, inline, session-import) and a derived /+identity split in the preference / retired schema.++No vault migration is required β the new schema parser accepts+both legacy (`status:`) and `_`-prefixed (`_status:`) shapes for+the entire v0.10.x line. The writer always emits the new shape;+existing files migrate lazily on the next dream rewrite, or+eagerly via `o2b brain migrate-frontmatter --apply --yes`.++### Added++- **`o2b brain scan-inline`** β capture `@osb` markers from any+ vault markdown file. Two shapes are recognised: a single line+ (`@osb feedback negative topic=... principle="..."`) and a+ fenced ``` ```osb ``` block with YAML body. Markers create a+ signal in `Brain/inbox/` via the same writer as `brain_feedback`,+ with `source_type: inline`, the source-file wikilink in `source`,+ and a `dedup_hash` over the normalised payload. After capture+ the source line is annotated `@osbβ [[sig-...]]` (inline form)+ or the info-string flips to `osb-checked` with a `<!-- @osbβ+ [[sig-...]] -->` comment line (block form), making re-runs+ idempotent. Default ignore set covers `Brain/`, `.git`,+ `node_modules`, `.obsidian`, `.trash`, `.stversions`,+ `.open-second-brain`; additional excludes via `--exclude`,+ scope narrowing via `--path`, dry-run via `--dry-run`.+- **`o2b brain import-session <path>`** β extract signals from a+ Claude Code / Codex CLI / Hermes session JSONL (or a directory+ of session files). Two extraction paths run in parallel:+ `@osb` markers in user / assistant message text (same parser+ as `scan-inline`), and replay of `brain_feedback` tool_use+ calls captured in the transcript. Each emitted signal carries+ `source_type: session` and a `session_ref: <path>#<turn-id>`+ for traceability. Autodetect runs on the first line; if it+ fails, exit 2 with a request to pass `--format`. The shared+ `dedup_hash` cross-deduplicates against signals already in the+ inbox (including those captured by `scan-inline`).+- **`o2b brain migrate-frontmatter`** β opt-in helper that walks+ `Brain/preferences/` and `Brain/retired/` and rewrites legacy+ Group C frontmatter keys (`status`, `applied_count`,+ `confirmed_at`, `last_evidence_at`, `violated_count`,+ `confidence`, `evidenced_by`, `contradicted_by`) to the+ `_`-prefixed form. Default is `--dry-run`; `--apply --yes`+ takes a pre-run snapshot under `Brain/.snapshots/migrate-...`,+ so rollback by run-id is the standard recovery path. Files+ carrying both shapes for the same field abort the migration+ with an actionable error.+- **`BrainSignal`** gains three optional frontmatter fields:+ `source_type` (`live` / `inline` / `session`; absent on+ legacy signals), `dedup_hash`, and `session_ref`. Non-live+ signals also get a `brain/source/<type>` tag for Obsidian+ filtering. Absence of `source_type` is interpreted as+ `live`; the parser never injects a default into the parsed+ object.+- **`src/core/brain/dedup-hash.ts`** β pure `computeDedupHash`+ shared between `scan-inline` and `import-session`. NFC+ normalisation + whitespace collapse on `principle`; `scope`+ defaults to empty string; SHA-256 over NUL-separated parts.+- **`src/core/brain/inline.ts`** β `discoverMarkers`,+ `parseInlineMarker`, `parseBlockMarker`. Single source of+ truth for `@osb` grammar.+- **`src/core/brain/sessions/`** β adapter registry plus three+ concrete adapters (`claude.ts`, `codex.ts`, `hermes.ts`) and+ the orchestrator (`import.ts`). Adding a fourth runtime is a+ new adapter file plus a registry entry, no other change.+- **`src/core/brain/sessions/validate-feedback.ts`** β extracted+ pure validator for the `brain_feedback` tool-use payload.+ Re-used by the MCP layer (`toolBrainFeedback`) and the+ session importer, so the contract cannot drift between+ surfaces.+- **Doctor `frontmatter-double-shape` warning** β surfaces a+ preference or retired file that carries both legacy and+ `_`-prefixed forms of the same Group C field (manual-edit+ corruption indicator).+- **Three new log-event kinds:** `scan-inline`, `import-session`,+ `migrate-frontmatter`. Each `o2b brain *` invocation appends+ one row to `Brain/log/<today>.md` (skipped on `--dry-run`).+- Test fixtures: `tests/fixtures/sessions/{claude,codex,hermes}-minimal.jsonl`.+ Anonymised five-line transcripts that lock the adapter+ detection + iteration contract.+- E2E scenario `tests/e2e/brain-capture-and-fields.test.ts`+ exercises the full chain: init β scan-inline β import-session+ β migrate-frontmatter β rollback.++### Changed++- **`parsePreference` / `parseRetired`** accept both the legacy+ (`status:`) and the new (`_status:`) shape for every Group C+ field. Files carrying both shapes for the same field raise a+ hard parse error (`frontmatter-double-shape` for doctor).+ Identity fields (`kind`, `id`, `created_at`,+ `unconfirmed_until`, `topic`, `principle`, `scope`, `tags`,+ `aliases`, `supersedes`, `pinned`) are not affected.+- **`writePreference`** emits Group C keys with the `_` prefix+ (`_status`, `_applied_count`, β¦). `moveToRetired` keeps+ `status: retired` un-prefixed on retired files (identity, not+ derived) and drops legacy keys from the inherited frontmatter+ before stamping retire metadata.+- **`writeSignal`** accepts the new optional fields and adds the+ `brain/source/<type>` tag when `source_type` is non-default.+ `parseSignal` round-trips them.+- **Backlinks collector** (`src/core/brain/backlinks.ts`) reads+ `evidenced_by` through the shared `normalizeDerivedKeys`+ helper so the index continues to resolve regardless of+ frontmatter shape.+- **`brain_doctor`** picks up the new `frontmatter-double-shape`+ warning. No existing lint codes change.+- **README** documents the three capture surfaces and lists the+ three new CLI verbs.+- **`skills/brain-memory/SKILL.md`** notes inline markers as the+ no-agent fallback path and points to `import-session` for+ back-filling sessions.++### Notes++- Hard removal of the legacy frontmatter shape is planned for+ a future minor release. The cutover is dependency-driven, not+ calendar-driven.+- `_brain.yaml: scan_inline.exclude:` is not yet honoured (the+ existing minimal YAML parser does not support inline arrays).+ Additional excludes go through the `--exclude` CLI flag in this+ release; YAML-config support is a follow-up.+- Three operator-only commands (`scan-inline`,+ `import-session`, `migrate-frontmatter`) are intentionally+ CLI-only β they don't appear in the MCP surface, consistent+ with how `init`, `reject`, `pin`, `unpin`, and `rollback` are+ kept off the agent loop.+## [0.10.1] - 2026-05-16Closes the "preference body is dead weight" gap. Every active and@@ -1242,6 +1375,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.2]: https://github.com/itechmeat/open-second-brain/compare/v0.10.1...v0.10.2[0.10.1]: https://github.com/itechmeat/open-second-brain/compare/v0.10.0...v0.10.1[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1diff --git a/README.md b/README.mdindex 232f3016..3eb1982f 100644--- a/README.md+++ b/README.md@@ -116,7 +116,7 @@ o2b mcp Run the MCP tool server (stdio)o2b tool-call Invoke an MCP tool handler from the CLIo2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks-# Brain (observing memory β 11 verbs)+# Brain (observing memory β 14 verbs)o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.mdo2b brain feedback Record one taste signal (--topic, --signal, --principle, ...)o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)@@ -127,6 +127,10 @@ o2b brain reject (CLI-only) Move a preference to retired/ with reaso2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshoto2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, β¦)+o2b brain backlinks List inbound references to a Brain artifact id+o2b brain scan-inline Capture `@osb` markers from vault markdown files (Daily/, project notes, β¦)+o2b brain import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)+o2b brain migrate-frontmatter (CLI-only) Rewrite legacy `status:` keys to `_status:`# Pay Memoryo2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/@@ -155,9 +159,9 @@ exposes the same deterministic operations as MCP tools:- **Core (3):** `second_brain_status`, `second_brain_query`,`vault_health`.-- **Brain (6):** `brain_feedback`, `brain_dream`,+- **Brain (7):** `brain_feedback`, `brain_dream`,`brain_apply_evidence`, `brain_digest`, `brain_query`,- `brain_doctor`. See the [Brain section](#brain-observing-memory)+ `brain_doctor`, `brain_backlinks`. See the [Brain section](#brain-observing-memory)below.- **Pay Memory (8):** `payment_memory_init`,`payment_receipt_append`, `asset_capture`,@@ -222,12 +226,34 @@ o2b brain dream --vault /path/to/vaulto2b brain digest --vault /path/to/vault --silent-if-empty```-Eleven CLI verbs in total: `init`, `feedback`, `dream`,+Fourteen CLI verbs in total: `init`, `feedback`, `dream`,`apply-evidence`, `digest`, `query`, `reject`, `pin`, `unpin`,-`rollback`, `doctor`. Six are mirrored as MCP tools (`brain_*`);-`init`, `reject`, `pin`, `unpin`, `rollback` are intentionally-CLI-only because they change the protected set or overwrite vault-state. Pre-run snapshots of `Brain/` go to `Brain/.snapshots/` and+`rollback`, `doctor`, `backlinks`, `scan-inline`, `import-session`,+`migrate-frontmatter`. Seven are mirrored as MCP tools (`brain_*`);+the rest are intentionally CLI-only because they change the+protected set, overwrite vault state, or are operator-only+maintenance commands.++### Capture surfaces++Three independent paths land a signal in `Brain/inbox/`:++- **Live** β the agent calls `brain_feedback` (MCP) or `o2b brain+ feedback` (CLI) the moment the rule is formulated.+- **Inline** β the user (or agent) writes an `@osb` marker into any+ vault markdown file. `o2b brain scan-inline` finds every marker,+ creates the corresponding signal, and annotates the source file+ with `@osbβ [[sig-...]]` so a re-run is a no-op. Two marker+ shapes: a single line `@osb feedback negative topic=... principle="..."`+ or a fenced ` ```osb` block with YAML inside.+- **Session import** β `o2b brain import-session <path>` reads a+ Claude Code / Codex CLI / Hermes session JSONL and extracts both+ `@osb` markers from message text and replays of `brain_feedback`+ tool-use calls. Useful when MCP wasn't available at recording time+ or the agent didn't make the call live.++All three paths share a normalised payload hash so the same rule+captured twice from different surfaces dedups automatically. Pre-run snapshots of `Brain/` go to `Brain/.snapshots/` andsupport `o2b brain rollback <run_id>`. Pinned preferences are exemptfrom automatic retire (`stale-no-evidence`, `expired-unconfirmed`,`rebutted`); only `o2b brain reject` can retire them.diff --git a/docs/plans/2026-05-16-brain-capture-and-fields-design.md b/docs/plans/2026-05-16-brain-capture-and-fields-design.mdnew file mode 100644index 00000000..15610f34--- /dev/null+++ b/docs/plans/2026-05-16-brain-capture-and-fields-design.md@@ -0,0 +1,1067 @@+# Brain β Capture Extensions and Derived-field Convention++Status: design+Target: Open Second Brain v0.10.2+Authors: Sergey Eroshenkov (product), Claude (drafting)++## 1. Overview++The v0.10 line shipped the deterministic core of the Brain layer β capture+(`brain_feedback`), accretion (`dream`), evidence (`brain_apply_evidence`),+search (`brain_search`), and v0.10.1 hygiene (`reject --reason`, recent-evidence+sections, body migration). Capture in v0.10 has one shape: a live MCP / CLI+call at the moment the rule is formulated. Every other surface β a rule jotted+into a Daily note, a rule stated in an offline session whose transcript only+exists on disk, a rule the agent missed in a busy conversation β is invisible+to Brain.++This document specifies three additions that close the capture gap and clean+up an unrelated frontmatter readability issue:++- **Β§9 inline `@osb` markers** β deterministic, no-LLM parser for `@osb`+ markers found anywhere in the vault. Each marker becomes a signal in+ `Brain/inbox/` through the same writer as `brain_feedback`.+- **Β§16 session-import** β `o2b brain import-session <path>` with an+ adapter registry for Claude Code, Codex CLI, and Hermes session JSONL+ files. Signals are extracted via two paths: `@osb` markers embedded+ in message text (reuses Β§9 parser) and replay of `brain_feedback`+ tool-use calls recorded in the transcript.+- **Β§24 `_field` prefix convention** β derived (dream-rewritten)+ fields on `pref-*.md` and `ret-*.md` frontmatter receive a `_`+ prefix (`_status`, `_applied_count`, β¦). Parser accepts both shapes+ for one minor; writer always emits the new shape. Migration helper+ `o2b brain migrate-frontmatter` available for users who want+ immediate, snapshotted migration instead of lazy dream-driven+ rewrites.++This plan covers Tier-A items Β§9, Β§16, and Β§24 from+`Projects/OpenSecondBrain/Features/_summary` (the vault-side product+brief).++## 2. Scope++In scope:++- New CLI verbs: `o2b brain scan-inline`, `o2b brain import-session`,+ `o2b brain migrate-frontmatter`. Each is intentionally CLI-only (no+ MCP mirror) β they are operator surfaces, not agent loops.+- New module `src/core/brain/inline.ts` shared by Β§9 and Β§16+ (single source of truth for the `@osb` marker grammar).+- New module tree `src/core/brain/sessions/` with adapter registry+ and three concrete adapters (`claude.ts`, `codex.ts`, `hermes.ts`).+- New module `src/core/brain/migrate-frontmatter.ts`.+- Extension of `BrainSignal` frontmatter with three optional fields:+ `source_type`, `dedup_hash`, `session_ref`. Default-shape on read+ is `live` to keep existing files identical.+- Extension of `BrainPreference` / `BrainRetired` parser to accept+ both legacy (`status:`) and `_`-prefixed (`_status:`) forms; writer+ emits only the new form.+- Doctor gets one new warning `frontmatter-double-shape` for a+ preference / retired file that has both shapes for the same field+ (manual-edit corruption signal).+- Three new log-event kinds: `scan-inline`, `import-session`,+ `migrate-frontmatter`.+- New optional `_brain.yaml` key `scan_inline.exclude: [...]`.++Out of scope:++- LLM-based or heuristic-phrase extraction of preference signals from+ session text (deferred to BRAIN-FUT-003; needs real observation+ data before tuning).+- MCP tools for `scan-inline` / `import-session` / `migrate-frontmatter`+ (operator commands, not agent loop; consistent with `init`, `reject`,+ `pin`, `unpin`, `rollback`, never exposed via MCP).+- Long-running watcher / daemon over `Brain/inbox/` or vault files+ (violates the "no daemon" invariant).+- Hard removal of the legacy frontmatter shape β planned for v0.12.0.+- Cross-vault dedup / external attribution beyond `session_ref`.+- Mutating writes inside session files (read-only by design β these+ files are runtime logs owned by Claude / Codex / Hermes).++## 3. Architectural Principles++1. **No LLM in core.** Both new capture paths are deterministic. The+ marker parser is a rule-based tokenizer; the session importer+ only extracts what is already marked or recorded by the agent.+2. **Filesystem-first.** Dedup state for `scan-inline` and+ `import-session` lives in the signal frontmatter (`dedup_hash`,+ `session_ref`), not in a sidecar ledger. The whole `Brain/` tree+ remains the source of truth.+3. **Single mutating writer is preserved.** Every signal β live,+ inline, or imported β goes through `writeSignal` in+ `src/core/brain/signal.ts`. The dream pass stays the only mutator+ of `preferences/` and `retired/`. Inline rewrite only touches+ user-authored markdown outside `Brain/`.+4. **Idempotency.** Re-running `scan-inline` on an unchanged vault+ creates no signals and no file rewrites. Re-running+ `import-session` on the same file creates no signals.+5. **Snapshot before destructive operator commands.**+ `migrate-frontmatter --apply` takes a pre-run snapshot through the+ existing `Brain/.snapshots/` infrastructure; rollback works+ identically to `dream`.+6. **CLI-only for operator commands.** The three new verbs are not+ exposed to MCP. Consistent with how `init`, `reject`, `pin`,+ `unpin`, `rollback` are kept off the agent loop.+7. **Read/write asymmetry on session files.** Session files belong+ to upstream runtimes (Claude, Codex, Hermes). We read them; we+ never write back.++## 4. Module Layout++```+src/core/brain/+ inline.ts # @osb marker parser (inline + fenced block)+ inline-rewrite.ts # atomic in-place mark-as-processed+ inline-scan.ts # vault walker that orchestrates inline.ts+ sessions/+ types.ts # SessionAdapter, SessionTurn, SessionToolCall+ registry.ts # adapter registry + autodetect+ claude.ts # Claude Code .jsonl adapter+ codex.ts # Codex CLI .jsonl adapter+ hermes.ts # Hermes .jsonl adapter+ import.ts # orchestrator: iterate β extract β writeSignal+ migrate-frontmatter.ts # opt-in rewriter for legacy frontmatter shape+src/cli/+ brain.ts # +3 cmdBrain handlers, +3 entries in VERB_HELP+src/core/brain/+ signal.ts # accepts new optional fields + tag extension+ preference.ts # parser accepts both shapes; writer emits new+ doctor.ts # +1 lint: frontmatter-double-shape+ types.ts # +BrainSignalSourceType, +new log event kinds+ log.ts # +helpers for the three new event kinds+tests/core/+ brain.inline.test.ts+ brain.inline-rewrite.test.ts+ brain.inline-scan.test.ts+ brain.sessions.claude.test.ts+ brain.sessions.codex.test.ts+ brain.sessions.hermes.test.ts+ brain.sessions.import.test.ts+ brain.migrate-frontmatter.test.ts+tests/cli/+ brain.test.ts # extended with 3 new verb sections+tests/fixtures/sessions/+ claude-minimal.jsonl+ codex-minimal.jsonl+ hermes-minimal.jsonl+```++Dependency graph (top-down):++```+inline-scan.ts ββββ¬ββΊ inline.ts ββββββββββββββ+ β β+sessions/import βββ€ β+ βββΊ sessions/registry ββΊ β+ sessions/{claude, β+ codex, hermes}.ts ββββΊβ+ βΌ+ writeSignal (signal.ts)+ β²+inline-rewrite.ts βββΊ fs-atomic + proper-lockfile+migrate-frontmatter βββΊ preference.ts + snapshot.ts+```++External dependencies introduced: zero. `proper-lockfile` already in+`package.json` is reused for the in-file rewrite path.++## 5. Β§9 β Inline `@osb` Markers++### 5.1 Marker format++Two syntaxes are accepted. The parser tries the block form first; if+the current line does not open a block, the inline form is tried.++**Inline (single line):**++```+@osb <kind> <signal> key=value key2="quoted value with spaces"+```++Concrete example:++```+@osb feedback negative topic=mocking principle="don't mock DB in integration tests" scope=testing+```++**Fenced block (info-string `osb`):**++````+```osb+kind: feedback+signal: negative+topic: mocking+principle: don't mock DB in integration tests+scope: testing+note: |+ Long-form context that does not fit one line.+ Multiple paragraphs allowed.+```+````++The info-string is `osb`, not `@osb` β info-strings in CommonMark are+language identifiers; the `@` sigil is reserved for the inline shape+that lives outside fenced blocks.++### 5.2 Required and optional fields++Required:++- `kind` β always `feedback` for now. The enum exists so future+ versions can add `apply-evidence` without changing the surface.+- `signal` β `positive` or `negative`. Same enum as `BrainSignal`.+- `topic` β kebab-slug; validated through the existing `validateSlug`+ used by `writeSignal`.+- `principle` β single line in inline form, may be multi-line in block+ form. NFC-normalized before hashing (see Β§6.4).++Optional:++- `scope` β slug-adjacent tag, same shape as in `brain_feedback`.+- `agent` β overrides the default `resolveAgentName(config)` result.+- `note` β long-form context. Block form only.+- `source` β comma-separated wikilinks (inline form) or YAML list+ (block form). When absent, the parser still records a wikilink to+ the source file as a single-element `source` array (so the captured+ signal carries provenance even without an explicit value).++Inline parser is a small hand-written tokenizer (not a regex) so it+handles escaped quotes inside `"..."` correctly. Block-form payload+goes through the existing simple frontmatter YAML reader from+`src/core/vault.ts`.++### 5.3 Scan scope and ignore set++The walker traverses the vault from `<vault>/` and visits every `*.md`+file whose path does not match the ignore set. Default ignore set:++```+.git/ # version control+node_modules/ # transitive+.open-second-brain/ # index / cache root+.obsidian/cache/ # Obsidian per-device state+.trash/ # Obsidian-trashed items+.stversions/ # Syncthing versioning+Brain/ # the derived layer (signals, prefs, logs)+Brain/.snapshots/ # tar.zst archives+```++`Brain/` is mandatory in the ignore set: signal files include the+verbatim user text in `## Raw`, and recursive scanning would create+self-referential signals.++Additional excludes go to `_brain.yaml`:++```yaml+scan_inline:+ exclude:+ - "AI Wiki" # example user-specific exclude+ - "Drafts/private" # example+```++Per-file size cap: 1 MiB. Files larger than the cap are skipped with+a `[WARN] file too large to scan` message in CLI output and the log+event. Non-UTF8 files are skipped silently (with the same warning).++### 5.4 Marker processing algorithm++For each scanned file, the walker produces a list of marker matches+top-down. Each match is processed in document order:++1. Parse the marker payload through `inline.ts:parseMarker(input)`.+ Malformed payload yields a `MalformedMarker` entry. In `--strict`+ mode, malformed markers raise the run exit code to 1; otherwise+ they are warnings.+2. Compute `dedup_hash` (see Β§8.4).+3. Consult the in-memory signal index (built once per run by+ scanning `Brain/inbox/` and `Brain/inbox/processed/` for the+ `dedup_hash` field) to decide whether the signal already exists.+4. If the signal already exists and the marker is not yet rewritten+ as `@osbβ` β perform only the in-file rewrite. Logged as+ `noted: already-captured`.+5. If the signal does not exist β `writeSignal(...)` with the+ payload, `source_type: 'inline'`, `dedup_hash: <hash>`, and the+ source-file wikilink in `source`. Then the in-file rewrite.++In-memory signal index format:++```ts+type DedupIndex = ReadonlyMap<+ string /* dedup_hash */,+ { id: string; path: string }+>;+```++Built lazily on first need per run; cost is one `readdir` plus one+frontmatter parse per signal β equivalent to what `dream` already+does on every pass.++### 5.5 In-file rewrite++**Inline:**++```+before: @osb feedback negative topic=mocking principle="..." scope=testing+after: @osbβ [[sig-2026-05-16-mocking]] feedback negative topic=mocking principle="..." scope=testing+```++**Block:** the info-string flips from `osb` to `osb-checked`, and the+first line of the block body is rewritten to embed the signal id as+an HTML comment (which markdown renderers will not interpret, since+the fence body is treated as literal text):++````+before:+```osb+kind: feedback+signal: negative+...+```++after:+```osb-checked+<!-- @osbβ [[sig-2026-05-16-mocking]] -->+kind: feedback+signal: negative+...+```+````++Reasons:++- `[[sig-...]]` wikilink is picked up by the existing+ `buildBacklinkIndex` from v0.9.1, providing a free reverse link.+- `@osbβ` (or `osb-checked` info-string) is the parser's "already+ processed" sentinel β the next `scan-inline` run skips it.+- The original payload remains visible to the human; the marker is+ not "consumed", it is annotated.++Write protocol: lock the source file with `proper-lockfile.lock(path,+{retries: 3, factor: 2})`, read full contents, apply all marker+rewrites in order, write to `<path>.tmp-<pid>`, `fsync`, `rename` over+the original. Standard `fs-atomic.ts` pattern.++### 5.6 CLI++```+o2b brain scan-inline [--vault <path>] [--path <subdir>...]+ [--dry-run] [--strict] [--json]+```++- `--path <subdir>` (repeatable): limit the walker to one or more+ vault-relative subdirectories. Used in CI / spot-checks.+- `--dry-run`: do not write signals, do not rewrite source files;+ emit the plan only.+- `--strict`: malformed markers raise exit code to 1.+- `--json`: structured report:++ ```json+ {+ "scanned": 142,+ "found": 4,+ "created": 3,+ "deduped": 1,+ "malformed": 0,+ "errors": [],+ "files_with_markers": [+ {"path": "Daily/2026-05-15.md", "markers": 2},+ {"path": "Projects/foo/notes.md", "markers": 2}+ ]+ }+ ```++Exit codes: `0` success, `1` error, `2` `--strict` with malformed+markers.++### 5.7 Log event++Appended to `Brain/log/<today>.md`:++```markdown+## 16:23:45Z β scan-inline+- run_id: scan-2026-05-16T16-23-45Z+- agent: claude-vps+- scanned: 142+- created: 3+- deduped: 1+- malformed: 0+```++The `run_id` follows the same `<verb>-<ISO-no-colons>` shape as+`dream` snapshots.++### 5.8 Edge cases++- **Marker inside another language's fence** (`\`\`\`python\n@osb β¦\n\`\`\``):+ the parser tracks fence context line-by-line. Markers inside a+ fence whose info-string is not `osb` are skipped. This prevents+ false-positives in technical documentation that shows OSB usage+ examples.+- **`@osb` in prose without recognized `kind`**: the inline parser+ requires the second token to be a known `kind`. `"@osb is great"`+ is not a marker; `"@osb feedback positive"` is.+- **Symlink loops**: the walker follows symlinks once (`find -L`+ semantics) and remembers visited inodes. Cycle protection prevents+ infinite loops.+- **Concurrent edit while scanning** (Obsidian / Syncthing): the+ per-file lock prevents partial writes; the atomic rename makes+ partial writes invisible to readers.+- **Duplicate markers within one file**: each occurrence is processed+ independently. Content-hash dedup ensures Brain receives one+ signal regardless.++## 6. Β§16 β Session-import++### 6.1 CLI++```+o2b brain import-session <path> [--vault <vault>]+ [--format auto|claude|codex|hermes]+ [--since <ISO>] [--dry-run] [--json]+```++- `<path>`: single `.jsonl` file or a directory. For a directory,+ the importer recurses and processes every `*.jsonl` file with its+ detected adapter.+- `--format`: force a specific adapter. Default is `auto`: the first+ line is read and run through `registry.detect()`. Failure to detect+ exits with code 2 and a message listing the adapters tried.+- `--since <ISO>`: process only turns with `timestamp >= since`. The+ dedup_hash already prevents duplicates on re-runs; this flag is+ for performance on large historical sessions.+- `--dry-run`: print the extraction plan, do not write signals.+- `--json`: structured report.++Exit codes: `0` success, `1` I/O or adapter error, `2` autodetect+failure with no `--format` given.++### 6.2 SessionAdapter interface++```ts+// src/core/brain/sessions/types.ts++export interface SessionTurn {+ /** Adapter-specific stable id (uuid / sequence number / synthetic). */+ readonly turnId: string;+ /** ISO-8601 UTC; synthesized when the format omits the field. */+ readonly timestamp: string;+ readonly role: 'user' | 'assistant' | 'system' | 'tool' | 'meta';+ /** Flat-text view of the turn's content blocks; undefined for meta. */+ readonly text?: string;+ /** Tool-use blocks emitted by the agent in this turn. */+ readonly toolCalls?: ReadonlyArray<SessionToolCall>;+}++export interface SessionToolCall {+ readonly name: string;+ readonly input: Record<string, unknown>;+ /** Tool-use id for tool_result correlation. */+ readonly id?: string;+}++export interface SessionAdapter {+ readonly id: 'claude' | 'codex' | 'hermes';+ /** True iff the adapter recognises the file from its first line. */+ detect(firstLine: string): boolean;+ /** Async iterator of normalised turns from a single .jsonl file. */+ iterate(path: string): AsyncIterable<SessionTurn>;+}+```++Each adapter:++- Implements `detect()` on a single first-line read.+- Streams turns via `AsyncIterable` so we never hold a multi-megabyte+ session in memory.+- Normalises content blocks (`type: "text"`, `type: "tool_use"`,+ array-of-blocks vs. string) into the flat `SessionTurn` shape.++`registry.ts` exports:++```ts+export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter>;+export function detectAdapter(firstLine: string): SessionAdapter | null;+export function getAdapter(id: SessionAdapter['id']): SessionAdapter;+```++### 6.3 Adapter detect heuristics++Derived from inspecting actual session files on the running server:++- **Claude Code (`claude.ts`):** first line is JSON containing either+ `"type":"queue-operation"` or an object with `parentUuid`,+ `sessionId`, `entrypoint` (and usually `version`, `gitBranch`).+- **Codex CLI (`codex.ts`):** first line contains+ `"type":"session_meta"` plus `"originator":"codex_exec"` or+ `"cli_version"` field.+- **Hermes (`hermes.ts`):** first line is `"role":"session_meta"` and+ carries a `"tools"` array (distinguishes from Claude `meta` events+ that lack the array).++If `detectAdapter()` returns null, autodetect fails. We deliberately+do **not** add fuzzy text heuristics β a misdetected adapter would+silently mis-parse content and pollute Brain.++### 6.4 Signal extraction++For every `SessionTurn` from an adapter, the orchestrator runs two+independent extractors:++**Path A β markers in message text** (only when `turn.role` is+`user` or `assistant` and `turn.text` is non-empty):++```ts+const markers = parseMarkers(turn.text);+for (const m of markers) {+ yield { kind: 'marker', payload: m, sourceTurn: turn };+}+```++This is the same `parseMarkers` from `inline.ts`. Users / agents who+type `@osb feedback ...` in chat get their signals captured even if+no MCP call happened.++**Path B β replay `brain_feedback` tool-use** (when `turn.toolCalls`+contains an entry with `name === 'brain_feedback'`):++```ts+for (const call of turn.toolCalls ?? []) {+ if (call.name !== 'brain_feedback') continue;+ const validated = validateBrainFeedbackInput(call.input);+ if (validated.ok) {+ yield { kind: 'replay', payload: validated.value, sourceTurn: turn };+ } else {+ // emit MalformedToolCall warning+ }+}+```++`validateBrainFeedbackInput` mirrors the validation in+`src/mcp/brain-tools.ts:toolBrainFeedback` but as a pure function+returning `{ok, value} | {ok: false, reason}`. Reused, not+re-implemented.++Turns with `role: 'tool' | 'system' | 'meta'` are skipped β no+content-bearing payload there.++### 6.5 Writing the signal++For each extracted entry:++1. Compute `dedup_hash` over `(topic, signal, principle, scope)` β+ identical algorithm to Β§9 (see Β§8.4 below). Important: a marker+ captured by `scan-inline` and the same text replayed from a+ session yield the same hash, so they dedup against each other.+2. Check the dedup index. Hits log as `deduped` and continue.+3. Otherwise, `writeSignal(...)` with:+ - `source_type: 'session'`+ - `agent`:+ - Claude session β `agent: 'claude'` (or the explicit value+ carried in the tool_use input).+ - Codex session β `agent: 'codex'`.+ - Hermes session β `agent: hermes-<role>` where `<role>` comes+ from `session_meta` (e.g. `hermes-product-tech-lead`),+ fallback `hermes` if missing.+ - `source`: `['[[<vault-rel-or-abs-path>:<turn-id>]]']` using the+ existing artifact-range wikilink form (Β§17 of v0.9.1).+ - `session_ref`: `<path>#<turnId>` as a structured field for+ machine processing.+ - `dedup_hash`: the computed hash.++### 6.6 Immutability of source session files++We do not modify session files. Rationale:++- They are runtime logs owned by Claude / Codex / Hermes.+- Their format, ownership, and sync model are upstream concerns.+- Mutation introduces inconsistency with whatever process appends to+ them (Claude session writer, Hermes gateway, Codex exec).++Idempotency relies on `dedup_hash` (for markers) and `session_ref`+(for tool-use replays). On a re-run, the orchestrator builds an+in-memory `Set<string>` of existing `dedup_hash` plus `session_ref`+values from the inbox / processed directories and skips matches.++### 6.7 Log event++One log block per session file (multiple blocks when `<path>` was a+directory):++```markdown+## 18:42:13Z β import-session+- run_id: imp-2026-05-16T18-42-13Z+- agent: claude-vps+- file: [[~/.claude/projects/-root/abc123.jsonl]]+- format: claude+- turns_scanned: 412+- signals_created: 5+- signals_deduped: 2+- tool_replays: 1+- malformed: 0+```++### 6.8 Error handling++- **Non-JSONL line in a `.jsonl` file**: each line is parsed+ independently. Bad lines yield `{ line, reason }` entries in the+ report. The run exit code is 1 if any line fails.+- **Turn missing `timestamp`**: synthesized from the prior turn's+ timestamp or epoch-zero for sort purposes. The created signal+ uses the orchestrator's wall-clock `created_at`.+- **Malformed marker in message text**: warning, continue. `--strict`+ promotes to exit 1.+- **`brain_feedback` tool-use with invalid input** (e.g. missing+ `principle`): warning, continue.+- **Adapter detect fails for one file inside a directory walk**:+ warning, skip the file, continue with the next.++## 7. Β§24 β `_field` Prefix Convention++### 7.1 Field partition++Frontmatter fields on `pref-*.md` and `ret-*.md` split into three+groups.++**Group A β identity (no prefix, immutable after creation):**++```+kind, id, created_at, topic, principle, scope, agent, tags, aliases,+unconfirmed_until, supersedes, superseded_by,+retired_at, retired_reason, retired_by, user_rejected_reason+```++**Group B β user-editable (no prefix):**++```+pinned+```++**Group C β derived (gains `_` prefix, dream rewrites freely):**++```+_status (was status)+_confirmed_at (was confirmed_at)+_last_evidence_at (was last_evidence_at)+_applied_count (was applied_count)+_violated_count (was violated_count)+_confidence (was confidence)+_evidenced_by (was evidenced_by)+_contradicted_by (was contradicted_by; reserved for BRAIN-FUT-002)+```++Notes:++- `unconfirmed_until` is set once at write time and not modified by+ dream; identity, no prefix.+- `evidenced_by` starts at creation but dream extends it under+ `noted-redundant`; derived, gets `_`.+- `tags` is auto-composed by `composePreferenceTags`, but Obsidian+ tooling reads the literal `tags:` key. Pragmatic exception: no+ prefix. A code comment documents this.+- `pinned` is the only Group B field today. Reserved without prefix+ for forward-compatibility with future user-editable flags.++### 7.2 Backward-compat policy++The v0.10.x parser accepts both `name` and `_name` for every Group C+field. The writer always emits the `_`-prefixed form. v0.12.0 will+remove the legacy-read path (a separate document at release time).++Reader behaviour (pseudo-code):++```ts+function readDerivedField(meta, name, kind) {+ const legacy = name in meta;+ const modern = `_${name}` in meta;+ if (legacy && modern) {+ throw new Error(+ `both '_${name}' and legacy '${name}' present; pick one`,+ );+ }+ return modern ? meta[`_${name}`] : meta[name];+}+```++The simultaneous-presence case is a hard error: a half-migrated file+indicates a manual-edit conflict that needs human resolution. The+doctor surfaces this as a `frontmatter-double-shape` warning so it+shows up in the daily digest.++Writer behaviour: always emits `_status`, `_applied_count`, etc.+Existing legacy files are not rewritten on read; they migrate+lazily the next time `dream` rewrites them for a legitimate reason+(refresh evidence sections, status change, retire). Files that never+change after the upgrade stay in legacy form indefinitely β and they+keep parsing correctly through the dual-shape parser.++### 7.3 Explicit migration helper++For users who want immediate migration with a snapshot fallback:++```+o2b brain migrate-frontmatter [--vault <path>]+ [--dry-run | --apply] [--yes] [--json]+```++- `--dry-run` (default): scan `preferences/` and `retired/`, list+ files with legacy-form keys, print a plan, exit 0.+- `--apply`: take a pre-run snapshot via `Brain/.snapshots/`, rewrite+ files atomically, log a `migrate-frontmatter` event, exit 0 on+ success. Requires `--yes` in non-interactive mode (parity with+ `o2b brain rollback`).+- `--json`: structured report.++Per-file algorithm under `--apply`:++1. `parseFrontmatter(path)` β `meta, body`.+2. If every Group C key is already in `_`-form β skip.+3. Otherwise, rename `name` β `_name` in `meta`. Body is untouched.+4. `formatFrontmatter(meta, body)` β `writeFrontmatterAtomic` with+ `overwrite: true`.+5. If both forms of the same field are present β abort the run with+ a clear error listing the offending file and instructing+ `o2b brain rollback migrate-...` to revert.++Log event:++```markdown+## 10:15:22Z β migrate-frontmatter+- run_id: migrate-2026-05-16T10-15-22Z+- agent: claude-vps+- snapshot: Brain/.snapshots/migrate-2026-05-16T10-15-22Z.tar.zst+- files_scanned: 47+- files_migrated: 39+- files_already_new: 8+- conflicts: 0+```++Rollback path is the standard one: `o2b brain rollback+migrate-2026-05-16T10-15-22Z`. No special code path.++### 7.4 Doctor extension++`runDoctor` adds one new warning code `frontmatter-double-shape`,+fired when a preference or retired file has both the legacy and the+prefixed form of the same Group C field. Severity: warning. Message+quotes the offending field name and suggests `o2b brain+migrate-frontmatter --apply` or hand-removal of the duplicate.++No "uses legacy form" warning is added β lazy migration through+dream natural rewrites makes the per-file noise more annoying than+useful.++## 8. Data Model Changes++### 8.1 BrainSignal β new optional fields++In `src/core/brain/types.ts`:++```ts+export const BRAIN_SIGNAL_SOURCE_TYPE = {+ /** Default for `brain_feedback` CLI / MCP calls. */+ live: 'live',+ /** Captured by `o2b brain scan-inline` from an @osb marker. */+ inline: 'inline',+ /** Replayed from a session file by `o2b brain import-session`. */+ session: 'session',+} as const;+export type BrainSignalSourceType =+ (typeof BRAIN_SIGNAL_SOURCE_TYPE)[keyof typeof BRAIN_SIGNAL_SOURCE_TYPE];++export interface BrainSignal {+ // existing fields...++ /**+ * Origin of the signal. Absent on read for legacy files; the+ * reader treats absence as 'live' but never injects a default into+ * the parsed object.+ */+ readonly source_type?: BrainSignalSourceType;++ /**+ * Normalised hash of (topic, signal, principle, scope). Anchor for+ * inline / session-import idempotency. Empty / absent for legacy+ * signals.+ */+ readonly dedup_hash?: string;++ /**+ * Source coordinates for session-imported signals:+ * `<path>#<turn-id>`. Empty for inline / live signals.+ */+ readonly session_ref?: string;+}+```++All three are optional on write and read. Absence is not coerced to a+default in the parsed object β downstream code distinguishes+`undefined` ("legacy file") from explicit `'live'`.++### 8.2 Tag extension++`composeSignalTags` in `signal.ts` gains one rule:++```ts+if (input.source_type && input.source_type !== 'live') {+ push(`brain/source/${input.source_type}`); // 'inline' or 'session'+}+```++`live` does not get a tag β default is the absence of the marker.+Obsidian users can filter by `tag:brain/source/inline` and similar.++### 8.3 Migration matrix++| Artifact | Before this release | After (writer) | New parser | Future break |+|---|---|---|---|---|+| `sig-*.md` without `source_type` | exists | unchanged | trace as `live` | unchanged |+| `sig-*.md` from `scan-inline` | β | `source_type: inline`, `dedup_hash` | parse normally | unchanged |+| `sig-*.md` from `import-session` | β | `source_type: session`, `dedup_hash`, `session_ref` | parse normally | unchanged |+| `pref-*.md` legacy frontmatter | `status:` | dream lazily rewrites to `_status:` | accepts both | hard break: only `_status:` |+| `pref-*.md` new frontmatter | β | `_status:` | parse normally | parse normally |++No wave-rewrite at upgrade time. New writes use the new shape;+existing reads continue working.++### 8.4 `dedup_hash` algorithm++```ts+import * as crypto from 'node:crypto';++export function computeDedupHash(input: {+ topic: string;+ signal: 'positive' | 'negative';+ principle: string;+ scope?: string;+}): string {+ const parts = [+ input.topic.trim(),+ input.signal,+ input.principle.normalize('NFC').trim().replace(/\s+/g, ' '),+ (input.scope ?? '').trim(),+ ];+ return crypto.createHash('sha256').update(parts.join('\u0000')).digest('hex');+}+```++Normalisation rationale:++- NFC for `principle` so Mac / Linux / Windows-typed text yields the+ same hash.+- Collapse internal whitespace in `principle` so cosmetic reflow does+ not create a new signal.+- `scope` trim with empty-string default β `scope=undefined` and+ `scope=""` hash identically.+- `agent` is deliberately excluded β the same rule from two agents+ is still one rule.++A user fixing a typo in `principle` after the first scan changes the+hash. The next scan creates a new signal. This is the intended+behaviour: a fixed typo is a different statement of the rule.++### 8.5 Public surface summary++**New CLI verbs:**++```+o2b brain scan-inline # Β§9+o2b brain import-session <path> # Β§16+o2b brain migrate-frontmatter # Β§24 (opt-in)+```++**New MCP tools:** none.++**New optional `_brain.yaml` keys:**++```yaml+scan_inline:+ exclude: [] # list of vault-relative paths+```++**New `BrainSignal` optional fields:**++```+source_type, dedup_hash, session_ref+```++**Updated `BrainPreference` / `BrainRetired` parse / write:**++- Parser reads both `name` and `_name` for Group C fields.+- Writer emits only `_name`.++**New log-event kinds (3):**++```+'scan-inline', 'import-session', 'migrate-frontmatter'+```++**New doctor lint:** `frontmatter-double-shape` (warning).++### 8.6 SOLID / KISS / DRY++- **SRP:** each module has one responsibility; orchestrators+ (`inline-scan.ts`, `sessions/import.ts`) only stitch.+- **OCP:** adapter-registry is open for extension β adding Cursor or+ another runtime is a new file plus a registry entry, no+ modification of existing adapters.+- **DIP:** CLI handlers depend on the `SessionAdapter` interface,+ not on concrete adapters.+- **KISS:** zero new external dependencies; one shared marker parser+ for Β§9 and Β§16; lazy migration for Β§24 instead of a wave-rewrite.+- **DRY:** `dedup_hash` is one algorithm shared by both new capture+ paths; in-file rewrite reuses `fs-atomic.ts` and `proper-lockfile`;+ migration reuses `snapshot.ts` and `rollback`.++## 9. Testing Strategy++### 9.1 Core unit tests++| File | Coverage |+|---|---|+| `tests/core/brain.inline.test.ts` | inline form positional + key=value + quoted; block form with YAML body; unknown `kind` β not a marker; escaped quotes; multi-marker per file; markers inside non-osb fences ignored; non-UTF8 input rejected |+| `tests/core/brain.inline-rewrite.test.ts` | inline β `@osbβ [[sig-...]]`; block β `osb-checked`; repeat-run is no-op; lock contention surfaced; atomic on partial write |+| `tests/core/brain.inline-scan.test.ts` | ignore set respected; `--path` narrows scope; size cap; symlink loop protection; dedup against existing inbox files |+| `tests/core/brain.sessions.claude.test.ts` | detect matches own format only; iterate normalises tool_use blocks; missing fields synthesised |+| `tests/core/brain.sessions.codex.test.ts` | same as above for Codex schema |+| `tests/core/brain.sessions.hermes.test.ts` | same as above for Hermes schema, including the role-derived agent name |+| `tests/core/brain.sessions.import.test.ts` | dedup between marker and tool_use replay; dedup on re-run; directory walk with one unknown file; `--since` filter |+| `tests/core/brain.migrate-frontmatter.test.ts` | dry-run prints plan and writes nothing; apply takes snapshot + rewrites; idempotent; double-shape file aborts with clear error; rollback restores |+| `tests/core/brain.preference.test.ts` (extended) | parser accepts both shapes; both-shapes file throws; writer emits `_name` only |+| `tests/core/brain.doctor.test.ts` (extended) | `frontmatter-double-shape` warning surfaces |+| `tests/core/brain.signal.test.ts` (extended) | `writeSignal` writes new fields; tag composer adds `brain/source/<type>`; parser reads them back |++### 9.2 CLI integration tests++`tests/cli/brain.test.ts` gains three sections:++- `scan-inline` β `--help`, missing vault, `--dry-run`, `--json`,+ `--strict` exit code parity.+- `import-session` β `--help`, autodetect failure on a junk file,+ `--format` override, directory walk, `--dry-run`.+- `migrate-frontmatter` β `--help`, `--dry-run` by default, `--apply`+ refuses without `--yes` on non-TTY, snapshot creation observed.++### 9.3 E2E++One scenario in `tests/e2e/`:++1. `o2b brain init` on a tmp vault.+2. Create `Daily/2026-05-16.md` with a `@osb feedback` marker.+3. `o2b brain scan-inline` β assert signal in inbox + rewrite in file.+4. `o2b brain dream` β assert promote.+5. `o2b brain migrate-frontmatter --apply --yes` β assert `_status`+ in the resulting pref file.+6. `o2b brain rollback migrate-...` β assert legacy shape restored.++### 9.4 Fixtures++`tests/fixtures/sessions/` contains three anonymised minimal JSONL+files:++- `claude-minimal.jsonl` β 5-10 turns, one marker in user message,+ one `brain_feedback` tool_use in assistant turn.+- `codex-minimal.jsonl` β same coverage in Codex schema+ (`session_meta` + `response_item`).+- `hermes-minimal.jsonl` β same in Hermes schema (`session_meta` ++ `user` + `assistant`).++All ids are deterministic dummies; no real secrets, paths, or+content. Generated by hand once and frozen β tests assert exact+parsed shape against golden expectations.++## 10. Documentation Updates++- **README.md:** under `## CLI` Brain block, add three new verb+ lines. Under `## Brain (observing memory)`, add a short paragraph+ on capture surfaces (live / inline / session-import) after the+ MCP-tools paragraph.+- **`docs/how-it-works.md`:** new subsection "Capture surfaces"+ with the three paths and a Mermaid extension of the existing+ flowchart showing `scan-inline` and `import-session` as+ alternative entry points into `Brain/inbox/`.+- **`skills/brain-memory/SKILL.md`:** one paragraph mentioning that+ `@osb` markers in Daily / project notes are an alternative path+ when no agent is in the loop. The skill stays principle-level;+ procedural detail belongs in README / how-it-works.+- **CHANGELOG.md:** new `## [0.10.2]` block with `### Added` /+ `### Changed` subsections. Release date filled at release time;+ no calendar dates in the PR commit.+- **`docs/plans/2026-05-15-brain-roadmap.md`:** mark BRAIN-FUT-003+ reference (heuristic-phrase detection) as the place to grow if+ session-import shows a real miss-rate.+- **`install.md`:** unchanged. Install flow is not affected.++## 11. Risks and Mitigations++| Risk | Mitigation |+|---|---|+| `scan-inline` corrupts a user file mid-write | Per-file lock + atomic rename; `--dry-run` available; no pre-run snapshot (operation is local to user-owned files outside `Brain/`, vault-level backup is the user's responsibility) |+| Adapter misdetects a foreign format and writes wrong-shape signals | Detect uses concrete format markers (`originator`, `entrypoint`, `cli_version`); failure to detect surfaces as exit 2 asking for `--format`; no fuzzy fallback |+| `migrate-frontmatter --apply` crashes mid-rewrite leaving the vault inconsistent | Pre-run snapshot through `Brain/.snapshots/`; per-file atomic rename; rollback by `run_id` |+| Marker parser captures example markers inside documentation | Markers inside fences whose info-string is not `osb` are skipped; inline parser requires a known `kind` token |+| Hash-based dedup misses a signal whose `principle` was edited after first scan | Documented as intended behaviour β a fixed typo is a different statement; dream merges duplicates downstream via `duplicate-preferences` lint |+| New optional `BrainSignal` fields confuse legacy readers | Backward-compat is one-directional only β new readers handle absence as `live`; old readers ignore unknown fields per existing YAML-parser tolerance |+| Session files contain secrets in `principle` text from a careless paste | Existing `sanitiseTextField` redactor already runs in `writeSignal`; covers tokens, API keys, bearers in v0.9.1 |++## 12. Implementation Roll-up++Order within the single PR. Each step ships typecheck + unit tests+green before the next.++1. **Β§24 parser foundation** β extend `parsePreference` and+ `parseRetired` to accept both shapes; writer emits new shape;+ doctor `frontmatter-double-shape` warning. Existing tests stay+ green; new parser tests pass.+2. **Β§24 migration tool** β `migrate-frontmatter.ts` plus CLI plus+ tests, including snapshot + rollback.+3. **Data model** β `BrainSignal` extension (`source_type`,+ `dedup_hash`, `session_ref`); `writeSignal` accepts them; tag+ composer extended; signal tests updated.+4. **Β§9 marker parser** β `inline.ts` with inline + block grammar;+ isolated unit tests. No CLI yet.+5. **Β§9 walker + rewrite** β `inline-scan.ts`, `inline-rewrite.ts`;+ `o2b brain scan-inline` CLI; integration tests.+6. **Β§16 adapter framework** β `sessions/types.ts`, `registry.ts`,+ three adapters with golden fixtures.+7. **Β§16 orchestrator + CLI** β `sessions/import.ts`;+ `o2b brain import-session` CLI.+8. **Cross-feature E2E** β scenario from Β§9.3 of this doc.+9. **Documentation** β design-doc cross-references, README,+ CHANGELOG, skill update, how-it-works extension.++## 13. Open Questions++- **Adapter ergonomics for non-server runtimes.** This server hosts+ Claude / Codex / Hermes session files. Users running OSB elsewhere+ may have different paths or different session formats. The+ initial surface accepts a generic `<path>` argument; documentation+ shows the three known formats. Adding a Cursor adapter is a+ follow-up if demand appears.+- **Skill update.** The `brain-memory` skill currently teaches+ `brain_feedback`. Documenting inline markers there risks the+ agent treating them as the primary path instead of MCP. The+ paragraph added in Β§10 frames inline markers as the+ no-agent-available fallback, not the default.+- **CHANGELOG style for `_field` rename.** This is technically a+ schema change visible to anyone parsing `pref-*.md` outside the+ project. The release entry will call it out under `### Changed`+ with an explicit migration note pointing at+ `migrate-frontmatter` and the v0.12.0 hard-break ETA being+ dependency-driven (no calendar date).++## 14. References++- `Projects/OpenSecondBrain/Features/_summary.md` β Tier-A items+ Β§9, Β§16, Β§24.+- `Projects/OpenSecondBrain/Features/rowboat.md` Β§1 β inline marker+ source.+- `Projects/OpenSecondBrain/Features/llm-wiki-compiler.md` Β§1 β+ session-import source.+- `Projects/OpenSecondBrain/Features/tolaria.md` Β§3 β `_field`+ prefix convention source.+- `docs/plans/2026-05-15-brain-observing-memory.md` β v0.9 base+ plan; section numbering and file shapes referenced here.+- `docs/plans/2026-05-16-brain-search-design.md` β v0.10 reference+ for design-doc structure.+- `docs/plans/2026-05-15-brain-roadmap.md` β BRAIN-FUT-003 for the+ deferred heuristic phrase detection.diff --git a/docs/plans/2026-05-16-brain-capture-and-fields-impl.md b/docs/plans/2026-05-16-brain-capture-and-fields-impl.mdnew file mode 100644index 00000000..38123822--- /dev/null+++ b/docs/plans/2026-05-16-brain-capture-and-fields-impl.md@@ -0,0 +1,1474 @@+# Brain Implementation Plan++> **For agentic workers:** Use `superpowers:executing-plans` to walk this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Ship three Tier-A items in one PR β inline `@osb` markers (Β§9), session-import (Β§16), `_field` prefix convention (Β§24). Target version: v0.10.2.++**Architecture:** Three independent slices that compose under one PR.+- Β§9 lives in `src/core/brain/inline*.ts` + `src/cli/brain.ts` (new verb).+- Β§16 lives in `src/core/brain/sessions/` + `src/cli/brain.ts` (new verb).+- Β§24 modifies `preference.ts` (parser + writer), adds `migrate-frontmatter.ts` + `src/cli/brain.ts` (new verb).+- A shared marker parser (`inline.ts`) services both Β§9 and Β§16. A shared `computeDedupHash` services both new capture paths.++**Tech Stack:** TypeScript on Bun. No new external dependencies. Reuses `proper-lockfile`, `fs-atomic.ts`, `snapshot.ts`, `writeSignal`, `writeFrontmatterAtomic` from existing code.++**Source of truth for behaviour:** [`docs/plans/2026-05-16-brain-capture-and-fields-design.md`](./2026-05-16-brain-capture-and-fields-design.md). Every task implements a slice of that spec β on conflict, the spec wins and this plan is updated.++---++## Plan-wide conventions++These apply to every task; do not re-state per step.++- **Imports.** Production code uses `node:`-prefixed builtins (`node:fs`, `node:crypto`). Tests use `import { test, expect, describe, beforeEach, afterEach } from "bun:test"`. Always `.ts` extension in imports.+- **Result shape.** Public-API return values are `Object.freeze`-d at the producing call site.+- **Errors.** Each new module defines its own typed error class (`InlineMarkerError`, `SessionImportError`, `MigrationError`). Non-typed exceptions bubble up unchanged.+- **No git from this plan.** Each task ends with **Pause for review (no commit)**. The user does all git work themselves.+- **No bait fallbacks.** Adapter autodetect failure β exit 2 with explicit message, never a silent wrong-adapter choice. Marker-with-unknown-kind β not a marker, never a heuristic guess.+- **Atomic writes** through `src/core/fs-atomic.ts:atomicWriteFileSync`. In-place rewrite of user files (Β§9) holds `proper-lockfile.lock(path, {retries: 3, factor: 2})` around read + write.+- **Verification.** Every task ends with `bun test tests/path/to/file.test.ts` and an expected pass count. End of each Phase: full `bun test` + `bun run typecheck` green.++## File map++Create:++```+src/core/brain/inline.ts β @osb marker parser (inline + fenced block); pure+src/core/brain/inline-rewrite.ts β atomic in-place "@osbβ" annotation+src/core/brain/inline-scan.ts β vault walker; orchestrates parse + rewrite + writeSignal+src/core/brain/sessions/types.ts β SessionAdapter, SessionTurn, SessionToolCall, SessionImportError+src/core/brain/sessions/registry.ts β adapter registry + detectAdapter()+src/core/brain/sessions/claude.ts β Claude Code .jsonl adapter+src/core/brain/sessions/codex.ts β Codex CLI .jsonl adapter+src/core/brain/sessions/hermes.ts β Hermes .jsonl adapter+src/core/brain/sessions/import.ts β orchestrator; iterates adapter, extracts, writes signals+src/core/brain/sessions/validate-feedback.ts β pure validator (re-used by MCP and import)+src/core/brain/migrate-frontmatter.ts β opt-in legacy β _-prefixed rewriter+src/core/brain/dedup-hash.ts β computeDedupHash(input) β string+tests/core/brain.inline.test.ts+tests/core/brain.inline-rewrite.test.ts+tests/core/brain.inline-scan.test.ts+tests/core/brain.dedup-hash.test.ts+tests/core/brain.sessions.types.test.ts+tests/core/brain.sessions.registry.test.ts+tests/core/brain.sessions.claude.test.ts+tests/core/brain.sessions.codex.test.ts+tests/core/brain.sessions.hermes.test.ts+tests/core/brain.sessions.validate-feedback.test.ts+tests/core/brain.sessions.import.test.ts+tests/core/brain.migrate-frontmatter.test.ts+tests/fixtures/sessions/claude-minimal.jsonl+tests/fixtures/sessions/codex-minimal.jsonl+tests/fixtures/sessions/hermes-minimal.jsonl+tests/e2e/brain-capture-and-fields.test.ts+```++Modify:++```+src/core/brain/types.ts β BRAIN_SIGNAL_SOURCE_TYPE enum, BrainSignal fields, 3 new log-event kinds+src/core/brain/signal.ts β writeSignal accepts source_type/dedup_hash/session_ref; tag composer extension; parser reads them back+src/core/brain/preference.ts β parser accepts both shapes; writer emits _-prefixed only; conflict throws+src/core/brain/doctor.ts β checks for frontmatter-double-shape warning+src/core/brain/log.ts β helpers for the 3 new event kinds (or via existing appendLogEvent)+src/core/brain/policy.ts β _brain.yaml schema accepts optional scan_inline.exclude+src/cli/brain.ts β 3 new verb handlers + VERB_HELP entries + dispatch+src/mcp/brain-tools.ts β validateBrainFeedbackInput extracted to sessions/validate-feedback.ts; no new MCP tools+tests/core/brain.preference.test.ts β dual-shape parse + writer-emits-new tests+tests/core/brain.signal.test.ts β new optional fields round-trip+tests/core/brain.doctor.test.ts β frontmatter-double-shape warning case+tests/cli/brain.test.ts β 3 new verb test sections+README.md β CLI table extension + capture-surfaces paragraph+docs/how-it-works.md β capture-surfaces subsection + Mermaid extension+skills/brain-memory/SKILL.md β @osb marker mention paragraph+CHANGELOG.md β ## [0.10.2] entry under Added / Changed+package.json β version 0.10.1 β 0.10.2 via `bun run sync-version`+pyproject.toml β version 0.10.1 β 0.10.2 via sync+```++---++## Phase 1 β Β§24 foundation (parser dual-shape, writer new-only)++Smallest, safest slice first. Existing tests must stay green throughout.++### Task 1: Dual-shape reader helper++**Files:**+- Create: nothing+- Modify: `src/core/brain/preference.ts` β add `readDerivedField` private helper+- Test: `tests/core/brain.preference.test.ts`++- [ ] **Step 1: Write failing test for dual-shape parser**++Add to `tests/core/brain.preference.test.ts`:++```ts+test("parsePreference reads legacy 'status:' shape", () => {+ const path = writeTempPref({ status: "confirmed", /* ... */ });+ const pref = parsePreference(path);+ expect(pref.status).toBe("confirmed");+});++test("parsePreference reads new '_status:' shape", () => {+ const path = writeTempPref({ _status: "confirmed", /* ... */ });+ const pref = parsePreference(path);+ expect(pref.status).toBe("confirmed");+});++test("parsePreference throws when both '_status' and 'status' present", () => {+ const path = writeTempPref({ status: "confirmed", _status: "confirmed" });+ expect(() => parsePreference(path)).toThrow(/both '_status' and legacy 'status' present/);+});+```++Cover every Group C field listed in spec Β§7.1 with the same three-case shape. Use a `describe.each` table to keep the test compact.++- [ ] **Step 2: Implement `readDerivedField` helper in `preference.ts`**++```ts+function readDerivedField(meta: Record<string, unknown>, name: string): unknown {+ const legacy = name in meta && meta[name] !== undefined && meta[name] !== null;+ const modern = `_${name}` in meta && meta[`_${name}`] !== undefined && meta[`_${name}`] !== null;+ if (legacy && modern) {+ throw new Error(+ `preference field collision: both '_${name}' and legacy '${name}' present; ` ++ `pick one (run \`o2b brain migrate-frontmatter --apply\` or hand-edit)`,+ );+ }+ return modern ? meta[`_${name}`] : meta[name];+}+```++Route `status`, `confirmed_at`, `last_evidence_at`, `applied_count`, `violated_count`, `confidence`, `evidenced_by`, `contradicted_by` (when applicable) through this helper. Identity fields (`kind`, `id`, `created_at`, `unconfirmed_until`, `topic`, `principle`, `scope`, `agent`, `aliases`, `tags`, `supersedes`, `pinned`) stay on the existing `requireField` / `requireString` path.++- [ ] **Step 3: `parseRetired` gets the same treatment**++Same set of Group C fields. Add the same describe.each block for retired fixtures.++- [ ] **Step 4: Verify**++Run: `bun test tests/core/brain.preference.test.ts`+Expected: all new tests pass; existing tests stay green.++**Pause for review (no commit).**++---++### Task 2: Writer emits `_`-prefixed Group C fields++**Files:**+- Modify: `src/core/brain/preference.ts` β `preferenceFrontmatter`, `moveToRetired`'s frontmatter rebuild+- Test: `tests/core/brain.preference.test.ts`++- [ ] **Step 1: Failing test for writer output shape**++```ts+test("writePreference emits '_status' not 'status'", () => {+ writePreference(vault, { /* ...minimal valid input... */, status: "confirmed", ... });+ const raw = readFileSync(prefPath, "utf8");+ expect(raw).toMatch(/^_status: confirmed$/m);+ expect(raw).not.toMatch(/^status: /m);+});+```++Mirror for each Group C field (`_applied_count`, `_violated_count`, `_confidence`, `_confirmed_at`, `_last_evidence_at`, `_evidenced_by`).++- [ ] **Step 2: Implement**++In `preferenceFrontmatter`:++```ts+const metadata: FrontmatterMap = {+ kind: "brain-preference",+ id,+ created_at: input.created_at,+ _confirmed_at: input.confirmed_at ?? "null",+ unconfirmed_until: input.unconfirmed_until,+ tags: [...tags],+ topic: input.topic.trim(),+ _status: input.status,+ principle: input.principle.trim(),+ _evidenced_by: [...input.evidenced_by],+ _applied_count: applied,+ _violated_count: violated,+ _last_evidence_at: input.last_evidence_at ?? "null",+ _confidence: confidence,+ pinned,+};+```++Update `moveToRetired`'s frontmatter rebuild loop to write Group C with the prefix. Skip the legacy keys when copying meta into `newMeta`.++- [ ] **Step 3: Verify whole `brain` test suite**++Run: `bun test tests/core/brain.preference.test.ts tests/core/brain.dream.test.ts tests/core/brain.digest.test.ts tests/core/brain.query.test.ts`++Expected: green. Dream / digest / query consume the parsed shape, which Task 1 normalised; on-disk write shape change should be invisible to them.++**Pause for review (no commit).**++---++### Task 3: Doctor `frontmatter-double-shape` warning++**Files:**+- Modify: `src/core/brain/doctor.ts`+- Test: `tests/core/brain.doctor.test.ts`++- [ ] **Step 1: Failing test**++```ts+test("doctor flags frontmatter-double-shape on collision file", () => {+ const path = writeTempPref({ status: "confirmed", _status: "confirmed", /*β¦*/ });+ const result = runDoctor(vault);+ expect(result.warnings.map(w => w.code)).toContain("frontmatter-double-shape");+});+```++- [ ] **Step 2: Implement check**++Since `parsePreference` already throws on the collision, capture that throw in `checkPreferences` (and `checkRetired`) and convert to a `frontmatter-double-shape` warning (not a `preference-invalid` error). Pattern-match the error message string against `/both '_.*' and legacy '.*' present/` β narrow enough to not catch unrelated throws.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.doctor.test.ts`+Expected: new case passes; existing doctor tests green.++**Pause for review (no commit).**++---++## Phase 2 β Β§24 migration tool++### Task 4: `computeDedupHash` (shared building block, scheduled here for phase ordering)++**Files:**+- Create: `src/core/brain/dedup-hash.ts`+- Test: `tests/core/brain.dedup-hash.test.ts`++- [ ] **Step 1: Failing test**++```ts+test("computeDedupHash is stable across NFC variants", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "naΓ―ve" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "naΓ―ve" });+ // ^ NFD form of Γ©+ expect(a).toBe(b);+});++test("computeDedupHash collapses internal whitespace in principle", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "a b c" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "a b c" });+ expect(a).toBe(b);+});++test("computeDedupHash treats undefined scope as empty scope", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "p", scope: "" });+ expect(a).toBe(b);+});++test("computeDedupHash differs when topic differs", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ const b = computeDedupHash({ topic: "y", signal: "negative", principle: "p" });+ expect(a).not.toBe(b);+});+```++- [ ] **Step 2: Implement**++```ts+import { createHash } from "node:crypto";++export interface DedupHashInput {+ readonly topic: string;+ readonly signal: 'positive' | 'negative';+ readonly principle: string;+ readonly scope?: string;+}++export function computeDedupHash(input: DedupHashInput): string {+ const parts = [+ input.topic.trim(),+ input.signal,+ input.principle.normalize("NFC").trim().replace(/\s+/g, " "),+ (input.scope ?? "").trim(),+ ];+ return createHash("sha256").update(parts.join("\u0000")).digest("hex");+}+```++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.dedup-hash.test.ts`+Expected: 4 pass.++**Pause for review (no commit).**++---++### Task 5: `migrate-frontmatter` core function++**Files:**+- Create: `src/core/brain/migrate-frontmatter.ts`+- Test: `tests/core/brain.migrate-frontmatter.test.ts`++- [ ] **Step 1: Define `MigrationError`, `MigrationPlan`, `MigrationResult`**++```ts+export class MigrationError extends Error {+ constructor(public readonly code: 'COLLISION' | 'PARSE' | 'IO', message: string) {+ super(message);+ this.name = 'MigrationError';+ }+}++export interface MigrationPlan {+ readonly files_scanned: number;+ readonly files_to_migrate: ReadonlyArray<string>;+ readonly files_already_new: ReadonlyArray<string>;+ readonly collisions: ReadonlyArray<{ path: string; field: string }>;+}++export interface MigrationResult {+ readonly run_id: string;+ readonly snapshot_path: string | null; // null for dry-run+ readonly plan: MigrationPlan;+ readonly files_migrated: ReadonlyArray<string>;+}+```++- [ ] **Step 2: Failing test for `planMigration` (pure)**++```ts+test("planMigration counts legacy / new / collision files", () => {+ // Set up tmp vault with 3 prefs: legacy, new, collision+ const plan = planMigration(vault);+ expect(plan.files_scanned).toBe(3);+ expect(plan.files_to_migrate.length).toBe(1);+ expect(plan.files_already_new.length).toBe(1);+ expect(plan.collisions.length).toBe(1);+});+```++- [ ] **Step 3: Implement `planMigration`**++Walk `Brain/preferences/` and `Brain/retired/`. For each file, parse frontmatter with the simple parser. Detect for each Group C field:+- Has `_name` only β already new.+- Has `name` only β to-migrate.+- Has both β collision (record path + field).+- Has neither β skip (the field is optional).++- [ ] **Step 4: Failing test for `applyMigration`**++```ts+test("applyMigration rewrites legacy keys to _-prefixed", async () => {+ // Set up tmp vault with a legacy pref file+ const result = await applyMigration(vault, { snapshot: true });+ expect(result.files_migrated.length).toBe(1);+ expect(readFileSync(prefPath, "utf8")).toMatch(/^_status: /m);+ expect(readFileSync(prefPath, "utf8")).not.toMatch(/^status: /m);+});++test("applyMigration aborts on collision file", async () => {+ // ... two-shape file present+ await expect(applyMigration(vault, { snapshot: true })).rejects.toThrow(MigrationError);+});++test("applyMigration takes a snapshot before rewriting", async () => {+ // ... legacy pref present+ const result = await applyMigration(vault, { snapshot: true });+ expect(result.snapshot_path).toBeTruthy();+ expect(existsSync(result.snapshot_path!)).toBe(true);+});+```++- [ ] **Step 5: Implement `applyMigration`**++```ts+export async function applyMigration(+ vault: string,+ opts: { snapshot: boolean; now?: Date },+): Promise<MigrationResult>+```++Algorithm:+1. `planMigration(vault)`. If `plan.collisions.length > 0` β throw `MigrationError('COLLISION', ...)`.+2. Generate `run_id = 'migrate-' + iso-no-colons(now)`.+3. If `opts.snapshot`, call existing `createSnapshot(vault, run_id)` from `snapshot.ts`.+4. For each file in `plan.files_to_migrate`:+ - Re-parse frontmatter.+ - Move legacy keys to `_`-prefixed keys (build a new `FrontmatterMap`).+ - `writeFrontmatterAtomic(path, newMeta, body, { overwrite: true })`.+5. Return `MigrationResult`.++- [ ] **Step 6: Verify**++Run: `bun test tests/core/brain.migrate-frontmatter.test.ts`+Expected: 5 tests pass.++**Pause for review (no commit).**++---++### Task 6: CLI `o2b brain migrate-frontmatter`++**Files:**+- Modify: `src/cli/brain.ts` β `cmdBrainMigrateFrontmatter`, dispatch, help+- Test: extend `tests/cli/brain.test.ts`++- [ ] **Step 1: Failing CLI tests**++```ts+describe("o2b brain migrate-frontmatter", () => {+ test("--dry-run by default; no files modified", async () => {+ // ... set up vault with one legacy pref+ const result = await runCli(["brain", "migrate-frontmatter", "--vault", vault]);+ expect(result.exitCode).toBe(0);+ expect(readFileSync(prefPath, "utf8")).toMatch(/^status: /m); // unchanged+ });++ test("--apply --yes rewrites files and takes a snapshot", async () => {+ const result = await runCli(["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"]);+ expect(result.exitCode).toBe(0);+ expect(readFileSync(prefPath, "utf8")).toMatch(/^_status: /m);+ expect(listSnapshots(vault).length).toBeGreaterThan(0);+ });++ test("--apply without --yes fails in non-TTY mode", async () => {+ const result = await runCli(["brain", "migrate-frontmatter", "--vault", vault, "--apply"]);+ expect(result.exitCode).toBe(1);+ expect(result.stderr).toMatch(/--yes/);+ });++ test("--json prints structured report", async () => {+ const result = await runCli(["brain", "migrate-frontmatter", "--vault", vault, "--json"]);+ const parsed = JSON.parse(result.stdout);+ expect(parsed.ok).toBe(true);+ expect(parsed.files_scanned).toBeGreaterThanOrEqual(0);+ });+});+```++- [ ] **Step 2: Implement handler in `brain.ts`**++Follow the pattern of existing CLI handlers (parse flags, resolve vault, delegate to core, emit json/text). Append `migrate-frontmatter` log event via `appendLogEvent` after a successful `--apply`.++- [ ] **Step 3: Register in dispatch + VERB_HELP**++Add case `"migrate-frontmatter"` to the switch in `handleBrainSubcommand`, entry in `VERB_HELP`, line in `BRAIN_HELP`.++- [ ] **Step 4: Verify**++Run: `bun test tests/cli/brain.test.ts`+Expected: 4 new tests pass; existing brain CLI tests green.++**Pause for review (no commit). End of Phase 2.** Full repo verification: `bun test && bun run typecheck`.++---++## Phase 3 β BrainSignal extension (`source_type`, `dedup_hash`, `session_ref`)++### Task 7: Types β `BRAIN_SIGNAL_SOURCE_TYPE`, BrainSignal optional fields, new log-event kinds++**Files:**+- Modify: `src/core/brain/types.ts`+- Test: `tests/core/brain.types.test.ts`++- [ ] **Step 1: Failing test (type-level + enum membership)**++```ts+test("BRAIN_SIGNAL_SOURCE_TYPE has live / inline / session", () => {+ expect(Object.values(BRAIN_SIGNAL_SOURCE_TYPE)).toEqual(["live", "inline", "session"]);+});++test("BRAIN_LOG_EVENT_KIND has scanInline / importSession / migrateFrontmatter", () => {+ expect(BRAIN_LOG_EVENT_KIND.scanInline).toBe("scan-inline");+ expect(BRAIN_LOG_EVENT_KIND.importSession).toBe("import-session");+ expect(BRAIN_LOG_EVENT_KIND.migrateFrontmatter).toBe("migrate-frontmatter");+});+```++- [ ] **Step 2: Add the const + type**++```ts+export const BRAIN_SIGNAL_SOURCE_TYPE = {+ live: "live",+ inline: "inline",+ session: "session",+} as const;+export type BrainSignalSourceType = typeof BRAIN_SIGNAL_SOURCE_TYPE[keyof typeof BRAIN_SIGNAL_SOURCE_TYPE];++export interface BrainSignal {+ // ... existing ...+ readonly source_type?: BrainSignalSourceType;+ readonly dedup_hash?: string;+ readonly session_ref?: string;+}++export const BRAIN_LOG_EVENT_KIND = {+ // ... existing ...+ scanInline: "scan-inline",+ importSession: "import-session",+ migrateFrontmatter: "migrate-frontmatter",+} as const;+```++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.types.test.ts`+Expected: 2 new tests pass; existing green.++**Pause for review (no commit).**++---++### Task 8: `writeSignal` accepts new fields + tag extension++**Files:**+- Modify: `src/core/brain/signal.ts`+- Test: `tests/core/brain.signal.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("writeSignal records source_type / dedup_hash / session_ref when provided", () => {+ const r = writeSignal(vault, { /* ... base inputs ... */, source_type: "inline", dedup_hash: "abc", });+ const raw = readFileSync(r.path, "utf8");+ expect(raw).toMatch(/^source_type: inline$/m);+ expect(raw).toMatch(/^dedup_hash: abc$/m);+});++test("writeSignal adds brain/source/<type> tag when non-live", () => {+ const r = writeSignal(vault, { /* ... */, source_type: "session" });+ const raw = readFileSync(r.path, "utf8");+ expect(raw).toMatch(/brain\/source\/session/);+});++test("writeSignal omits source-type tag when live (default)", () => {+ const r = writeSignal(vault, { /* ... no source_type */ });+ const raw = readFileSync(r.path, "utf8");+ expect(raw).not.toMatch(/brain\/source\//);+});++test("parseSignal round-trips new optional fields", () => {+ const r = writeSignal(vault, { /* ... */, source_type: "inline", dedup_hash: "h", session_ref: "ref#1" });+ const parsed = parseSignal(r.path);+ expect(parsed.source_type).toBe("inline");+ expect(parsed.dedup_hash).toBe("h");+ expect(parsed.session_ref).toBe("ref#1");+});+```++- [ ] **Step 2: Implement**++Extend `WriteSignalInput` with optional `source_type`, `dedup_hash`, `session_ref`. In `composeSignalTags`, add the `brain/source/<type>` push when `source_type !== 'live'`. In the frontmatter map, add the three fields when present. In `parseSignal`, read them as optional scalar strings.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.signal.test.ts`+Expected: 4 new pass.++**Pause for review (no commit).**++---++### Task 9: Extract `validateBrainFeedbackInput` from MCP layer++**Files:**+- Create: `src/core/brain/sessions/validate-feedback.ts`+- Modify: `src/mcp/brain-tools.ts` (re-use the helper)+- Test: `tests/core/brain.sessions.validate-feedback.test.ts`++- [ ] **Step 1: Failing test**++```ts+test("validateBrainFeedbackInput accepts a valid payload", () => {+ const out = validateBrainFeedbackInput({ topic: "t", signal: "positive", principle: "p" });+ expect(out.ok).toBe(true);+});++test("validateBrainFeedbackInput rejects missing principle", () => {+ const out = validateBrainFeedbackInput({ topic: "t", signal: "positive" });+ expect(out.ok).toBe(false);+ expect(out.reason).toMatch(/principle/);+});++test("validateBrainFeedbackInput rejects invalid signal enum", () => {+ const out = validateBrainFeedbackInput({ topic: "t", signal: "maybe", principle: "p" });+ expect(out.ok).toBe(false);+});+```++- [ ] **Step 2: Implement pure validator**++```ts+export type ValidatedFeedback = { topic: string; signal: 'positive'|'negative'; principle: string; scope?: string; agent?: string; raw?: string };+export type ValidationResult = { ok: true; value: ValidatedFeedback } | { ok: false; reason: string };++export function validateBrainFeedbackInput(input: unknown): ValidationResult { /* ... */ }+```++Mirror the checks `toolBrainFeedback` runs in `src/mcp/brain-tools.ts` (topic non-empty string, signal in enum, principle non-empty, scope optional string, etc.) but as a pure function returning a tagged union.++- [ ] **Step 3: Refactor MCP layer to call the helper**++`toolBrainFeedback` in `src/mcp/brain-tools.ts` switches from local string coercions to `validateBrainFeedbackInput`. Public behaviour identical; verify with existing MCP tests.++- [ ] **Step 4: Verify**++Run: `bun test tests/core/brain.sessions.validate-feedback.test.ts tests/mcp/`+Expected: 3 new pass + MCP tests green.++**Pause for review (no commit). End of Phase 3.**++---++## Phase 4 β Β§9 marker parser++### Task 10: Inline-form parser++**Files:**+- Create: `src/core/brain/inline.ts` (initial: inline form only)+- Test: `tests/core/brain.inline.test.ts`++- [ ] **Step 1: Define the parsed shape**++```ts+export interface ParsedMarker {+ readonly kind: 'feedback'; // forward-compat enum (only 'feedback' for now)+ readonly signal: 'positive' | 'negative';+ readonly topic: string;+ readonly principle: string;+ readonly scope?: string;+ readonly agent?: string;+ readonly note?: string;+ readonly source?: ReadonlyArray<string>;+ readonly originLine: number; // 1-based; identifies the marker in file+ readonly originText: string; // verbatim marker text (for rewrite)+}++export class InlineMarkerError extends Error {+ constructor(public readonly code: 'PARSE'|'UNKNOWN_KIND'|'BAD_ENUM', message: string) {+ super(message); this.name = 'InlineMarkerError';+ }+}+```++- [ ] **Step 2: Failing tests for inline form**++```ts+test("parseInlineMarker handles positional + key=value", () => {+ const m = parseInlineMarker(`@osb feedback negative topic=mocking principle="don't mock DB"`, 1);+ expect(m?.kind).toBe("feedback");+ expect(m?.signal).toBe("negative");+ expect(m?.topic).toBe("mocking");+ expect(m?.principle).toBe("don't mock DB");+});++test("parseInlineMarker handles quoted strings with spaces and escapes", () => {+ const m = parseInlineMarker(`@osb feedback positive topic=t principle="line with \\"quotes\\""`, 1);+ expect(m?.principle).toBe(`line with "quotes"`);+});++test("parseInlineMarker returns null for unknown kind", () => {+ const m = parseInlineMarker(`@osb foo bar topic=t`, 1);+ expect(m).toBeNull();+});++test("parseInlineMarker returns null for non-marker prose", () => {+ expect(parseInlineMarker(`This is @osb in the middle of text`, 1)).toBeNull();+});++test("parseInlineMarker requires topic, signal, principle", () => {+ expect(parseInlineMarker(`@osb feedback positive`, 1)).toBeNull();+});+```++- [ ] **Step 3: Implement tokenizer**++Hand-written state-machine: skip leading whitespace, consume `@osb`, kind token, signal token, then loop over `key=value` pairs. Value may be unquoted (no whitespace) or `"..."` with `\"` and `\\` escapes. Reject markers that don't start at column 0 of the trimmed line (avoids matching `@osb` mentions inside prose).++Required-field check at end: bail with `null` (not error) when missing required β keeps the walker silent on near-misses. `--strict` mode in CLI surfaces them separately via a second pass.++- [ ] **Step 4: Verify**++Run: `bun test tests/core/brain.inline.test.ts`+Expected: 5 pass.++**Pause for review (no commit).**++---++### Task 11: Fenced-block parser (`osb` info-string)++**Files:**+- Modify: `src/core/brain/inline.ts`+- Test: `tests/core/brain.inline.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("parseBlockMarker handles multi-line block", () => {+ const block = ["kind: feedback", "signal: negative", "topic: t", "principle: long principle text"].join("\n");+ const m = parseBlockMarker(block, 5);+ expect(m?.kind).toBe("feedback");+ expect(m?.principle).toBe("long principle text");+});++test("parseBlockMarker handles YAML pipe (multi-line scalar) for note", () => {+ const block = [+ "kind: feedback", "signal: negative", "topic: t", "principle: p",+ "note: |", " multi-line", " context"+ ].join("\n");+ const m = parseBlockMarker(block, 1);+ expect(m?.note).toBe("multi-line\ncontext");+});++test("parseBlockMarker rejects block with unknown kind", () => {+ const block = ["kind: lol", "signal: negative", "topic: t", "principle: p"].join("\n");+ expect(parseBlockMarker(block, 1)).toBeNull();+});+```++- [ ] **Step 2: Implement**++Reuse `parseFrontmatter`-style simple YAML reader from `src/core/vault.ts` for the block body (string keys, string/array scalar values, pipe `|` multi-line). Validate required fields + enums.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.inline.test.ts`+Expected: 3 new pass.++**Pause for review (no commit).**++---++### Task 12: File-level marker discovery (line-by-line + fence tracking)++**Files:**+- Modify: `src/core/brain/inline.ts` β exported `discoverMarkers(content)`+- Test: `tests/core/brain.inline.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("discoverMarkers finds inline markers", () => {+ const text = "before\n@osb feedback negative topic=t principle=p\nafter";+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(1);+ expect(markers[0].kind).toBe("feedback");+ expect(markers[0].originLine).toBe(2);+});++test("discoverMarkers finds fenced osb blocks", () => {+ const text = "before\n```osb\nkind: feedback\nsignal: positive\ntopic: t\nprinciple: p\n```\nafter";+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(1);+});++test("discoverMarkers ignores markers inside non-osb fences", () => {+ const text = "```python\n@osb feedback negative topic=t principle=p\n```";+ expect(discoverMarkers(text).length).toBe(0);+});++test("discoverMarkers skips already-checked markers", () => {+ const text = "@osbβ [[sig-foo]] feedback negative topic=t principle=p";+ expect(discoverMarkers(text).length).toBe(0);+});+```++- [ ] **Step 2: Implement**++Single-pass line walker tracks fence-open / fence-close state. Inside a fence: if info-string === "osb", collect lines until close, then parseBlockMarker. Outside: try parseInlineMarker per line. Skip lines starting with `@osbβ` or fences whose info-string is `osb-checked` (already-processed sentinels).++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.inline.test.ts`+Expected: 4 new pass.++**Pause for review (no commit). End of Phase 4.**++---++## Phase 5 β Β§9 walker + rewrite + CLI++### Task 13: In-place rewrite of source files++**Files:**+- Create: `src/core/brain/inline-rewrite.ts`+- Test: `tests/core/brain.inline-rewrite.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("rewriteInline replaces inline marker with @osbβ + signal id", async () => {+ const path = writeTmpFile("@osb feedback negative topic=t principle=p\n");+ await rewriteMarkers(path, [{ originLine: 1, originText: "...", signalId: "sig-2026-05-16-t" }], { kind: "inline" });+ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/^@osbβ \[\[sig-2026-05-16-t\]\] feedback negative topic=t/m);+});++test("rewriteBlock flips info-string to osb-checked and inserts HTML comment", async () => {+ const path = writeTmpFile("```osb\nkind: feedback\nsignal: positive\ntopic: t\nprinciple: p\n```\n");+ await rewriteMarkers(path, [{ originLine: 1, originText: "...", signalId: "sig-2026-05-16-t" }], { kind: "block" });+ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/^```osb-checked$/m);+ expect(after).toMatch(/^<!-- @osbβ \[\[sig-2026-05-16-t\]\] -->$/m);+});++test("rewriteMarkers is idempotent (second run is a no-op)", async () => {+ // ... rewrite once, capture sha, rewrite again, expect same sha+});++test("rewriteMarkers acquires file lock", async () => {+ // ... use proper-lockfile to lock the file; second concurrent rewrite waits+});+```++- [ ] **Step 2: Implement**++```ts+export interface RewriteOp {+ readonly originLine: number;+ readonly originText: string;+ readonly signalId: string;+ readonly kind: 'inline' | 'block';+}++export async function rewriteMarkers(path: string, ops: ReadonlyArray<RewriteOp>): Promise<void>+```++Inside:+1. `proper-lockfile.lock(path, { retries: 3, factor: 2 })`.+2. Read full file, split into lines.+3. Sort ops descending by `originLine` (so later edits don't shift earlier indices β but since we rewrite to same line count, doesn't matter; still sort for safety).+4. For inline kind: replace prefix `@osb ` with `@osbβ [[sig-id]] ` on `originLine`.+5. For block kind: find the opening fence line (== `originLine` minus offset to the line we got), flip `osb` β `osb-checked`, insert `<!-- @osbβ [[sig-id]] -->` as first body line.+6. Write to `<path>.tmp-<pid>`, `fsync`, `rename` over original.+7. Release lock.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.inline-rewrite.test.ts`+Expected: 4 pass.++**Pause for review (no commit).**++---++### Task 14: Vault walker + dedup index++**Files:**+- Create: `src/core/brain/inline-scan.ts`+- Test: `tests/core/brain.inline-scan.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("scanInline finds markers in Daily/ but skips Brain/", async () => {+ // ... setup+ const result = await scanInline(vault, { dryRun: true });+ expect(result.scanned).toBeGreaterThan(0);+ expect(result.found).toBe(1);+});++test("scanInline respects _brain.yaml scan_inline.exclude", async () => {+ // ... add exclude: ['Projects/private']+ expect(result.found).toBe(0); // marker only in excluded path+});++test("scanInline dedups against existing inbox via dedup_hash", async () => {+ // ... existing sig with same dedup_hash present+ const result = await scanInline(vault);+ expect(result.created).toBe(0);+ expect(result.deduped).toBe(1);+});++test("scanInline rewrites source file when signal is created", async () => {+ // ... daily note with marker+ const result = await scanInline(vault);+ expect(readFileSync(dailyPath, "utf8")).toMatch(/@osbβ \[\[sig-/);+});++test("scanInline --strict + malformed marker β result.malformed > 0", async () => {+ // ... daily note with `@osb feedback` (missing principle) β flagged in strict only+});++test("scanInline skips files larger than 1 MiB", async () => {+ // ... 2-MB markdown file with a marker β not scanned; warning recorded+});+```++- [ ] **Step 2: Implement**++```ts+export interface ScanInlineOptions {+ readonly dryRun?: boolean;+ readonly strict?: boolean;+ readonly paths?: ReadonlyArray<string>; // narrow to vault-relative subdirs+}++export interface ScanInlineResult {+ readonly scanned: number;+ readonly found: number;+ readonly created: number;+ readonly deduped: number;+ readonly malformed: number;+ readonly errors: ReadonlyArray<{ path: string; message: string }>;+ readonly filesWithMarkers: ReadonlyArray<{ path: string; markers: number }>;+}++export async function scanInline(vault: string, opts: ScanInlineOptions = {}): Promise<ScanInlineResult>+```++Algorithm:+1. Build the ignore set: default + `scan_inline.exclude` from `_brain.yaml` + always `Brain/`.+2. Walk vault for `*.md` files (reuse `walker.ts` pattern from `src/core/search/` if cleanly extractable; otherwise write a small walker inline β both are fine, do not over-share).+3. Build the in-memory dedup index by scanning `Brain/inbox/` + `Brain/inbox/processed/`: parse each signal frontmatter, collect `dedup_hash` β `id` map.+4. For each markdown file:+ - Stat β skip if size > 1 MiB.+ - Read content.+ - `discoverMarkers(content)` β list of `ParsedMarker`.+ - For each marker:+ - Compute `dedup_hash`.+ - Look up in dedup index. If present:+ - If file content already shows `@osbβ` at that line β no-op (counts as deduped).+ - Else β rewrite source file (annotate with existing signal id), counts as deduped.+ - Else:+ - In `dryRun` mode: don't write; just count.+ - Else: `writeSignal(...)` with source_type=inline, dedup_hash, source=[`[[<rel-path>]]`], then `rewriteMarkers(...)`.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.inline-scan.test.ts`+Expected: 6 pass.++**Pause for review (no commit).**++---++### Task 15: `_brain.yaml` schema accepts `scan_inline.exclude`++**Files:**+- Modify: `src/core/brain/policy.ts`+- Test: `tests/core/brain.policy.test.ts`++- [ ] **Step 1: Failing test**++```ts+test("loadBrainConfig accepts scan_inline.exclude array", () => {+ writeYaml(`schema_version: 1\nscan_inline:\n exclude: ["AI Wiki"]\n`);+ const cfg = loadBrainConfig(vault);+ expect(cfg.scan_inline?.exclude).toEqual(["AI Wiki"]);+});++test("loadBrainConfig defaults scan_inline.exclude to []", () => {+ // ... no scan_inline key+ const cfg = loadBrainConfig(vault);+ expect(cfg.scan_inline?.exclude ?? []).toEqual([]);+});++test("loadBrainConfig rejects non-array scan_inline.exclude", () => {+ writeYaml(`schema_version: 1\nscan_inline:\n exclude: "not an array"\n`);+ expect(() => loadBrainConfig(vault)).toThrow();+});+```++- [ ] **Step 2: Implement**++Extend the `BrainConfig` interface in `types.ts` with `scan_inline?: { exclude: ReadonlyArray<string> }`. Add validation in `policy.ts`.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.policy.test.ts`+Expected: 3 new pass.++**Pause for review (no commit).**++---++### Task 16: CLI `o2b brain scan-inline`++**Files:**+- Modify: `src/cli/brain.ts`+- Test: extend `tests/cli/brain.test.ts`++- [ ] **Step 1: Failing CLI tests**++```ts+describe("o2b brain scan-inline", () => {+ test("--dry-run prints plan, writes nothing", async () => { /* ... */ });+ test("default run creates signal + rewrites file", async () => { /* ... */ });+ test("--json structured output", async () => { /* ... */ });+ test("--strict exits 2 on malformed", async () => { /* ... */ });+ test("--path narrows scope", async () => { /* ... */ });+});+```++- [ ] **Step 2: Implement `cmdBrainScanInline`**++Same handler pattern as other CLI verbs. After successful run, append a `scan-inline` log event.++- [ ] **Step 3: Register dispatch + VERB_HELP + BRAIN_HELP**++- [ ] **Step 4: Verify**++Run: `bun test tests/cli/brain.test.ts`+Expected: 5 new pass.++**Pause for review (no commit). End of Phase 5.** Full repo: `bun test && bun run typecheck`.++---++## Phase 6 β Β§16 adapter framework++### Task 17: SessionAdapter types++**Files:**+- Create: `src/core/brain/sessions/types.ts`+- Test: `tests/core/brain.sessions.types.test.ts`++- [ ] **Step 1: Failing test (compilation + shape)**++```ts+test("SessionAdapter interface compiles and types match", () => {+ const stub: SessionAdapter = {+ id: "claude",+ detect: () => false,+ iterate: async function* () { /* empty */ }+ };+ expect(stub.id).toBe("claude");+});++test("SessionImportError carries code", () => {+ const e = new SessionImportError("DETECT_FAIL", "no adapter");+ expect(e.code).toBe("DETECT_FAIL");+ expect(e.name).toBe("SessionImportError");+});+```++- [ ] **Step 2: Implement types as in spec Β§6.2**++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.sessions.types.test.ts`+Expected: 2 pass.++**Pause for review (no commit).**++---++### Task 18: Claude adapter + fixture++**Files:**+- Create: `tests/fixtures/sessions/claude-minimal.jsonl`+- Create: `src/core/brain/sessions/claude.ts`+- Test: `tests/core/brain.sessions.claude.test.ts`++- [ ] **Step 1: Hand-craft anonymised fixture**++5-10 lines representing one session: `type:"queue-operation"` lead, `type:"user"` with message containing `@osb feedback ...` marker, `type:"assistant"` with `tool_use` block calling `brain_feedback`, a few content/text-only turns.++- [ ] **Step 2: Failing tests**++```ts+test("claude adapter detects own format", () => {+ const first = readFirstLine("tests/fixtures/sessions/claude-minimal.jsonl");+ expect(claudeAdapter.detect(first)).toBe(true);+});++test("claude adapter rejects codex first line", () => {+ expect(claudeAdapter.detect(`{"type":"session_meta","originator":"codex_exec"}`)).toBe(false);+});++test("claude adapter iterates user / assistant turns", async () => {+ const turns: SessionTurn[] = [];+ for await (const t of claudeAdapter.iterate("tests/fixtures/sessions/claude-minimal.jsonl")) {+ turns.push(t);+ }+ expect(turns.filter(t => t.role === "user").length).toBeGreaterThan(0);+ expect(turns.filter(t => t.role === "assistant").length).toBeGreaterThan(0);+});++test("claude adapter normalises tool_use blocks", async () => {+ const turns: SessionTurn[] = [];+ for await (const t of claudeAdapter.iterate("tests/fixtures/sessions/claude-minimal.jsonl")) {+ turns.push(t);+ }+ const withTool = turns.find(t => (t.toolCalls?.length ?? 0) > 0);+ expect(withTool?.toolCalls?.[0]?.name).toBe("brain_feedback");+});+```++- [ ] **Step 3: Implement claude adapter**++`detect`: parse first line as JSON; pass if `type === 'queue-operation'` OR has `parentUuid` + `sessionId` + `entrypoint`.++`iterate`: read line-by-line (use Bun's `Bun.file(path).text()` then `.split("\n")` for simplicity at this size; switch to streaming if fixtures grow). For each JSON object:+- Skip `type === "queue-operation"`.+- Map `type` to role; `message.content` to `text`. Array-of-blocks: concatenate text-type blocks, extract `tool_use` blocks into `toolCalls`.++- [ ] **Step 4: Verify**++Run: `bun test tests/core/brain.sessions.claude.test.ts`+Expected: 4 pass.++**Pause for review (no commit).**++---++### Task 19: Codex adapter + fixture++Same structure as Task 18, schema is Codex JSONL (`type:"session_meta"`, `type:"response_item"`, etc.).++Tests cover detect-own, reject-claude-and-hermes, iterate, tool_use normalisation.++**Pause for review (no commit).**++---++### Task 20: Hermes adapter + fixture++Same structure as Task 18 for Hermes JSONL (`role:"session_meta"` with `tools` array, `role:"user"`, `role:"assistant"`).++Agent name inference: read `profile` or similar from `session_meta`, surface as `hermes-<profile>`. Fallback `hermes` when no profile present.++**Pause for review (no commit).**++---++### Task 21: Registry + autodetect++**Files:**+- Create: `src/core/brain/sessions/registry.ts`+- Test: `tests/core/brain.sessions.registry.test.ts`++- [ ] **Step 1: Failing test**++```ts+test("detectAdapter returns the right adapter for each format", () => {+ expect(detectAdapter(`{"type":"queue-operation"...}`)?.id).toBe("claude");+ expect(detectAdapter(`{"type":"session_meta","originator":"codex_exec"...}`)?.id).toBe("codex");+ expect(detectAdapter(`{"role":"session_meta","tools":[...]}`)?.id).toBe("hermes");+});++test("detectAdapter returns null for unknown format", () => {+ expect(detectAdapter(`{"foo":"bar"}`)).toBeNull();+});++test("getAdapter returns adapter by id", () => {+ expect(getAdapter("claude").id).toBe("claude");+});+```++- [ ] **Step 2: Implement**++```ts+export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = [claudeAdapter, codexAdapter, hermesAdapter];+export function detectAdapter(firstLine: string): SessionAdapter | null;+export function getAdapter(id: SessionAdapter['id']): SessionAdapter;+```++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.sessions.registry.test.ts`+Expected: 3 pass.++**Pause for review (no commit). End of Phase 6.**++---++## Phase 7 β Β§16 orchestrator + CLI++### Task 22: Orchestrator (extract β dedup β writeSignal)++**Files:**+- Create: `src/core/brain/sessions/import.ts`+- Test: `tests/core/brain.sessions.import.test.ts`++- [ ] **Step 1: Failing tests**++```ts+test("importSession creates signals from @osb markers in user messages", async () => {+ const result = await importSession(vault, "tests/fixtures/sessions/claude-minimal.jsonl");+ expect(result.signals_created).toBeGreaterThan(0);+});++test("importSession replays brain_feedback tool_use calls", async () => {+ const result = await importSession(vault, "tests/fixtures/sessions/claude-minimal.jsonl");+ expect(result.tool_replays).toBeGreaterThan(0);+});++test("importSession dedups marker + replay of same payload to one signal", async () => {+ // ... fixture has both a marker and a tool_use with identical normalised payload+ const result = await importSession(vault, fixturePath);+ // The marker and the tool_use replay produce the same dedup_hash β only one signal+ expect(result.signals_created).toBe(1);+});++test("importSession is idempotent (second run creates 0 signals)", async () => {+ await importSession(vault, fixturePath);+ const second = await importSession(vault, fixturePath);+ expect(second.signals_created).toBe(0);+});++test("importSession walks a directory", async () => {+ // ... directory with 3 jsonl files+ const result = await importSessionPath(vault, dirPath);+ expect(result.files.length).toBe(3);+});++test("importSession exit 2 when autodetect fails and --format absent", async () => {+ // ... file with junk first line+ await expect(importSession(vault, junkPath)).rejects.toThrow(SessionImportError);+});+```++- [ ] **Step 2: Implement**++```ts+export interface ImportSessionOptions {+ readonly format?: 'auto' | SessionAdapter['id'];+ readonly since?: Date;+ readonly dryRun?: boolean;+}++export interface ImportSessionResult {+ readonly file: string;+ readonly format: SessionAdapter['id'];+ readonly turns_scanned: number;+ readonly signals_created: number;+ readonly signals_deduped: number;+ readonly tool_replays: number;+ readonly malformed: number;+}++export async function importSession(vault: string, path: string, opts: ImportSessionOptions = {}): Promise<ImportSessionResult>+export async function importSessionPath(vault: string, path: string, opts: ImportSessionOptions = {}): Promise<{ files: ReadonlyArray<ImportSessionResult> }>+```++Algorithm:+1. Detect adapter (read first line, run registry) unless `opts.format` given.+2. Build the in-memory dedup index from `Brain/inbox/` + `processed/` (both `dedup_hash` and `session_ref` keys).+3. For each turn from `adapter.iterate(path)`:+ - If `opts.since` set and turn.timestamp < since β skip.+ - Path A: `discoverMarkers(turn.text ?? "")` β for each, build payload, dedup-check, writeSignal with source_type=session, source=[`[[<path>:<turnId>]]`], session_ref=`<path>#<turnId>`, dedup_hash.+ - Path B: for each `toolCalls[].name === 'brain_feedback'`, validate via `validateBrainFeedbackInput`, dedup-check by `dedup_hash`, writeSignal with same params.+4. Return result; emit log event.++- [ ] **Step 3: Verify**++Run: `bun test tests/core/brain.sessions.import.test.ts`+Expected: 6 pass.++**Pause for review (no commit).**++---++### Task 23: CLI `o2b brain import-session`++**Files:**+- Modify: `src/cli/brain.ts`+- Test: extend `tests/cli/brain.test.ts`++- [ ] **Step 1: Failing CLI tests**++```ts+describe("o2b brain import-session", () => {+ test("imports a single file", async () => { /* ... */ });+ test("walks a directory", async () => { /* ... */ });+ test("--format override", async () => { /* ... */ });+ test("--since filters turns", async () => { /* ... */ });+ test("--dry-run writes nothing", async () => { /* ... */ });+ test("--json structured output", async () => { /* ... */ });+ test("exit 2 on autodetect failure", async () => { /* ... */ });+});+```++- [ ] **Step 2: Implement `cmdBrainImportSession`**++Standard handler. Append `import-session` log event per file processed.++- [ ] **Step 3: Register dispatch + VERB_HELP + BRAIN_HELP**++- [ ] **Step 4: Verify**++Run: `bun test tests/cli/brain.test.ts`+Expected: 7 new pass.++**Pause for review (no commit). End of Phase 7.** Full repo: `bun test && bun run typecheck`.++---++## Phase 8 β Cross-feature E2E++### Task 24: End-to-end scenario++**Files:**+- Create: `tests/e2e/brain-capture-and-fields.test.ts`++- [ ] **Step 1: Write the scenario**++```ts+test("capture+migrate end-to-end", async () => {+ const vault = await createTempVault();+ await runCli(["init", "--vault", vault, "--name", "test"]);+ await runCli(["brain", "init", "--vault", vault]);++ // 1. Create Daily note with a marker+ writeFileSync(join(vault, "Daily", "2026-05-16.md"),+ "Some note.\n@osb feedback negative topic=mocking principle=\"don't mock DB\" scope=testing\n");++ // 2. scan-inline+ const scan = await runCli(["brain", "scan-inline", "--vault", vault, "--json"]);+ expect(JSON.parse(scan.stdout).created).toBe(1);+ expect(readFileSync(join(vault, "Daily", "2026-05-16.md"), "utf8")).toMatch(/@osbβ \[\[sig-/);++ // 3. dream β promote+ // ... arrange: pass enough thresholds via force-confirmed or repeated signals+ // (e2e uses --force-confirmed via feedback or hand-writes a pref)++ // 4. migrate-frontmatter --apply+ const migrate = await runCli(["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes", "--json"]);+ expect(migrate.exitCode).toBe(0);++ // 5. Pref file uses _-prefixed shape+ const prefPath = join(vault, "Brain", "preferences", "pref-mocking.md");+ expect(readFileSync(prefPath, "utf8")).toMatch(/^_status: /m);++ // 6. Rollback restores legacy shape (sanity check on the snapshot/rollback path)+ // ... extract run_id, runCli(["brain", "rollback", run_id, "--vault", vault, "--yes"])+});+```++- [ ] **Step 2: Verify**++Run: `bun test tests/e2e/brain-capture-and-fields.test.ts`+Expected: 1 scenario passes.++**Pause for review (no commit). End of Phase 8.**++---++## Phase 9 β Documentation + version bump++### Task 25: README updates++**Files:**+- Modify: `README.md`++- [ ] **Step 1: Extend the CLI Brain block with 3 new lines**++```+o2b brain scan-inline Capture @osb markers from vault files+o2b brain import-session Replay signals from Claude/Codex/Hermes session jsonl+o2b brain migrate-frontmatter Rewrite legacy `status:` keys to `_status:` (opt-in)+```++- [ ] **Step 2: Add a "Capture surfaces" paragraph under Brain section**++Short paragraph: three paths to get a signal into `Brain/inbox/` β live `brain_feedback`, inline `@osb` markers via `scan-inline`, session import via `import-session`.++**Pause for review (no commit).**++---++### Task 26: `docs/how-it-works.md` extension++**Files:**+- Modify: `docs/how-it-works.md`++- [ ] **Step 1: Add "Capture surfaces" subsection**++Reference the spec for full detail. Add a one-line addition to the Mermaid flowchart:++```mermaid+flowchart LR+ Agent[Agent / human]+ Daily[Daily / project notes]+ Session[Session JSONL files]+ Agent -- brain_feedback --> Inbox[(Brain/inbox/)]+ Daily -- @osb scan-inline --> Inbox+ Session -- import-session --> Inbox+ ...+```++**Pause for review (no commit).**++---++### Task 27: `skills/brain-memory/SKILL.md` update++**Files:**+- Modify: `skills/brain-memory/SKILL.md`++- [ ] **Step 1: Add the fallback paragraph**++One paragraph after the existing `brain_feedback` guidance: when the agent is not available at the moment the rule is formed, the user can write `@osb feedback ...` into any vault note; `o2b brain scan-inline` later picks it up. Frame as fallback path, not default.++**Pause for review (no commit).**++---++### Task 28: CHANGELOG + version bump++**Files:**+- Modify: `package.json` (version 0.10.1 β 0.10.2)+- Modify: `CHANGELOG.md` (new `## [0.10.2]` block)+- Modify: `pyproject.toml` (via `bun run sync-version`)++- [ ] **Step 1: Bump package.json version**++Manually edit `version: "0.10.2"` in `package.json`. Run `bun run sync-version` to mirror to `pyproject.toml`.++- [ ] **Step 2: Add CHANGELOG entry**++Append a new block directly under the changelog header, before `## [0.10.1]`:++```markdown+## [0.10.2] - <release-date>++Implements Tier-A items Β§9 (inline @osb markers), Β§16 (session-import),+and Β§24 (`_field` prefix convention) from+`Projects/OpenSecondBrain/Features/_summary`. Two new capture surfaces+complement the live `brain_feedback` path; preference frontmatter+gains a `_`-prefix convention for derived fields.++### Added+- ...+### Changed+- ...+```++Fill in concrete bullets per implementation. No `[Unreleased]` section.++- [ ] **Step 3: Verify**++Run: `bun run sync-version --check && bun test && bun run typecheck`+Expected: all green; versions aligned.++**Pause for review (no commit). End of Phase 9.**++---++## Final verification++- [ ] `bun test` β full suite green.+- [ ] `bun run typecheck` β green.+- [ ] `o2b brain scan-inline --help`, `o2b brain import-session --help`, `o2b brain migrate-frontmatter --help` β render correctly.+- [ ] `o2b brain doctor` β reports `frontmatter-double-shape` warning shape on a hand-crafted collision file.+- [ ] CHANGELOG `## [0.10.2]` entry filled.+- [ ] Spec doc cross-referenced from CHANGELOG and README capture-surfaces paragraph.++PR is ready for user review. No git operations performed by the agent; the user runs `git status`, `git add`, `git commit`, `git push`, and `gh pr create` themselves.++---++## References++- Design doc: `docs/plans/2026-05-16-brain-capture-and-fields-design.md`.+- Source feature briefs: `Projects/OpenSecondBrain/Features/{rowboat,llm-wiki-compiler,tolaria}.md`.+- Prior plan structure: `docs/plans/2026-05-16-brain-search-impl.md`.+- Prior plan-wide convention: `docs/plans/2026-05-15-brain-observing-memory.md`.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex c37bfffe..0dbabd30 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.1",+ "version": "0.10.2","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 1c5d0718..4ebf4d51 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.1",+ "version": "0.10.2","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.yamlindex 0e5872f1..0337c407 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.1"+version: "0.10.2"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex a9e99a34..6233090e 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.1",+ "version": "0.10.2","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 09fc1b63..8971d2dd 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.1"+version: "0.10.2"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 46cd60d9..c2b6c79e 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.1"+version = "0.10.2"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.mdindex 800439b3..d3efe3c6 100644--- a/skills/brain-memory/SKILL.md+++ b/skills/brain-memory/SKILL.md@@ -112,3 +112,37 @@ o2b brain apply-evidence \- Do not edit historical signals, preferences, or log entries by hand β the `dream` pass is the only writer for transitions.- Do not write into `Brain/.snapshots/` or `Brain/retired/` directly β those are managed by `dream` and `o2b brain reject` only.- `o2b brain reject` requires `--reason <text>` from v0.10.1 onward. The reason is persisted on the retired file as `user_rejected_reason`. The next dream pass will mark any future signal on the same `(topic, scope)` as `signal-suppressed` and move it straight to `processed/` β do not re-record the same signal hoping it will re-grow into a preference. If you genuinely disagree with a past reject, raise it with the user; do not route around it via `brain_feedback`.++## Fallback capture surfaces++When no agent is in the loop at the moment the rule is formed, the+user can write an `@osb` marker directly into any vault markdown+file β a Daily note, a project plan, a self-chat scratchpad. The+operator runs `o2b brain scan-inline` later to capture every marker+into `Brain/inbox/`. Two shapes are recognised:++```text+@osb feedback negative topic=mocking principle="don't mock DB in integration tests" scope=testing+```++````markdown+```osb+kind: feedback+signal: negative+topic: mocking+principle: don't mock DB in integration tests+scope: testing+```+````++This is a fallback path, not the default. When you (the agent) hear+a preference live, call `brain_feedback` directly β the inline+marker exists for situations where MCP is unavailable. After scan,+the source line becomes `@osbβ [[sig-...]]` so a second run is+idempotent.++For session JSONLs (Claude / Codex / Hermes exports) the equivalent+operator command is `o2b brain import-session <path>` β it replays+both `@osb` markers in message text and live `brain_feedback`+tool_use calls. Useful for back-filling sessions where the agent+didn't make the call.diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 3a3b3413..50ceb1ee 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -38,6 +38,17 @@ import {BrainPreferenceNotFoundError,} from "../core/brain/apply-evidence.ts";import { dream } from "../core/brain/dream.ts";+import {+ applyMigration,+ MigrationError,+ planMigration,+} from "../core/brain/migrate-frontmatter.ts";+import { scanInline } from "../core/brain/inline-scan.ts";+import {+ importSession,+ importSessionPath,+} from "../core/brain/sessions/import.ts";+import { SessionImportError } from "../core/brain/sessions/types.ts";import { moveToRetired, parsePreference, writePreference } from "../core/brain/preference.ts";import { preferencePath } from "../core/brain/paths.ts";import { isoDate, isoSecond } from "../core/brain/time.ts";@@ -864,6 +875,350 @@ async function cmdBrainBacklinks(argv: string[]): Promise<number> {return 0;}+async function cmdBrainImportSession(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ format: { type: "string" },+ since: { type: "string" },+ "dry-run": { type: "boolean" },+ agent: { type: "string" },+ json: { type: "boolean" },+ });+ if (positional.length < 1) {+ return fail("brain import-session requires a <path> argument");+ }+ const sessionPath = positional[0]!;+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);++ // --format validation: only adapter ids registered in the registry.+ const formatRaw = flags["format"] as string | undefined;+ let format: "claude" | "codex" | "hermes" | undefined;+ if (formatRaw !== undefined && formatRaw !== "auto") {+ if (formatRaw !== "claude" && formatRaw !== "codex" && formatRaw !== "hermes") {+ return fail(+ `--format must be one of auto|claude|codex|hermes; got ${formatRaw}`,+ );+ }+ format = formatRaw;+ }++ // Parse --since. Strict ISO-8601 first β `new Date(raw)` alone is+ // too permissive (year-only strings, locale-specific shapes). Same+ // contract as cmdBrainDigest / cmdBrainQuery / cmdBrainDream.+ let since: Date | undefined;+ if (flags["since"]) {+ const raw = String(flags["since"]);+ if (!ISO_8601_RE.test(raw)) {+ return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);+ }+ const d = new Date(raw);+ if (!Number.isFinite(d.getTime())) {+ return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);+ }+ since = d;+ }++ // Decide single-file vs directory based on stat.+ let stat;+ try {+ stat = statSync(sessionPath);+ } catch (err) {+ return fail(`cannot stat ${sessionPath}: ${(err as Error).message ?? err}`);+ }++ try {+ const result = stat.isDirectory()+ ? await importSessionPath(vault, sessionPath, {+ agent,+ ...(format ? { format } : {}),+ ...(since ? { since } : {}),+ dryRun: Boolean(flags["dry-run"]),+ })+ : {+ files: [+ await importSession(vault, sessionPath, {+ agent,+ ...(format ? { format } : {}),+ ...(since ? { since } : {}),+ dryRun: Boolean(flags["dry-run"]),+ }),+ ],+ warnings: [],+ };++ // Log one event per file processed (skip dry-run).+ if (!flags["dry-run"]) {+ for (const f of result.files) {+ try {+ appendLogEvent(vault, {+ timestamp: isoSecond(new Date()),+ eventType: BRAIN_LOG_EVENT_KIND.importSession,+ body: {+ agent,+ file: `[[${f.file}]]`,+ format: f.format,+ turns_scanned: String(f.turns_scanned),+ signals_created: String(f.signals_created),+ signals_deduped: String(f.signals_deduped),+ tool_replays: String(f.tool_replays),+ malformed: String(f.malformed),+ },+ });+ } catch (err) {+ process.stderr.write(+ `warning: append import-session log failed: ${(err as Error).message}\n`,+ );+ }+ }+ }++ if (flags["json"]) {+ okJson({+ files: result.files.map((f) => ({+ file: f.file,+ format: f.format,+ turns_scanned: f.turns_scanned,+ signals_created: f.signals_created,+ signals_deduped: f.signals_deduped,+ tool_replays: f.tool_replays,+ malformed: f.malformed,+ errors: f.errors,+ })),+ warnings: result.warnings,+ });+ } else {+ for (const f of result.files) {+ ok(`file: ${f.file}`);+ ok(` format: ${f.format}`);+ ok(` turns_scanned: ${f.turns_scanned}`);+ ok(` signals_created: ${f.signals_created}`);+ ok(` signals_deduped: ${f.signals_deduped}`);+ ok(` tool_replays: ${f.tool_replays}`);+ if (f.malformed > 0) ok(` malformed: ${f.malformed}`);+ for (const e of f.errors) {+ info(` error: ${e.path}: ${e.message}`);+ }+ }+ for (const w of result.warnings) {+ info(` warning: ${w.path}: ${w.message}`);+ }+ }+ return 0;+ } catch (exc) {+ if (exc instanceof SessionImportError) {+ process.stderr.write(`error: ${exc.message}\n`);+ // DETECT_FAIL / UNKNOWN_FORMAT β exit 2 (operator picks --format).+ if (exc.code === "DETECT_FAIL" || exc.code === "UNKNOWN_FORMAT") return 2;+ return 1;+ }+ return fail(`import-session failed: ${(exc as Error).message ?? exc}`);+ }+}++async function cmdBrainScanInline(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "dry-run": { type: "boolean" },+ strict: { type: "boolean" },+ path: { type: "string-array" },+ exclude: { type: "string-array" },+ agent: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);++ let result;+ try {+ result = await scanInline(vault, {+ agent,+ dryRun: Boolean(flags["dry-run"]),+ paths: (flags["path"] as string[] | undefined) ?? [],+ exclude: (flags["exclude"] as string[] | undefined) ?? [],+ });+ } catch (exc) {+ return fail(`scan-inline failed: ${(exc as Error).message ?? exc}`);+ }++ // Log event (skip on --dry-run so audit trail only reflects actual writes).+ if (!flags["dry-run"]) {+ try {+ appendLogEvent(vault, {+ timestamp: isoSecond(new Date()),+ eventType: BRAIN_LOG_EVENT_KIND.scanInline,+ body: {+ agent,+ scanned: String(result.scanned),+ found: String(result.found),+ created: String(result.created),+ deduped: String(result.deduped),+ malformed: String(result.malformed),+ errors: String(result.errors.length),+ },+ });+ } catch (err) {+ process.stderr.write(+ `warning: append scan-inline log failed: ${(err as Error).message}\n`,+ );+ }+ }++ if (flags["json"]) {+ okJson({+ scanned: result.scanned,+ found: result.found,+ created: result.created,+ deduped: result.deduped,+ malformed: result.malformed,+ errors: result.errors.map((e) => ({ path: e.path, message: e.message })),+ files_with_markers: result.filesWithMarkers.map((f) => ({+ path: f.path,+ markers: f.markers,+ })),+ });+ } else {+ ok(`scanned: ${result.scanned}`);+ ok(`found: ${result.found}`);+ ok(`created: ${result.created}`);+ ok(`deduped: ${result.deduped}`);+ if (result.malformed > 0) ok(`malformed: ${result.malformed}`);+ for (const e of result.errors) {+ info(` error: ${e.path}: ${e.message}`);+ }+ }+ if (flags["strict"] && result.malformed > 0) return 2;+ return 0;+}++async function cmdBrainMigrateFrontmatter(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ "dry-run": { type: "boolean" },+ apply: { type: "boolean" },+ yes: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const agent = resolveAgentName(config);++ // Mutually exclusive: --dry-run and --apply both set is operator+ // confusion; default is dry-run.+ if (flags["dry-run"] && flags["apply"]) {+ return fail(+ "brain migrate-frontmatter: --dry-run and --apply are mutually exclusive",+ );+ }+ const apply = Boolean(flags["apply"]);++ // Non-interactive guard mirrors `o2b brain rollback`: --json output+ // or non-TTY stdin must pass --yes, otherwise a missed prompt would+ // hang or silently misbehave.+ if (apply && !flags["yes"]) {+ if (flags["json"] || !process.stdin.isTTY) {+ return fail(+ "brain migrate-frontmatter --apply requires --yes in non-interactive mode (--json or non-TTY stdin)",+ );+ }+ }++ if (!apply) {+ // Dry-run path.+ let plan;+ try {+ plan = planMigration(vault);+ } catch (exc) {+ return fail(+ `migrate-frontmatter plan failed: ${(exc as Error).message ?? exc}`,+ );+ }+ if (flags["json"]) {+ okJson({+ files_scanned: plan.files_scanned,+ files_to_migrate: plan.files_to_migrate.length,+ files_already_new: plan.files_already_new.length,+ collisions: plan.collisions.length,+ collision_files: plan.collisions.map((c) => ({+ path: c.path,+ field: c.field,+ })),+ });+ return 0;+ }+ ok(`files_scanned: ${plan.files_scanned}`);+ ok(`files_to_migrate: ${plan.files_to_migrate.length}`);+ ok(`files_already_new: ${plan.files_already_new.length}`);+ ok(`collisions: ${plan.collisions.length}`);+ if (plan.collisions.length > 0) {+ info("Collisions (both legacy and '_'-prefixed shape present):");+ for (const c of plan.collisions) {+ info(` - ${c.path} (field: ${c.field})`);+ }+ }+ if (plan.files_to_migrate.length === 0) {+ ok("nothing to migrate; re-run with --apply --yes when there is.");+ } else {+ ok("re-run with --apply --yes to rewrite these files.");+ }+ return 0;+ }++ // Apply path.+ let result;+ try {+ result = await applyMigration(vault, { snapshot: true, now: new Date() });+ } catch (exc) {+ if (exc instanceof MigrationError) {+ // Surface the collision / parse / io error with the structured+ // message exactly as the core returns it.+ process.stderr.write(`error: ${exc.message}\n`);+ return 1;+ }+ return fail(`migrate-frontmatter failed: ${(exc as Error).message ?? exc}`);+ }++ // Emit a log event so the audit trail records the rewrite.+ try {+ appendLogEvent(vault, {+ timestamp: isoSecond(new Date()),+ eventType: BRAIN_LOG_EVENT_KIND.migrateFrontmatter,+ body: {+ run_id: result.run_id,+ agent,+ snapshot: result.snapshot_path ?? "(none)",+ files_scanned: String(result.plan.files_scanned),+ files_migrated: String(result.files_migrated.length),+ files_already_new: String(result.plan.files_already_new.length),+ collisions: String(result.plan.collisions.length),+ },+ });+ } catch (err) {+ process.stderr.write(+ `warning: append migrate-frontmatter log failed: ${(err as Error).message}\n`,+ );+ }++ if (flags["json"]) {+ okJson({+ run_id: result.run_id,+ snapshot_path: result.snapshot_path,+ files_scanned: result.plan.files_scanned,+ files_migrated: result.files_migrated.length,+ files_already_new: result.plan.files_already_new.length,+ collisions: result.plan.collisions.length,+ });+ return 0;+ }+ ok(`run_id: ${result.run_id}`);+ ok(`snapshot: ${result.snapshot_path ?? "(none)"}`);+ ok(`files_migrated: ${result.files_migrated.length}`);+ ok(`files_already_new: ${result.plan.files_already_new.length}`);+ return 0;+}+async function cmdBrainDoctor(argv: string[]): Promise<number> {const { flags } = parse(argv, {vault: { type: "string" },@@ -926,8 +1281,11 @@ Brain verbs (observing memory):pin Mark a preference exempt from automatic retire (idempotent)unpin Clear the pinned flag (idempotent)rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes)- doctor Validate Brain invariants (--strict promotes warnings to exit 2)- backlinks List inbound references to a Brain artifact id+ doctor Validate Brain invariants (--strict promotes warnings to exit 2)+ backlinks List inbound references to a Brain artifact id+ migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'+ scan-inline Capture @osb markers from vault markdown files (Daily/, project notes, etc.)+ import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)Common flags:--vault <path> Override the configured vault@@ -976,6 +1334,28 @@ const VERB_HELP: Record<string, string> = {backlinks:"usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +"List inbound references to the given Brain artifact id (preference, retired, signal).\n",+ "migrate-frontmatter":+ "usage: o2b brain migrate-frontmatter [--vault <path>] [--apply] [--yes] [--json]\n" ++ "Rewrite legacy Group C frontmatter keys ('status:', 'applied_count:', ...)\n" ++ "to the '_'-prefixed shape across Brain/preferences/ and Brain/retired/.\n" ++ "Default is --dry-run; --apply takes a pre-run snapshot (rollback via run_id).\n" ++ "--apply requires --yes in non-interactive mode (--json or non-TTY stdin).\n",+ "scan-inline":+ "usage: o2b brain scan-inline [--vault <path>] [--path <subdir>...] [--exclude <subdir>...]\n" ++ " [--dry-run] [--strict] [--json] [--agent <name>]\n" ++ "Walk the vault for @osb markers (inline form and fenced 'osb' blocks),\n" ++ "create signals in Brain/inbox/, and annotate the source files with\n" ++ "@osbβ [[sig-...]]. Brain/, .git, node_modules, and similar directories\n" ++ "are always skipped. Idempotent on re-run.\n",+ "import-session":+ "usage: o2b brain import-session <path> [--vault <vault>]\n" ++ " [--format auto|claude|codex|hermes]\n" ++ " [--since <ISO>] [--dry-run] [--json]\n" ++ "Extract signals from a Claude / Codex / Hermes session .jsonl file (or\n" ++ "directory of .jsonl files). Two extraction paths run in parallel:\n" ++ "@osb markers in user/assistant messages, and replay of brain_feedback\n" ++ "tool_use calls. Dedup against the inbox by normalised payload hash.\n" ++ "Autodetect failure exits 2 β pass --format to override.\n",};// ββ Public entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -1035,6 +1415,12 @@ export async function handleBrainSubcommand(return await cmdBrainDoctor(rest);case "backlinks":return await cmdBrainBacklinks(rest);+ case "migrate-frontmatter":+ return await cmdBrainMigrateFrontmatter(rest);+ case "scan-inline":+ return await cmdBrainScanInline(rest);+ case "import-session":+ return await cmdBrainImportSession(rest);default:process.stderr.write(`error: unknown brain verb: ${verb}\n`);process.stdout.write(BRAIN_HELP);diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.tsindex e413e025..18f993bd 100644--- a/src/core/brain/backlinks.ts+++ b/src/core/brain/backlinks.ts@@ -31,6 +31,7 @@ import { join } from "node:path";import { extractWikilinks, parseFrontmatter } from "../vault.ts";import { parseLogDay } from "./log.ts";import { brainDirs } from "./paths.ts";+import { normalizeDerivedKeys } from "./preference.ts";import { normaliseWikilinkTarget } from "./wikilink.ts";// ----- Public types --------------------------------------------------------@@ -126,7 +127,14 @@ function collectPreferences(let meta: Record<string, unknown>;let body: string;try {- [meta, body] = parseFrontmatter(full);+ const [rawMeta, rawBody] = parseFrontmatter(full);+ // Collapse legacy / `_`-prefixed Group C keys so this+ // collector reads the same shape regardless of which the file+ // was written in. Collision aborts the row (caller's job to+ // flag via `brain_doctor`), but the rest of the index keeps+ // building.+ meta = normalizeDerivedKeys(rawMeta);+ body = rawBody;} catch {continue;}diff --git a/src/core/brain/dedup-hash.ts b/src/core/brain/dedup-hash.tsnew file mode 100644index 00000000..dc687ed5--- /dev/null+++ b/src/core/brain/dedup-hash.ts@@ -0,0 +1,98 @@+/**+ * Content hash used by `o2b brain scan-inline` (Β§9) and `o2b brain+ * import-session` (Β§16) to dedup signals.+ *+ * The hash is computed over a normalised view of the signal payload β+ * topic, signal sign, principle, scope. Two payloads that describe+ * the same rule hash identically even when the source text differs+ * in cosmetic ways (Unicode normal form, whitespace, missing-vs-empty+ * scope). A real edit to `principle` (typo fix, rephrasing) changes+ * the hash β by design: the user re-stated the rule, treat it as a+ * fresh signal.+ *+ * `agent` is deliberately excluded. The same rule from two different+ * agents is still one rule; dream is what assigns provenance through+ * `evidenced_by`.+ *+ * Output: lowercase hex sha256 (64 chars).+ */++import { createHash } from "node:crypto";+import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { parseFrontmatter } from "../vault.ts";+import { brainDirs } from "./paths.ts";++export interface DedupHashInput {+ readonly topic: string;+ readonly signal: "positive" | "negative";+ readonly principle: string;+ readonly scope?: string;+}++export interface DedupIndexEntry {+ readonly id: string;+ readonly path: string;+}++/**+ * Read-side complement of {@link computeDedupHash}. Walks+ * `Brain/inbox/` and `Brain/inbox/processed/`, parses every+ * `sig-*.md`, and builds `hash β {id, path}` (first-seen wins).+ *+ * Shared between `o2b brain scan-inline` and `o2b brain+ * import-session` so the two capture paths cross-deduplicate+ * automatically. Both surfaces also mutate the returned map as new+ * signals are written, which keeps the index hot for the rest of+ * the run.+ *+ * `onError` is an optional sink for per-file parse failures. By+ * default they are silently skipped β the doctor command surfaces+ * malformed signals separately, and the dedup builder is best-effort.+ */+export function buildDedupIndex(+ vault: string,+ opts: { onError?: (path: string, message: string) => void } = {},+): Map<string, DedupIndexEntry> {+ const out = new Map<string, DedupIndexEntry>();+ const dirs = brainDirs(vault);+ for (const dir of [dirs.inbox, dirs.processed]) {+ if (!existsSync(dir)) continue;+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;+ const path = join(dir, name);+ try {+ const [meta] = parseFrontmatter(path);+ const hash = meta["dedup_hash"];+ const id = meta["id"];+ if (+ typeof hash === "string" &&+ typeof id === "string" &&+ hash.length > 0 &&+ !out.has(hash)+ ) {+ out.set(hash, { id, path });+ }+ } catch (err) {+ opts.onError?.(+ path,+ `dedup-index parse failed: ${(err as Error).message ?? String(err)}`,+ );+ }+ }+ }+ return out;+}++export function computeDedupHash(input: DedupHashInput): string {+ // Use NUL as the field separator so a topic / principle containing+ // any printable character can't collide with the next field's prefix.+ const parts = [+ input.topic.trim(),+ input.signal,+ input.principle.normalize("NFC").trim().replace(/\s+/g, " "),+ (input.scope ?? "").trim(),+ ];+ return createHash("sha256").update(parts.join("\u0000")).digest("hex");+}diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex babe04c2..c2de0091 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -49,6 +49,7 @@ import {} from "./policy.ts";import { brainConfigPath, brainDirs } from "./paths.ts";import {+ BrainDoubleShapeError,BrainStatusFolderMismatchError,parsePreference,parseRetired,@@ -342,6 +343,17 @@ function checkPreferences(path,message: err.message,});+ } else if (err instanceof BrainDoubleShapeError) {+ // Β§24 dual-shape parser collision is operator-actionable+ // (run `o2b brain migrate-frontmatter --apply` or hand-edit+ // the file). Surface as warning, not error, so the dream+ // loop still proceeds for the rest of the vault.+ issues.push({+ severity: "warning",+ code: "frontmatter-double-shape",+ path,+ message: err.message,+ });} else {// Distinguish field-missing errors (write-time contract) from// unexpected throws so the CLI report stays useful.@@ -416,6 +428,13 @@ function checkRetired(path,message: err.message,});+ } else if (err instanceof BrainDoubleShapeError) {+ issues.push({+ severity: "warning",+ code: "frontmatter-double-shape",+ path,+ message: err.message,+ });} else {const msg = (err as Error).message ?? String(err);const isMissingField = /missing field/.test(msg);diff --git a/src/core/brain/inline-rewrite.ts b/src/core/brain/inline-rewrite.tsnew file mode 100644index 00000000..c712cee7--- /dev/null+++ b/src/core/brain/inline-rewrite.ts@@ -0,0 +1,114 @@+/**+ * Atomic in-place annotation of `@osb` markers with their captured+ * signal id.+ *+ * Two shapes:+ *+ * - Inline: prepend `β [[<sig-id>]] ` between `@osb` and the rest of+ * the line. The leading sentinel `@osbβ` is what {@link+ * discoverMarkers} skips on a re-run, providing idempotency.+ *+ * - Block: flip the opening info-string `osb` β `osb-checked` and+ * insert `<!-- @osbβ [[<sig-id>]] -->` as the new first body line.+ * The fence body is preserved verbatim so the human-readable+ * payload stays in the source file (Obsidian renderers don't+ * interpret HTML comments inside fenced blocks).+ *+ * Concurrency: a `proper-lockfile` lock on the parent directory+ * serialises rewrites β the same shared-lock pattern as+ * {@link appendEvent}. Per-file locks would race against the temp+ * file `atomicWriteFileSync` itself creates next to the target.+ *+ * Atomicity: writes go through {@link atomicWriteFileSync}, which+ * uses the tmp-file-and-rename pattern. A crash mid-rewrite leaves+ * the previous version intact; the new version becomes visible only+ * after the directory entry is updated.+ */++import { mkdirSync, readFileSync } from "node:fs";+import { dirname } from "node:path";++import lockfile from "proper-lockfile";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import type { ParsedMarker } from "./inline.ts";++export interface RewriteOp {+ readonly marker: ParsedMarker;+ /** Resulting `sig-<date>-<slug>` (or any other id) to embed. */+ readonly signalId: string;+}++/**+ * Apply every op to the file at `path`. Ops are applied in document+ * order; line-shift from inserting a block-comment is handled by+ * processing the op list in reverse (so earlier line indices stay+ * valid).+ */+export async function rewriteMarkers(+ path: string,+ ops: ReadonlyArray<RewriteOp>,+): Promise<void> {+ if (ops.length === 0) return;++ // proper-lockfile requires the target to exist; locking the parent+ // dir mirrors what `appendEvent` does for Daily/.+ const parent = dirname(path);+ mkdirSync(parent, { recursive: true });++ const release = await lockfile.lock(parent, {+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },+ stale: 10_000,+ realpath: false,+ });+ try {+ const original = readFileSync(path, "utf8");+ const lines = original.split("\n");++ // Sort ops descending by originLine so that inserts in block-form+ // ops don't shift the line indices of earlier ops.+ const sorted = [...ops].sort(+ (a, b) => b.marker.originLine - a.marker.originLine,+ );++ for (const op of sorted) {+ const idx = op.marker.originLine - 1;+ if (idx < 0 || idx >= lines.length) {+ // Off-the-end: file changed since the marker was discovered.+ // Skip silently rather than corrupt; the caller's next+ // `discoverMarkers` will re-find the live state.+ continue;+ }+ if (op.marker.shape === "inline") {+ const line = lines[idx]!;+ // Replace the leading '@osb' with '@osbβ [[id]]' β preserve any+ // leading whitespace.+ const replaced = line.replace(+ /@osb(?=\s)/,+ `@osbβ [[${op.signalId}]]`,+ );+ lines[idx] = replaced;+ } else {+ // Block form: idx points at the opening ```osb line. Use an+ // exact-match check so an already-rewritten `\`\`\`osb-checked`+ // fence (from a stale op replay) cannot be re-annotated.+ const fenceLine = lines[idx]!;+ if (!/^\s*```osb\s*$/.test(fenceLine)) {+ continue;+ }+ // Preserve any leading whitespace before the fence (CommonMark+ // allows up to 3 spaces of indentation on a fence).+ const indent = fenceLine.match(/^\s*/)?.[0] ?? "";+ lines[idx] = `${indent}\`\`\`osb-checked`;+ // Insert the HTML-comment sentinel as the first body line.+ lines.splice(idx + 1, 0, `<!-- @osbβ [[${op.signalId}]] -->`);+ }+ }++ const updated = lines.join("\n");+ if (updated === original) return; // nothing to do (defensive)+ atomicWriteFileSync(path, updated);+ } finally {+ await release();+ }+}diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.tsnew file mode 100644index 00000000..e642d2a2--- /dev/null+++ b/src/core/brain/inline-scan.ts@@ -0,0 +1,272 @@+/**+ * Vault walker for `o2b brain scan-inline` (Β§9). Finds `@osb` markers+ * in markdown files outside `Brain/`, dedups them against the+ * existing inbox via {@link computeDedupHash}, writes a new signal+ * via {@link writeSignal}, and annotates the source file in place+ * via {@link rewriteMarkers}.+ *+ * Walker invariants:+ *+ * - Recursive walk from `<vault>/` over every `*.md` file.+ * - Hard-skip set: `.git`, `node_modules`, `.open-second-brain`,+ * `.obsidian/cache`, `.trash`, `.stversions`, `Brain/` (the+ * derived layer β markers inside it would self-reference).+ * - User excludes: passed via `opts.exclude` (vault-relative paths,+ * matched against `<vault>/<exclude>` prefix).+ * - User include narrowing: when `opts.paths` is non-empty, only+ * files whose path starts with one of those prefixes are scanned.+ * - Per-file size cap: 1 MiB. Larger files are skipped with an+ * error entry in the report.+ *+ * Dedup: the in-memory `dedup_hash` β existing-signal-id index is+ * built once per run by scanning `Brain/inbox/` and+ * `Brain/inbox/processed/`. A marker whose hash already maps to an+ * existing signal triggers only a rewrite (annotate the source+ * file), not a new signal.+ */++import {+ Dirent,+ readFileSync,+ readdirSync,+ statSync,+} from "node:fs";+import { join, relative, sep } from "node:path";++import {+ buildDedupIndex,+ computeDedupHash,+ type DedupIndexEntry,+} from "./dedup-hash.ts";+import { discoverMarkersDetailed, type ParsedMarker } from "./inline.ts";+import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";+import { writeSignal } from "./signal.ts";+import { isoDate, isoSecond } from "./time.ts";+import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";++const HARD_SKIP_DIRS: ReadonlyArray<string> = Object.freeze([+ ".git",+ "node_modules",+ ".open-second-brain",+ ".obsidian",+ ".trash",+ ".stversions",+ "Brain",+]);++const MAX_FILE_SIZE_BYTES = 1_048_576; // 1 MiB++export interface ScanInlineOptions {+ /** Agent identity stamped on every signal created by this run. */+ readonly agent: string;+ /** When true, do not write signals or rewrite source files. */+ readonly dryRun?: boolean;+ /** Narrow the walker to vault-relative subdirs only. */+ readonly paths?: ReadonlyArray<string>;+ /** Additional vault-relative exclude prefixes. */+ readonly exclude?: ReadonlyArray<string>;+ /** Wall clock for `created_at` / `date` stamping. Tests pin this. */+ readonly now?: Date;+}++export interface ScanInlineErrorEntry {+ readonly path: string;+ readonly message: string;+}++export interface ScanInlineFileSummary {+ readonly path: string;+ readonly markers: number;+}++export interface ScanInlineResult {+ readonly scanned: number;+ readonly found: number;+ readonly created: number;+ readonly deduped: number;+ readonly malformed: number;+ readonly errors: ReadonlyArray<ScanInlineErrorEntry>;+ readonly filesWithMarkers: ReadonlyArray<ScanInlineFileSummary>;+}++export async function scanInline(+ vault: string,+ opts: ScanInlineOptions,+): Promise<ScanInlineResult> {+ const now = opts.now ?? new Date();+ const errors: ScanInlineErrorEntry[] = [];+ const filesWithMarkers: ScanInlineFileSummary[] = [];++ // Build dedup index once per run. Parse failures get surfaced+ // through the per-file errors array so the JSON report exposes+ // them; doctor flags malformed signals separately.+ const dedupIndex: Map<string, DedupIndexEntry> = buildDedupIndex(vault, {+ onError: (path, message) => errors.push({ path, message }),+ });++ let scanned = 0;+ let found = 0;+ let created = 0;+ let deduped = 0;+ let malformed = 0; // reserved β not surfaced separately yet++ const includePrefixes = (opts.paths ?? []).map((p) => normalisePrefix(p));+ const userExcludes = (opts.exclude ?? []).map((p) => normalisePrefix(p));++ for (const filePath of walkVault(vault, includePrefixes, userExcludes)) {+ scanned++;+ let stat;+ try {+ stat = statSync(filePath);+ } catch {+ continue;+ }+ if (stat.size > MAX_FILE_SIZE_BYTES) {+ errors.push({+ path: filePath,+ message: `file too large to scan (${stat.size} bytes; cap ${MAX_FILE_SIZE_BYTES})`,+ });+ continue;+ }+ let content: string;+ try {+ content = readFileSync(filePath, "utf8");+ } catch (err) {+ errors.push({+ path: filePath,+ message: `read failed: ${(err as Error).message ?? String(err)}`,+ });+ continue;+ }+ const discovery = discoverMarkersDetailed(content);+ malformed += discovery.malformed;+ const markers = discovery.markers;+ if (markers.length === 0) continue;+ found += markers.length;+ filesWithMarkers.push({ path: filePath, markers: markers.length });++ const rewriteOps: RewriteOp[] = [];+ for (const marker of markers) {+ const hash = computeDedupHash({+ topic: marker.topic,+ signal: marker.signal,+ principle: marker.principle,+ ...(marker.scope ? { scope: marker.scope } : {}),+ });+ const existing = dedupIndex.get(hash);+ if (existing) {+ deduped++;+ if (!opts.dryRun) {+ rewriteOps.push({ marker, signalId: existing.id });+ }+ continue;+ }+ if (opts.dryRun) continue;+ // Create the signal.+ const vaultRelSource = relative(vault, filePath).split(sep).join("/");+ const sourceList = marker.source+ ? [...marker.source, `[[${vaultRelSource}]]`]+ : [`[[${vaultRelSource}]]`];+ try {+ const res = writeSignal(vault, {+ topic: marker.topic,+ signal: marker.signal,+ agent: marker.agent ?? opts.agent,+ principle: marker.principle,+ created_at: isoSecond(now),+ date: isoDate(now),+ slug: marker.topic,+ ...(marker.scope ? { scope: marker.scope } : {}),+ source: sourceList,+ source_type: BRAIN_SIGNAL_SOURCE_TYPE.inline,+ dedup_hash: hash,+ ...(marker.note ? { raw: marker.note } : {}),+ });+ dedupIndex.set(hash, { id: res.id, path: res.path });+ rewriteOps.push({ marker, signalId: res.id });+ created++;+ } catch (err) {+ errors.push({+ path: filePath,+ message: `writeSignal failed: ${(err as Error).message ?? String(err)}`,+ });+ }+ }++ if (rewriteOps.length > 0 && !opts.dryRun) {+ try {+ await rewriteMarkers(filePath, rewriteOps);+ } catch (err) {+ errors.push({+ path: filePath,+ message: `rewriteMarkers failed: ${(err as Error).message ?? String(err)}`,+ });+ }+ }+ }++ return Object.freeze({+ scanned,+ found,+ created,+ deduped,+ malformed,+ errors: Object.freeze(errors),+ filesWithMarkers: Object.freeze(filesWithMarkers),+ });+}++// ----- Walker ---------------------------------------------------------------++function normalisePrefix(rel: string): string {+ // Strip leading/trailing slashes; normalise separator to OS-native.+ const trimmed = rel.replace(/^\/+|\/+$/g, "");+ return trimmed.split("/").join(sep);+}++function* walkVault(+ vault: string,+ includePrefixes: ReadonlyArray<string>,+ userExcludes: ReadonlyArray<string>,+): Generator<string> {+ const stack: string[] = [vault];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let entries: Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ const full = join(dir, entry.name);+ const rel = relative(vault, full);++ // Hard skip: name-based at any depth.+ if (entry.isDirectory() && HARD_SKIP_DIRS.includes(entry.name)) continue;++ // User excludes: prefix match for both dirs and files.+ if (userExcludes.some((p) => rel === p || rel.startsWith(p + sep))) {+ continue;+ }++ if (entry.isDirectory()) {+ // Include-narrowing only applies to files: directories must+ // descend so subtree files inside an include prefix are reached.+ stack.push(full);+ continue;+ }+ if (!entry.isFile()) continue;+ if (!entry.name.endsWith(".md")) continue;++ if (includePrefixes.length > 0) {+ const matches = includePrefixes.some(+ (p) => rel === p || rel.startsWith(p + sep),+ );+ if (!matches) continue;+ }++ yield full;+ }+ }+}diff --git a/src/core/brain/inline.ts b/src/core/brain/inline.tsnew file mode 100644index 00000000..8a69fe0b--- /dev/null+++ b/src/core/brain/inline.ts@@ -0,0 +1,396 @@+/**+ * `@osb` marker parser β the deterministic, no-LLM grammar shared+ * between Β§9 (vault scan) and Β§16 (session-text scan).+ *+ * Two surface forms, one shape on output. Both are recognised by+ * {@link discoverMarkers}, which walks a file's content line-by-line+ * tracking fenced-code-block state so markers inside non-`osb` fences+ * (Python / TypeScript / docs examples) are not mistakenly captured.+ *+ * - Inline (single line, anchored at start-of-line):+ *+ * @osb feedback negative topic=mocking principle="don't mock DB"+ *+ * - Block (fenced code block whose info-string is `osb`):+ *+ * ```osb+ * kind: feedback+ * signal: negative+ * topic: t+ * principle: long form text+ * ```+ *+ * Both produce a {@link ParsedMarker} with the same field set. The+ * `shape` field disambiguates so the rewriter (Β§9) can re-emit the+ * sentinel correctly (`@osbβ [[sig-id]] ...` for inline, info-string+ * flip to `osb-checked` for block).+ *+ * Strictness: a syntactically wrong marker (unknown `kind`, missing+ * required field, bad enum value) returns `null` from the+ * single-line / block parsers β the walker treats null as "this is+ * not a marker" and moves on. CLI `--strict` mode surfaces those+ * misses as warnings separately; the parser itself is silent.+ */++const KNOWN_KINDS: ReadonlyArray<string> = ["feedback"];+const KNOWN_SIGNALS: ReadonlyArray<string> = ["positive", "negative"];++export type MarkerKind = "feedback";+export type MarkerSignal = "positive" | "negative";+export type MarkerShape = "inline" | "block";++export interface ParsedMarker {+ readonly kind: MarkerKind;+ readonly signal: MarkerSignal;+ readonly topic: string;+ readonly principle: string;+ readonly scope?: string;+ readonly agent?: string;+ readonly note?: string;+ readonly source?: ReadonlyArray<string>;+ /** 1-based line number where the marker starts in the source file. */+ readonly originLine: number;+ /** Verbatim text of the source marker β for rewriter / audit. */+ readonly originText: string;+ readonly shape: MarkerShape;+}++export interface MarkerDiscoveryResult {+ readonly markers: ReadonlyArray<ParsedMarker>;+ /**+ * Count of syntactically-recognisable marker attempts that failed+ * validation. Plain prose such as "@osb is great" is not counted;+ * "@osb feedback ..." with missing / invalid required fields is.+ */+ readonly malformed: number;+}++// ββ Inline parser βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Token-by-token state machine. Accepts:+ * - whitespace at start of line+ * - `@osb` literal+ * - two positional tokens: `kind` (must be in KNOWN_KINDS) and+ * `signal` (must be in KNOWN_SIGNALS)+ * - any number of `key=value` pairs. `value` is either unquoted+ * (no whitespace) or `"..."` with `\"` and `\\` escapes.+ *+ * Returns null on any structural deviation. Required fields+ * (`topic`, `principle`) must be present.+ */+export function parseInlineMarker(line: string, lineNo: number): ParsedMarker | null {+ const originText = line;+ let i = 0;+ const n = line.length;++ const skipWs = (): void => {+ while (i < n && (line[i] === " " || line[i] === "\t")) i++;+ };++ skipWs();+ // Must start with `@osb` and a whitespace boundary so `@osbβ` and+ // `@osbar` don't qualify.+ if (!line.startsWith("@osb", i)) return null;+ i += 4;+ if (i < n && line[i] !== " " && line[i] !== "\t") return null;+ skipWs();++ // Positional `kind`.+ const kindToken = readBareToken();+ if (kindToken === null || !KNOWN_KINDS.includes(kindToken)) return null;+ skipWs();++ // Positional `signal`.+ const signalToken = readBareToken();+ if (signalToken === null || !KNOWN_SIGNALS.includes(signalToken)) return null;+ skipWs();++ const fields: Record<string, string | string[]> = {};+ while (i < n) {+ const key = readKey();+ if (key === null) return null;+ if (i >= n || line[i] !== "=") return null;+ i++; // consume '='+ const value = readValue();+ if (value === null) return null;+ if (fields[key] === undefined) {+ fields[key] = value;+ } else {+ // Second occurrence: promote to array. (Rare in inline form;+ // mainly there so `source=a source=b` works.)+ const prev = fields[key];+ fields[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];+ }+ skipWs();+ }++ const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;+ const principle =+ typeof fields["principle"] === "string" ? fields["principle"] : null;+ if (!topic || !principle) return null;++ const out: ParsedMarker = {+ kind: kindToken as MarkerKind,+ signal: signalToken as MarkerSignal,+ topic,+ principle,+ ...(typeof fields["scope"] === "string" ? { scope: fields["scope"] } : {}),+ ...(typeof fields["agent"] === "string" ? { agent: fields["agent"] } : {}),+ ...(typeof fields["note"] === "string" ? { note: fields["note"] } : {}),+ ...(fields["source"] !== undefined+ ? {+ source: Array.isArray(fields["source"])+ ? [...(fields["source"] as string[])]+ : [fields["source"] as string],+ }+ : {}),+ originLine: lineNo,+ originText,+ shape: "inline",+ };+ return out;++ // ----- nested readers ----------------------------------------------------+ function readBareToken(): string | null {+ const start = i;+ while (i < n && line[i] !== " " && line[i] !== "\t" && line[i] !== "=") i++;+ if (i === start) return null;+ return line.slice(start, i);+ }+ function readKey(): string | null {+ // Identifier head must be alpha or underscore; subsequent chars+ // also allow digits and `-`. Testing the per-char class explicitly+ // (rather than the full-key regex per-char) avoids terminating+ // parsing at the first hyphen or digit after position 0.+ const start = i;+ if (i >= n || !/[A-Za-z_]/.test(line[i]!)) return null;+ i++;+ while (i < n && /[A-Za-z0-9_-]/.test(line[i]!)) i++;+ return line.slice(start, i);+ }+ function readValue(): string | null {+ if (i >= n) return null;+ if (line[i] === '"') {+ // Quoted with backslash escapes.+ i++; // consume opening "+ let out = "";+ while (i < n) {+ const ch = line[i]!;+ if (ch === "\\") {+ if (i + 1 >= n) return null;+ const next = line[i + 1]!;+ if (next === '"' || next === "\\") {+ out += next;+ i += 2;+ continue;+ }+ // Unknown escape: pass through literally.+ out += ch;+ i++;+ continue;+ }+ if (ch === '"') {+ i++; // consume closing "+ return out;+ }+ out += ch;+ i++;+ }+ return null; // unterminated string+ }+ // Unquoted: read until whitespace or EOL. Brackets are part of the+ // token (so `source=[[Daily/2026-05-14]]` round-trips intact).+ const start = i;+ while (i < n && line[i] !== " " && line[i] !== "\t") i++;+ return line.slice(start, i);+ }+}++// ββ Block parser ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Parse the body of a fenced `osb` block (everything between the open+ * and close fences, exclusive). The body follows a very small subset+ * of YAML: `key: value` per line, optional `# comments`, optional+ * blank lines. Multi-line `note: |` is supported for the `note` field+ * specifically β the only field where multiple lines are common.+ *+ * Returns null on the same conditions as inline parsing (unknown kind,+ * missing required field, bad enum).+ */+export function parseBlockMarker(body: string, fenceStartLine: number): ParsedMarker | null {+ const lines = body.split("\n");+ const fields: Record<string, string | string[]> = {};+ let i = 0;+ while (i < lines.length) {+ const raw = lines[i]!;+ const stripped = raw.trim();+ if (stripped === "" || stripped.startsWith("#")) {+ i++;+ continue;+ }+ const eq = stripped.indexOf(":");+ if (eq < 0) {+ i++;+ continue; // tolerate stray lines silently+ }+ const key = stripped.slice(0, eq).trim();+ let value: string = stripped.slice(eq + 1).trim();+ if (value === "|") {+ // Multi-line block scalar. Consume indented subsequent lines.+ const parts: string[] = [];+ i++;+ while (i < lines.length) {+ const nxt = lines[i]!;+ if (nxt.startsWith(" ")) {+ parts.push(nxt.slice(2));+ i++;+ continue;+ }+ if (nxt.trim() === "") {+ parts.push("");+ i++;+ continue;+ }+ break;+ }+ // Strip trailing empty lines that bled from blank rows.+ while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();+ fields[key] = parts.join("\n");+ continue;+ }+ fields[key] = stripQuotes(value);+ i++;+ }++ const kind = typeof fields["kind"] === "string" ? fields["kind"] : null;+ if (kind === null || !KNOWN_KINDS.includes(kind)) return null;+ const signal = typeof fields["signal"] === "string" ? fields["signal"] : null;+ if (signal === null || !KNOWN_SIGNALS.includes(signal)) return null;+ const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;+ const principle =+ typeof fields["principle"] === "string" ? fields["principle"] : null;+ if (!topic || !principle) return null;++ return {+ kind: kind as MarkerKind,+ signal: signal as MarkerSignal,+ topic,+ principle,+ ...(typeof fields["scope"] === "string" ? { scope: fields["scope"] } : {}),+ ...(typeof fields["agent"] === "string" ? { agent: fields["agent"] } : {}),+ ...(typeof fields["note"] === "string" ? { note: fields["note"] } : {}),+ ...(fields["source"] !== undefined+ ? {+ source: Array.isArray(fields["source"])+ ? [...(fields["source"] as string[])]+ : [fields["source"] as string],+ }+ : {}),+ originLine: fenceStartLine,+ originText: body,+ shape: "block",+ };+}++function stripQuotes(s: string): string {+ if (s.length >= 2) {+ const first = s[0];+ const last = s[s.length - 1];+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {+ return s.slice(1, -1);+ }+ }+ return s;+}++// ββ File-level discovery ββββββββββββββββββββββββββββββββββββββββββββββββββββ++const FENCE_RE = /^```([A-Za-z0-9_-]*)\s*$/;++/**+ * Walk the file content line-by-line, returning every marker found in+ * document order. Tracks fenced-code-block state so:+ *+ * - markers inside fences whose info-string is not `osb` are skipped+ * (technical documentation that contains literal `@osb feedback`+ * example markers stays inert);+ * - blocks whose info-string is `osb-checked` are skipped (already+ * processed by a prior `scan-inline` run);+ * - inline lines starting with `@osbβ` (the inline sentinel) are+ * skipped.+ */+export function discoverMarkersDetailed(content: string): MarkerDiscoveryResult {+ const lines = content.split("\n");+ const out: ParsedMarker[] = [];+ let malformed = 0;+ let i = 0;+ while (i < lines.length) {+ const line = lines[i]!;+ const fenceMatch = FENCE_RE.exec(line.trim());+ if (fenceMatch) {+ const infoString = fenceMatch[1] ?? "";+ const fenceStartLineNumber = i + 1; // 1-based+ // Collect body up to the next ``` line.+ const bodyLines: string[] = [];+ let closed = false;+ i++;+ while (i < lines.length) {+ const inner = lines[i]!;+ if (inner.trim().startsWith("```")) {+ i++; // consume closing fence+ closed = true;+ break;+ }+ bodyLines.push(inner);+ i++;+ }+ if (infoString === "osb") {+ if (!closed) {+ // Unterminated `osb` fence β treat as malformed so trailing+ // document content isn't accidentally parsed as a marker.+ malformed++;+ continue;+ }+ const parsed = parseBlockMarker(+ bodyLines.join("\n"),+ fenceStartLineNumber,+ );+ if (parsed) out.push(parsed);+ else malformed++;+ }+ // `osb-checked` and every other info-string: skip silently.+ continue;+ }+ // Inline path. Skip the sentinel form `@osbβ ...` so a re-run+ // doesn't re-process a previously captured marker.+ const trimmed = line.trimStart();+ if (trimmed.startsWith("@osbβ")) {+ i++;+ continue;+ }+ if (trimmed.startsWith("@osb")) {+ const parsed = parseInlineMarker(line, i + 1);+ if (parsed) out.push(parsed);+ else if (looksLikeInlineMarkerAttempt(trimmed)) malformed++;+ }+ i++;+ }+ return Object.freeze({+ markers: Object.freeze(out),+ malformed,+ });+}++export function discoverMarkers(content: string): ReadonlyArray<ParsedMarker> {+ return discoverMarkersDetailed(content).markers;+}++function looksLikeInlineMarkerAttempt(trimmedLine: string): boolean {+ if (!trimmedLine.startsWith("@osb")) return false;+ const rest = trimmedLine.slice(4);+ if (rest.length > 0 && rest[0] !== " " && rest[0] !== "\t") return false;+ const kind = rest.trimStart().split(/[ \t=]/, 1)[0] ?? "";+ return KNOWN_KINDS.includes(kind);+}diff --git a/src/core/brain/migrate-frontmatter.ts b/src/core/brain/migrate-frontmatter.tsnew file mode 100644index 00000000..37ff3598--- /dev/null+++ b/src/core/brain/migrate-frontmatter.ts@@ -0,0 +1,235 @@+/**+ * Opt-in helper that rewrites legacy-shape Group C frontmatter keys+ * (`status:`, `applied_count:`, ...) to the `_`-prefixed form (Β§24)+ * across `Brain/preferences/` and `Brain/retired/`.+ *+ * Two-phase contract:+ *+ * - {@link planMigration} (pure scan) β walks the directories,+ * reports per-file classification: already-new, to-migrate, or+ * collision (both shapes present in the same file). Read-only.+ *+ * - {@link applyMigration} (rewriting) β runs `planMigration` first,+ * aborts if collisions are present, optionally takes a `Brain/`+ * snapshot (so `o2b brain rollback migrate-...` works), then+ * atomically rewrites every to-migrate file.+ *+ * The migration is deliberately non-default: dream-driven natural+ * rewrites also migrate files lazily on every refresh pass, which+ * keeps the upgrade painless. `migrate-frontmatter` exists for users+ * who want immediate, snapshot-fenced migration.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import type { FrontmatterMap } from "../types.ts";+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";+import { brainDirs } from "./paths.ts";+import { DERIVED_FIELDS } from "./preference.ts";+import { createSnapshot } from "./snapshot.ts";+import { isoSecond } from "./time.ts";++/**+ * On `brain-retired` files, `status` is identity (the literal+ * `"retired"`), not derived. Filter the shared Group C list+ * accordingly so migration leaves retired-file `status:` exactly+ * where it is.+ */+function derivedFieldsForKind(kind: unknown): ReadonlyArray<string> {+ if (kind === "brain-retired") {+ return DERIVED_FIELDS.filter((f) => f !== "status");+ }+ return DERIVED_FIELDS;+}++export class MigrationError extends Error {+ readonly code: "COLLISION" | "PARSE" | "IO";+ readonly collisions?: ReadonlyArray<{ path: string; field: string }>;++ constructor(+ code: "COLLISION" | "PARSE" | "IO",+ message: string,+ collisions?: ReadonlyArray<{ path: string; field: string }>,+ ) {+ super(message);+ this.name = "MigrationError";+ this.code = code;+ if (collisions !== undefined) this.collisions = collisions;+ }+}++export interface MigrationPlan {+ readonly files_scanned: number;+ readonly files_to_migrate: ReadonlyArray<string>;+ readonly files_already_new: ReadonlyArray<string>;+ readonly collisions: ReadonlyArray<{ path: string; field: string }>;+}++export interface MigrationResult {+ readonly run_id: string;+ /** `null` when `snapshot: false`, otherwise the .tar.zst path. */+ readonly snapshot_path: string | null;+ readonly plan: MigrationPlan;+ readonly files_migrated: ReadonlyArray<string>;+}++export interface ApplyMigrationOptions {+ /** Take a pre-run `Brain/` snapshot before rewriting. */+ readonly snapshot: boolean;+ /** Wall clock used to build the `run_id`. Tests pin this. */+ readonly now?: Date;+}++// ----- Internal helpers -----------------------------------------------------++/**+ * Classify a single file's frontmatter against the dual-shape policy.+ * Returns `'new'` if every Group C key present is already `_`-prefixed,+ * `'legacy'` if at least one is in legacy form (and no collisions),+ * `'collision'` if any key has BOTH shapes (caller surfaces).+ *+ * Files that fail to parse are classified as `'parse-error'`. Doctor+ * is the surface that reports parse errors to the operator β migration+ * skips them silently.+ */+function classifyFile(+ path: string,+): { kind: "new" | "legacy" | "collision" | "parse-error"; conflictField?: string } {+ let meta: Record<string, unknown>;+ try {+ [meta] = parseFrontmatter(path);+ } catch {+ return { kind: "parse-error" };+ }+ let sawLegacy = false;+ const derived = derivedFieldsForKind(meta["kind"]);+ for (const name of derived) {+ const hasLegacy = name in meta && meta[name] !== undefined;+ const hasModern = `_${name}` in meta && meta[`_${name}`] !== undefined;+ if (hasLegacy && hasModern) {+ return { kind: "collision", conflictField: name };+ }+ if (hasLegacy) sawLegacy = true;+ }+ return { kind: sawLegacy ? "legacy" : "new" };+}++/**+ * In-place rename of legacy Group C keys to their `_`-prefixed form.+ * Returns a new `FrontmatterMap` β the input is left untouched. Order+ * is preserved (Object.entries iteration order survives rename).+ */+function rewriteLegacyKeys(meta: Record<string, unknown>): FrontmatterMap {+ const out: FrontmatterMap = {};+ const derived = new Set(derivedFieldsForKind(meta["kind"]));+ for (const [k, v] of Object.entries(meta)) {+ if (derived.has(k)) {+ out[`_${k}`] = v as never;+ } else {+ out[k] = v as never;+ }+ }+ return out;+}++function listMarkdown(dir: string, prefix: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md")) continue;+ if (!name.startsWith(prefix)) continue;+ out.push(join(dir, name));+ }+ out.sort();+ return out;+}++// ----- Public API -----------------------------------------------------------++export function planMigration(vault: string): MigrationPlan {+ const dirs = brainDirs(vault);+ const files = [+ ...listMarkdown(dirs.preferences, "pref-"),+ ...listMarkdown(dirs.retired, "ret-"),+ ];+ const toMigrate: string[] = [];+ const alreadyNew: string[] = [];+ const collisions: { path: string; field: string }[] = [];+ let scanned = 0;+ for (const path of files) {+ scanned++;+ const c = classifyFile(path);+ if (c.kind === "collision") {+ collisions.push({ path, field: c.conflictField! });+ } else if (c.kind === "legacy") {+ toMigrate.push(path);+ } else if (c.kind === "new") {+ alreadyNew.push(path);+ }+ // 'parse-error': silently skipped; doctor reports separately+ }+ return Object.freeze({+ files_scanned: scanned,+ files_to_migrate: Object.freeze(toMigrate),+ files_already_new: Object.freeze(alreadyNew),+ collisions: Object.freeze(collisions),+ });+}++export async function applyMigration(+ vault: string,+ opts: ApplyMigrationOptions,+): Promise<MigrationResult> {+ const now = opts.now ?? new Date();+ const plan = planMigration(vault);++ if (plan.collisions.length > 0) {+ const first = plan.collisions[0]!;+ throw new MigrationError(+ "COLLISION",+ `migration aborted: ${plan.collisions.length} file(s) carry both legacy ` ++ `and '_'-prefixed shape for the same field. ` ++ `First: ${first.path} (field '${first.field}'). ` ++ `Hand-edit the file(s) to keep one form, then re-run.`,+ plan.collisions,+ );+ }++ // run_id uses isoSecond with `:` replaced β same shape dream uses,+ // accepted by validateRunId.+ const runId = `migrate-${isoSecond(now).replace(/:/g, "-")}`;+ let snapshotPath: string | null = null;+ if (opts.snapshot) {+ const snap = createSnapshot(vault, runId);+ snapshotPath = snap.path;+ }++ const migrated: string[] = [];+ for (const path of plan.files_to_migrate) {+ let raw: Record<string, unknown>;+ let body: string;+ try {+ [raw, body] = parseFrontmatter(path);+ } catch (err) {+ throw new MigrationError(+ "PARSE",+ `failed to parse ${path}: ${(err as Error).message ?? String(err)}`,+ );+ }+ const renamed = rewriteLegacyKeys(raw);+ writeFrontmatterAtomic(path, renamed, body, {+ overwrite: true,+ existsErrorKind: "preference",+ vaultForRelativePath: vault,+ });+ migrated.push(path);+ }++ return Object.freeze({+ run_id: runId,+ snapshot_path: snapshotPath,+ plan,+ files_migrated: Object.freeze(migrated),+ });+}diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex af269520..1cb40cd3 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -62,6 +62,26 @@ import {// ----- Errors ---------------------------------------------------------------+/**+ * Raised when a preference / retired file carries the same Group C+ * field in both legacy (`status:`) and `_`-prefixed (`_status:`)+ * shapes. The doctor downgrades this to a `frontmatter-double-shape`+ * warning; `o2b brain migrate-frontmatter` aborts on it. Doing the+ * dispatch by typed class (rather than regex-matching the message)+ * keeps the contract stable across error-text rewording.+ */+export class BrainDoubleShapeError extends Error {+ readonly field: string;+ constructor(field: string) {+ super(+ `preference field collision: both '_${field}' and legacy '${field}' present; ` ++ `pick one (run \`o2b brain migrate-frontmatter --apply\` or hand-edit)`,+ );+ this.name = "BrainDoubleShapeError";+ this.field = field;+ }+}+/*** Raised when a preference / retired file disagrees with the folder* it lives in. Surfaces both pieces of information so the caller (and@@ -273,6 +293,12 @@ function preferenceFrontmatter(const applied = input.applied_count ?? 0;const violated = input.violated_count ?? 0;+ // Β§24: Group C derived fields gain `_` prefix so the visual+ // boundary between "what dream owns" and "what the user owns"+ // becomes obvious in Obsidian. Identity (`kind`, `id`, `created_at`,+ // `unconfirmed_until`, `topic`, `principle`, `scope`, `tags`,+ // `aliases`, `supersedes`) and user-editable (`pinned`) stay+ // unprefixed. Parser accepts both shapes; writer only emits the new.const metadata: FrontmatterMap = {kind: "brain-preference",id,@@ -281,17 +307,17 @@ function preferenceFrontmatter(// an empty string and the loader coerces back to `null`. We store// the literal text "null" rather than an empty value to keep the// emitted YAML one-token per line and the field always present.- confirmed_at: input.confirmed_at ?? "null",+ _confirmed_at: input.confirmed_at ?? "null",unconfirmed_until: input.unconfirmed_until,tags: [...tags],topic: input.topic.trim(),- status: input.status,+ _status: input.status,principle: input.principle.trim(),- evidenced_by: [...input.evidenced_by],- applied_count: applied,- violated_count: violated,- last_evidence_at: input.last_evidence_at ?? "null",- confidence,+ _evidenced_by: [...input.evidenced_by],+ _applied_count: applied,+ _violated_count: violated,+ _last_evidence_at: input.last_evidence_at ?? "null",+ _confidence: confidence,pinned,};if (input.scope?.trim()) metadata["scope"] = input.scope.trim();@@ -388,14 +414,67 @@ function renderEvidenceSection(// ----- Parsers --------------------------------------------------------------+/**+ * Group C β derived fields that get a `_` prefix in the on-disk+ * shape (dream-rewritten state, see Β§24). Parser accepts both+ * `name` and `_name`; writer always emits `_name`. Listed once so+ * both `parsePreference`, `parseRetired`, and the migration helper+ * share the same list β a follow-up adding a derived field updates+ * exactly this constant.+ */+export const DERIVED_FIELDS: ReadonlyArray<string> = Object.freeze([+ "status",+ "confirmed_at",+ "last_evidence_at",+ "applied_count",+ "violated_count",+ "confidence",+ "evidenced_by",+ "contradicted_by",+]);++/**+ * Resolve dual-shape Group C keys to their canonical (un-prefixed)+ * form so every downstream `meta[name]` call site keeps working. When+ * both `name` and `_name` are present in the same file, throws+ * {@link BrainDoubleShapeError} β the manual-edit corruption case+ * `brain_doctor` surfaces as `frontmatter-double-shape`.+ *+ * Returns a shallow copy of `meta`; original is untouched. Exported+ * because the backlink index and other raw-frontmatter consumers+ * need the same normalisation rules.+ */+export function normalizeDerivedKeys(meta: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = { ...meta };+ for (const name of DERIVED_FIELDS) {+ const prefixed = `_${name}`;+ const hasLegacy = name in out && out[name] !== undefined;+ const hasModern = prefixed in out && out[prefixed] !== undefined;+ if (hasLegacy && hasModern) {+ throw new BrainDoubleShapeError(name);+ }+ if (hasModern) {+ out[name] = out[prefixed];+ delete out[prefixed];+ }+ }+ return out;+}+/*** Parse a preference file. Defaults `pinned` to `false` when the field* is absent (Β§5.3). Throws {@link BrainStatusFolderMismatchError} when* the file lives in `preferences/` but its `status` reads `retired`* (or any other state outside `unconfirmed` / `confirmed`).+ *+ * Accepts both the legacy frontmatter shape (`status:`,+ * `applied_count:`, β¦) and the new `_`-prefixed shape (`_status:`,+ * `_applied_count:`, β¦). Presence of both forms for the same field+ * is a hard error β see {@link normalizeDerivedKeys}.*/export function parsePreference(path: string): BrainPreference {- const [meta, _body] = parseFrontmatter(path);+ const [rawMeta, _body] = parseFrontmatter(path);+ const meta = normalizeDerivedKeys(rawMeta);// `_body` is unused for preferences β the body is purely human prose;// every machine-actionable field lives in the frontmatter.void _body;@@ -466,9 +545,13 @@ export function parsePreference(path: string): BrainPreference {* Parse a retired-preference file. Mirrors {@link parsePreference} but* enforces the `retired/` folder invariant and validates the* `retired_reason` enum.+ *+ * Shares {@link normalizeDerivedKeys} with `parsePreference` so+ * both forms of Group C frontmatter parse identically.*/export function parseRetired(path: string): BrainRetired {- const [meta] = parseFrontmatter(path);+ const [rawMeta] = parseFrontmatter(path);+ const meta = normalizeDerivedKeys(rawMeta);requireField(meta, "kind", path);if (meta["kind"] !== "brain-retired") {@@ -600,8 +683,11 @@ export function moveToRetired(// `confirmed_at`), and stamp the retire metadata on top.const newMeta: FrontmatterMap = {};for (const [k, v] of Object.entries(meta)) {- if (k === "kind" || k === "id" || k === "status") continue;- if (k === "unconfirmed_until" || k === "confirmed_at") continue;+ // Identity keys overwritten below.+ if (k === "kind" || k === "id" || k === "status" || k === "_status") continue;+ // Fields that don't apply to retired (drop both shapes per Β§24).+ if (k === "unconfirmed_until") continue;+ if (k === "confirmed_at" || k === "_confirmed_at") continue;if (k === "tags") {// Replace the `brain/preference` tag with `brain/retired`.const arr = Array.isArray(v) ? [...v] : [];diff --git a/src/core/brain/sessions/claude.ts b/src/core/brain/sessions/claude.tsnew file mode 100644index 00000000..76beace1--- /dev/null+++ b/src/core/brain/sessions/claude.ts@@ -0,0 +1,126 @@+/**+ * Claude Code .jsonl adapter.+ *+ * Each line is a JSON object. Two shapes matter:+ *+ * - `{ "type": "queue-operation", ... }` β runtime queue events;+ * ignored.+ * - `{ "parentUuid": ..., "type": "user"|"assistant",+ * "message": { "role": ..., "content": ... },+ * "uuid": ..., "timestamp": ..., "sessionId": ... }`+ * β actual conversation turns. `content` is either a string (user+ * plain text) or an array of blocks (`text` / `tool_use` / etc.).+ *+ * The adapter normalises both shapes into {@link SessionTurn} with+ * `text` (flat-text view) and optional `toolCalls`. `system` and+ * `tool` roles are not emitted by Claude Code's JSONL β we map any+ * non-user/non-assistant `type` to skip.+ */++import { readFileSync } from "node:fs";++import type {+ SessionAdapter,+ SessionToolCall,+ SessionTurn,+} from "./types.ts";++interface ClaudeBlock {+ readonly type?: string;+ readonly text?: string;+ readonly name?: string;+ readonly id?: string;+ readonly input?: Record<string, unknown>;+}++/** Parse a single Claude JSONL line into a `SessionTurn`, or null to skip. */+function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {+ if (obj === null || typeof obj !== "object") return null;+ const o = obj as Record<string, unknown>;+ // queue-operation: not a turn.+ if (o["type"] === "queue-operation") return null;+ const role = o["type"];+ if (role !== "user" && role !== "assistant") return null;++ const turnId =+ typeof o["uuid"] === "string" && o["uuid"].length > 0+ ? o["uuid"]+ : `synth-${fallbackIndex}`;+ const timestamp =+ typeof o["timestamp"] === "string" && o["timestamp"].length > 0+ ? o["timestamp"]+ : new Date(0).toISOString();++ const message = o["message"];+ if (message === null || typeof message !== "object") {+ // Turn without payload β emit empty (still distinguishes user-vs-assistant).+ return { turnId, timestamp, role };+ }+ const content = (message as Record<string, unknown>)["content"];++ if (typeof content === "string") {+ return { turnId, timestamp, role, text: content };+ }+ if (!Array.isArray(content)) {+ return { turnId, timestamp, role };+ }+ const texts: string[] = [];+ const tools: SessionToolCall[] = [];+ for (const raw of content) {+ if (raw === null || typeof raw !== "object") continue;+ const b = raw as ClaudeBlock;+ if (b.type === "text" && typeof b.text === "string") {+ texts.push(b.text);+ } else if (b.type === "tool_use" && typeof b.name === "string") {+ tools.push({+ name: b.name,+ input: (b.input ?? {}) as Record<string, unknown>,+ ...(typeof b.id === "string" ? { id: b.id } : {}),+ });+ }+ }+ const turn: SessionTurn = {+ turnId,+ timestamp,+ role,+ ...(texts.length > 0 ? { text: texts.join("\n") } : {}),+ ...(tools.length > 0 ? { toolCalls: tools } : {}),+ };+ return turn;+}++export const claudeAdapter: SessionAdapter = {+ id: "claude",+ detect(firstLine: string): boolean {+ let obj: unknown;+ try {+ obj = JSON.parse(firstLine);+ } catch {+ return false;+ }+ if (obj === null || typeof obj !== "object") return false;+ const o = obj as Record<string, unknown>;+ if (o["type"] === "queue-operation") return true;+ const hasClaudeShape =+ "parentUuid" in o && "sessionId" in o && "entrypoint" in o;+ return hasClaudeShape;+ },+ async *iterate(path: string): AsyncIterable<SessionTurn> {+ const text = readFileSync(path, "utf8");+ const lines = text.split("\n");+ let i = 0;+ for (const line of lines) {+ i++;+ const trimmed = line.trim();+ if (trimmed === "") continue;+ let obj: unknown;+ try {+ obj = JSON.parse(trimmed);+ } catch {+ continue; // malformed line β skip silently; doctor / report can flag.+ }+ const turn = turnFromLine(obj, i);+ if (turn) yield turn;+ }+ },+};diff --git a/src/core/brain/sessions/codex.ts b/src/core/brain/sessions/codex.tsnew file mode 100644index 00000000..8986d29d--- /dev/null+++ b/src/core/brain/sessions/codex.ts@@ -0,0 +1,165 @@+/**+ * Codex CLI .jsonl adapter.+ *+ * Each line is `{ timestamp, type, payload }`. We care about:+ *+ * - `type === "response_item"` AND+ * - `payload.type === "message"` β a user / assistant / system turn+ * whose `payload.content` is an array of typed blocks+ * (`input_text` / `output_text`, both carry `.text`).+ * - `payload.type === "function_call"` β a tool-use call. The+ * `arguments` field is a JSON-encoded **string**, not a value;+ * we parse it back to an object so downstream code reads the+ * same shape as Claude tool_use input.+ *+ * Everything else (`event_msg`, `token_count`, `session_meta`,+ * `reasoning`, ...) is skipped.+ *+ * Function-call turns are emitted under `role: "assistant"` because+ * the agent is the one issuing the call. We keep the original turn+ * id (`payload.call_id` falls back to a synthetic seq) so the+ * orchestrator can construct a stable `session_ref` for dedup.+ */++import { readFileSync } from "node:fs";++import type {+ SessionAdapter,+ SessionToolCall,+ SessionTurn,+} from "./types.ts";++interface CodexBlock {+ readonly type?: string;+ readonly text?: string;+}++function buildMessageTurn(+ obj: Record<string, unknown>,+ fallbackIndex: number,+): SessionTurn | null {+ const payload = obj["payload"] as Record<string, unknown> | undefined;+ if (!payload) return null;+ const role = payload["role"];+ if (role !== "user" && role !== "assistant" && role !== "system") return null;+ const turnId = `codex-msg-${fallbackIndex}`;+ const timestamp =+ typeof obj["timestamp"] === "string" ? (obj["timestamp"] as string) : new Date(0).toISOString();++ const content = payload["content"];+ if (!Array.isArray(content)) {+ return { turnId, timestamp, role: role as SessionTurn["role"] };+ }+ const texts: string[] = [];+ for (const raw of content) {+ if (raw === null || typeof raw !== "object") continue;+ const b = raw as CodexBlock;+ if (+ (b.type === "input_text" || b.type === "output_text") &&+ typeof b.text === "string"+ ) {+ texts.push(b.text);+ }+ }+ return {+ turnId,+ timestamp,+ role: role as SessionTurn["role"],+ ...(texts.length > 0 ? { text: texts.join("\n") } : {}),+ };+}++function buildFunctionCallTurn(+ obj: Record<string, unknown>,+ fallbackIndex: number,+): SessionTurn | null {+ const payload = obj["payload"] as Record<string, unknown> | undefined;+ if (!payload) return null;+ const name = payload["name"];+ if (typeof name !== "string" || name.length === 0) return null;+ const callId =+ typeof payload["call_id"] === "string" ? (payload["call_id"] as string) : undefined;+ // `arguments` is a JSON-encoded string in Codex's schema. Decode+ // defensively β a malformed JSON string surfaces as the raw text+ // under `_raw_arguments` so downstream validation can still report+ // a useful error.+ let input: Record<string, unknown> = {};+ const rawArgs = payload["arguments"];+ if (typeof rawArgs === "string" && rawArgs.length > 0) {+ try {+ const parsed = JSON.parse(rawArgs);+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ input = parsed as Record<string, unknown>;+ } else {+ input = { _raw_arguments: rawArgs };+ }+ } catch {+ input = { _raw_arguments: rawArgs };+ }+ } else if (rawArgs !== undefined && rawArgs !== null && typeof rawArgs === "object") {+ input = rawArgs as Record<string, unknown>;+ }+ const tc: SessionToolCall = {+ name,+ input,+ ...(callId !== undefined ? { id: callId } : {}),+ };+ const turnId =+ callId !== undefined ? `codex-fc-${callId}` : `codex-fc-${fallbackIndex}`;+ const timestamp =+ typeof obj["timestamp"] === "string" ? (obj["timestamp"] as string) : new Date(0).toISOString();+ return {+ turnId,+ timestamp,+ role: "assistant",+ toolCalls: [tc],+ };+}++export const codexAdapter: SessionAdapter = {+ id: "codex",+ detect(firstLine: string): boolean {+ let obj: unknown;+ try {+ obj = JSON.parse(firstLine);+ } catch {+ return false;+ }+ if (obj === null || typeof obj !== "object") return false;+ const o = obj as Record<string, unknown>;+ if (o["type"] !== "session_meta") return false;+ const payload = o["payload"];+ if (payload === null || typeof payload !== "object") return false;+ const p = payload as Record<string, unknown>;+ return p["originator"] === "codex_exec" || typeof p["cli_version"] === "string";+ },+ async *iterate(path: string): AsyncIterable<SessionTurn> {+ const text = readFileSync(path, "utf8");+ let i = 0;+ for (const line of text.split("\n")) {+ i++;+ const trimmed = line.trim();+ if (trimmed === "") continue;+ let obj: unknown;+ try {+ obj = JSON.parse(trimmed);+ } catch {+ continue;+ }+ if (obj === null || typeof obj !== "object") continue;+ const o = obj as Record<string, unknown>;+ if (o["type"] !== "response_item") continue;+ const payload = o["payload"] as Record<string, unknown> | undefined;+ if (!payload) continue;+ if (payload["type"] === "message") {+ const turn = buildMessageTurn(o, i);+ if (turn) yield turn;+ } else if (payload["type"] === "function_call") {+ const turn = buildFunctionCallTurn(o, i);+ if (turn) yield turn;+ }+ // Other payload types (reasoning, function_call_output, ...) are+ // skipped β they don't carry signals or tool-use calls we want.+ }+ },+};diff --git a/src/core/brain/sessions/hermes.ts b/src/core/brain/sessions/hermes.tsnew file mode 100644index 00000000..e59f1aae--- /dev/null+++ b/src/core/brain/sessions/hermes.ts@@ -0,0 +1,140 @@+/**+ * Hermes Agent .jsonl adapter.+ *+ * First line is a meta block `{ "role": "session_meta", "tools":+ * [...], ... }`. Conversation turns:+ *+ * - `{ "role": "user" | "assistant" | "tool",+ * "content": string-or-empty,+ * "tool_calls"?: [{ id, call_id, type: "function",+ * function: { name, arguments: "json-string" } }],+ * "timestamp": "ISO" }`+ *+ * The `tool` role is skipped β it carries function-call results, not+ * agent-issued signals. `session_meta` is skipped too. User and+ * assistant rows are emitted; assistant rows with `tool_calls` get+ * the calls flattened into `SessionToolCall[]` with JSON-decoded+ * arguments.+ *+ * Hermes timestamps are stored without a `Z` suffix (e.g.+ * `2026-05-03T19:59:06.411024`). We accept them as-is β they parse+ * the same with `new Date()`.+ */++import { readFileSync } from "node:fs";++import type {+ SessionAdapter,+ SessionToolCall,+ SessionTurn,+} from "./types.ts";++interface HermesToolCall {+ readonly id?: string;+ readonly call_id?: string;+ readonly type?: string;+ readonly function?: {+ readonly name?: string;+ readonly arguments?: string;+ };+}++function decodeArguments(raw: unknown): Record<string, unknown> {+ if (typeof raw === "string" && raw.length > 0) {+ try {+ const parsed = JSON.parse(raw);+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ return { _raw_arguments: raw };+ } catch {+ return { _raw_arguments: raw };+ }+ }+ if (raw !== undefined && raw !== null && typeof raw === "object" && !Array.isArray(raw)) {+ return raw as Record<string, unknown>;+ }+ return {};+}++function buildTurn(+ obj: Record<string, unknown>,+ fallbackIndex: number,+): SessionTurn | null {+ const role = obj["role"];+ if (role !== "user" && role !== "assistant") return null;+ const turnId = `hermes-${fallbackIndex}`;+ const timestamp =+ typeof obj["timestamp"] === "string" && obj["timestamp"].length > 0+ ? (obj["timestamp"] as string)+ : new Date(0).toISOString();++ const text =+ typeof obj["content"] === "string" && obj["content"].length > 0+ ? (obj["content"] as string)+ : undefined;++ const rawCalls = obj["tool_calls"];+ let toolCalls: SessionToolCall[] | undefined;+ if (Array.isArray(rawCalls)) {+ const collected: SessionToolCall[] = [];+ for (const raw of rawCalls) {+ if (raw === null || typeof raw !== "object") continue;+ const tc = raw as HermesToolCall;+ const fn = tc.function;+ if (!fn || typeof fn.name !== "string") continue;+ const id = tc.id ?? tc.call_id;+ collected.push({+ name: fn.name,+ input: decodeArguments(fn.arguments),+ ...(typeof id === "string" ? { id } : {}),+ });+ }+ if (collected.length > 0) toolCalls = collected;+ }++ return {+ turnId,+ timestamp,+ role,+ ...(text !== undefined ? { text } : {}),+ ...(toolCalls !== undefined ? { toolCalls } : {}),+ };+}++export const hermesAdapter: SessionAdapter = {+ id: "hermes",+ detect(firstLine: string): boolean {+ let obj: unknown;+ try {+ obj = JSON.parse(firstLine);+ } catch {+ return false;+ }+ if (obj === null || typeof obj !== "object") return false;+ const o = obj as Record<string, unknown>;+ if (o["role"] !== "session_meta") return false;+ // `tools` is the discriminator that separates Hermes from any+ // other "role: session_meta" shape (Claude / Codex meta lines+ // never set `tools` as a top-level array).+ return Array.isArray(o["tools"]);+ },+ async *iterate(path: string): AsyncIterable<SessionTurn> {+ const text = readFileSync(path, "utf8");+ let i = 0;+ for (const line of text.split("\n")) {+ i++;+ const trimmed = line.trim();+ if (trimmed === "") continue;+ let obj: unknown;+ try {+ obj = JSON.parse(trimmed);+ } catch {+ continue;+ }+ if (obj === null || typeof obj !== "object") continue;+ const turn = buildTurn(obj as Record<string, unknown>, i);+ if (turn) yield turn;+ }+ },+};diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsnew file mode 100644index 00000000..566f0f90--- /dev/null+++ b/src/core/brain/sessions/import.ts@@ -0,0 +1,348 @@+/**+ * Session-import orchestrator (Β§16).+ *+ * Public surface:+ *+ * - {@link importSession} β single-file import. Returns per-file+ * counters and the resolved adapter id.+ * - {@link importSessionPath} β convenience wrapper that walks a+ * directory, calling importSession on every `*.jsonl` inside.+ * Files whose autodetect fails surface as `warnings` rather than+ * killing the run; valid files still get processed.+ *+ * Extraction pipeline per turn:+ *+ * 1. `discoverMarkers(turn.text)` β for each marker, build a+ * payload via {@link computeDedupHash}; create a signal with+ * `source_type: 'session'` unless the hash already exists in+ * `Brain/inbox/` or `processed/`.+ * 2. For each `tool_use` block named `brain_feedback`: validate+ * input via {@link validateBrainFeedbackInput}, compute the+ * same hash; dedup-check; create signal.+ *+ * Idempotency: dedup index is built once at the start of each+ * `importSession` run by reading the inbox and processed dirs. A+ * second run on the same file finds every hash already present.+ */++import {+ existsSync,+ lstatSync,+ readdirSync,+ readFileSync,+ statSync,+} from "node:fs";+import { join, resolve } from "node:path";++import {+ buildDedupIndex,+ computeDedupHash,+ type DedupIndexEntry,+} from "../dedup-hash.ts";+import { discoverMarkersDetailed } from "../inline.ts";+import { writeSignal } from "../signal.ts";+import { isoDate, isoSecond } from "../time.ts";+import { BRAIN_SIGNAL_SOURCE_TYPE } from "../types.ts";+import { detectAdapter, getAdapter } from "./registry.ts";+import {+ SessionImportError,+ type SessionAdapter,+ type SessionAdapterId,+ type SessionTurn,+} from "./types.ts";+import { validateBrainFeedbackInput } from "./validate-feedback.ts";++export interface ImportSessionOptions {+ /** Agent identity stamped on signals when the turn has no own agent. */+ readonly agent: string;+ /** Force a specific adapter, bypassing autodetect. */+ readonly format?: SessionAdapterId;+ /** ISO timestamp β process only turns at or after this. */+ readonly since?: Date;+ /** When true, don't write any signal. Counters still populate. */+ readonly dryRun?: boolean;+ /** Wall clock for stamping `created_at`. Tests pin this. */+ readonly now?: Date;+ /**+ * Optional pre-built dedup index. When importing a directory of+ * session files, the orchestrator builds the index once and+ * threads it through every per-file call so the inbox isn't+ * re-scanned per file. Internal contract; CLI does not pass it.+ */+ readonly dedupIndex?: Map<string, DedupIndexEntry>;+}++export interface ImportSessionResult {+ readonly file: string;+ readonly format: SessionAdapterId;+ readonly turns_scanned: number;+ readonly signals_created: number;+ readonly signals_deduped: number;+ readonly tool_replays: number;+ readonly malformed: number;+ readonly errors: ReadonlyArray<{ path: string; message: string }>;+}++export interface ImportSessionPathResult {+ readonly files: ReadonlyArray<ImportSessionResult>;+ /** Per-file warnings (autodetect failures, IO errors). */+ readonly warnings: ReadonlyArray<{ path: string; message: string }>;+}++function firstLineOfFile(path: string): string {+ // Read the file and slice up to the first newline. Cheaper than a+ // streaming reader for our small fixtures, fine for production+ // session files that are typically 50-500 KB.+ const text = readFileSync(path, "utf8");+ const nl = text.indexOf("\n");+ return nl < 0 ? text : text.slice(0, nl);+}++/** Pick an adapter β by explicit format, or autodetect. */+function chooseAdapter(path: string, format?: SessionAdapterId): SessionAdapter {+ if (format !== undefined) {+ return getAdapter(format);+ }+ const first = firstLineOfFile(path);+ const a = detectAdapter(first);+ if (!a) {+ throw new SessionImportError(+ "DETECT_FAIL",+ `could not autodetect session format for ${path}; pass --format to override`,+ );+ }+ return a;+}++export async function importSession(+ vault: string,+ path: string,+ opts: ImportSessionOptions,+): Promise<ImportSessionResult> {+ if (!existsSync(path)) {+ throw new SessionImportError("IO", `session file does not exist: ${path}`);+ }+ const adapter = chooseAdapter(path, opts.format);+ // Reuse the caller-supplied index when present (directory walk lifts+ // the build out of the per-file loop). Otherwise build our own.+ const dedup = opts.dedupIndex ?? buildDedupIndex(vault);++ const now = opts.now ?? new Date();+ const sinceMs = opts.since ? opts.since.getTime() : undefined;+ const absPath = resolve(path);+ const errors: { path: string; message: string }[] = [];++ let turnsScanned = 0;+ let signalsCreated = 0;+ let signalsDeduped = 0;+ let toolReplays = 0;+ let malformed = 0;++ // Inline helper that wraps the writeSignal call with the consistent+ // shape every session-imported signal shares.+ const emit = (input: {+ topic: string;+ signal: "positive" | "negative";+ principle: string;+ scope?: string;+ agent: string;+ note?: string;+ turnId: string;+ dedupHash: string;+ }): void => {+ if (dedup.has(input.dedupHash)) {+ signalsDeduped++;+ return;+ }+ if (opts.dryRun) {+ // Mirror scan-inline: dry-run reports the dedup hit count and+ // turns scanned, but `signals_created` stays 0 β nothing was+ // actually written.+ return;+ }+ const sessionRef = `${absPath}#${input.turnId}`;+ try {+ const res = writeSignal(vault, {+ topic: input.topic,+ signal: input.signal,+ agent: input.agent,+ principle: input.principle,+ created_at: isoSecond(now),+ date: isoDate(now),+ slug: input.topic,+ ...(input.scope ? { scope: input.scope } : {}),+ source: [`[[${sessionRef}]]`],+ source_type: BRAIN_SIGNAL_SOURCE_TYPE.session,+ dedup_hash: input.dedupHash,+ session_ref: sessionRef,+ ...(input.note ? { raw: input.note } : {}),+ });+ dedup.set(input.dedupHash, { id: res.id, path: res.path });+ signalsCreated++;+ } catch (err) {+ errors.push({+ path: absPath,+ message: `writeSignal failed: ${(err as Error).message ?? String(err)}`,+ });+ }+ };++ for await (const turn of adapter.iterate(path)) {+ turnsScanned++;+ if (sinceMs !== undefined) {+ const t = Date.parse(turn.timestamp);+ if (Number.isFinite(t) && t < sinceMs) continue;+ }++ // Path A β markers in text.+ if (turn.text && (turn.role === "user" || turn.role === "assistant")) {+ const discovery = discoverMarkersDetailed(turn.text);+ malformed += discovery.malformed;+ const markers = discovery.markers;+ for (const m of markers) {+ const hash = computeDedupHash({+ topic: m.topic,+ signal: m.signal,+ principle: m.principle,+ ...(m.scope ? { scope: m.scope } : {}),+ });+ emit({+ topic: m.topic,+ signal: m.signal,+ principle: m.principle,+ ...(m.scope ? { scope: m.scope } : {}),+ agent: m.agent ?? agentLabelForTurn(turn, adapter.id, opts.agent),+ ...(m.note ? { note: m.note } : {}),+ turnId: turn.turnId,+ dedupHash: hash,+ });+ }+ }++ // Path B β brain_feedback tool_use replay.+ for (const call of turn.toolCalls ?? []) {+ if (call.name !== "brain_feedback") continue;+ const validated = validateBrainFeedbackInput(call.input);+ if (!validated.ok) {+ malformed++;+ continue;+ }+ const v = validated.value;+ const hash = computeDedupHash({+ topic: v.topic,+ signal: v.signal,+ principle: v.principle,+ ...(v.scope ? { scope: v.scope } : {}),+ });+ toolReplays++;+ emit({+ topic: v.topic,+ signal: v.signal,+ principle: v.principle,+ ...(v.scope ? { scope: v.scope } : {}),+ agent: v.agent ?? agentLabelForTurn(turn, adapter.id, opts.agent),+ ...(v.raw ? { note: v.raw } : {}),+ turnId: call.id ?? turn.turnId,+ dedupHash: hash,+ });+ }+ }++ return Object.freeze({+ file: absPath,+ format: adapter.id,+ turns_scanned: turnsScanned,+ signals_created: signalsCreated,+ signals_deduped: signalsDeduped,+ tool_replays: toolReplays,+ malformed,+ errors: Object.freeze(errors),+ });+}++/**+ * Compose the `agent` field for a session-imported signal. Order of+ * preference: the marker / tool-input's explicit agent (handled by+ * the caller, not here), then a per-adapter default, finally+ * `opts.agent`.+ */+function agentLabelForTurn(+ turn: SessionTurn,+ adapter: SessionAdapterId,+ fallback: string,+): string {+ void turn; // reserved for future per-turn role-aware fallback+ switch (adapter) {+ case "claude":+ return "claude";+ case "codex":+ return "codex";+ case "hermes":+ return "hermes";+ default:+ return fallback;+ }+}++export async function importSessionPath(+ vault: string,+ path: string,+ opts: ImportSessionOptions,+): Promise<ImportSessionPathResult> {+ const stat = statSync(path);+ if (stat.isFile()) {+ const res = await importSession(vault, path, opts);+ return Object.freeze({ files: Object.freeze([res]), warnings: Object.freeze([]) });+ }+ // Directory walk: build the dedup index ONCE and thread it through+ // every per-file `importSession` call. emit() mutates the shared map+ // as new signals are written, so cross-file dedup happens too.+ const files: ImportSessionResult[] = [];+ const warnings: { path: string; message: string }[] = [];+ const queue: string[] = [];+ const collect = (dir: string): void => {+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ let st;+ try {+ // lstat (not stat) so symlink cycles can't drive the walker+ // into infinite recursion. Symlink-following session-exports+ // are atypical; if real demand surfaces we can switch to a+ // visited-inode set instead.+ st = lstatSync(full);+ } catch {+ continue;+ }+ if (st.isSymbolicLink()) continue;+ if (st.isDirectory()) {+ collect(full);+ continue;+ }+ if (name.endsWith(".jsonl")) queue.push(full);+ }+ };+ collect(path);+ queue.sort();++ const sharedDedup = opts.dedupIndex ?? buildDedupIndex(vault);+ const perFileOpts: ImportSessionOptions = { ...opts, dedupIndex: sharedDedup };++ // Sequential β writes go to the same Brain/inbox/ and share the+ // dedup map; parallelising would race on both.+ for (const file of queue) {+ try {+ const res = await importSession(vault, file, perFileOpts);+ files.push(res);+ } catch (err) {+ if (err instanceof SessionImportError) {+ warnings.push({ path: file, message: err.message });+ continue;+ }+ throw err;+ }+ }+ return Object.freeze({+ files: Object.freeze(files),+ warnings: Object.freeze(warnings),+ });+}diff --git a/src/core/brain/sessions/registry.ts b/src/core/brain/sessions/registry.tsnew file mode 100644index 00000000..6b9cfdf3--- /dev/null+++ b/src/core/brain/sessions/registry.ts@@ -0,0 +1,45 @@+/**+ * Adapter registry. The single place that knows about every concrete+ * session adapter. Adding a fourth runtime is:+ *+ * 1. Drop `sessions/<new>.ts` with a `SessionAdapter` export.+ * 2. Append to {@link SESSION_ADAPTERS}.+ * 3. Add the new id to the `SessionAdapterId` union in `types.ts`.+ *+ * No other code path changes.+ */++import { claudeAdapter } from "./claude.ts";+import { codexAdapter } from "./codex.ts";+import { hermesAdapter } from "./hermes.ts";+import type { SessionAdapter, SessionAdapterId } from "./types.ts";++export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([+ claudeAdapter,+ codexAdapter,+ hermesAdapter,+]);++/**+ * Probe each adapter's `detect()` in registry order, return the first+ * match. Adapters identify on structural fields rather than fuzzy+ * heuristics, so two adapters matching the same line would be a+ * design bug β `tests/core/brain.sessions.registry.test.ts` locks+ * the cross-table.+ */+export function detectAdapter(firstLine: string): SessionAdapter | null {+ for (const a of SESSION_ADAPTERS) {+ if (a.detect(firstLine)) return a;+ }+ return null;+}++export function getAdapter(id: SessionAdapterId): SessionAdapter {+ for (const a of SESSION_ADAPTERS) {+ if (a.id === id) return a;+ }+ // The union type makes this unreachable at compile time, but a+ // runtime guard keeps the failure mode honest if SESSION_ADAPTERS+ // is ever mutated out from under us.+ throw new Error(`no SessionAdapter registered with id '${id}'`);+}diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsnew file mode 100644index 00000000..f3323d09--- /dev/null+++ b/src/core/brain/sessions/types.ts@@ -0,0 +1,74 @@+/**+ * Public contract for `o2b brain import-session` adapters (Β§16).+ *+ * Each runtime (Claude Code, Codex CLI, Hermes) stores chat+ * transcripts in its own JSONL schema. An adapter normalises one+ * such schema into the `SessionTurn` shape so the orchestrator+ * (`sessions/import.ts`) can extract `@osb` markers from text and+ * replay `brain_feedback` tool-use calls without caring which+ * runtime wrote the file.+ *+ * Closed-set ID enum: extending to a new runtime requires adding a+ * new id literal here, a new module under `sessions/`, and a registry+ * entry β no other code path needs to change.+ */++export type SessionAdapterId = "claude" | "codex" | "hermes";++export interface SessionToolCall {+ /** Tool name as emitted by the runtime, e.g. `brain_feedback`. */+ readonly name: string;+ /** Tool input as the runtime serialised it. Validated downstream. */+ readonly input: Record<string, unknown>;+ /** Optional tool-use id for tool_result correlation. */+ readonly id?: string;+}++export interface SessionTurn {+ /** Adapter-specific stable id (UUID / sequence / synthetic). */+ readonly turnId: string;+ /** ISO-8601 UTC. Adapters synthesize from epoch if the field is absent. */+ readonly timestamp: string;+ readonly role: "user" | "assistant" | "system" | "tool" | "meta";+ /** Flat-text view of the turn's content blocks; undefined for meta. */+ readonly text?: string;+ /** Tool-use blocks emitted by the agent in this turn. */+ readonly toolCalls?: ReadonlyArray<SessionToolCall>;+}++export interface SessionAdapter {+ readonly id: SessionAdapterId;+ /**+ * Match the first line of the session file. Adapters identify by+ * structural fields (`"originator":"codex_exec"`, `"role":"session_meta"`,+ * etc.), not fuzzy text. False positives across adapters are+ * unacceptable β they would silently mis-parse content.+ */+ detect(firstLine: string): boolean;+ /** Stream normalised turns from a single .jsonl file. */+ iterate(path: string): AsyncIterable<SessionTurn>;+}++/**+ * Typed error surface for the session import flow. `code` lets the+ * CLI map back to the Β§6.8 exit-code matrix:+ *+ * - `DETECT_FAIL` β autodetect didn't recognise the file. Exit 2,+ * user should pass `--format`.+ * - `IO` β read / open failure. Exit 1.+ * - `PARSE` β JSONL or per-line JSON failure. Exit 1.+ * - `UNKNOWN_FORMAT` β `--format` argument doesn't match any+ * registered adapter. Exit 2.+ */+export class SessionImportError extends Error {+ readonly code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT";++ constructor(+ code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT",+ message: string,+ ) {+ super(message);+ this.name = "SessionImportError";+ this.code = code;+ }+}diff --git a/src/core/brain/sessions/validate-feedback.ts b/src/core/brain/sessions/validate-feedback.tsnew file mode 100644index 00000000..c3217f96--- /dev/null+++ b/src/core/brain/sessions/validate-feedback.ts@@ -0,0 +1,119 @@+/**+ * Pure validator for the `brain_feedback` tool-use payload.+ *+ * Shared between two surfaces:+ * - `src/mcp/brain-tools.ts:toolBrainFeedback` (live MCP invocation).+ * - `src/core/brain/sessions/import.ts` (replay of `brain_feedback`+ * tool_use calls extracted from a session JSONL by Β§16).+ *+ * Single source of truth so the MCP contract and the session-replay+ * contract cannot drift. Returns a tagged-union result instead of+ * throwing β callers branch on `ok` and surface the right error+ * envelope (`MCPError` for MCP, soft warning for import).+ */++import { BRAIN_SIGNAL_SIGN } from "../types.ts";++export interface ValidatedFeedback {+ readonly topic: string;+ readonly signal: "positive" | "negative";+ readonly principle: string;+ readonly scope?: string;+ readonly agent?: string;+ readonly raw?: string;+ readonly source?: ReadonlyArray<string>;+ readonly force_confirmed?: boolean;+}++export type ValidationResult =+ | { ok: true; value: ValidatedFeedback }+ | { ok: false; reason: string };++function nonEmptyString(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ return trimmed === "" ? null : trimmed;+}++function optionalString(value: unknown): string | null | "INVALID" {+ if (value === undefined || value === null) return null;+ if (typeof value !== "string") return "INVALID";+ const trimmed = value.trim();+ return trimmed === "" ? null : trimmed;+}++function optionalStringArray(value: unknown): ReadonlyArray<string> | null | "INVALID" {+ if (value === undefined || value === null) return null;+ if (!Array.isArray(value)) return "INVALID";+ const out: string[] = [];+ for (const item of value) {+ if (typeof item !== "string") return "INVALID";+ out.push(item);+ }+ return out;+}++export function validateBrainFeedbackInput(input: unknown): ValidationResult {+ if (input === null || input === undefined || typeof input !== "object") {+ return { ok: false, reason: "brain_feedback input must be a non-null object" };+ }+ const record = input as Record<string, unknown>;++ const topic = nonEmptyString(record["topic"]);+ if (topic === null) {+ return { ok: false, reason: "brain_feedback missing required field: topic" };+ }++ const signalRaw = nonEmptyString(record["signal"]);+ if (signalRaw === null) {+ return { ok: false, reason: "brain_feedback missing required field: signal" };+ }+ if (+ signalRaw !== BRAIN_SIGNAL_SIGN.positive &&+ signalRaw !== BRAIN_SIGNAL_SIGN.negative+ ) {+ return {+ ok: false,+ reason: `brain_feedback field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(signalRaw)}`,+ };+ }++ const principle = nonEmptyString(record["principle"]);+ if (principle === null) {+ return { ok: false, reason: "brain_feedback missing required field: principle" };+ }++ const scope = optionalString(record["scope"]);+ if (scope === "INVALID") return { ok: false, reason: "scope must be a string" };++ const agent = optionalString(record["agent"]);+ if (agent === "INVALID") return { ok: false, reason: "agent must be a string" };++ const raw = optionalString(record["raw"]);+ if (raw === "INVALID") return { ok: false, reason: "raw must be a string" };++ const source = optionalStringArray(record["source"]);+ if (source === "INVALID") {+ return { ok: false, reason: "source must be an array of strings" };+ }++ let force_confirmed: boolean | undefined;+ if (record["force_confirmed"] !== undefined && record["force_confirmed"] !== null) {+ if (typeof record["force_confirmed"] !== "boolean") {+ return { ok: false, reason: "force_confirmed must be a boolean" };+ }+ force_confirmed = record["force_confirmed"];+ }++ const value: ValidatedFeedback = {+ topic,+ signal: signalRaw as "positive" | "negative",+ principle,+ ...(scope !== null ? { scope } : {}),+ ...(agent !== null ? { agent } : {}),+ ...(raw !== null ? { raw } : {}),+ ...(source !== null ? { source } : {}),+ ...(force_confirmed !== undefined ? { force_confirmed } : {}),+ };+ return { ok: true, value };+}diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 1cd6f370..a971fedf 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -30,8 +30,11 @@ import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";import { allocateSlug, brainDirs, validateIsoDate } from "./paths.ts";import {BRAIN_SIGNAL_SIGN,+ BRAIN_SIGNAL_SOURCE_TYPE,+ isBrainSignalSourceType,type BrainSignal,type BrainSignalSign,+ type BrainSignalSourceType,} from "./types.ts";/** Filename prefix without the trailing dash, e.g. `sig-2026-05-14`. */@@ -63,6 +66,17 @@ export interface WriteSignalInput {readonly raw?: string;/** Optional extra tags merged after the canonical set. */readonly extraTags?: ReadonlyArray<string>;+ /**+ * Capture-extension fields (Β§9 / Β§16). When `source_type` is omitted+ * on the input side, the writer treats the signal as `live` and+ * emits NO `source_type` / `brain/source/*` key β the absence of the+ * field carries the meaning.+ */+ readonly source_type?: BrainSignalSourceType;+ /** Normalised payload hash for idempotency (Β§9 / Β§16). */+ readonly dedup_hash?: string;+ /** Session coordinates `<path>#<turn-id>` (Β§16). */+ readonly session_ref?: string;}export interface WriteSignalOptions {@@ -121,6 +135,14 @@ export function writeSignal(`signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(sanitised.signal)}`,);}+ if (+ sanitised.source_type !== undefined &&+ !isBrainSignalSourceType(sanitised.source_type)+ ) {+ throw new Error(+ `signal field 'source_type' must be 'live', 'inline', or 'session'; got ${JSON.stringify(sanitised.source_type)}`,+ );+ }const dirs = brainDirs(vault);const allocated = allocateSlug({@@ -156,6 +178,22 @@ export function writeSignal(if (sanitised.source && sanitised.source.length > 0) {metadata["source"] = [...sanitised.source];}+ // Capture-extension fields. `source_type: 'live'` is the implicit+ // default β we skip writing it so files written by older OSB+ // versions and freshly-written live signals stay byte-stable. Only+ // `inline` / `session` get surfaced explicitly.+ if (+ sanitised.source_type !== undefined &&+ sanitised.source_type !== BRAIN_SIGNAL_SOURCE_TYPE.live+ ) {+ metadata["source_type"] = sanitised.source_type;+ }+ if (sanitised.dedup_hash && sanitised.dedup_hash.trim()) {+ metadata["dedup_hash"] = sanitised.dedup_hash.trim();+ }+ if (sanitised.session_ref && sanitised.session_ref.trim()) {+ metadata["session_ref"] = sanitised.session_ref.trim();+ }const body = renderSignalBody(sanitised);writeFrontmatterAtomic(allocated.path, metadata, body, {@@ -267,6 +305,47 @@ export function parseSignal(path: string): BrainSignal {const raw = extractRawSection(body);+ // Capture-extension optional fields. Absence stays as `undefined`+ // on the returned object β never coerced to a default, so callers+ // can distinguish files written by older OSB versions from+ // explicit values.+ let source_type: BrainSignalSourceType | undefined;+ if (meta["source_type"] !== undefined) {+ const v = meta["source_type"];+ if (typeof v !== "string") {+ throw new Error(`signal field 'source_type' must be a string (${path})`);+ }+ const trimmed = v.trim();+ if (trimmed) {+ if (!isBrainSignalSourceType(trimmed)) {+ throw new Error(+ `signal field 'source_type' must be 'live', 'inline', or 'session'; got ${JSON.stringify(trimmed)} (${path})`,+ );+ }+ source_type = trimmed;+ }+ }++ let dedup_hash: string | undefined;+ if (meta["dedup_hash"] !== undefined) {+ const v = meta["dedup_hash"];+ if (typeof v !== "string") {+ throw new Error(`signal field 'dedup_hash' must be a string (${path})`);+ }+ const trimmed = v.trim();+ if (trimmed) dedup_hash = trimmed;+ }++ let session_ref: string | undefined;+ if (meta["session_ref"] !== undefined) {+ const v = meta["session_ref"];+ if (typeof v !== "string") {+ throw new Error(`signal field 'session_ref' must be a string (${path})`);+ }+ const trimmed = v.trim();+ if (trimmed) session_ref = trimmed;+ }+const result: BrainSignal = {kind: "brain-signal",id,@@ -279,6 +358,9 @@ export function parseSignal(path: string): BrainSignal {...(scope !== undefined ? { scope } : {}),...(source !== undefined ? { source } : {}),...(raw !== undefined ? { raw } : {}),+ ...(source_type !== undefined ? { source_type } : {}),+ ...(dedup_hash !== undefined ? { dedup_hash } : {}),+ ...(session_ref !== undefined ? { session_ref } : {}),};return Object.freeze(result);}@@ -306,6 +388,15 @@ function composeSignalTags(input: WriteSignalInput): string[] {if (input.scope && input.scope.trim()) {push(`brain/scope/${input.scope.trim()}`);}+ // Non-default source_type gets its own tag so Obsidian users can+ // filter `tag:brain/source/inline` etc. `live` is the implicit+ // default and stays tag-less.+ if (+ input.source_type !== undefined &&+ input.source_type !== BRAIN_SIGNAL_SOURCE_TYPE.live+ ) {+ push(`brain/source/${input.source_type}`);+ }for (const t of input.extraTags ?? []) {if (t.trim()) push(t.trim());}diff --git a/src/core/brain/status.ts b/src/core/brain/status.tsindex 18bc2b83..e4b3cef8 100644--- a/src/core/brain/status.ts+++ b/src/core/brain/status.ts@@ -165,10 +165,24 @@ function readFrontmatterStatus(path: string): string {// quoted values (`status: "confirmed"`) and other legal YAML// shapes round-trip correctly. Files we can't parse bucket under// `unknown` β doctor surfaces them as schema errors elsewhere.+ //+ // Read both legacy `status:` and the `_status:` shape (Β§24).+ // When both shapes are present we treat the file as `unknown` β+ // same collision policy as `normalizeDerivedKeys` (doctor flags+ // it as `frontmatter-double-shape`). Counting it as the modern+ // value here would silently mask the corruption.try {const [meta] = parseFrontmatter(path);- const status = meta["status"];- return typeof status === "string" && status.length > 0 ? status : "unknown";+ // Presence-based collision detection so an empty `_status:`+ // alongside a populated `status:` (or vice versa) is still flagged+ // as a double-shape file β matches `normalizeDerivedKeys`.+ const hasLegacy = "status" in meta && meta["status"] !== undefined;+ const hasModern = "_status" in meta && meta["_status"] !== undefined;+ if (hasLegacy && hasModern) return "unknown";+ const value = hasModern ? meta["_status"] : meta["status"];+ if (typeof value !== "string") return "unknown";+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : "unknown";} catch {return "unknown";}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 5e3d019f..dfecf4aa 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -25,6 +25,34 @@ export const BRAIN_SIGNAL_SIGN = {export type BrainSignalSign =(typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGNAL_SIGN];+/**+ * Where the signal came from (Β§9 / Β§16 capture extensions). Absent+ * on signals written by older OSB versions; the reader treats absence+ * as `live` but never injects a default into the parsed object.+ *+ * - `live` β written by live `brain_feedback` (CLI or MCP).+ * - `inline` β captured by `o2b brain scan-inline` from an+ * `@osb` marker in a vault file.+ * - `session` β replayed from a session JSONL by+ * `o2b brain import-session`.+ */+export const BRAIN_SIGNAL_SOURCE_TYPE = {+ live: "live",+ inline: "inline",+ session: "session",+} as const;+export type BrainSignalSourceType =+ (typeof BRAIN_SIGNAL_SOURCE_TYPE)[keyof typeof BRAIN_SIGNAL_SOURCE_TYPE];++const BRAIN_SIGNAL_SOURCE_TYPE_VALUES: ReadonlyArray<BrainSignalSourceType> =+ Object.values(BRAIN_SIGNAL_SOURCE_TYPE);++/** Type-guard for the enum union β used by writer + parser. */+export function isBrainSignalSourceType(v: unknown): v is BrainSignalSourceType {+ return typeof v === "string"+ && (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v);+}+export const BRAIN_PREFERENCE_STATUS = {unconfirmed: "unconfirmed",confirmed: "confirmed",@@ -115,6 +143,24 @@ export const BRAIN_LOG_EVENT_KIND = {* suppression decision is recoverable.*/signalSuppressed: "signal-suppressed",+ /**+ * `scan-inline` (Β§9) β operator ran `o2b brain scan-inline`.+ * Payload: counters (`scanned`, `created`, `deduped`, `malformed`).+ */+ scanInline: "scan-inline",+ /**+ * `import-session` (Β§16) β operator ran+ * `o2b brain import-session <path>`. One log block per session+ * file; payload references the file and adapter id.+ */+ importSession: "import-session",+ /**+ * `migrate-frontmatter` (Β§24) β operator ran+ * `o2b brain migrate-frontmatter --apply` to rewrite legacy+ * frontmatter to the `_`-prefixed shape. Payload carries the run+ * id, snapshot path, and counters.+ */+ migrateFrontmatter: "migrate-frontmatter",} as const;export type BrainLogEventKind =(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];@@ -157,6 +203,24 @@ export interface BrainSignal {readonly principle: string;/** Optional free-form raw body following the frontmatter. */readonly raw?: string;+ /**+ * Origin of the signal (Β§9 / Β§16). Absent on signals written by+ * older OSB versions β downstream code must treat undefined as+ * semantically equivalent to `live`, never inject a default.+ */+ readonly source_type?: BrainSignalSourceType;+ /**+ * Normalised payload hash anchored to (topic, signal, principle,+ * scope). Idempotency anchor for `scan-inline` (Β§9) and+ * `import-session` (Β§16). Absent on signals written by older OSB+ * versions.+ */+ readonly dedup_hash?: string;+ /**+ * Source coordinates for session-imported signals (Β§16):+ * `<path>#<turn-id>`. Empty / absent for inline / live signals.+ */+ readonly session_ref?: string;}/**@@ -370,6 +434,34 @@ export interface BrainRollbackLogEvent extends BrainLogEventBase {readonly run_id: string;}+/**+ * `scan-inline` entry β operator ran `o2b brain scan-inline`. Payload+ * keys are counters: `scanned`, `found`, `created`, `deduped`,+ * `malformed`, `errors`, plus the agent identity.+ */+export interface BrainScanInlineLogEvent extends BrainLogEventBase {+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.scanInline;+}++/**+ * `import-session` entry β one block per session file imported by+ * `o2b brain import-session`. Payload carries the file wikilink,+ * adapter id, and counters.+ */+export interface BrainImportSessionLogEvent extends BrainLogEventBase {+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.importSession;+}++/**+ * `migrate-frontmatter` entry β operator ran+ * `o2b brain migrate-frontmatter --apply`. Payload carries the run+ * id, snapshot path, and per-bucket counters.+ */+export interface BrainMigrateFrontmatterLogEvent extends BrainLogEventBase {+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.migrateFrontmatter;+ readonly run_id: string;+}+/** Discriminated union of every concrete log event type. */export type BrainLogEvent =| BrainDreamLogEvent@@ -383,7 +475,10 @@ export type BrainLogEvent =| BrainSignalSuppressedLogEvent| BrainSkipCorruptedLogEvent| BrainPinLogEvent- | BrainRollbackLogEvent;+ | BrainRollbackLogEvent+ | BrainScanInlineLogEvent+ | BrainImportSessionLogEvent+ | BrainMigrateFrontmatterLogEvent;// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 8c50e6e2..a99e6fe5 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -57,6 +57,7 @@ import {import { writeSignal } from "../core/brain/signal.ts";import { writePreference } from "../core/brain/preference.ts";import { preferencePath } from "../core/brain/paths.ts";+import { validateBrainFeedbackInput } from "../core/brain/sessions/validate-feedback.ts";import { isoDate, isoSecond } from "../core/brain/time.ts";import { loadBrainConfig } from "../core/brain/policy.ts";import { slugify } from "../core/vault.ts";@@ -191,26 +192,24 @@ async function toolBrainFeedback(ctx: ServerContext,args: Record<string, unknown>,): Promise<Record<string, unknown>> {- const topic = coerceStr(args, "topic", true)!;- const signalRaw = coerceStr(args, "signal", true)!;- if (- signalRaw !== BRAIN_SIGNAL_SIGN.positive &&- signalRaw !== BRAIN_SIGNAL_SIGN.negative- ) {- throw new MCPError(- INVALID_PARAMS,- `argument 'signal' must be 'positive' or 'negative'`,- );+ // Single source of truth for the brain_feedback payload contract β+ // session-replay (sessions/import.ts) and the MCP live path now go+ // through the same validator so rule shape cannot drift between the+ // two surfaces.+ const validated = validateBrainFeedbackInput(args);+ if (!validated.ok) {+ throw new MCPError(INVALID_PARAMS, validated.reason);}- const principle = coerceStr(args, "principle", true)!;- const scope = coerceStr(args, "scope", false);- const source = coerceStrList(args, "source");- const agentArg = coerceStr(args, "agent", false);- const raw = coerceStr(args, "raw", false);- const forceConfirmed = coerceBool(args, "force_confirmed");+ const { topic, signal: signalRaw, principle, scope, raw, source, force_confirmed } =+ validated.value;+ const forceConfirmed = force_confirmed ?? false;+ // Agent-fallback stays MCP-side: validator just hands back the user-+ // supplied value (or undefined); the live path resolves via config+ // when absent.const agent =- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ normalizeAgentArgument(validated.value.agent ?? null) ??+ resolveAgentName(ctx.configPath ?? undefined);const now = new Date();const date = isoDate(now);const createdAt = isoSecond(now);@@ -221,15 +220,15 @@ async function toolBrainFeedback(// across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY// creates a confirmed pref below.const sigResult = writeSignal(ctx.vault, {- topic: topic.trim(),+ topic,signal: signalRaw as BrainSignalSign,agent,- principle: principle.trim(),+ principle,created_at: createdAt,date,slug,...(scope ? { scope } : {}),- ...(source && source.length > 0 ? { source } : {}),+ ...(source && source.length > 0 ? { source: [...source] } : {}),...(raw ? { raw } : {}),});diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.tsindex cef67d95..4cc0c049 100644--- a/tests/cli/brain.test.ts+++ b/tests/cli/brain.test.ts@@ -909,6 +909,158 @@ describe("brain doctor", () => {});});+// ββ Β§9 scan-inline CLI ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("brain scan-inline", () => {+ test("finds inline marker, creates signal, rewrites source file", async () => {+ await bootstrap();+ const notePath = join(vault, "Daily", "2026-05-16.md");+ mkdirSync(join(vault, "Daily"), { recursive: true });+ writeFileSync(+ notePath,+ "@osb feedback negative topic=cli-test principle=p\n",+ "utf8",+ );++ const r = await runCli(["brain", "scan-inline", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toMatch(/created: 1/);++ const after = readFileSync(notePath, "utf8");+ expect(after).toMatch(/@osbβ \[\[sig-/);++ const inbox = join(vault, "Brain", "inbox");+ const sigs = readdirSync(inbox).filter((n) => n.startsWith("sig-"));+ expect(sigs.length).toBe(1);+ });++ test("--dry-run does not write signals or rewrite files", async () => {+ await bootstrap();+ const notePath = join(vault, "Daily", "2026-05-16.md");+ mkdirSync(join(vault, "Daily"), { recursive: true });+ writeFileSync(+ notePath,+ "@osb feedback negative topic=dry principle=p\n",+ "utf8",+ );+ const before = readFileSync(notePath, "utf8");++ const r = await runCli(+ ["brain", "scan-inline", "--vault", vault, "--dry-run"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(readFileSync(notePath, "utf8")).toBe(before);+ const inbox = join(vault, "Brain", "inbox");+ expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(0);+ });++ test("--json emits machine-readable summary", async () => {+ await bootstrap();+ mkdirSync(join(vault, "Daily"), { recursive: true });+ writeFileSync(+ join(vault, "Daily", "x.md"),+ "@osb feedback negative topic=jt principle=p\n",+ "utf8",+ );+ const r = await runCli(+ ["brain", "scan-inline", "--vault", vault, "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.ok).toBe(true);+ expect(parsed.created).toBe(1);+ expect(parsed.found).toBe(1);+ });++ test("--strict exits 2 when malformed marker attempts are present", async () => {+ await bootstrap();+ mkdirSync(join(vault, "Daily"), { recursive: true });+ writeFileSync(+ join(vault, "Daily", "bad.md"),+ "@osb feedback negative topic=missing-principle\n",+ "utf8",+ );+ const r = await runCli(+ ["brain", "scan-inline", "--vault", vault, "--strict"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stdout).toMatch(/malformed: 1/);+ });+});++// ββ Β§16 import-session CLI ββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("brain import-session", () => {+ test("imports a single .jsonl file and creates signals", async () => {+ await bootstrap();+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/claude-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toMatch(/signals_created: [1-9]/);++ const inbox = join(vault, "Brain", "inbox");+ const sigs = readdirSync(inbox).filter((n) => n.startsWith("sig-"));+ expect(sigs.length).toBeGreaterThan(0);+ });++ test("--dry-run does not create signals", async () => {+ await bootstrap();+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/claude-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault, "--dry-run"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const inbox = join(vault, "Brain", "inbox");+ expect(+ readdirSync(inbox).filter((n) => n.startsWith("sig-")).length,+ ).toBe(0);+ });++ test("--json structured output", async () => {+ await bootstrap();+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/codex-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault, "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.ok).toBe(true);+ expect(parsed.files.length).toBe(1);+ expect(parsed.files[0].format).toBe("codex");+ });++ test("exit 2 on unknown format without --format flag", async () => {+ await bootstrap();+ const junk = join(tmp, "junk.jsonl");+ writeFileSync(junk, '{"foo":"bar"}\n', "utf8");+ const r = await runCli(+ ["brain", "import-session", junk, "--vault", vault],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr.toLowerCase()).toMatch(/autodetect|format/);+ });+});+describe("brain vault resolution", () => {test("no vault flag and no machine config exits 1 with hint", async () => {const cfg = join(tmp, "non-existent-config.yaml");@@ -919,3 +1071,127 @@ describe("brain vault resolution", () => {expect(r.stderr.toLowerCase()).toContain("vault");});});++// ββ Β§24 migrate-frontmatter CLI βββββββββββββββββββββββββββββββββββββββββββββ++describe("brain migrate-frontmatter", () => {+ /** Write a legacy-shape pref file under the bootstrapped vault. */+ function writeLegacyPref(slug: string): string {+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "confirmed_at: 2026-05-15T10:00:00Z",+ "evidenced_by: []",+ "applied_count: 1",+ "violated_count: 0",+ "last_evidence_at: null",+ "confidence: low",+ "---",+ "",+ ].join("\n"),+ "utf8",+ );+ return path;+ }++ test("--dry-run (default) prints plan and modifies no files", async () => {+ await bootstrap();+ const prefPath = writeLegacyPref("dry-rule");+ const before = readFileSync(prefPath, "utf8");++ const r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toMatch(/files_to_migrate: 1/);+ expect(readFileSync(prefPath, "utf8")).toBe(before);+ });++ test("--apply --yes rewrites files and takes a snapshot", async () => {+ await bootstrap();+ const prefPath = writeLegacyPref("apply-rule");++ const r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);++ const raw = readFileSync(prefPath, "utf8");+ expect(raw).toMatch(/^_status: confirmed$/m);+ expect(raw).not.toMatch(/^status: /m);++ const snapDir = join(vault, "Brain", ".snapshots");+ const snaps = readdirSync(snapDir).filter((n) => n.startsWith("migrate-"));+ expect(snaps.length).toBeGreaterThan(0);+ });++ test("--apply without --yes in non-interactive mode exits 1", async () => {+ await bootstrap();+ writeLegacyPref("no-yes");+ const r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault, "--apply"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(1);+ expect(r.stderr.toLowerCase()).toMatch(/--yes/);+ });++ test("--json emits machine-readable summary", async () => {+ await bootstrap();+ writeLegacyPref("json-rule");+ const r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault, "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.ok).toBe(true);+ expect(parsed.files_scanned).toBe(1);+ expect(parsed.files_to_migrate).toBe(1);+ });++ test("--apply on collision file aborts with exit 1", async () => {+ await bootstrap();+ // Write a file with both shapes+ const path = join(vault, "Brain", "preferences", "pref-collision.md");+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ "id: pref-collision",+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ "tags: [brain, brain/preference, brain/topic/collision]",+ "topic: collision",+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "_status: confirmed",+ "evidenced_by: []",+ "---",+ "",+ ].join("\n"),+ "utf8",+ );+ const r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(1);+ expect(r.stderr).toMatch(/collision/i);+ });+});diff --git a/tests/core/brain.dedup-hash.test.ts b/tests/core/brain.dedup-hash.test.tsnew file mode 100644index 00000000..4ce9d0a1--- /dev/null+++ b/tests/core/brain.dedup-hash.test.ts@@ -0,0 +1,69 @@+/**+ * Tests for `computeDedupHash` β the normalised payload hash shared+ * between Β§9 inline `scan-inline` and Β§16 `import-session` for+ * idempotency. A marker in a Daily note and the same payload replayed+ * from a session tool_use must hash identically.+ */++import { describe, expect, test } from "bun:test";++import { computeDedupHash } from "../../src/core/brain/dedup-hash.ts";++describe("computeDedupHash", () => {+ test("returns a 64-char hex sha256 digest", () => {+ const h = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ expect(h).toMatch(/^[0-9a-f]{64}$/);+ });++ test("is stable across NFC variants of the same character", () => {+ // "naΓ―ve" β first form is NFC (single Γ―), second is NFD (i + combining Β¨).+ const nfc = "naΓ―ve";+ const nfd = "naiΜve";+ expect(nfc).not.toBe(nfd); // sanity: they really are different code units+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: nfc });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: nfd });+ expect(a).toBe(b);+ });++ test("collapses runs of internal whitespace in principle", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "a b c" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "a b c" });+ expect(a).toBe(b);+ });++ test("trims leading/trailing whitespace in principle", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: " p " });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ expect(a).toBe(b);+ });++ test("treats undefined and empty-string scope identically", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "p", scope: "" });+ expect(a).toBe(b);+ });++ test("differs when topic differs", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ const b = computeDedupHash({ topic: "y", signal: "negative", principle: "p" });+ expect(a).not.toBe(b);+ });++ test("differs when signal flips sign", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p" });+ const b = computeDedupHash({ topic: "x", signal: "positive", principle: "p" });+ expect(a).not.toBe(b);+ });++ test("differs when principle differs after normalisation", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p1" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "p2" });+ expect(a).not.toBe(b);+ });++ test("differs when scope differs", () => {+ const a = computeDedupHash({ topic: "x", signal: "negative", principle: "p", scope: "ru" });+ const b = computeDedupHash({ topic: "x", signal: "negative", principle: "p", scope: "en" });+ expect(a).not.toBe(b);+ });+});diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.tsindex 01f0dca4..b948112f 100644--- a/tests/core/brain.doctor.test.ts+++ b/tests/core/brain.doctor.test.ts@@ -731,3 +731,76 @@ describe("broken backlinks", () => {expect(res.warnings.filter((w) => w.code === "broken-backlinks")).toHaveLength(0);});});++// ββ Β§24 dual-shape lint βββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("frontmatter-double-shape lint (Β§24)", () => {+ test("flags a preference with both 'status:' and '_status:'", () => {+ const path = preferencePath(tmp, "double-shape");+ const content = [+ "---",+ "kind: brain-preference",+ "id: pref-double-shape",+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ "tags: [brain, brain/preference, brain/topic/double-shape]",+ "topic: double-shape",+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "_status: confirmed",+ "evidenced_by: []",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");++ const res = runDoctor(tmp);+ const found = res.warnings.find((w) => w.code === "frontmatter-double-shape");+ expect(found).toBeDefined();+ expect(found!.path).toBe(path);+ expect(found!.message).toMatch(/_status.*legacy 'status'/);+ });++ test("flags a retired with both 'applied_count:' and '_applied_count:'", () => {+ const path = retiredPath(tmp, "double-shape-ret");+ const content = [+ "---",+ "kind: brain-retired",+ "id: ret-double-shape-ret",+ "created_at: 2026-05-14T10:42:00Z",+ "retired_at: 2026-08-12T05:00:00Z",+ "retired_reason: stale-no-evidence",+ "retired_by: '[[Brain/log/2026-08-12]]'",+ "tags: [brain, brain/retired, brain/topic/double-shape-ret]",+ "topic: double-shape-ret",+ "principle: Some rule",+ "status: retired",+ "pinned: false",+ "applied_count: 3",+ "_applied_count: 3",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");++ const res = runDoctor(tmp);+ const found = res.warnings.find((w) => w.code === "frontmatter-double-shape");+ expect(found).toBeDefined();+ expect(found!.message).toMatch(/_applied_count.*legacy 'applied_count'/);+ });++ test("does NOT flag a file using only the new '_status:' shape", () => {+ writePreference(tmp, {+ slug: "clean-new",+ topic: "clean-new",+ principle: "Some rule",+ created_at: "2026-05-14T10:42:00Z",+ unconfirmed_until: "2026-05-28T10:42:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ });+ const res = runDoctor(tmp);+ expect(res.warnings.filter((w) => w.code === "frontmatter-double-shape")).toHaveLength(0);+ });+});diff --git a/tests/core/brain.inline-rewrite.test.ts b/tests/core/brain.inline-rewrite.test.tsnew file mode 100644index 00000000..865fcc7d--- /dev/null+++ b/tests/core/brain.inline-rewrite.test.ts@@ -0,0 +1,169 @@+/**+ * Tests for `inline-rewrite.ts` β atomic in-place annotation of+ * `@osb` markers with `@osbβ [[sig-...]]` (inline form) and info-string+ * flip from `osb` β `osb-checked` (block form).+ */++import { afterEach, beforeEach, expect, describe, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { rewriteMarkers } from "../../src/core/brain/inline-rewrite.ts";+import { discoverMarkers } from "../../src/core/brain/inline.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-inline-rewrite-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function writeTmp(name: string, content: string): string {+ const path = join(tmp, name);+ writeFileSync(path, content, "utf8");+ return path;+}++describe("rewriteMarkers (inline form)", () => {+ test("rewrites '@osb ' to '@osbβ [[sig-...]] '", async () => {+ const path = writeTmp(+ "note.md",+ "Some text\n@osb feedback negative topic=t principle=p\nMore text\n",+ );+ const markers = discoverMarkers(readFileSync(path, "utf8"));+ expect(markers.length).toBe(1);++ await rewriteMarkers(path, [+ { marker: markers[0]!, signalId: "sig-2026-05-16-t" },+ ]);++ const after = readFileSync(path, "utf8");+ expect(after).toMatch(+ /^@osbβ \[\[sig-2026-05-16-t\]\] feedback negative topic=t principle=p$/m,+ );+ expect(after).toMatch(/^Some text$/m);+ expect(after).toMatch(/^More text$/m);+ });++ test("re-running discoverMarkers after rewrite returns zero matches", async () => {+ const path = writeTmp(+ "note.md",+ "@osb feedback negative topic=t principle=p\n",+ );+ const first = discoverMarkers(readFileSync(path, "utf8"));+ await rewriteMarkers(path, [+ { marker: first[0]!, signalId: "sig-x" },+ ]);+ const second = discoverMarkers(readFileSync(path, "utf8"));+ expect(second.length).toBe(0);+ });+});++describe("rewriteMarkers (block form)", () => {+ test("flips info-string osb β osb-checked and prepends '<!-- @osbβ [[id]] -->'", async () => {+ const path = writeTmp(+ "note.md",+ [+ "Before",+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: t",+ "principle: p",+ "```",+ "After",+ "",+ ].join("\n"),+ );+ const markers = discoverMarkers(readFileSync(path, "utf8"));+ expect(markers.length).toBe(1);++ await rewriteMarkers(path, [+ { marker: markers[0]!, signalId: "sig-2026-05-16-t" },+ ]);++ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/^```osb-checked$/m);+ expect(after).toMatch(/^<!-- @osbβ \[\[sig-2026-05-16-t\]\] -->$/m);+ // Body preserved.+ expect(after).toMatch(/^kind: feedback$/m);+ expect(after).toMatch(/^principle: p$/m);+ // Closing fence unchanged.+ expect(after).toMatch(/^```$/m);+ });++ test("block rewrite is idempotent (re-run yields no new markers)", async () => {+ const path = writeTmp(+ "note.md",+ [+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: t",+ "principle: p",+ "```",+ "",+ ].join("\n"),+ );+ const first = discoverMarkers(readFileSync(path, "utf8"));+ await rewriteMarkers(path, [+ { marker: first[0]!, signalId: "sig-x" },+ ]);+ const second = discoverMarkers(readFileSync(path, "utf8"));+ expect(second.length).toBe(0);+ });+});++describe("rewriteMarkers β mixed and multiple", () => {+ test("processes multiple inline markers in order", async () => {+ const path = writeTmp(+ "note.md",+ [+ "@osb feedback negative topic=a principle=pa",+ "...",+ "@osb feedback positive topic=b principle=pb",+ "",+ ].join("\n"),+ );+ const markers = discoverMarkers(readFileSync(path, "utf8"));+ expect(markers.length).toBe(2);+ await rewriteMarkers(path, [+ { marker: markers[0]!, signalId: "sig-aaa" },+ { marker: markers[1]!, signalId: "sig-bbb" },+ ]);+ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/@osbβ \[\[sig-aaa\]\] feedback negative topic=a/);+ expect(after).toMatch(/@osbβ \[\[sig-bbb\]\] feedback positive topic=b/);+ });++ test("handles mixed inline + block markers", async () => {+ const path = writeTmp(+ "note.md",+ [+ "@osb feedback negative topic=a principle=pa",+ "",+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: b",+ "principle: pb",+ "```",+ "",+ ].join("\n"),+ );+ const markers = discoverMarkers(readFileSync(path, "utf8"));+ expect(markers.length).toBe(2);+ await rewriteMarkers(path, [+ { marker: markers[0]!, signalId: "sig-aaa" },+ { marker: markers[1]!, signalId: "sig-bbb" },+ ]);+ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/^@osbβ \[\[sig-aaa\]\] feedback negative/m);+ expect(after).toMatch(/^```osb-checked$/m);+ expect(after).toMatch(/^<!-- @osbβ \[\[sig-bbb\]\] -->$/m);+ });+});diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.tsnew file mode 100644index 00000000..e5b54f83--- /dev/null+++ b/tests/core/brain.inline-scan.test.ts@@ -0,0 +1,227 @@+/**+ * Tests for `inline-scan.ts` β the vault walker that finds @osb markers,+ * dedups against the existing inbox, writes signals, and rewrites the+ * source files.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { brainDirs } from "../../src/core/brain/paths.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { scanInline } from "../../src/core/brain/inline-scan.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-inline-scan-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function writeMd(rel: string, content: string): string {+ const path = join(tmp, rel);+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, content, "utf8");+ return path;+}++describe("scanInline", () => {+ test("finds an inline marker in Daily/ and creates a signal in inbox/", async () => {+ writeMd(+ "Daily/2026-05-16.md",+ "Note text\n@osb feedback negative topic=mocking principle=\"don't mock DB\"\n",+ );+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.scanned).toBeGreaterThan(0);+ expect(result.found).toBe(1);+ expect(result.created).toBe(1);+ expect(result.deduped).toBe(0);++ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));+ expect(inboxFiles.length).toBe(1);+ const sig = readFileSync(join(brainDirs(tmp).inbox, inboxFiles[0]!), "utf8");+ expect(sig).toMatch(/^source_type: inline$/m);+ expect(sig).toMatch(/^dedup_hash: /m);+ expect(sig).toMatch(/topic: mocking/);+ });++ test("skips Brain/ when walking (no self-recursion)", async () => {+ // Plant a marker-like line INSIDE Brain/ to confirm we skip it.+ writeFileSync(+ join(brainDirs(tmp).inbox, "sig-fake.md"),+ "---\nkind: brain-signal\n---\n@osb feedback negative topic=fake principle=x\n",+ "utf8",+ );+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.found).toBe(0);+ });++ test("rewrites the source file to '@osbβ [[sig-...]]'", async () => {+ const notePath = writeMd(+ "Daily/2026-05-16.md",+ "@osb feedback negative topic=rewrite principle=p\n",+ );+ await scanInline(tmp, { agent: "test" });+ const after = readFileSync(notePath, "utf8");+ expect(after).toMatch(/^@osbβ \[\[sig-.*-rewrite\]\] feedback negative topic=rewrite principle=p$/m);+ });++ test("is idempotent on second run (rewritten markers ignored)", async () => {+ writeMd(+ "Daily/2026-05-16.md",+ "@osb feedback negative topic=idemp principle=p\n",+ );+ const first = await scanInline(tmp, { agent: "test" });+ expect(first.created).toBe(1);++ const second = await scanInline(tmp, { agent: "test" });+ expect(second.found).toBe(0);+ expect(second.created).toBe(0);+ expect(second.deduped).toBe(0);+ });++ test("dedups against an existing inbox signal with the same dedup_hash", async () => {+ // First run creates one signal.+ const notePath = writeMd(+ "Daily/2026-05-16.md",+ "@osb feedback negative topic=dup principle=p\n",+ );+ await scanInline(tmp, { agent: "test" });++ // Restore the marker (simulate user re-pasting).+ writeFileSync(notePath, "@osb feedback negative topic=dup principle=p\n");++ const second = await scanInline(tmp, { agent: "test" });+ expect(second.found).toBe(1);+ expect(second.created).toBe(0);+ expect(second.deduped).toBe(1);++ // Only one signal on disk.+ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));+ expect(inboxFiles.length).toBe(1);+ });++ test("--dry-run does not write signals or rewrite files", async () => {+ const notePath = writeMd(+ "Daily/2026-05-16.md",+ "@osb feedback negative topic=dry principle=p\n",+ );+ const before = readFileSync(notePath, "utf8");+ const result = await scanInline(tmp, { agent: "test", dryRun: true });+ expect(result.found).toBe(1);+ expect(result.created).toBe(0);+ expect(readFileSync(notePath, "utf8")).toBe(before);+ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));+ expect(inboxFiles.length).toBe(0);+ });++ test("processes a fenced 'osb' block and writes signal + rewrites info-string", async () => {+ const notePath = writeMd(+ "Projects/foo.md",+ [+ "Before",+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: block-test",+ "principle: long form text",+ "```",+ "After",+ "",+ ].join("\n"),+ );+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.created).toBe(1);+ const after = readFileSync(notePath, "utf8");+ expect(after).toMatch(/^```osb-checked$/m);+ expect(after).toMatch(/^<!-- @osbβ \[\[sig-.*-block-test\]\] -->$/m);+ });++ test("--paths narrows the walker to specific subdirs", async () => {+ writeMd("Daily/d.md", "@osb feedback negative topic=in-daily principle=p\n");+ writeMd("Projects/p.md", "@osb feedback negative topic=in-projects principle=p\n");+ const result = await scanInline(tmp, {+ agent: "test",+ paths: ["Daily"],+ });+ expect(result.created).toBe(1);+ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));+ const content = inboxFiles.map((f) =>+ readFileSync(join(brainDirs(tmp).inbox, f), "utf8"),+ );+ const joined = content.join("");+ expect(joined).toMatch(/topic: in-daily/);+ expect(joined).not.toMatch(/topic: in-projects/);+ });++ test("--exclude excludes additional directories", async () => {+ writeMd("Daily/d.md", "@osb feedback negative topic=ok principle=p\n");+ writeMd("Private/p.md", "@osb feedback negative topic=secret principle=p\n");+ const result = await scanInline(tmp, {+ agent: "test",+ exclude: ["Private"],+ });+ expect(result.created).toBe(1);+ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));+ const joined = inboxFiles+ .map((f) => readFileSync(join(brainDirs(tmp).inbox, f), "utf8"))+ .join("");+ expect(joined).toMatch(/topic: ok/);+ expect(joined).not.toMatch(/topic: secret/);+ });++ test("skips .git and node_modules by default", async () => {+ writeMd(".git/info.md", "@osb feedback negative topic=git principle=p\n");+ writeMd("node_modules/lib.md", "@osb feedback negative topic=nm principle=p\n");+ writeMd("Daily/d.md", "@osb feedback negative topic=visible principle=p\n");+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.created).toBe(1);+ });++ test("skips files larger than 1 MiB", async () => {+ // Build a marker preceded by 1.5 MiB of filler.+ const filler = "x".repeat(1_500_000);+ writeMd(+ "Big/huge.md",+ `${filler}\n@osb feedback negative topic=huge principle=p\n`,+ );+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.found).toBe(0);+ expect(result.errors.some((e) => e.message.includes("too large"))).toBe(true);+ });++ test("counts malformed marker attempts without creating signals", async () => {+ writeMd("Daily/bad.md", "@osb feedback negative topic=missing-principle\n");+ const result = await scanInline(tmp, { agent: "test" });+ expect(result.found).toBe(0);+ expect(result.created).toBe(0);+ expect(result.malformed).toBe(1);+ });+});diff --git a/tests/core/brain.inline.test.ts b/tests/core/brain.inline.test.tsnew file mode 100644index 00000000..706234f5--- /dev/null+++ b/tests/core/brain.inline.test.ts@@ -0,0 +1,254 @@+/**+ * Tests for `src/core/brain/inline.ts` β the `@osb` marker parser+ * shared by Β§9 (vault scan) and Β§16 (session-text scan).+ *+ * Three layers:+ * 1. `parseInlineMarker(line, lineNo)` β single-line `@osb ...` syntax.+ * 2. `parseBlockMarker(body, fenceStartLine)` β YAML-like fenced+ * block with info-string `osb`.+ * 3. `discoverMarkers(content)` β file-level orchestrator that walks+ * lines, tracks fence state, and ignores already-checked markers.+ */++import { describe, expect, test } from "bun:test";++import {+ discoverMarkersDetailed,+ discoverMarkers,+ parseBlockMarker,+ parseInlineMarker,+} from "../../src/core/brain/inline.ts";++// ββ Inline form βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("parseInlineMarker", () => {+ test("recognises positional kind + signal + key=value pairs", () => {+ const m = parseInlineMarker(+ `@osb feedback negative topic=mocking principle="don't mock DB"`,+ 1,+ );+ expect(m).not.toBeNull();+ if (m === null) return;+ expect(m.kind).toBe("feedback");+ expect(m.signal).toBe("negative");+ expect(m.topic).toBe("mocking");+ expect(m.principle).toBe("don't mock DB");+ expect(m.originLine).toBe(1);+ expect(m.shape).toBe("inline");+ });++ test("parses quoted strings with embedded escapes", () => {+ const m = parseInlineMarker(+ `@osb feedback positive topic=t principle="line with \\"quotes\\" and \\\\backslash"`,+ 5,+ );+ expect(m).not.toBeNull();+ if (m === null) return;+ expect(m.principle).toBe(`line with "quotes" and \\backslash`);+ });++ test("accepts unquoted single-word values", () => {+ const m = parseInlineMarker(+ "@osb feedback positive topic=foo principle=bar scope=writing",+ 1,+ );+ expect(m).not.toBeNull();+ if (m === null) return;+ expect(m.topic).toBe("foo");+ expect(m.principle).toBe("bar");+ expect(m.scope).toBe("writing");+ });++ test("returns null when 'kind' is unknown", () => {+ expect(parseInlineMarker(`@osb foo bar topic=t principle=p`, 1)).toBeNull();+ });++ test("returns null when '@osb' is in the middle of a line", () => {+ expect(+ parseInlineMarker(`This is @osb feedback positive topic=t principle=p`, 1),+ ).toBeNull();+ });++ test("returns null when required field is missing", () => {+ // No `principle`.+ expect(parseInlineMarker(`@osb feedback positive topic=t`, 1)).toBeNull();+ // No `signal`.+ expect(parseInlineMarker(`@osb feedback topic=t principle=p`, 1)).toBeNull();+ });++ test("returns null when signal value is not in the enum", () => {+ expect(+ parseInlineMarker(`@osb feedback maybe topic=t principle=p`, 1),+ ).toBeNull();+ });++ test("accepts leading whitespace before '@osb'", () => {+ const m = parseInlineMarker(+ ` @osb feedback negative topic=t principle=p`,+ 1,+ );+ expect(m).not.toBeNull();+ });++ test("captures optional agent / note / source", () => {+ const m = parseInlineMarker(+ `@osb feedback negative topic=t principle=p agent=claude source=[[Daily/2026-05-14]]`,+ 1,+ );+ expect(m).not.toBeNull();+ if (m === null) return;+ expect(m.agent).toBe("claude");+ expect(m.source).toEqual(["[[Daily/2026-05-14]]"]);+ });+});++// ββ Block form ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("parseBlockMarker", () => {+ test("parses a multi-line YAML body", () => {+ const body = [+ "kind: feedback",+ "signal: negative",+ "topic: t",+ "principle: long principle text",+ "scope: testing",+ ].join("\n");+ const m = parseBlockMarker(body, 5);+ expect(m).not.toBeNull();+ if (m === null) return;+ expect(m.kind).toBe("feedback");+ expect(m.signal).toBe("negative");+ expect(m.principle).toBe("long principle text");+ expect(m.scope).toBe("testing");+ expect(m.shape).toBe("block");+ expect(m.originLine).toBe(5);+ });++ test("returns null on unknown kind", () => {+ const body = [+ "kind: lol",+ "signal: negative",+ "topic: t",+ "principle: p",+ ].join("\n");+ expect(parseBlockMarker(body, 1)).toBeNull();+ });++ test("returns null when required field is missing", () => {+ const body = ["kind: feedback", "signal: negative", "topic: t"].join("\n");+ expect(parseBlockMarker(body, 1)).toBeNull();+ });++ test("ignores comments and blank lines", () => {+ const body = [+ "# leading comment",+ "kind: feedback",+ "",+ "signal: positive",+ "topic: t",+ "principle: p",+ ].join("\n");+ const m = parseBlockMarker(body, 1);+ expect(m).not.toBeNull();+ });+});++// ββ File-level discovery ββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("discoverMarkers", () => {+ test("finds inline markers", () => {+ const text = [+ "Some note text",+ "@osb feedback negative topic=t principle=p",+ "More text",+ ].join("\n");+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(1);+ expect(markers[0]!.shape).toBe("inline");+ expect(markers[0]!.originLine).toBe(2);+ });++ test("finds fenced 'osb' blocks", () => {+ const text = [+ "Before",+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: t",+ "principle: p",+ "```",+ "After",+ ].join("\n");+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(1);+ expect(markers[0]!.shape).toBe("block");+ expect(markers[0]!.originLine).toBe(2); // line with ```osb+ });++ test("ignores '@osb' inside non-osb fences (code samples in docs)", () => {+ const text = [+ "```python",+ "@osb feedback negative topic=t principle=p",+ "```",+ ].join("\n");+ expect(discoverMarkers(text).length).toBe(0);+ });++ test("ignores already-checked inline markers (@osbβ)", () => {+ const text = "@osbβ [[sig-foo]] feedback negative topic=t principle=p";+ expect(discoverMarkers(text).length).toBe(0);+ });++ test("ignores already-checked fenced blocks (osb-checked)", () => {+ const text = [+ "```osb-checked",+ "<!-- @osbβ [[sig-x]] -->",+ "kind: feedback",+ "signal: positive",+ "topic: t",+ "principle: p",+ "```",+ ].join("\n");+ expect(discoverMarkers(text).length).toBe(0);+ });++ test("finds multiple markers in document order", () => {+ const text = [+ "@osb feedback negative topic=a principle=p1",+ "...",+ "@osb feedback positive topic=b principle=p2",+ "...",+ "```osb",+ "kind: feedback",+ "signal: negative",+ "topic: c",+ "principle: p3",+ "```",+ ].join("\n");+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(3);+ expect(markers.map((m) => m.topic)).toEqual(["a", "b", "c"]);+ });++ test("preserves verbatim originText for inline markers", () => {+ const text = `@osb feedback negative topic=t principle="don't mock"`;+ const markers = discoverMarkers(text);+ expect(markers.length).toBe(1);+ expect(markers[0]!.originText).toBe(text);+ });++ test("reports malformed marker attempts separately from prose", () => {+ const text = [+ "@osb is great prose, not a marker",+ "@osb feedback negative topic=t",+ "```osb",+ "kind: feedback",+ "signal: positive",+ "topic: t",+ "```",+ ].join("\n");+ const result = discoverMarkersDetailed(text);+ expect(result.markers.length).toBe(0);+ expect(result.malformed).toBe(2);+ });+});diff --git a/tests/core/brain.migrate-frontmatter.test.ts b/tests/core/brain.migrate-frontmatter.test.tsnew file mode 100644index 00000000..047030cd--- /dev/null+++ b/tests/core/brain.migrate-frontmatter.test.ts@@ -0,0 +1,269 @@+/**+ * Tests for `migrate-frontmatter` β the opt-in helper that rewrites+ * legacy-shape Group C frontmatter keys (`status:`, `applied_count:`,+ * ...) to the `_`-prefixed form (Β§24) across `Brain/preferences/`+ * and `Brain/retired/`.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ brainDirs,+ preferencePath,+ retiredPath,+} from "../../src/core/brain/paths.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";+import {+ applyMigration,+ MigrationError,+ planMigration,+} from "../../src/core/brain/migrate-frontmatter.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { listSnapshots } from "../../src/core/brain/snapshot.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-migrate-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {+ mkdirSync(d, { recursive: true });+ }+ // Required for createSnapshot's config-load step+ atomicWriteFileSync(+ join(dirs.brain, "_brain.yaml"),+ DEFAULT_BRAIN_CONFIG_YAML,+ );+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function writeLegacyPref(slug: string): string {+ const path = preferencePath(tmp, slug);+ const content = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "confirmed_at: 2026-05-15T10:00:00Z",+ "evidenced_by: []",+ "applied_count: 1",+ "violated_count: 0",+ "last_evidence_at: null",+ "confidence: low",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++function writeNewPref(slug: string): string {+ const path = preferencePath(tmp, slug);+ const content = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "pinned: false",+ "_status: confirmed",+ "_confirmed_at: 2026-05-15T10:00:00Z",+ "_evidenced_by: []",+ "_applied_count: 1",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: low",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++function writeCollisionPref(slug: string): string {+ const path = preferencePath(tmp, slug);+ const content = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "_status: confirmed",+ "evidenced_by: []",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++function writeLegacyRetired(slug: string): string {+ const path = retiredPath(tmp, slug);+ const content = [+ "---",+ "kind: brain-retired",+ `id: ret-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "retired_at: 2026-08-12T05:00:00Z",+ "retired_reason: stale-no-evidence",+ "retired_by: '[[Brain/log/2026-08-12]]'",+ `tags: [brain, brain/retired, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "status: retired",+ "pinned: false",+ "evidenced_by: []",+ "applied_count: 4",+ "violated_count: 1",+ "last_evidence_at: 2026-05-20T10:00:00Z",+ "confidence: medium",+ "---",+ "",+ ].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++describe("planMigration", () => {+ test("counts legacy / new / collision files", () => {+ writeLegacyPref("legacy-a");+ writeNewPref("new-a");+ writeCollisionPref("collision-a");+ writeLegacyRetired("legacy-r");++ const plan = planMigration(tmp);++ expect(plan.files_scanned).toBe(4);+ expect(plan.files_to_migrate.length).toBe(2); // legacy pref + legacy retired+ expect(plan.files_already_new.length).toBe(1);+ expect(plan.collisions.length).toBe(1);+ expect(plan.collisions[0]!.field).toBe("status");+ });++ test("returns zero counts on an empty vault", () => {+ const plan = planMigration(tmp);+ expect(plan.files_scanned).toBe(0);+ expect(plan.files_to_migrate.length).toBe(0);+ expect(plan.files_already_new.length).toBe(0);+ expect(plan.collisions.length).toBe(0);+ });+});++describe("applyMigration", () => {+ test("rewrites legacy keys to _-prefixed", async () => {+ const path = writeLegacyPref("alpha");+ const result = await applyMigration(tmp, {+ snapshot: false,+ now: new Date("2026-05-16T10:15:22Z"),+ });++ expect(result.files_migrated.length).toBe(1);++ const raw = readFileSync(path, "utf8");+ expect(raw).toMatch(/^_status: confirmed$/m);+ expect(raw).toMatch(/^_applied_count: 1$/m);+ expect(raw).toMatch(/^_confidence: low$/m);+ expect(raw).not.toMatch(/^status: /m);+ expect(raw).not.toMatch(/^applied_count: /m);+ });++ test("preserves identity fields and body", async () => {+ const path = writeLegacyPref("beta");+ const original = readFileSync(path, "utf8");+ expect(original).toMatch(/^principle: Some rule$/m);++ await applyMigration(tmp, { snapshot: false, now: new Date() });+ const after = readFileSync(path, "utf8");+ expect(after).toMatch(/^principle: Some rule$/m);+ expect(after).toMatch(/^topic: beta$/m);+ expect(after).toMatch(/^kind: brain-preference$/m);+ expect(after).toMatch(/^id: pref-beta$/m);+ });++ test("is idempotent (second run is a no-op)", async () => {+ writeLegacyPref("gamma");+ const first = await applyMigration(tmp, { snapshot: false, now: new Date() });+ const second = await applyMigration(tmp, { snapshot: false, now: new Date() });+ expect(first.files_migrated.length).toBe(1);+ expect(second.files_migrated.length).toBe(0);+ });++ test("takes a snapshot when snapshot: true", async () => {+ writeLegacyPref("delta");+ const result = await applyMigration(tmp, {+ snapshot: true,+ now: new Date("2026-05-16T10:15:22Z"),+ });+ expect(result.snapshot_path).toBeTruthy();+ expect(existsSync(result.snapshot_path!)).toBe(true);+ const snaps = listSnapshots(tmp);+ expect(snaps.length).toBe(1);+ expect(snaps[0]!.run_id).toMatch(/^migrate-/);+ });++ test("aborts with MigrationError when a collision file is present", async () => {+ writeLegacyPref("ok");+ writeCollisionPref("bad");+ await expect(+ applyMigration(tmp, { snapshot: false, now: new Date() }),+ ).rejects.toThrow(MigrationError);+ });++ test("collision check runs BEFORE any rewrite (atomic-ish abort)", async () => {+ const okPath = writeLegacyPref("ok");+ writeCollisionPref("bad");+ const before = readFileSync(okPath, "utf8");+ try {+ await applyMigration(tmp, { snapshot: false, now: new Date() });+ } catch {+ /* expected */+ }+ const after = readFileSync(okPath, "utf8");+ expect(after).toBe(before);+ });++ test("processes retired/ as well as preferences/", async () => {+ const retPath = writeLegacyRetired("epsilon");+ await applyMigration(tmp, { snapshot: false, now: new Date() });+ const raw = readFileSync(retPath, "utf8");+ expect(raw).toMatch(/^_applied_count: 4$/m);+ expect(raw).not.toMatch(/^applied_count: /m);+ // `status: retired` is identity on retired files, must stay unprefixed.+ expect(raw).toMatch(/^status: retired$/m);+ });+});diff --git a/tests/core/brain.preference.test.ts b/tests/core/brain.preference.test.tsindex a8ebc3c0..3567d576 100644--- a/tests/core/brain.preference.test.ts+++ b/tests/core/brain.preference.test.ts@@ -1,5 +1,12 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -325,3 +332,266 @@ describe("status enum validation", () => {);});});++// ββ Β§24 dual-shape frontmatter ββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Write a hand-crafted preference file under `<tmp>/Brain/preferences/`+ * with the given frontmatter lines. Used by the dual-shape tests to+ * insert legacy / new-form / both-form Group C keys verbatim, since+ * `writePreference` always emits one canonical shape.+ */+function writeRawPref(tmp: string, slug: string, fmLines: ReadonlyArray<string>): string {+ const dirs = brainDirs(tmp);+ mkdirSync(dirs.preferences, { recursive: true });+ const path = preferencePath(tmp, slug);+ const content = ["---", ...fmLines, "---", "", "## Principle", "", "Some rule", ""].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++function writeRawRetired(tmp: string, slug: string, fmLines: ReadonlyArray<string>): string {+ const dirs = brainDirs(tmp);+ mkdirSync(dirs.retired, { recursive: true });+ const path = retiredPath(tmp, slug);+ const content = ["---", ...fmLines, "---", "", "## Retired", "", "Reason: stale-no-evidence", ""].join("\n");+ writeFileSync(path, content, "utf8");+ return path;+}++const PREF_BASE_FM = (slug: string): string[] => [+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ `tags: [brain, brain/preference, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "pinned: false",+];++const RET_BASE_FM = (slug: string): string[] => [+ "kind: brain-retired",+ `id: ret-${slug}`,+ "created_at: 2026-05-14T10:42:00Z",+ "retired_at: 2026-08-12T05:00:00Z",+ "retired_reason: stale-no-evidence",+ "retired_by: '[[Brain/log/2026-08-12]]'",+ `tags: [brain, brain/retired, brain/topic/${slug}]`,+ `topic: ${slug}`,+ "principle: Some rule",+ "status: retired",+ "pinned: false",+];++describe("parsePreference accepts both legacy and _-prefixed shapes (Β§24)", () => {+ test("reads legacy 'status:' form", () => {+ const path = writeRawPref(tmp, "legacy-status", [+ ...PREF_BASE_FM("legacy-status"),+ "status: confirmed",+ "confirmed_at: 2026-05-15T10:00:00Z",+ "evidenced_by: []",+ "applied_count: 1",+ "violated_count: 0",+ "last_evidence_at: 2026-05-20T10:00:00Z",+ "confidence: low",+ ]);+ const parsed = parsePreference(path);+ expect(parsed.status).toBe("confirmed");+ expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");+ expect(parsed.applied_count).toBe(1);+ expect(parsed.confidence).toBe("low");+ expect(parsed.last_evidence_at).toBe("2026-05-20T10:00:00Z");+ });++ test("reads new '_status:' form", () => {+ const path = writeRawPref(tmp, "new-status", [+ ...PREF_BASE_FM("new-status"),+ "_status: confirmed",+ "_confirmed_at: 2026-05-15T10:00:00Z",+ "_evidenced_by: []",+ "_applied_count: 1",+ "_violated_count: 0",+ "_last_evidence_at: 2026-05-20T10:00:00Z",+ "_confidence: low",+ ]);+ const parsed = parsePreference(path);+ expect(parsed.status).toBe("confirmed");+ expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");+ expect(parsed.applied_count).toBe(1);+ expect(parsed.confidence).toBe("low");+ expect(parsed.last_evidence_at).toBe("2026-05-20T10:00:00Z");+ });++ test("throws when both 'status' and '_status' are present", () => {+ const path = writeRawPref(tmp, "collision", [+ ...PREF_BASE_FM("collision"),+ "status: confirmed",+ "_status: confirmed",+ "evidenced_by: []",+ ]);+ expect(() => parsePreference(path)).toThrow(+ /both '_status' and legacy 'status' present/,+ );+ });++ test("throws when both 'applied_count' and '_applied_count' are present", () => {+ const path = writeRawPref(tmp, "applied-collision", [+ ...PREF_BASE_FM("applied-collision"),+ "_status: confirmed",+ "applied_count: 3",+ "_applied_count: 3",+ "evidenced_by: []",+ ]);+ expect(() => parsePreference(path)).toThrow(+ /both '_applied_count' and legacy 'applied_count' present/,+ );+ });++ test("reads mixed (some legacy, some new) shape without collision", () => {+ const path = writeRawPref(tmp, "mixed", [+ ...PREF_BASE_FM("mixed"),+ "_status: confirmed", // new form+ "confirmed_at: 2026-05-15T10:00:00Z", // legacy form+ "evidenced_by: []", // legacy form+ "_applied_count: 2", // new form+ ]);+ const parsed = parsePreference(path);+ expect(parsed.status).toBe("confirmed");+ expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");+ expect(parsed.applied_count).toBe(2);+ });+});++describe("parseRetired accepts both legacy and _-prefixed shapes (Β§24)", () => {+ test("reads legacy form", () => {+ const path = writeRawRetired(tmp, "legacy-ret", [+ ...RET_BASE_FM("legacy-ret"),+ "evidenced_by: ['[[sig-x]]']",+ "applied_count: 5",+ "violated_count: 1",+ "last_evidence_at: 2026-05-20T10:00:00Z",+ "confidence: medium",+ ]);+ const parsed = parseRetired(path);+ expect(parsed.applied_count).toBe(5);+ expect(parsed.confidence).toBe("medium");+ expect(parsed.evidenced_by).toEqual(["[[sig-x]]"]);+ });++ test("reads new '_'-prefixed form", () => {+ const path = writeRawRetired(tmp, "new-ret", [+ ...RET_BASE_FM("new-ret"),+ "_evidenced_by: ['[[sig-x]]']",+ "_applied_count: 5",+ "_violated_count: 1",+ "_last_evidence_at: 2026-05-20T10:00:00Z",+ "_confidence: medium",+ ]);+ const parsed = parseRetired(path);+ expect(parsed.applied_count).toBe(5);+ expect(parsed.confidence).toBe("medium");+ expect(parsed.evidenced_by).toEqual(["[[sig-x]]"]);+ });++ test("throws on legacy+new collision", () => {+ const path = writeRawRetired(tmp, "ret-collision", [+ ...RET_BASE_FM("ret-collision"),+ "applied_count: 3",+ "_applied_count: 3",+ ]);+ expect(() => parseRetired(path)).toThrow(+ /both '_applied_count' and legacy 'applied_count' present/,+ );+ });+});++describe("writePreference emits _-prefixed Group C fields (Β§24)", () => {+ test("emits '_status:' instead of 'status:'", () => {+ const res = writePreference(tmp, basePrefInput());+ const raw = readFileSync(res.path, "utf8");+ expect(raw).toMatch(/^_status: unconfirmed$/m);+ expect(raw).not.toMatch(/^status: /m);+ });++ test("emits '_applied_count:' / '_violated_count:'", () => {+ const res = writePreference(+ tmp,+ basePrefInput({ status: "confirmed", applied_count: 4, violated_count: 1 }),+ );+ const raw = readFileSync(res.path, "utf8");+ expect(raw).toMatch(/^_applied_count: 4$/m);+ expect(raw).toMatch(/^_violated_count: 1$/m);+ expect(raw).not.toMatch(/^applied_count: /m);+ expect(raw).not.toMatch(/^violated_count: /m);+ });++ test("emits '_confirmed_at:' / '_last_evidence_at:' / '_confidence:'", () => {+ const res = writePreference(+ tmp,+ basePrefInput({+ status: "confirmed",+ confirmed_at: "2026-05-15T10:00:00Z",+ last_evidence_at: "2026-05-20T10:00:00Z",+ confidence: "medium",+ }),+ );+ const raw = readFileSync(res.path, "utf8");+ expect(raw).toMatch(/^_confirmed_at: "?2026-05-15T10:00:00Z"?$/m);+ expect(raw).toMatch(/^_last_evidence_at: "?2026-05-20T10:00:00Z"?$/m);+ expect(raw).toMatch(/^_confidence: medium$/m);+ });++ test("emits '_evidenced_by:' instead of 'evidenced_by:'", () => {+ const res = writePreference(tmp, basePrefInput());+ const raw = readFileSync(res.path, "utf8");+ expect(raw).toMatch(/^_evidenced_by: \[/m);+ expect(raw).not.toMatch(/^evidenced_by: /m);+ });++ test("writePreference + parsePreference round-trip via new shape", () => {+ const res = writePreference(+ tmp,+ basePrefInput({+ status: "confirmed",+ confirmed_at: "2026-05-15T10:00:00Z",+ applied_count: 7,+ }),+ );+ const parsed = parsePreference(res.path);+ expect(parsed.status).toBe("confirmed");+ expect(parsed.confirmed_at).toBe("2026-05-15T10:00:00Z");+ expect(parsed.applied_count).toBe(7);+ });++ test("identity fields ('topic', 'principle', 'pinned', 'tags') stay un-prefixed", () => {+ const res = writePreference(tmp, basePrefInput({ pinned: true }));+ const raw = readFileSync(res.path, "utf8");+ expect(raw).toMatch(/^topic: /m);+ expect(raw).toMatch(/^principle: /m);+ expect(raw).toMatch(/^pinned: true$/m);+ expect(raw).toMatch(/^tags: \[/m);+ expect(raw).toMatch(/^kind: brain-preference$/m);+ expect(raw).toMatch(/^id: pref-/m);+ expect(raw).toMatch(/^created_at: /m);+ expect(raw).toMatch(/^unconfirmed_until: /m);+ });+});++describe("moveToRetired carries _-prefixed shape forward (Β§24)", () => {+ test("retired file uses new shape for Group C fields", () => {+ const written = writePreference(+ tmp,+ basePrefInput({ status: "confirmed", applied_count: 3 }),+ );+ const result = moveToRetired(tmp, written.path, "stale-no-evidence", {+ now: new Date("2026-08-12T05:00:00Z"),+ retired_by: "[[Brain/log/2026-08-12]]",+ });+ const raw = readFileSync(result.path, "utf8");+ expect(raw).toMatch(/^_applied_count: 3$/m);+ expect(raw).not.toMatch(/^applied_count: /m);+ // 'status:' on the retired file is identity (always 'retired'), not derived.+ expect(raw).toMatch(/^status: retired$/m);+ });+});diff --git a/tests/core/brain.sessions.claude.test.ts b/tests/core/brain.sessions.claude.test.tsnew file mode 100644index 00000000..cb368a5a--- /dev/null+++ b/tests/core/brain.sessions.claude.test.ts@@ -0,0 +1,92 @@+/**+ * Claude Code .jsonl adapter tests. Source fixture:+ * `tests/fixtures/sessions/claude-minimal.jsonl`.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { claudeAdapter } from "../../src/core/brain/sessions/claude.ts";+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";++const FIXTURE = resolve("tests/fixtures/sessions/claude-minimal.jsonl");++function firstLine(path: string): string {+ return readFileSync(path, "utf8").split("\n")[0]!;+}++async function collect(path: string): Promise<SessionTurn[]> {+ const out: SessionTurn[] = [];+ for await (const t of claudeAdapter.iterate(path)) out.push(t);+ return out;+}++describe("claudeAdapter.detect", () => {+ test("matches its own format", () => {+ expect(claudeAdapter.detect(firstLine(FIXTURE))).toBe(true);+ });++ test("matches the parentUuid / sessionId / entrypoint shape directly", () => {+ const line =+ '{"parentUuid":null,"sessionId":"x","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"hi"},"uuid":"a","timestamp":"2026-05-16T00:00:00Z"}';+ expect(claudeAdapter.detect(line)).toBe(true);+ });++ test("rejects codex first line", () => {+ const codexFirst =+ '{"timestamp":"2026-05-08T20:59:25.611Z","type":"session_meta","payload":{"originator":"codex_exec"}}';+ expect(claudeAdapter.detect(codexFirst)).toBe(false);+ });++ test("rejects hermes first line", () => {+ const hermesFirst =+ '{"role":"session_meta","tools":[{"type":"function","function":{"name":"a"}}]}';+ expect(claudeAdapter.detect(hermesFirst)).toBe(false);+ });++ test("rejects malformed JSON", () => {+ expect(claudeAdapter.detect("not json")).toBe(false);+ });+});++describe("claudeAdapter.iterate", () => {+ test("emits user + assistant turns and skips queue-operation entries", async () => {+ const turns = await collect(FIXTURE);+ const userTurns = turns.filter((t) => t.role === "user");+ const assistantTurns = turns.filter((t) => t.role === "assistant");+ expect(userTurns.length).toBe(2);+ expect(assistantTurns.length).toBe(1);+ // queue-operation events are not yielded.+ expect(turns.some((t) => t.role === "meta")).toBe(false);+ });++ test("flattens string-content user messages into `text`", async () => {+ const turns = await collect(FIXTURE);+ const userOne = turns.find((t) => t.turnId === "turn-user-1");+ expect(userOne).toBeDefined();+ expect(userOne!.text).toContain("@osb feedback negative topic=mocking");+ });++ test("flattens block-content assistant messages into `text` + extracts toolCalls", async () => {+ const turns = await collect(FIXTURE);+ const assistant = turns.find((t) => t.turnId === "turn-assistant-1");+ expect(assistant).toBeDefined();+ expect(assistant!.text).toContain("I'll record that as a preference");+ expect(assistant!.toolCalls).toBeDefined();+ expect(assistant!.toolCalls!.length).toBe(1);+ expect(assistant!.toolCalls![0]!.name).toBe("brain_feedback");+ expect(assistant!.toolCalls![0]!.input).toMatchObject({+ topic: "mocking",+ signal: "negative",+ });+ expect(assistant!.toolCalls![0]!.id).toBe("tu-1");+ });++ test("preserves ISO timestamp on each turn", async () => {+ const turns = await collect(FIXTURE);+ for (const t of turns) {+ expect(t.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ }+ });+});diff --git a/tests/core/brain.sessions.codex.test.ts b/tests/core/brain.sessions.codex.test.tsnew file mode 100644index 00000000..294e65af--- /dev/null+++ b/tests/core/brain.sessions.codex.test.ts@@ -0,0 +1,73 @@+/**+ * Codex CLI .jsonl adapter tests.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { codexAdapter } from "../../src/core/brain/sessions/codex.ts";+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";++const FIXTURE = resolve("tests/fixtures/sessions/codex-minimal.jsonl");++function firstLine(path: string): string {+ return readFileSync(path, "utf8").split("\n")[0]!;+}++async function collect(path: string): Promise<SessionTurn[]> {+ const out: SessionTurn[] = [];+ for await (const t of codexAdapter.iterate(path)) out.push(t);+ return out;+}++describe("codexAdapter.detect", () => {+ test("matches its own format", () => {+ expect(codexAdapter.detect(firstLine(FIXTURE))).toBe(true);+ });++ test("rejects claude first line", () => {+ expect(codexAdapter.detect('{"type":"queue-operation","operation":"x"}')).toBe(false);+ });++ test("rejects hermes first line", () => {+ expect(codexAdapter.detect('{"role":"session_meta","tools":[]}')).toBe(false);+ });++ test("requires the originator=codex_exec marker", () => {+ expect(+ codexAdapter.detect('{"timestamp":"x","type":"session_meta","payload":{"foo":"bar"}}'),+ ).toBe(false);+ });+});++describe("codexAdapter.iterate", () => {+ test("yields user and assistant message turns, skips event_msg / session_meta", async () => {+ const turns = await collect(FIXTURE);+ expect(turns.filter((t) => t.role === "user").length).toBe(1);+ expect(turns.filter((t) => t.role === "assistant").length).toBeGreaterThan(0);+ // event_msg / session_meta entries are not yielded as turns.+ expect(turns.some((t) => t.role === "meta")).toBe(false);+ });++ test("flattens input_text / output_text blocks into `text`", async () => {+ const turns = await collect(FIXTURE);+ const user = turns.find((t) => t.role === "user");+ expect(user?.text).toContain("@osb feedback negative topic=mocking");+ const assistant = turns.find((t) => t.role === "assistant" && t.text);+ expect(assistant?.text).toContain("I'll record that as a preference");+ });++ test("parses function_call into toolCalls (arguments JSON-decoded)", async () => {+ const turns = await collect(FIXTURE);+ const withTool = turns.find((t) => (t.toolCalls?.length ?? 0) > 0);+ expect(withTool).toBeDefined();+ const call = withTool!.toolCalls![0]!;+ expect(call.name).toBe("brain_feedback");+ expect(call.input).toMatchObject({+ topic: "mocking",+ signal: "negative",+ });+ expect(call.id).toBe("call_codex_1");+ });+});diff --git a/tests/core/brain.sessions.hermes.test.ts b/tests/core/brain.sessions.hermes.test.tsnew file mode 100644index 00000000..cae56879--- /dev/null+++ b/tests/core/brain.sessions.hermes.test.ts@@ -0,0 +1,76 @@+/**+ * Hermes .jsonl adapter tests.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { hermesAdapter } from "../../src/core/brain/sessions/hermes.ts";+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";++const FIXTURE = resolve("tests/fixtures/sessions/hermes-minimal.jsonl");++function firstLine(path: string): string {+ return readFileSync(path, "utf8").split("\n")[0]!;+}++async function collect(path: string): Promise<SessionTurn[]> {+ const out: SessionTurn[] = [];+ for await (const t of hermesAdapter.iterate(path)) out.push(t);+ return out;+}++describe("hermesAdapter.detect", () => {+ test("matches its own format", () => {+ expect(hermesAdapter.detect(firstLine(FIXTURE))).toBe(true);+ });++ test("rejects codex first line (different role shape)", () => {+ expect(+ hermesAdapter.detect(+ '{"timestamp":"x","type":"session_meta","payload":{"originator":"codex_exec"}}',+ ),+ ).toBe(false);+ });++ test("rejects claude first line", () => {+ expect(hermesAdapter.detect('{"type":"queue-operation","operation":"x"}')).toBe(false);+ });++ test("requires 'tools' array on the meta line", () => {+ expect(hermesAdapter.detect('{"role":"session_meta"}')).toBe(false);+ expect(+ hermesAdapter.detect('{"role":"session_meta","tools":"not-an-array"}'),+ ).toBe(false);+ });+});++describe("hermesAdapter.iterate", () => {+ test("yields user and assistant turns, skips session_meta and tool roles", async () => {+ const turns = await collect(FIXTURE);+ expect(turns.filter((t) => t.role === "user").length).toBe(1);+ expect(turns.filter((t) => t.role === "assistant").length).toBe(2);+ expect(turns.some((t) => t.role === "meta")).toBe(false);+ expect(turns.some((t) => t.role === "tool")).toBe(false);+ });++ test("user text contains the @osb marker", async () => {+ const turns = await collect(FIXTURE);+ const user = turns.find((t) => t.role === "user");+ expect(user?.text).toContain("@osb feedback negative");+ });++ test("parses tool_calls block, decoding JSON arguments", async () => {+ const turns = await collect(FIXTURE);+ const withTool = turns.find((t) => (t.toolCalls?.length ?? 0) > 0);+ expect(withTool).toBeDefined();+ const call = withTool!.toolCalls![0]!;+ expect(call.name).toBe("brain_feedback");+ expect(call.input).toMatchObject({+ topic: "mocking",+ signal: "negative",+ });+ expect(call.id).toBe("call_hermes_1");+ });+});diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.tsnew file mode 100644index 00000000..00ad9dde--- /dev/null+++ b/tests/core/brain.sessions.import.test.ts@@ -0,0 +1,187 @@+/**+ * Orchestrator tests for `o2b brain import-session`.+ *+ * Validates the cross-cutting behaviours: marker + tool_use replay+ * extraction, dedup by hash, dedup on re-run, directory walk,+ * autodetect failure, and the dry-run mode.+ */++import { afterEach, beforeEach, 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 { brainDirs } from "../../src/core/brain/paths.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import {+ importSession,+ importSessionPath,+} from "../../src/core/brain/sessions/import.ts";+import { SessionImportError } from "../../src/core/brain/sessions/types.ts";++const CLAUDE = resolve("tests/fixtures/sessions/claude-minimal.jsonl");+const CODEX = resolve("tests/fixtures/sessions/codex-minimal.jsonl");+const HERMES = resolve("tests/fixtures/sessions/hermes-minimal.jsonl");++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-import-"));+ const dirs = brainDirs(tmp);+ for (const d of [dirs.brain, dirs.inbox, dirs.processed, dirs.preferences, dirs.retired, dirs.log, dirs.snapshots]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("importSession", () => {+ test("creates signals from @osb markers in claude user messages", async () => {+ const res = await importSession(tmp, CLAUDE, { agent: "test" });+ expect(res.format).toBe("claude");+ expect(res.signals_created).toBeGreaterThan(0);+ });++ test("creates signals from tool_use brain_feedback replays", async () => {+ const res = await importSession(tmp, CLAUDE, { agent: "test" });+ // The fixture has 1 marker AND 1 tool_use with the same NORMALISED+ // payload-but-different `principle` text. They are distinct+ // dedup_hashes, so we expect 2 signals.+ expect(res.signals_created).toBe(2);+ expect(res.tool_replays).toBe(1);+ });++ test("dedups when marker and tool_use have identical payloads", async () => {+ // Build a fixture where both have the same principle string.+ const fixturePath = join(tmp, "matched.jsonl");+ writeFileSync(+ fixturePath,+ [+ '{"type":"queue-operation","timestamp":"2026-05-16T10:00:00.000Z","sessionId":"x"}',+ '{"parentUuid":null,"sessionId":"x","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"@osb feedback negative topic=match principle=\\"same-principle\\""},"uuid":"u1","timestamp":"2026-05-16T10:00:01.000Z"}',+ '{"parentUuid":"u1","sessionId":"x","entrypoint":"sdk-cli","type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"tu-1","name":"brain_feedback","input":{"topic":"match","signal":"negative","principle":"same-principle"}}]},"uuid":"a1","timestamp":"2026-05-16T10:00:02.000Z"}',+ "",+ ].join("\n"),+ );+ const res = await importSession(tmp, fixturePath, { agent: "test" });+ expect(res.signals_created).toBe(1);+ expect(res.signals_deduped).toBe(1);+ });++ test("is idempotent on re-run (zero new signals)", async () => {+ const first = await importSession(tmp, CLAUDE, { agent: "test" });+ expect(first.signals_created).toBeGreaterThan(0);+ const second = await importSession(tmp, CLAUDE, { agent: "test" });+ expect(second.signals_created).toBe(0);+ expect(second.signals_deduped).toBe(first.signals_created);+ });++ test("dry-run does not write signals", async () => {+ const res = await importSession(tmp, CLAUDE, { agent: "test", dryRun: true });+ expect(res.signals_created).toBe(0);+ const inbox = readdirSync(brainDirs(tmp).inbox).filter((n) => n.startsWith("sig-"));+ expect(inbox.length).toBe(0);+ });++ test("handles the codex fixture", async () => {+ const res = await importSession(tmp, CODEX, { agent: "test" });+ expect(res.format).toBe("codex");+ expect(res.signals_created).toBeGreaterThan(0);+ });++ test("handles the hermes fixture and stamps agent from session profile", async () => {+ const res = await importSession(tmp, HERMES, { agent: "test" });+ expect(res.format).toBe("hermes");+ expect(res.signals_created).toBeGreaterThan(0);+ });++ test("throws SessionImportError(DETECT_FAIL) on unknown format", async () => {+ const junk = join(tmp, "junk.jsonl");+ writeFileSync(junk, '{"foo":"bar"}\n');+ let caught: unknown;+ try {+ await importSession(tmp, junk, { agent: "test" });+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(SessionImportError);+ expect((caught as SessionImportError).code).toBe("DETECT_FAIL");+ });++ test("counts malformed @osb marker attempts in session text", async () => {+ const fixturePath = join(tmp, "malformed-marker.jsonl");+ writeFileSync(+ fixturePath,+ [+ '{"parentUuid":null,"sessionId":"x","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"@osb feedback negative topic=missing-principle"},"uuid":"u1","timestamp":"2026-05-16T10:00:01.000Z"}',+ "",+ ].join("\n"),+ );+ const res = await importSession(tmp, fixturePath, { agent: "test" });+ expect(res.signals_created).toBe(0);+ expect(res.malformed).toBe(1);+ });++ test("--format override bypasses autodetect", async () => {+ const junk = join(tmp, "junk.jsonl");+ writeFileSync(junk, '{"foo":"bar"}\n');+ // Should not throw β adapter chosen explicitly, iteration just+ // yields nothing.+ const res = await importSession(tmp, junk, { agent: "test", format: "claude" });+ expect(res.format).toBe("claude");+ expect(res.signals_created).toBe(0);+ });+});++describe("importSessionPath (directory walk)", () => {+ test("processes every jsonl in a directory", async () => {+ const dir = join(tmp, "sessions");+ mkdirSync(dir, { recursive: true });+ // Hand-link the fixtures so each file matches a different adapter.+ writeFileSync(+ join(dir, "a.jsonl"),+ [+ '{"parentUuid":null,"sessionId":"x","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"@osb feedback negative topic=dir-a principle=p"},"uuid":"u","timestamp":"2026-05-16T10:00:00Z"}',+ "",+ ].join("\n"),+ );+ writeFileSync(+ join(dir, "b.jsonl"),+ [+ '{"role":"session_meta","tools":[]}',+ '{"role":"user","content":"@osb feedback negative topic=dir-b principle=p","timestamp":"2026-05-16T10:00:00"}',+ "",+ ].join("\n"),+ );+ const result = await importSessionPath(tmp, dir, { agent: "test" });+ expect(result.files.length).toBe(2);+ const created = result.files.reduce((s, r) => s + r.signals_created, 0);+ expect(created).toBe(2);+ });++ test("skips unknown-format files with a warning entry", async () => {+ const dir = join(tmp, "mixed");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "junk.jsonl"), '{"foo":"bar"}\n');+ writeFileSync(+ join(dir, "valid.jsonl"),+ [+ '{"parentUuid":null,"sessionId":"x","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"@osb feedback negative topic=mixed principle=p"},"uuid":"u","timestamp":"2026-05-16T10:00:00Z"}',+ "",+ ].join("\n"),+ );+ const result = await importSessionPath(tmp, dir, { agent: "test" });+ expect(result.files.length).toBe(1);+ expect(result.warnings.length).toBe(1);+ });+});diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.tsnew file mode 100644index 00000000..ad409fba--- /dev/null+++ b/tests/core/brain.sessions.registry.test.ts@@ -0,0 +1,57 @@+/**+ * Adapter registry + autodetect β cross-table tests to confirm no+ * adapter mis-recognises a foreign format.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import {+ detectAdapter,+ getAdapter,+ SESSION_ADAPTERS,+} from "../../src/core/brain/sessions/registry.ts";++const FIXTURES = {+ claude: resolve("tests/fixtures/sessions/claude-minimal.jsonl"),+ codex: resolve("tests/fixtures/sessions/codex-minimal.jsonl"),+ hermes: resolve("tests/fixtures/sessions/hermes-minimal.jsonl"),+};++function firstLine(path: string): string {+ return readFileSync(path, "utf8").split("\n")[0]!;+}++describe("registry β single source of adapters", () => {+ test("exposes all three adapters", () => {+ const ids = SESSION_ADAPTERS.map((a) => a.id).sort();+ expect(ids).toEqual(["claude", "codex", "hermes"]);+ });++ test("getAdapter returns each by id", () => {+ expect(getAdapter("claude").id).toBe("claude");+ expect(getAdapter("codex").id).toBe("codex");+ expect(getAdapter("hermes").id).toBe("hermes");+ });+});++describe("detectAdapter β autodetect across all three formats", () => {+ test("picks claude on the claude fixture", () => {+ expect(detectAdapter(firstLine(FIXTURES.claude))?.id).toBe("claude");+ });+ test("picks codex on the codex fixture", () => {+ expect(detectAdapter(firstLine(FIXTURES.codex))?.id).toBe("codex");+ });+ test("picks hermes on the hermes fixture", () => {+ expect(detectAdapter(firstLine(FIXTURES.hermes))?.id).toBe("hermes");+ });++ test("returns null on unknown JSON", () => {+ expect(detectAdapter(`{"foo":"bar"}`)).toBeNull();+ });++ test("returns null on non-JSON garbage", () => {+ expect(detectAdapter("not json at all")).toBeNull();+ });+});diff --git a/tests/core/brain.sessions.types.test.ts b/tests/core/brain.sessions.types.test.tsnew file mode 100644index 00000000..b1b9d959--- /dev/null+++ b/tests/core/brain.sessions.types.test.ts@@ -0,0 +1,58 @@+/**+ * Tests for `sessions/types.ts` β the session-import adapter contract.+ */++import { describe, expect, test } from "bun:test";++import {+ SessionImportError,+ type SessionAdapter,+ type SessionToolCall,+ type SessionTurn,+} from "../../src/core/brain/sessions/types.ts";++describe("SessionImportError", () => {+ test("carries a typed code", () => {+ const err = new SessionImportError("DETECT_FAIL", "no adapter recognised this file");+ expect(err).toBeInstanceOf(Error);+ expect(err.name).toBe("SessionImportError");+ expect(err.code).toBe("DETECT_FAIL");+ });++ test("supports IO and PARSE codes", () => {+ expect(new SessionImportError("IO", "read failed").code).toBe("IO");+ expect(new SessionImportError("PARSE", "json garbled").code).toBe("PARSE");+ });+});++describe("SessionAdapter / SessionTurn / SessionToolCall shape (compile-time)", () => {+ test("a minimal stub adapter satisfies the interface", () => {+ const stub: SessionAdapter = {+ id: "claude",+ detect: () => false,+ iterate: async function* (_path: string) {+ void _path;+ /* empty */+ },+ };+ expect(stub.id).toBe("claude");+ });++ test("SessionTurn shape compiles with optional fields", () => {+ const turn: SessionTurn = {+ turnId: "t1",+ timestamp: "2026-05-16T00:00:00Z",+ role: "user",+ };+ expect(turn.role).toBe("user");+ expect(turn.text).toBeUndefined();+ });++ test("SessionToolCall shape compiles", () => {+ const call: SessionToolCall = {+ name: "brain_feedback",+ input: { topic: "t", signal: "negative", principle: "p" },+ };+ expect(call.name).toBe("brain_feedback");+ });+});diff --git a/tests/core/brain.sessions.validate-feedback.test.ts b/tests/core/brain.sessions.validate-feedback.test.tsnew file mode 100644index 00000000..39aab021--- /dev/null+++ b/tests/core/brain.sessions.validate-feedback.test.ts@@ -0,0 +1,99 @@+/**+ * Tests for `validateBrainFeedbackInput` β the pure validator shared+ * between the MCP layer (`toolBrainFeedback`) and the Β§16 session+ * importer that replays `brain_feedback` tool_use calls.+ */++import { describe, expect, test } from "bun:test";++import { validateBrainFeedbackInput } from "../../src/core/brain/sessions/validate-feedback.ts";++describe("validateBrainFeedbackInput", () => {+ test("accepts a minimal valid payload", () => {+ const r = validateBrainFeedbackInput({+ topic: "no-internal-abbrev",+ signal: "negative",+ principle: "Do not use internal abbreviations",+ });+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.value.topic).toBe("no-internal-abbrev");+ expect(r.value.signal).toBe("negative");+ expect(r.value.principle).toBe("Do not use internal abbreviations");+ }+ });++ test("accepts optional scope / agent / raw", () => {+ const r = validateBrainFeedbackInput({+ topic: "t",+ signal: "positive",+ principle: "p",+ scope: "writing",+ agent: "claude",+ raw: "quoted text",+ });+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.value.scope).toBe("writing");+ expect(r.value.agent).toBe("claude");+ expect(r.value.raw).toBe("quoted text");+ }+ });++ test("rejects when topic is missing", () => {+ const r = validateBrainFeedbackInput({ signal: "negative", principle: "p" });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/topic/);+ });++ test("rejects when signal is missing", () => {+ const r = validateBrainFeedbackInput({ topic: "t", principle: "p" });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/signal/);+ });++ test("rejects when principle is missing", () => {+ const r = validateBrainFeedbackInput({ topic: "t", signal: "negative" });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/principle/);+ });++ test("rejects empty-string required fields", () => {+ const r = validateBrainFeedbackInput({+ topic: "",+ signal: "negative",+ principle: "p",+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/topic/);+ });++ test("rejects invalid signal enum value", () => {+ const r = validateBrainFeedbackInput({+ topic: "t",+ signal: "maybe",+ principle: "p",+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/signal/);+ });++ test("rejects non-string types", () => {+ const r = validateBrainFeedbackInput({+ topic: 42,+ signal: "negative",+ principle: "p",+ });+ expect(r.ok).toBe(false);+ });++ test("rejects null / undefined input", () => {+ expect(validateBrainFeedbackInput(null).ok).toBe(false);+ expect(validateBrainFeedbackInput(undefined).ok).toBe(false);+ });++ test("rejects non-object scalar input", () => {+ expect(validateBrainFeedbackInput("not an object").ok).toBe(false);+ expect(validateBrainFeedbackInput(123).ok).toBe(false);+ });+});diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.tsindex 3b7b7bb2..42fc7578 100644--- a/tests/core/brain.signal.test.ts+++ b/tests/core/brain.signal.test.ts@@ -257,3 +257,83 @@ describe("writeSignal β sanitisation (Β§7)", () => {).toThrow(/signal missing field: principle/);});});++// ββ Β§9 / Β§16: source_type / dedup_hash / session_ref βββββββββββββββββββββββββ++describe("writeSignal β capture-extension fields (Β§9/Β§16)", () => {+ test("records source_type / dedup_hash / session_ref when provided", () => {+ const r = writeSignal(+ tmp,+ baseInput({+ slug: "ext-fields",+ source_type: "inline",+ dedup_hash: "deadbeef".repeat(8),+ session_ref: "Daily/2026-05-14.md#turn-7",+ }),+ );+ const raw = readFileSync(r.path, "utf8");+ expect(raw).toMatch(/^source_type: inline$/m);+ expect(raw).toMatch(/^dedup_hash: deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef$/m);+ expect(raw).toMatch(/^session_ref: /m);+ });++ test("adds brain/source/<type> tag when source_type is 'inline'", () => {+ const r = writeSignal(+ tmp,+ baseInput({ slug: "inline-tag", source_type: "inline" }),+ );+ const raw = readFileSync(r.path, "utf8");+ expect(raw).toMatch(/brain\/source\/inline/);+ });++ test("adds brain/source/<type> tag when source_type is 'session'", () => {+ const r = writeSignal(+ tmp,+ baseInput({ slug: "session-tag", source_type: "session" }),+ );+ const raw = readFileSync(r.path, "utf8");+ expect(raw).toMatch(/brain\/source\/session/);+ });++ test("omits brain/source/* tag when source_type is 'live' (default)", () => {+ const r = writeSignal(tmp, baseInput({ slug: "live-default" }));+ const raw = readFileSync(r.path, "utf8");+ expect(raw).not.toMatch(/brain\/source\//);+ });++ test("parseSignal round-trips source_type / dedup_hash / session_ref", () => {+ const r = writeSignal(+ tmp,+ baseInput({+ slug: "roundtrip",+ source_type: "session",+ dedup_hash: "abc123",+ session_ref: "claude.jsonl#abc",+ }),+ );+ const parsed = parseSignal(r.path);+ expect(parsed.source_type).toBe("session");+ expect(parsed.dedup_hash).toBe("abc123");+ expect(parsed.session_ref).toBe("claude.jsonl#abc");+ });++ test("parseSignal returns undefined for capture-extension fields when absent (legacy file)", () => {+ const r = writeSignal(tmp, baseInput({ slug: "no-ext-fields" }));+ const parsed = parseSignal(r.path);+ expect(parsed.source_type).toBeUndefined();+ expect(parsed.dedup_hash).toBeUndefined();+ expect(parsed.session_ref).toBeUndefined();+ });++ test("rejects unknown source_type values", () => {+ expect(() =>+ writeSignal(+ tmp,+ baseInput({+ slug: "bad-source-type",+ source_type: "bogus" as unknown as "live",+ }),+ ),+ ).toThrow(/source_type/);+ });+});diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.tsindex bc310525..effaaf26 100644--- a/tests/core/brain.types.test.ts+++ b/tests/core/brain.types.test.ts@@ -54,7 +54,7 @@ describe("BRAIN_* const enums", () => {expect(BRAIN_APPLY_RESULT.outdated).toBe("outdated");});- test("BRAIN_LOG_EVENT_KIND covers every event type listed in Β§5.5 / Β§7.4", () => {+ test("BRAIN_LOG_EVENT_KIND covers every event type listed in Β§5.5 / Β§7.4 + capture-extensions Β§9/Β§16/Β§24", () => {const expected = new Set<string>(["dream","feedback",@@ -69,6 +69,10 @@ describe("BRAIN_* const enums", () => {"pin","unpin","rollback",+ // capture extensions + frontmatter migration+ "scan-inline",+ "import-session",+ "migrate-frontmatter",]);const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));expect(actual).toEqual(expected);diff --git a/tests/e2e/brain-capture-and-fields.test.ts b/tests/e2e/brain-capture-and-fields.test.tsnew file mode 100644index 00000000..67926dd0--- /dev/null+++ b/tests/e2e/brain-capture-and-fields.test.ts@@ -0,0 +1,149 @@+/**+ * End-to-end scenario for the capture extensions + frontmatter migration.+ *+ * Exercises the full chain across CLI invocations:+ * 1. `o2b init` + `o2b brain init` bootstrap a fresh vault.+ * 2. A Daily note with an `@osb` marker is dropped on disk.+ * 3. `o2b brain scan-inline` captures the marker into Brain/inbox/+ * and annotates the Daily note with `@osbβ [[sig-...]]`.+ * 4. The session import path picks up the same marker shape from a+ * transcript fixture (different topic to confirm independence).+ * 5. `o2b brain migrate-frontmatter --apply --yes` rewrites a+ * hand-crafted legacy-shape pref file into the `_`-prefixed+ * form and lands a snapshot under Brain/.snapshots/.+ * 6. `o2b brain rollback <run_id>` restores the pre-migration shape.+ *+ * If any step fails, the chain breaks and we see which seam is broken.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-capture-fields-e2e-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("capture + migration end-to-end", () => {+ test("inline scan β session import β migrate β rollback", async () => {+ // Step 1: bootstrap+ let r = await runCli(["init", "--vault", vault, "--name", "Test"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ r = await runCli(["brain", "init", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);++ // Step 2: drop a Daily note with an inline marker+ mkdirSync(join(vault, "Daily"), { recursive: true });+ const dailyPath = join(vault, "Daily", "2026-05-16.md");+ writeFileSync(+ dailyPath,+ [+ "# Daily notes",+ "",+ "@osb feedback negative topic=e2e-inline principle=\"no e2e shortcuts\"",+ "",+ ].join("\n"),+ "utf8",+ );++ // Step 3: scan-inline captures + rewrites+ r = await runCli(["brain", "scan-inline", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toMatch(/created: 1/);+ expect(readFileSync(dailyPath, "utf8")).toMatch(/@osbβ \[\[sig-/);++ const inbox = join(vault, "Brain", "inbox");+ const inlineSigs = readdirSync(inbox).filter((n) => n.startsWith("sig-"));+ expect(inlineSigs.length).toBe(1);++ // Step 4: import-session adds an independent signal from the+ // claude fixture (topic=mocking, distinct from e2e-inline).+ const fixturePath = resolve("tests/fixtures/sessions/claude-minimal.jsonl");+ r = await runCli(+ ["brain", "import-session", fixturePath, "--vault", vault],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);++ const sigsAfterImport = readdirSync(inbox).filter((n) => n.startsWith("sig-"));+ expect(sigsAfterImport.length).toBeGreaterThan(inlineSigs.length);++ // Step 5: hand-write a legacy-shape preference, then migrate.+ const legacyPrefPath = join(vault, "Brain", "preferences", "pref-legacy-e2e.md");+ writeFileSync(+ legacyPrefPath,+ [+ "---",+ "kind: brain-preference",+ "id: pref-legacy-e2e",+ "created_at: 2026-05-14T10:42:00Z",+ "unconfirmed_until: 2026-05-28T10:42:00Z",+ "tags: [brain, brain/preference, brain/topic/legacy-e2e]",+ "topic: legacy-e2e",+ "principle: Some rule",+ "pinned: false",+ "status: confirmed",+ "confirmed_at: 2026-05-15T10:00:00Z",+ "evidenced_by: []",+ "applied_count: 1",+ "violated_count: 0",+ "last_evidence_at: null",+ "confidence: low",+ "---",+ "",+ ].join("\n"),+ "utf8",+ );+ r = await runCli(+ ["brain", "migrate-frontmatter", "--vault", vault, "--apply", "--yes"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const afterMigrate = readFileSync(legacyPrefPath, "utf8");+ expect(afterMigrate).toMatch(/^_status: confirmed$/m);+ expect(afterMigrate).not.toMatch(/^status: confirmed$/m);++ const snapDir = join(vault, "Brain", ".snapshots");+ const snaps = readdirSync(snapDir).filter((n) => n.startsWith("migrate-"));+ expect(snaps.length).toBe(1);++ // Step 6: rollback restores the legacy shape.+ const runId = snaps[0]!.replace(/\.tar\.zst$/, "");+ r = await runCli(+ ["brain", "rollback", runId, "--vault", vault, "--yes"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(existsSync(legacyPrefPath)).toBe(true);+ const afterRollback = readFileSync(legacyPrefPath, "utf8");+ expect(afterRollback).toMatch(/^status: confirmed$/m);+ expect(afterRollback).not.toMatch(/^_status: confirmed$/m);+ }, 60_000);+});diff --git a/tests/fixtures/sessions/claude-minimal.jsonl b/tests/fixtures/sessions/claude-minimal.jsonlnew file mode 100644index 00000000..63c8a73f--- /dev/null+++ b/tests/fixtures/sessions/claude-minimal.jsonl@@ -0,0 +1,5 @@+{"type":"queue-operation","operation":"enqueue","timestamp":"2026-05-16T10:00:00.100Z","sessionId":"00000000-0000-0000-0000-000000000001","content":"How should I handle DB mocking?"}+{"parentUuid":null,"isSidechain":false,"promptId":"fake-prompt-1","type":"user","message":{"role":"user","content":"How should I handle DB mocking?\n@osb feedback negative topic=mocking principle=\"don't mock DB in integration tests\" scope=testing"},"uuid":"turn-user-1","timestamp":"2026-05-16T10:00:00.200Z","permissionMode":"default","userType":"external","entrypoint":"sdk-cli","cwd":"/tmp","sessionId":"00000000-0000-0000-0000-000000000001","version":"2.1.126","gitBranch":"HEAD"}+{"parentUuid":"turn-user-1","isSidechain":false,"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"I'll record that as a preference."},{"type":"tool_use","id":"tu-1","name":"brain_feedback","input":{"topic":"mocking","signal":"negative","principle":"avoid mocking the database in integration tests","scope":"testing"}}]},"uuid":"turn-assistant-1","timestamp":"2026-05-16T10:00:01.000Z","sessionId":"00000000-0000-0000-0000-000000000001"}+{"type":"queue-operation","operation":"dequeue","timestamp":"2026-05-16T10:00:01.500Z","sessionId":"00000000-0000-0000-0000-000000000001"}+{"parentUuid":"turn-assistant-1","isSidechain":false,"type":"user","message":{"role":"user","content":"Thanks."},"uuid":"turn-user-2","timestamp":"2026-05-16T10:00:02.000Z","sessionId":"00000000-0000-0000-0000-000000000001"}diff --git a/tests/fixtures/sessions/codex-minimal.jsonl b/tests/fixtures/sessions/codex-minimal.jsonlnew file mode 100644index 00000000..75ec4fb8--- /dev/null+++ b/tests/fixtures/sessions/codex-minimal.jsonl@@ -0,0 +1,5 @@+{"timestamp":"2026-05-16T10:00:00.000Z","type":"session_meta","payload":{"id":"00000000-0000-0000-0000-000000000002","timestamp":"2026-05-16T10:00:00.000Z","cwd":"/tmp","originator":"codex_exec","cli_version":"0.129.0","source":"exec","model_provider":"openai"}}+{"timestamp":"2026-05-16T10:00:00.100Z","type":"event_msg","payload":{"type":"task_started","turn_id":"turn-1","started_at":1778273962}}+{"timestamp":"2026-05-16T10:00:00.200Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"How should I handle DB mocking?\n@osb feedback negative topic=mocking principle=\"don't mock DB in integration tests\" scope=testing"}]}}+{"timestamp":"2026-05-16T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"I'll record that as a preference."}],"phase":"final_answer"}}+{"timestamp":"2026-05-16T10:00:01.100Z","type":"response_item","payload":{"type":"function_call","name":"brain_feedback","arguments":"{\"topic\":\"mocking\",\"signal\":\"negative\",\"principle\":\"avoid mocking the database in integration tests\",\"scope\":\"testing\"}","call_id":"call_codex_1"}}diff --git a/tests/fixtures/sessions/hermes-minimal.jsonl b/tests/fixtures/sessions/hermes-minimal.jsonlnew file mode 100644index 00000000..a8dfc6cf--- /dev/null+++ b/tests/fixtures/sessions/hermes-minimal.jsonl@@ -0,0 +1,5 @@+{"role": "session_meta", "tools": [{"type": "function", "function": {"name": "brain_feedback", "description": "Record a Brain taste signal"}}], "profile": "product-tech-lead"}+{"role": "user", "content": "How should I handle DB mocking?\n@osb feedback negative topic=mocking principle=\"don't mock DB in integration tests\" scope=testing", "timestamp": "2026-05-16T10:00:00.200000"}+{"role": "assistant", "content": "I'll record that as a preference.", "reasoning": null, "finish_reason": "stop", "timestamp": "2026-05-16T10:00:01.000000"}+{"role": "assistant", "content": "", "reasoning": null, "finish_reason": "tool_calls", "tool_calls": [{"id": "call_hermes_1", "call_id": "call_hermes_1", "type": "function", "function": {"name": "brain_feedback", "arguments": "{\"topic\":\"mocking\",\"signal\":\"negative\",\"principle\":\"avoid mocking the database in integration tests\",\"scope\":\"testing\"}"}}], "timestamp": "2026-05-16T10:00:01.500000"}+{"role": "tool", "content": "{\"ok\": true}", "timestamp": "2026-05-16T10:00:02.000000"}diff --git a/tests/mcp/resources.test.ts b/tests/mcp/resources.test.tsindex 49837e99..e13db859 100644--- a/tests/mcp/resources.test.ts+++ b/tests/mcp/resources.test.ts@@ -375,6 +375,42 @@ describe("MCP resources β read osb://status", () => {expect(text).toContain("confirmed: 1");expect(text).toContain("## Activity");});++ test("file with both 'status:' and '_status:' counts as unknown (collision policy)", async () => {+ // Hand-write a file carrying both shapes β same collision policy+ // as parsePreference / brain_doctor, so the status reader must+ // not silently pick one and hide the corruption.+ const path = `${vault}/Brain/preferences/pref-double-shape.md`;+ const { writeFileSync } = await import("node:fs");+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ "id: pref-double-shape",+ "created_at: 2026-05-01T00:00:00Z",+ "unconfirmed_until: 2026-05-30T00:00:00Z",+ "tags: [brain, brain/preference, brain/topic/double]",+ "topic: double",+ "principle: Rule",+ "pinned: false",+ "status: confirmed",+ "_status: confirmed",+ "evidenced_by: []",+ "---",+ "",+ ].join("\n"),+ "utf8",+ );++ const server = makeServer();+ await initialize(server);+ const r = await read(server, "osb://status");+ const text = r.result.contents[0].text as string;+ expect(text).toContain("preferences: 1");+ expect(text).toContain("unknown: 1");+ expect(text).not.toContain("confirmed: 1");+ });});describe("MCP resources β read osb://backlinks/{id}", () => {