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
feat: runtime schema packs foundation - schema vocabulary, artifact taxonomy, schema inspection (#52)
Sol Aitkenf62918ccbbf7
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 7ccc86cb..92869475 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.24.0",+ "version": "0.25.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 042d6fe3..8d2e913d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.24.0",+ "version": "0.25.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4535a61c..9e8a3284 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,29 @@ 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.25.0] - 2026-05-30++Runtime schema packs foundation. Vaults can now declare custom taxonomy tokens+in `Brain/_brain.yaml` and inspect resolved schema usage without introducing a+mutation-heavy registry or changing deterministic dream behavior.++### Added++- Shared runtime schema vocabulary boundary with built-in `preference`,+ `feedback`, `note`, and Brain log event kinds plus deterministic+ normalization and validation for optional `_brain.yaml schema:` declarations.+- Optional inert `schema_type:` metadata on preferences, retired preferences,+ and signals. Writers omit the field unless supplied; parsers normalize token+ shape and can validate against a resolved vocabulary when callers opt in.+- Read-only schema inspection report plus `o2b brain schema [--json]`, showing+ resolved vocabulary, artifact token usage, unknown tokens, and unused custom+ declarations.++### Notes++- Full schema mutation primitives, MCP admin operations, schema-author skill,+ and lifecycle/control enum widening remain deferred behind the foundation ADR.+## [0.24.0] - 2026-05-30Brain model semantics foundation. Preferences can now carry explicit typed@@ -2159,7 +2182,7 @@ with `source_type: inline`, the source-file wikilink in `source`,and a `dedup_hash`over the normalised payload. After capturethe 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+ [[sig-...]] -->`comment line (block form), making re-runsidempotent. Default ignore set covers`Brain/`, `.git`,`node_modules`, `.obsidian`, `.trash`, `.stversions`,`.open-second-brain`; additional excludes via `--exclude`,diff --git a/README.md b/README.mdindex de2f22cd..0278df43 100644--- a/README.md+++ b/README.md@@ -106,7 +106,7 @@ The capabilities you actually feel day to day:| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows; `brain_agent_query` and `brain_agent_diff` let you inspect which agent contributed what. || 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osbβ` checkmark so re-runs skip it. || 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` / `monthly` summarise what changed; `o2b brain intent-review` previews whether signal clusters are ready before the next `dream`; `o2b brain retention` recommends keep/improve/park/prune actions without deleting anything. |-| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Preference files can now declare typed relationships such as `depends_on:` and `refines:`, plus `memory_layer` / `memory_branch` labels, and the explorer surfaces those semantics without changing the Markdown source of truth. Double-click a node β Obsidian opens the underlying note. |+| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Preference files can now declare typed relationships such as `depends_on:` and `refines:`, plus `memory_layer` / `memory_branch` labels and optional `schema_type:` taxonomy metadata; `o2b brain schema` audits those tokens without changing the Markdown source of truth. Double-click a node β Obsidian opens the underlying note. || 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. || 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. || 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |@@ -128,6 +128,7 @@ o2b brain monthly --month 2026-05 --json # Month-level Brain synthesiso2b brain audit pref-foo --json # Full mutation trail for one preferenceo2b brain morning-brief --json # Session-start summary (prefs, open questions, notes)o2b brain sources --json # Per-source signal dashboard+o2b brain schema --json # Runtime schema vocabulary + usage reporto2b brain graph-export --out graph.json # Export the vault knowledge grapho2b brain semantics-backfill --json # Dry-run typed preference-edge repair proposalso2b vault profile switch work # Activate a named multi-vault profilediff --git a/docs/brainstorm/runtime-schema-packs-foundation/adr.md b/docs/brainstorm/runtime-schema-packs-foundation/adr.mdnew file mode 100644index 00000000..108f43df--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/adr.md@@ -0,0 +1,30 @@+# ADR: Runtime schema packs live in `_brain.yaml` first++## Status++Accepted for the Runtime Schema Packs Foundation PR.++## Context++The upstream schema-pack tasks describe a broad system: runtime-declared page/take kinds, atomic mutation primitives, MCP/admin operations, CLI authoring verbs, locks, audit logs, and an agent-facing schema-author workflow. Open Second Brain currently keeps Brain state in plain Markdown plus a small `_brain.yaml` policy file. Several core vocabularies are closed `as const` objects because deterministic algorithms depend on exhaustive state handling.++Recent work added `relation-vocab.ts`, a successful single validation boundary where adding a relation token is data-driven and migration-free. The schema-pack foundation should use that lesson without turning every operational enum into an arbitrary string.++## Decision++For the first schema-pack release, store user-declared schema vocabulary in an optional `schema:` block inside `Brain/_brain.yaml` and resolve it through one shared Brain schema vocabulary module. The release is read-only/introspection-first: it can validate declarations, parse inert schema metadata on Brain artifacts, and report declared-vs-used tokens, but it does not mutate schema packs or change `dream` lifecycle behavior.++Operational lifecycle enums remain closed in this PR. Custom schema tokens are taxonomy metadata, not alternate states for `dream`, retire, apply-evidence, or audit state machines.++## Consequences++- Default vaults remain byte-compatible: no `schema:` block means built-in vocabulary only.+- Future mutation primitives have a clear target: editing `_brain.yaml`'s `schema:` block with atomic config writes and validation.+- The implementation avoids a second schema store and avoids a heavy YAML dependency.+- The foundation does not yet satisfy the full Schema Cathedral surface. That is intentional; mutation, locks, admin MCP tools, and schema-author workflow need a later PR.++## Rejected alternatives++- **Dedicated `Brain/_schema/` registry.** More faithful to the upstream system, but it adds a second store and active-pack lifecycle before Open Second Brain has proven the user-facing need.+- **Pure in-code widening.** Lowest implementation risk, but it would ship almost no operator-visible capability.+- **Opening lifecycle enums immediately.** Too risky: `preference.status`, retire reasons, apply results, and log event kinds drive deterministic control flow. Arbitrary user tokens there need separate designs for every consuming algorithm.diff --git a/docs/brainstorm/runtime-schema-packs-foundation/cli-output/claude.md b/docs/brainstorm/runtime-schema-packs-foundation/cli-output/claude.mdnew file mode 100644index 00000000..03a3fd71--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/cli-output/claude.md@@ -0,0 +1,39 @@+### Variant 1: `_brain.yaml` schema block + shared vocabulary boundary++- **Approach**: Add one optional `schema:` block to `_brain.yaml` that declares user extensions to the otherwise-closed vocabularies (custom preference categories/scopes, extra signal source types, custom log/event kinds, custom page/note types). Resolve it through a single new `schema-vocab.ts` boundary modeled on `relation-vocab.ts`: built-in `as const` defaults are frozen, declared extensions are merged in, and `isKnown*` predicates replace compile-time exhaustiveness at the SQL/frontmatter narrowing points. Ship read-only introspection only β a `o2b brain schema --json` verb and a `doctor` lint that reports declared-vs-used types β and defer all mutation.+- **Trade-offs**:+ - Pro: Reuses the established data-driven single-boundary pattern (`relation-vocab.ts`) and the forward-compat resolver pattern already in `policy.ts`; no new parser, no second store.+ - Pro: Default install stays byte-identical (absent `schema:` block β resolver returns frozen built-in defaults, predicates behave exactly as the current closed unions).+ - Pro: The child's 11 mutation primitives become "edit one `schema:` block" β a clean, bounded extension point that needs no architectural change later.+ - Con: The tiny indent-aware YAML parser must grow to carry richer declarations (lists of maps for typed entries), or declarations must be flattened into the existing two-level shape.+ - Con: One config block as the home for several distinct vocabularies risks an awkward schema if the kinds diverge.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Dedicated schema-pack registry under `Brain/_schema/`++- **Approach**: Introduce a first-class schema-pack concept living in its own vault location (a `Brain/_schema/` directory of pack markdown files, or a single `Brain/_schema.yaml`), with an active-pack selector and a pack loader/registry that the core vocabularies consult at runtime. This mirrors gbrain's schema-pack model most faithfully and gives the future Schema Cathedral a natural home (pack-lock, mutate-audit, multi-pack switching). The foundation slice ships the loader, the registry, active-pack resolution, and read-only introspection/lint; mutation stays out.+- **Trade-offs**:+ - Pro: Most faithful to the upstream design; the full child surface (pack-lock, per-pack stats, switching) drops in without re-architecting.+ - Pro: Cleanly separates schema declarations from runtime tuning knobs in `_brain.yaml`.+ - Con: Directly tensions the "do not add a second graph or a parallel hidden schema store" constraint β a dedicated registry is a new store with its own format and lifecycle.+ - Con: Largest surface for a bounded PR; introduces pack selection/precedence semantics the foundation doesn't strictly need.+ - Con: Higher chance of accidentally widening legacy fixtures, since a new store changes how every vocabulary resolves.+- **Complexity**: large+- **Risk**: medium++### Variant 3: In-code union widening with built-in extension points only++- **Approach**: Widen the closed `as const` unions to typed-string with a centralized known-set (extending the tolerance pattern already used by `PrefAuditOp` and the log-kind reader), narrowing at SQL-row/frontmatter boundaries via `isKnown*` predicates β but expose no user-facing declaration surface this PR. The vocabulary is seeded purely from built-in defaults; introspection reports those built-ins. This delivers exactly gbrain's "widen casts, validate at runtime" type-system change and leaves the declaration mechanism entirely to the child.+- **Trade-offs**:+ - Pro: Smallest, lowest-risk change; touches only the type boundary, no config or YAML changes at all.+ - Pro: Makes the eventual declaration mechanism trivial β predicates and narrowing points already exist.+ - Pro: Easiest to prove default/legacy behavior is unchanged, since there is no new input surface.+ - Con: Delivers no user-observable value (no custom types yet) β it is a pure refactor that opens a door without a way to walk through it.+ - Con: Risks designing the predicate seam without a concrete declaration consumer, so the child PR may still need to reshape it.+- **Complexity**: small+- **Risk**: low++### Recommended: Variant 1++**Rationale**: It satisfies every hard constraint β no second store, no heavy YAML, defaults byte-identical, one shared validation boundary, read-only-first β while reusing two patterns the codebase already trusts (`relation-vocab.ts` and the `policy.ts` optional-block resolver). Unlike Variant 3 it ships real custom-type capability, and unlike Variant 2 it keeps the foundation small and avoids a parallel schema store, while still giving the child's mutation primitives a clean target (the `schema:` block) to evolve.diff --git a/docs/brainstorm/runtime-schema-packs-foundation/cli-output/prompt.md b/docs/brainstorm/runtime-schema-packs-foundation/cli-output/prompt.mdnew file mode 100644index 00000000..d528ae8d--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/cli-output/prompt.md@@ -0,0 +1,132 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++This is a bounded multi-task PR for Open Second Brain. It combines the parent runtime schema-pack foundation with only the foundation slice of the child schema-pack mutation surface.++## Task 1: t_dc01c9f7 - [upstream:gbrain] Runtime-extensible schema packs with custom page types and take kinds++**Source**: https://github.com/garrytan/gbrain/commit/5a2bdd2+**Repo**: garrytan/gbrain (18439 stars)+**Commit**: 5a2bdd2 (2026-05-22T20:00:00Z) - PR #1248++### What++Schema packs: open PageType and TakeKind from closed unions to string types. Validation moves from compile-time exhaustiveness to runtime checks against the active schema pack. Schema packs declare custom page types at runtime (paper, researcher, therapy-session, apple-note, tweet-bundle). The engine accepts arbitrary user-declared types without schema migrations. 13 as PageType and 3 as TakeKind casts widen to as string, with runtime narrowing at SQL row boundaries.++### Why useful for Open Second Brain++Open Second Brain preferences use a fixed status enum (confirmed/quarantine/retired) and signal types are closed. A schema pack system would let users define custom preference categories, signal types, and log event kinds without modifying Open Second Brain source code. This would support domain-specific brain setups (for example, a research vault with paper/researcher types, or a project vault with milestone/decision types) while keeping the core stable.++### Status in Open Second Brain++- Verdict: not_in_osb_useful+- Codegraph hints: Open Second Brain preference types in src/core/brain/preference.ts, status in src/core/brain/status.ts, signal processing in src/core/brain/signal.ts. All use closed enums/unions. No runtime type declaration system or schema pack registry exists.++### Notes++The migration path from closed to open types is non-trivial. gbrain's approach of widening casts and moving validation to runtime is one pattern. Open Second Brain could start with a schema-pack registry file that declares allowed custom types, then validate against it at the MCP tool boundary.++Validator comments:++- parent of t_cbf4967f.+- priority 2.+- foundational change - opening closed PageType/TakeKind unions to runtime validation needs an ADR.++## Task 2: t_cbf4967f - [upstream:gbrain] Schema pack mutation primitives + 9 MCP ops + 14 CLI verbs + schema-author skill++**Source**: https://github.com/garrytan/gbrain/commit/3c1cc8a4d665d1c2557e3381a3213332d54a5ff8+**Repo**: garrytan/gbrain (18439 stars)+**Commit**: 3c1cc8a (2026-05-23T23:46:01Z)++### What++Schema Cathedral v3: production-grade schema pack authoring system with 11 mutation primitives (add_type, remove_type, update_type, add_alias, remove_alias, add_prefix, remove_prefix, add_link_type, remove_link_type, set_extractable, set_expert_routing), each wrapped in withMutation for atomic .tmp+fsync+rename operations with pre-write lint validation gates. Pack-lock provides atomic file-level locking with stale detection (TTL + liveness probe). 9 new MCP operations exposed for remote OAuth agents: get_active_schema_pack, list_schema_packs, schema_stats, schema_lint, schema_graph, schema_explain_type, schema_review_orphans (read-scope), schema_apply_mutations (admin-scope, batched), reload_schema_pack. 14 new CLI verbs for schema management. Stats command provides per-type counts, coverage scores, and dead-prefix detection. Sync command does chunked UPDATE (1000-row batches) for backfilling page.type. Schema-author skill with 36 trigger phrases routes agents to evolve schema packs via a 7-phase workflow (brain -> assess -> propose -> apply -> sync -> verify -> commit). Mutate-audit logs ISO-week JSONL with privacy redaction.++### Why useful for Open Second Brain++Open Second Brain preferences use fixed closed enums (confirmed/quarantine/retired status, fixed signal types). A schema pack system would let users define custom preference categories, signal types, and event kinds without modifying Open Second Brain source. The MCP operations would allow remote agents to evolve the brain schema over HTTPS, enabling multi-tenant federation. The mutation primitives with atomic guarantees and audit logging provide a production-safe path for schema evolution. The schema-author skill gives agents a discoverable workflow for taxonomy management.++### Status in Open Second Brain++- Verdict: not_in_osb_useful+- Codegraph hints: src/core/brain/preference.ts:92 (status method, closed enum); src/core/brain/dream.ts:191 (dream function); src/mcp/server.ts:56 (MCP tools registration); src/mcp/tools.ts:57 (ToolDefinition). No schema pack registry, no runtime type declaration system, no mutation primitives, no atomic pack-lock, no schema-author skill. Open Second Brain types are all compile-time closed unions.++### Notes++Related to existing task t_dc01c9f7 (runtime-extensible schema packs - opening PageType/TakeKind from closed unions). Schema Cathedral v3 goes much further: adds the full mutation + MCP + CLI + skill surface. If t_dc01c9f7 is implemented first, this task becomes a natural extension. The pack-lock atomic acquire pattern (openSync wx, TTL refresh, stale-steal) is reusable for any concurrent-write scenario in Open Second Brain.++Validator comments:++- child of t_dc01c9f7.+- priority 2.+- lowered because the 11-primitive + 9 MCP-op + 14 CLI-verb + skill surface is blocked by the parent and far exceeds one week; it cannot precede the foundation.++# Project context++Project: Open Second Brain+Language/runtime: TypeScript on Bun. Source of truth is plain Markdown under Brain/ in an Obsidian-compatible vault. The core Brain algorithms are deterministic; no LLM belongs in `dream` or core validation paths.++Recent commits:++- 14d1ee1 feat: brain model semantics foundation - typed preference relations, memory labels, dry-run backfill (#51)+- 3a5d5c3 feat: agent capability CLI integration - runtime MCP capabilities, inherited JSON, completions (#50)+- a085bfa feat: vault portability + session economy - codec, sources dashboard, vault-map tokens, multi-vault profiles, graph export/import (#49)+- 73e4a28 feat: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)+- bd49cd5 feat: recall and ranking quality - Weibull recency, query intent, synonym expansion, recall budgets, query cache, pre-compress pack (#47)+- cbbe18f feat: typed graph semantics - typed relations, visibility scoping, MCP landscape (#46)+- 5fa7eb0 feat: MCP context economy - preview budget, artifact fetch, recall hint (#45)+- 2bd3f48 v0.17.0 - Brain Lifecycle Review Suite (#44)+- 9b87838 v0.16.0 - Agent boundary control surfaces (#43)+- feca6a7 v0.15.0 - Cross-agent query foundation (#41)++Related files:++- src/core/brain/types.ts - closed `as const` vocabularies for signal sign/source type, preference status, confidence, memory layer, retired reason, apply result, and log event kind; `BrainConfig` type for `_brain.yaml`.+- src/core/brain/preference.ts - preference/retired parser and writer; validates status/folder invariants; recently added optional preference semantics fields.+- src/core/brain/signal.ts - signal writer/parser; validates signal sign/source type; keeps legacy signal frontmatter lean and byte-stable.+- src/core/brain/status.ts - status snapshot counts preference statuses, including unknown values, without mutating.+- src/core/brain/policy.ts - tiny indent-aware `_brain.yaml` parser/validator; no external YAML dependency; unknown top-level keys warn, sub-block keys warn; defaults are frozen.+- src/core/graph/relation-vocab.ts - recent example of a single data-driven validation boundary with default vocabulary and frontmatter classification.+- src/cli/brain/verbs/\*, src/cli/brain/help-text.ts, src/cli/command-manifest.ts - established CLI verb registration and read-only JSON patterns.+- tests/core/brain/_.test.ts and tests/cli/_ - test style: Bun tests, temp vault fixtures, byte-identical/back-compat checks.++Conventions:++- Additive, opt-in features should keep default installs byte-identical where practical.+- Prefer one shared validation boundary over duplicated token lists at call sites.+- Keep Markdown/YAML source-of-truth human-readable; do not add hidden state outside the vault for Brain semantics.+- Use structured APIs and existing helpers (`parseFrontmatter`, `formatFrontmatter`, `writeFrontmatterAtomic`, `validateSlug`, `brainDirs`) instead of ad hoc string parsing.+- Mutating Brain commands take snapshots and have dry-run/guardrails where they touch more than one file; this PR should avoid the full mutation surface unless clearly justified.+- CLI read verbs should support `--json` with stable structured output.+- Public docs use full project name, not abbreviations.+- Version bump happens before GitHub push per operator override.++Constraints:++- Do not implement the full Schema Cathedral surface in this PR. The bounded goal is a foundation that unblocks future mutation primitives, not 11 mutations + 9 MCP ops + 14 CLI verbs + schema-author skill.+- Do not break existing closed-core behavior: existing statuses/signals/log kinds must continue to validate and parse as before.+- Do not introduce a heavy YAML parser unless the design makes an unusually strong case; the project currently uses a tiny `_brain.yaml` parser.+- Do not add a second graph or a parallel hidden schema store. Prefer frontmatter/config-native declarations.+- Do not add LLM-dependent schema authoring to the core.+- Favor read-only/introspection/lint surfaces first; defer mutating schema-pack application unless the variant can keep the scope small and safe.+- Tests must prove default behavior and legacy fixtures are not widened accidentally.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>++- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N++**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/runtime-schema-packs-foundation/design.md b/docs/brainstorm/runtime-schema-packs-foundation/design.mdnew file mode 100644index 00000000..13a46bdc--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/design.md@@ -0,0 +1,72 @@+# Runtime Schema Packs Foundation - schema vocabulary without a second store++**Status:** draft+**Author:** GitHub Copilot (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain currently has several closed vocabularies encoded as TypeScript `as const` objects: signal source types, preference lifecycle status, retired reasons, apply results, log event kinds, memory layers, and graph relations. The recent relation-vocabulary work proved that a single data-driven validation boundary can add meaning without migrations or duplicated token lists. Schema-pack tasks ask for the same extensibility for user/domain taxonomies, but the full upstream Schema Cathedral surface is too large for one safe release.++The root design challenge is separating taxonomy from behavior. Some existing tokens are lifecycle controls consumed by deterministic algorithms (`dream`, retire logic, audit readers). Opening them directly would make exhaustive state handling less trustworthy. This foundation should introduce runtime-declared schema vocabulary in a way that is useful now, keeps legacy behavior byte-compatible, and gives future mutation primitives a stable target.++## Scope++- Add an optional `_brain.yaml` `schema:` block as the single user-facing declaration surface for schema-pack taxonomy.+- Add a shared Brain schema vocabulary boundary, analogous to `relation-vocab.ts`, that merges built-in defaults with validated `schema:` declarations.+- Add optional schema metadata on Brain artifacts where it is safe and inert, starting with preference/retired and signal frontmatter fields that do not change core lifecycle behavior.+- Add a pure read-only schema report that can show the resolved vocabulary, scan declared-vs-used schema metadata, and report unknown or unused tokens.+- Add a small CLI read surface, `o2b brain schema`, with JSON output for show/lint/stats-style inspection.+- Add focused tests proving default installs and legacy fixtures remain unchanged when no `schema:` block or schema metadata exists.++## Out of scope++- The full `t_cbf4967f` mutation surface: 11 mutation primitives, 9 MCP operations, 14 CLI verbs, pack-lock, mutate-audit, and schema-author skill.+- Opening core lifecycle state machines (`preference.status`, `dream` transitions, retire reasons, apply-evidence results) to arbitrary user tokens in this PR.+- A dedicated `Brain/_schema/` registry or other second schema store.+- Remote/admin MCP schema mutation tools.+- Backfilling existing artifacts to add schema metadata.+- Search-ranking, `dream`, retention, or doctor behavior changes based on custom schema types beyond read-only lint/reporting.++## Chosen approach++Use Variant 1 from the consultant output: `_brain.yaml` gets a small optional `schema:` block, and core code resolves it through one shared vocabulary module. The module exposes built-in defaults, token normalization, pack validation, and predicates for known schema tokens. The implementation will stay read-first: operators can declare schema tokens and inspect/lint usage, while future PRs can add atomic mutation primitives against the same config block.++The key narrowing is that custom schema tokens are taxonomy metadata, not replacements for operational state. For example, a preference can carry a validated schema type/category, but its lifecycle `status` remains one of `unconfirmed | confirmed | quarantine` until a future design proves how custom lifecycle states interact with deterministic `dream`.++## Design decisions++- **Use `_brain.yaml` instead of `Brain/_schema/`.** The project already stores vault policy and optional feature knobs in `_brain.yaml`; a `schema:` block keeps the foundation visible, editable, and free of a second store lifecycle.+- **Keep the schema block flat enough for the existing parser.** Prefer arrays of string tokens under named keys, e.g. `schema.preference_types`, `schema.signal_types`, `schema.page_types`, and `schema.log_event_kinds`. Rich descriptions, aliases, routing hints, and mutation audit belong to later Schema Cathedral work.+- **Separate taxonomy from lifecycle state.** Do not widen `BrainPreferenceStatus` or `BRAIN_LOG_EVENT_KIND` call sites just to satisfy the upstream analogy. Instead, introduce explicit schema metadata fields whose behavior is inert unless a read-only report inspects them.+- **One validation boundary.** All schema-token validation flows through a new core module. Parsers and CLI reports must not copy token lists.+- **Legacy-safe writer behavior.** Optional schema metadata is emitted only when supplied. Existing preference/signal fixtures without schema metadata should remain byte-identical.+- **Read-only first.** The CLI should show resolved vocabulary and report unknown/unused token usage. It should not edit `_brain.yaml` or rewrite artifacts in this PR.++## File changes++Expected new files:++- `src/core/brain/schema-vocab.ts` - schema token normalization, defaults, resolver model, validation predicates.+- `src/core/brain/schema-report.ts` - pure read-only show/lint/stats report over resolved vocabulary and artifact usage.+- `src/cli/brain/verbs/schema.ts` - CLI read surface for resolved schema/report output.+- `tests/core/brain/schema-vocab.test.ts` - vocabulary and validation tests.+- `tests/core/brain/schema-report.test.ts` - read-only report/lint tests.+- `tests/cli/brain-schema-cli.test.ts` - CLI JSON and human output tests.++Expected modified files:++- `src/core/brain/types.ts` - optional config/artifact schema types.+- `src/core/brain/policy.ts` - `_brain.yaml` parser/validator support for optional `schema:` block.+- `src/core/brain/preference.ts` - optional schema metadata parse/write for preferences and retired artifacts.+- `src/core/brain/signal.ts` - optional schema metadata parse/write for signals.+- `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/help-text.ts`, `src/cli/command-manifest.ts` - CLI registration and discovery.+- `docs/cli-reference.md`, `README.md`, `CHANGELOG.md` - Phase 5 user-facing docs.+- Version manifests - Phase 5 version bump before push per operator override.++## Risks and constraints++- **YAML parser shape.** The current parser handles one nested block with scalar values and simple inline arrays. If multiline arrays are unsupported for schema blocks, implementation should either extend the parser minimally and test it, or require inline arrays for this release.+- **Field naming.** `schema_type` is explicit and avoids conflicting with existing `kind`, `status`, and graph `type` terms. The final implementation should choose names that are easy to grep and do not imply lifecycle mutation.+- **Log event support.** Existing log readers consume operational event kinds. The first report may need to scan raw log frontmatter defensively rather than widening every log consumer.+- **Scope pressure from child task.** Mutation primitives, locks, and MCP admin tools are tempting follow-ups but remain out of scope unless the foundation cannot be useful without them.diff --git a/docs/brainstorm/runtime-schema-packs-foundation/plan.md b/docs/brainstorm/runtime-schema-packs-foundation/plan.mdnew file mode 100644index 00000000..0a5949af--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/plan.md@@ -0,0 +1,39 @@+# Runtime Schema Packs Foundation - implementation plan++## Tasks++### Task 1: Schema vocabulary core++- **Files**: `src/core/brain/schema-vocab.ts`, `tests/core/brain/schema-vocab.test.ts`.+- **Acceptance**: Tests prove built-in vocabulary is frozen, tokens normalize deterministically, invalid tokens are rejected with field-specific errors, duplicate declarations collapse deterministically, and absent config resolves to built-ins only.+- **Depends on**: none.++### Task 2: `_brain.yaml` schema block++- **Files**: `src/core/brain/types.ts`, `src/core/brain/policy.ts`, `tests/core/brain.policy.test.ts` or a focused schema config test.+- **Acceptance**: Tests prove `schema:` is optional, default config remains unchanged, inline arrays parse, invalid tokens fail with field names, unknown schema subkeys warn, and resolved schema vocabulary merges built-ins with user declarations.+- **Depends on**: Task 1.++### Task 3: Artifact schema metadata++- **Files**: `src/core/brain/types.ts`, `src/core/brain/preference.ts`, `src/core/brain/signal.ts`, focused parser/writer tests.+- **Acceptance**: Tests prove preferences/retired artifacts and signals parse optional schema metadata when present, writers emit it only when supplied, invalid schema metadata is rejected when a vocabulary is provided, and existing no-schema fixtures remain byte-identical.+- **Depends on**: Task 1 and Task 2.++### Task 4: Read-only schema report++- **Files**: `src/core/brain/schema-report.ts`, `tests/core/brain/schema-report.test.ts`.+- **Acceptance**: Tests prove the report returns resolved vocabulary, used token counts by artifact kind, unknown token findings, unused declared-token findings, stable ordering, and frozen output without mutating the vault.+- **Depends on**: Task 1, Task 2, Task 3.++### Task 5: CLI schema inspection++- **Files**: `src/cli/brain/verbs/schema.ts`, `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/help-text.ts`, `src/cli/command-manifest.ts`, `tests/cli/brain-schema-cli.test.ts`.+- **Acceptance**: `o2b brain schema [--vault <path>] [--json]` prints a human summary and a stable JSON report. CLI tests cover a default vault, a custom schema block, and unknown-token lint output.+- **Depends on**: Task 4.++### Task 6: Phase 5 docs and version++- **Files**: `README.md`, `docs/cli-reference.md`, `CHANGELOG.md`, version manifests.+- **Acceptance**: Docs describe schema-pack foundation, explicit out-of-scope mutation surface, and CLI usage. `bun run sync-version:check` passes after version bump.+- **Depends on**: Tasks 1-5 and Phase 4 QA.diff --git a/docs/brainstorm/runtime-schema-packs-foundation/variants.md b/docs/brainstorm/runtime-schema-packs-foundation/variants.mdnew file mode 100644index 00000000..29e32c90--- /dev/null+++ b/docs/brainstorm/runtime-schema-packs-foundation/variants.md@@ -0,0 +1,56 @@+# Runtime Schema Packs Foundation - variants++## Task scope++Selected kanban tasks:++- `t_dc01c9f7` - runtime-extensible schema packs with custom page types and take kinds.+- `t_cbf4967f` - schema pack mutation primitives + MCP/CLI/schema-author surface, bounded to the foundation slice only.++The child task's full mutation surface is intentionally out of scope for this PR.++## Consultant variants++### Variant 1: `_brain.yaml` schema block + shared vocabulary boundary++- **Approach**: Add one optional `schema:` block to `_brain.yaml` that declares user extensions to the otherwise-closed vocabularies (custom preference categories/scopes, extra signal source types, custom log/event kinds, custom page/note types). Resolve it through a single new `schema-vocab.ts` boundary modeled on `relation-vocab.ts`: built-in `as const` defaults are frozen, declared extensions are merged in, and `isKnown*` predicates replace compile-time exhaustiveness at the SQL/frontmatter narrowing points. Ship read-only introspection only - a `o2b brain schema --json` verb and a `doctor` lint that reports declared-vs-used types - and defer all mutation.+- **Trade-offs**:+ - Pro: Reuses the established data-driven single-boundary pattern (`relation-vocab.ts`) and the forward-compat resolver pattern already in `policy.ts`; no new parser, no second store.+ - Pro: Default install stays byte-identical (absent `schema:` block -> resolver returns frozen built-in defaults, predicates behave exactly as the current closed unions).+ - Pro: The child's 11 mutation primitives become "edit one `schema:` block" - a clean, bounded extension point that needs no architectural change later.+ - Con: The tiny indent-aware YAML parser must grow to carry richer declarations (lists of maps for typed entries), or declarations must be flattened into the existing two-level shape.+ - Con: One config block as the home for several distinct vocabularies risks an awkward schema if the kinds diverge.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Dedicated schema-pack registry under `Brain/_schema/`++- **Approach**: Introduce a first-class schema-pack concept living in its own vault location (a `Brain/_schema/` directory of pack markdown files, or a single `Brain/_schema.yaml`), with an active-pack selector and a pack loader/registry that the core vocabularies consult at runtime. This mirrors gbrain's schema-pack model most faithfully and gives the future Schema Cathedral a natural home (pack-lock, mutate-audit, multi-pack switching). The foundation slice ships the loader, the registry, active-pack resolution, and read-only introspection/lint; mutation stays out.+- **Trade-offs**:+ - Pro: Most faithful to the upstream design; the full child surface (pack-lock, per-pack stats, switching) drops in without re-architecting.+ - Pro: Cleanly separates schema declarations from runtime tuning knobs in `_brain.yaml`.+ - Con: Directly tensions the "do not add a second graph or a parallel hidden schema store" constraint - a dedicated registry is a new store with its own format and lifecycle.+ - Con: Largest surface for a bounded PR; introduces pack selection/precedence semantics the foundation doesn't strictly need.+ - Con: Higher chance of accidentally widening legacy fixtures, since a new store changes how every vocabulary resolves.+- **Complexity**: large+- **Risk**: medium++### Variant 3: In-code union widening with built-in extension points only++- **Approach**: Widen the closed `as const` unions to typed-string with a centralized known-set (extending the tolerance pattern already used by `PrefAuditOp` and the log-kind reader), narrowing at SQL-row/frontmatter boundaries via `isKnown*` predicates - but expose no user-facing declaration surface this PR. The vocabulary is seeded purely from built-in defaults; introspection reports those built-ins. This delivers exactly gbrain's "widen casts, validate at runtime" type-system change and leaves the declaration mechanism entirely to the child.+- **Trade-offs**:+ - Pro: Smallest, lowest-risk change; touches only the type boundary, no config or YAML changes at all.+ - Pro: Makes the eventual declaration mechanism trivial - predicates and narrowing points already exist.+ - Pro: Easiest to prove default/legacy behavior is unchanged, since there is no new input surface.+ - Con: Delivers no user-observable value (no custom types yet) - it is a pure refactor that opens a door without a way to walk through it.+ - Con: Risks designing the predicate seam without a concrete declaration consumer, so the child PR may still need to reshape it.+- **Complexity**: small+- **Risk**: low++### Recommended: Variant 1++**Rationale**: It satisfies every hard constraint - no second store, no heavy YAML, defaults byte-identical, one shared validation boundary, read-only-first - while reusing two patterns the codebase already trusts (`relation-vocab.ts` and the `policy.ts` optional-block resolver). Unlike Variant 3 it ships real custom-type capability, and unlike Variant 2 it keeps the foundation small and avoids a parallel schema store, while still giving the child's mutation primitives a clean target (the `schema:` block) to evolve.++## Orchestrator decision++I accept Variant 1 with one deliberate narrowing: this PR must not blindly widen operational lifecycle enums such as preference `status` or the `dream` state machine. Those tokens are behavior controls, not just taxonomy. The schema pack foundation should first provide a user-declared taxonomy and validation boundary for optional schema metadata, plus read-only introspection/lint/stats surfaces. Future mutation primitives can target the same `_brain.yaml` `schema:` block once the foundation is stable.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex dec7d7ea..ed494b85 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -55,6 +55,7 @@ o2b brain audit Render a preference's full mutation audit trail (so2b brain morning-brief Read-only session-start summary (since v0.21.0): top confirmed preferences, recent reconcile open questions, recent notes; bounded by --max-chars-per-memory / --max-total-chars; --top-k / --lookback-dayso2b brain codec Deterministic lossless session codec (since v0.22.0): --compress | --expand over stdin or --in <file>; structured content preserved byte-for-byteo2b brain sources Read-only dashboard of signals by (agent, source_type) (since v0.22.0): active/processed + distinct-topic counts; --json+o2b brain schema Read-only runtime schema report (since v0.25.0): resolved vocabulary, artifact schema_type usage, unknown tokens, unused declarations; --jsono2b brain graph-export Serialise the vault knowledge graph (pages, wikilinks, typed relations) to a stable graph.json (since v0.22.0): stdout or --out <file>o2b brain graph-import Reconstruct vault page stubs from a graph.json (since v0.22.0): --mode skip|overwrite|merge; vault-guarded writeso2b brain backlinks List inbound references to a Brain artifact iddiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 48415216..462f6c0d 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.24.0",+ "version": "0.25.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 8266b7e8..ba355c1e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.24.0",+ "version": "0.25.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 22240117..dd4c6f0c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.24.0"+version: "0.25.0"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 8c45d9d0..f40e2072 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.24.0",+ "version": "0.25.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 5887ef89..7699595a 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.24.0"+version: "0.25.0"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 03ea8f90..015d53db 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.24.0"+version = "0.25.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 6c253ca8..d8a8db8b 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -35,6 +35,7 @@ import {cmdBrainMorningBrief,cmdBrainCodec,cmdBrainSources,+ cmdBrainSchema,cmdBrainGraphExport,cmdBrainGraphImport,cmdBrainBacklinks,@@ -140,6 +141,8 @@ export async function handleBrainSubcommand(return await cmdBrainCodec(rest);case "sources":return await cmdBrainSources(rest);+ case "schema":+ return await cmdBrainSchema(rest);case "graph-export":return await cmdBrainGraphExport(rest);case "graph-import":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 6179acae..b2a710da 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -42,6 +42,7 @@ Brain verbs (observing memory):morning-brief Session-start summary: top prefs, open questions, recent notescodec Compress/expand session prose with the deterministic codec (stdin/--in)sources Read-only dashboard of signals by (agent, source_type)+ schema Inspect resolved schema vocabulary and artifact token usagegraph-export Serialise the vault knowledge graph to graph.jsongraph-import Reconstruct vault pages from graph.json (--mode skip|overwrite|merge)backlinks List inbound references to a Brain artifact id@@ -191,6 +192,10 @@ export const VERB_HELP: Record<string, string> = {"usage: o2b brain sources [--vault <path>] [--json]\n" +"Read-only dashboard of the brain's signals grouped by (agent, source_type)\n" +"with active/processed and distinct-topic counts.\n",+ schema:+ "usage: o2b brain schema [--vault <path>] [--json]\n" ++ "Read-only report of the resolved runtime schema vocabulary, artifact\n" ++ "schema_type usage counts, and unknown/unused taxonomy findings.\n","graph-export":"usage: o2b brain graph-export [--vault <path>] [--out <file>]\n" +"Serialise the vault knowledge graph (pages, wikilinks, typed relations) to a\n" +diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 2cb90c94..2084f052 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -22,6 +22,7 @@ export { cmdBrainAudit } from "./audit.ts";export { cmdBrainMorningBrief } from "./morning-brief.ts";export { cmdBrainCodec } from "./codec.ts";export { cmdBrainSources } from "./sources.ts";+export { cmdBrainSchema } from "./schema.ts";export { cmdBrainGraphExport } from "./graph-export.ts";export { cmdBrainGraphImport } from "./graph-import.ts";export { cmdBrainBacklinks } from "./backlinks.ts";diff --git a/src/cli/brain/verbs/schema.ts b/src/cli/brain/verbs/schema.tsnew file mode 100644index 00000000..0f714cf4--- /dev/null+++ b/src/cli/brain/verbs/schema.ts@@ -0,0 +1,66 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ buildSchemaReport,+ type BrainSchemaReport,+ type SchemaReportFinding,+} from "../../../core/brain/schema-report.ts";+import { SCHEMA_VOCAB_CATEGORIES } from "../../../core/brain/schema-vocab.ts";+import { fail, parse, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainSchema(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();++ let report: BrainSchemaReport;+ try {+ const vault = resolveBrainVault(+ flags["vault"] as string | undefined,+ config,+ );+ report = buildSchemaReport(vault);+ } catch (exc) {+ return fail(`schema failed: ${(exc as Error).message ?? exc}`);+ }++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(renderSchemaReportText(report));+ return 0;+}++function renderSchemaReportText(report: BrainSchemaReport): string {+ const lines = ["brain schema", "", "vocabulary:"];+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ lines.push(+ ` ${category}: ${report.vocabulary[category].join(", ") || "(none)"}`,+ );+ }+ lines.push("", "usage:");+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ const usage = report.usage[category]+ .map((item) => `${item.token} x${item.count}`)+ .join(", ");+ lines.push(` ${category} usage: ${usage || "(none)"}`);+ }+ lines.push("", "findings:");+ if (report.findings.length === 0) {+ lines.push(" none");+ } else {+ for (const finding of report.findings)+ lines.push(` ${renderFinding(finding)}`);+ }+ return lines.join("\n") + "\n";+}++function renderFinding(finding: SchemaReportFinding): string {+ if (finding.kind === "unknown-token") {+ return `[unknown-token] ${finding.category} ${finding.token} (${finding.path})`;+ }+ return `[unused-declaration] ${finding.category} ${finding.token}`;+}diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex e15a6c1a..66d1862f 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -119,6 +119,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("morning-brief", "Render session-start summary"),command("codec", "Compress or expand session prose"),command("sources", "Show signal source dashboard"),+ command("schema", "Inspect Brain schema vocabulary"),command("graph-export", "Export vault graph"),command("graph-import", "Import vault graph stubs"),command("backlinks", "List inbound Brain references"),diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 30440fcf..ba75f8ab 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -28,6 +28,7 @@ import type {BrainHealthConfig,BrainLinkGraphConfig,BrainNotesConfig,+ BrainSchemaConfig,BrainMostAppliedConfig,BrainTemporalConfig,BrainVaultConfig,@@ -38,11 +39,19 @@ import type {ResolvedBrainNotesConfig,ResolvedBrainTemporalConfig,} from "./types.ts";+import {+ SCHEMA_VOCAB_CATEGORIES,+ SchemaVocabularyError,+ validateSchemaDeclarations,+} from "./schema-vocab.ts";// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to// break the module-init cycle: the resolver lives in `index.ts` and// itself imports `loadBrainConfig` from this file. See the// `defaults.ts` header for the rationale.-import { classifyVaultIgnoreRule, DEFAULT_VAULT_IGNORE_PATHS } from "../vault-scope/defaults.ts";+import {+ classifyVaultIgnoreRule,+ DEFAULT_VAULT_IGNORE_PATHS,+} from "../vault-scope/defaults.ts";import { brainConfigPath } from "./paths.ts";/** Schema versions this build understands. Bump on incompatible changes. */@@ -90,30 +99,36 @@ export const INSTRUCTION_FILE_MAX_LINES_CEILING = 10000;* - `instruction_file_max_lines: 200` matches the documented* compliance ceiling.*/-export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.freeze({- promotion_min_signals: 1,- promotion_min_distinct_agents: 1,- promotion_min_age_days: 0,- instruction_file_max_lines: 200,-}) as ResolvedBrainGuardrailConfig;+export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig =+ Object.freeze({+ promotion_min_signals: 1,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 200,+ }) as ResolvedBrainGuardrailConfig;/*** Merge a parsed `guardrails` block (or `undefined`) with* `BRAIN_GUARDRAIL_DEFAULTS`. Returns a fully-populated struct so* consumers do not branch on optional fields.*/-export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfig {+export function resolveGuardrails(+ cfg: BrainConfig,+): ResolvedBrainGuardrailConfig {const g = cfg.guardrails;if (g === undefined) return BRAIN_GUARDRAIL_DEFAULTS;return {promotion_min_signals:g.promotion_min_signals ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals,promotion_min_distinct_agents:- g.promotion_min_distinct_agents ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,+ g.promotion_min_distinct_agents ??+ BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,promotion_min_age_days:- g.promotion_min_age_days ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,+ g.promotion_min_age_days ??+ BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,instruction_file_max_lines:- g.instruction_file_max_lines ?? BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,+ g.instruction_file_max_lines ??+ BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,};}@@ -134,25 +149,31 @@ export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfi* vault-root instruction file `brain_context` surfaces when* present. Configurable per vault.*/-export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig = Object.freeze({- moc_min_outbound_links: 5,- moc_min_link_ratio: 0.3,- vault_instruction_file: "VAULT.md",-}) as ResolvedBrainLinkGraphConfig;+export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig =+ Object.freeze({+ moc_min_outbound_links: 5,+ moc_min_link_ratio: 0.3,+ vault_instruction_file: "VAULT.md",+ }) as ResolvedBrainLinkGraphConfig;/*** Merge a parsed `link_graph` block (or `undefined`) with* `BRAIN_LINK_GRAPH_DEFAULTS`.*/-export function resolveLinkGraph(cfg: BrainConfig): ResolvedBrainLinkGraphConfig {+export function resolveLinkGraph(+ cfg: BrainConfig,+): ResolvedBrainLinkGraphConfig {const lg = cfg.link_graph;if (lg === undefined) return BRAIN_LINK_GRAPH_DEFAULTS;return {moc_min_outbound_links:- lg.moc_min_outbound_links ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,- moc_min_link_ratio: lg.moc_min_link_ratio ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,+ lg.moc_min_outbound_links ??+ BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,+ moc_min_link_ratio:+ lg.moc_min_link_ratio ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,vault_instruction_file:- lg.vault_instruction_file ?? BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,+ lg.vault_instruction_file ??+ BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,};}@@ -171,13 +192,14 @@ export function resolveLinkGraph(cfg: BrainConfig): ResolvedBrainLinkGraphConfig* - `daily_window_offset_hours: 0` - daily-brief windows align* with UTC midnight by default.*/-export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig = Object.freeze({- stale_pref_days: 90,- stale_signal_days: 30,- stale_log_days: 180,- weekly_start_dow: 1,- daily_window_offset_hours: 0,-}) as ResolvedBrainTemporalConfig;+export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig =+ Object.freeze({+ stale_pref_days: 90,+ stale_signal_days: 30,+ stale_log_days: 180,+ weekly_start_dow: 1,+ daily_window_offset_hours: 0,+ }) as ResolvedBrainTemporalConfig;/*** Merge a parsed `temporal` block (or `undefined`) with@@ -187,12 +209,16 @@ export function resolveTemporal(cfg: BrainConfig): ResolvedBrainTemporalConfig {const tp = cfg.temporal;if (tp === undefined) return BRAIN_TEMPORAL_DEFAULTS;return {- stale_pref_days: tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,- stale_signal_days: tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,+ stale_pref_days:+ tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,+ stale_signal_days:+ tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,stale_log_days: tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,- weekly_start_dow: tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,+ weekly_start_dow:+ tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,daily_window_offset_hours:- tp.daily_window_offset_hours ?? BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,+ tp.daily_window_offset_hours ??+ BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,};}@@ -226,12 +252,16 @@ export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {const h = cfg.health;if (h === undefined) return BRAIN_HEALTH_DEFAULTS;return {- contradiction_jaccard: h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,+ contradiction_jaccard:+ h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,concept_gap_min_frequency:- h.concept_gap_min_frequency ?? BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,+ h.concept_gap_min_frequency ??+ BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,stale_claim_max_age_days:- h.stale_claim_max_age_days ?? BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,- remediation_step_cap: h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,+ h.stale_claim_max_age_days ??+ BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,+ remediation_step_cap:+ h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,};}@@ -282,7 +312,9 @@ export function loadNotesConfigSafe(vault: string): ResolvedBrainNotesConfig {* consumer (MCP wrappers, CLI verbs) so a freshly-initialised vault* still produces a useful report.*/-export function loadTemporalConfigSafe(vault: string): ResolvedBrainTemporalConfig {+export function loadTemporalConfigSafe(+ vault: string,+): ResolvedBrainTemporalConfig {try {return resolveTemporal(loadBrainConfig(vault));} catch {@@ -506,7 +538,10 @@ export function loadBrainConfigDetailed(vault: string): LoadBrainConfigResult {* a synthetic label like `"<test fixture>"` so the failure points at* something useful.*/-export function validateBrainConfig(parsed: unknown, source: string | null = null): BrainConfig {+export function validateBrainConfig(+ parsed: unknown,+ source: string | null = null,+): BrainConfig {return validateBrainConfigDetailed(parsed, source).config;}@@ -520,7 +555,11 @@ export function validateBrainConfigDetailed(source: string | null = null,): ValidateResult {if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {- throw new BrainConfigError("config root must be a map of keys", null, source);+ throw new BrainConfigError(+ "config root must be a map of keys",+ null,+ source,+ );}const obj = parsed as Record<string, unknown>;const warnings: BrainConfigLoadWarning[] = [];@@ -597,8 +636,16 @@ export function validateBrainConfigDetailed(DEFAULT_BRAIN_CONFIG.dream as unknown as Readonly<Record<string, number>>,source,);- requirePositiveInteger("dream.candidate_threshold", dream.candidate_threshold, source);- requirePositiveInteger("dream.unconfirmed_window_days", dream.unconfirmed_window_days, source);+ requirePositiveInteger(+ "dream.candidate_threshold",+ dream.candidate_threshold,+ source,+ );+ requirePositiveInteger(+ "dream.unconfirmed_window_days",+ dream.unconfirmed_window_days,+ source,+ );requirePositiveInteger("dream.contradiction_window_days",dream.contradiction_window_days,@@ -611,15 +658,25 @@ export function validateBrainConfigDetailed(DEFAULT_BRAIN_CONFIG.retire as unknown as Readonly<Record<string, number>>,source,);- requirePositiveInteger("retire.stale_evidence_days", retire.stale_evidence_days, source);+ requirePositiveInteger(+ "retire.stale_evidence_days",+ retire.stale_evidence_days,+ source,+ );const confidence = mergeBlock("confidence",obj["confidence"],- DEFAULT_BRAIN_CONFIG.confidence as unknown as Readonly<Record<string, number>>,+ DEFAULT_BRAIN_CONFIG.confidence as unknown as Readonly<+ Record<string, number>+ >,+ source,+ );+ requireNonNegativeInteger(+ "confidence.low_max_applied",+ confidence.low_max_applied,source,);- requireNonNegativeInteger("confidence.low_max_applied", confidence.low_max_applied, source);requireUnitInterval("confidence.medium_min", confidence.medium_min, source);requireUnitInterval("confidence.high_min", confidence.high_min, source);if ((confidence.medium_min as number) >= (confidence.high_min as number)) {@@ -634,10 +691,16 @@ export function validateBrainConfigDetailed(const snapshots = mergeBlock("snapshots",obj["snapshots"],- DEFAULT_BRAIN_CONFIG.snapshots as unknown as Readonly<Record<string, number>>,+ DEFAULT_BRAIN_CONFIG.snapshots as unknown as Readonly<+ Record<string, number>+ >,+ source,+ );+ requirePositiveInteger(+ "snapshots.retention_count",+ snapshots.retention_count,source,);- requirePositiveInteger("snapshots.retention_count", snapshots.retention_count, source);// Optional `vault` block (v0.10.9). Hard-error on shape problems β// exclusions affect every walker, silent ignore would be a footgun.@@ -740,7 +803,11 @@ export function validateBrainConfigDetailed(let active: BrainActiveConfig | undefined;if ("active" in obj) {const rawActive = obj["active"];- if (typeof rawActive !== "object" || rawActive === null || Array.isArray(rawActive)) {+ if (+ typeof rawActive !== "object" ||+ rawActive === null ||+ Array.isArray(rawActive)+ ) {throw new BrainConfigError(`block must be a map of keys; got ${describe(rawActive)}`,"active",@@ -755,7 +822,9 @@ export function validateBrainConfigDetailed(const windowDays = hasWindow? activeMap["most_applied_window_days"]: MOST_APPLIED_WINDOW_DAYS_DEFAULT;- const limit = hasLimit ? activeMap["most_applied_limit"] : MOST_APPLIED_LIMIT_DEFAULT;+ const limit = hasLimit+ ? activeMap["most_applied_limit"]+ : MOST_APPLIED_LIMIT_DEFAULT;if (typeof windowDays !== "number" ||!Number.isInteger(windowDays) ||@@ -857,7 +926,9 @@ export function validateBrainConfigDetailed(});ok = false;} else {- const badIdx = (drObj["known_agents"] as unknown[]).findIndex((v) => typeof v !== "string");+ const badIdx = (drObj["known_agents"] as unknown[]).findIndex(+ (v) => typeof v !== "string",+ );if (badIdx >= 0) {warnings.push({path: source ?? "<config>",@@ -915,7 +986,9 @@ export function validateBrainConfigDetailed(rawMap["promotion_min_distinct_agents"],source,);- partial.promotion_min_distinct_agents = rawMap["promotion_min_distinct_agents"] as number;+ partial.promotion_min_distinct_agents = rawMap[+ "promotion_min_distinct_agents"+ ] as number;}if ("promotion_min_age_days" in rawMap) {requireNonNegativeInteger(@@ -923,7 +996,9 @@ export function validateBrainConfigDetailed(rawMap["promotion_min_age_days"],source,);- partial.promotion_min_age_days = rawMap["promotion_min_age_days"] as number;+ partial.promotion_min_age_days = rawMap[+ "promotion_min_age_days"+ ] as number;}if ("instruction_file_max_lines" in rawMap) {requirePositiveInteger(@@ -979,7 +1054,11 @@ export function validateBrainConfigDetailed(if ("link_graph" in obj) {const rawLg = obj["link_graph"];if (typeof rawLg !== "object" || rawLg === null || Array.isArray(rawLg)) {- throw new BrainConfigError("link_graph must be a mapping", "link_graph", source);+ throw new BrainConfigError(+ "link_graph must be a mapping",+ "link_graph",+ source,+ );}const lgObj = rawLg as Record<string, unknown>;const partialLg: Record<string, unknown> = {};@@ -1021,7 +1100,11 @@ export function validateBrainConfigDetailed(// Reject absolute paths and `..` traversal at load time so// the config surface fails loudly instead of silently// omitting the envelope field at read time.- if (trimmed.startsWith("/") || trimmed.startsWith("\\") || trimmed.includes("..")) {+ if (+ trimmed.startsWith("/") ||+ trimmed.startsWith("\\") ||+ trimmed.includes("..")+ ) {throw new BrainConfigError("must be a vault-relative path without '..' segments","link_graph.vault_instruction_file",@@ -1043,7 +1126,10 @@ export function validateBrainConfigDetailed(});}}- linkGraph = Object.keys(partialLg).length > 0 ? (partialLg as BrainLinkGraphConfig) : {};+ linkGraph =+ Object.keys(partialLg).length > 0+ ? (partialLg as BrainLinkGraphConfig)+ : {};}// Optional `temporal` block (v0.10.18). Shape:@@ -1059,7 +1145,11 @@ export function validateBrainConfigDetailed(if ("temporal" in obj) {const rawTp = obj["temporal"];if (typeof rawTp !== "object" || rawTp === null || Array.isArray(rawTp)) {- throw new BrainConfigError("temporal must be a mapping", "temporal", source);+ throw new BrainConfigError(+ "temporal must be a mapping",+ "temporal",+ source,+ );}const tpObj = rawTp as Record<string, unknown>;const partialTp: Record<string, unknown> = {};@@ -1070,7 +1160,11 @@ export function validateBrainConfigDetailed(if (key in tpObj) {const v = tpObj[key];if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError("must be a positive integer", `temporal.${key}`, source);+ throw new BrainConfigError(+ "must be a positive integer",+ `temporal.${key}`,+ source,+ );}partialTp[key] = v;}@@ -1113,7 +1207,10 @@ export function validateBrainConfigDetailed(});}}- temporal = Object.keys(partialTp).length > 0 ? (partialTp as BrainTemporalConfig) : {};+ temporal =+ Object.keys(partialTp).length > 0+ ? (partialTp as BrainTemporalConfig)+ : {};}// Optional `health:` block (v0.14.0). Shape:@@ -1144,13 +1241,23 @@ export function validateBrainConfigDetailed(partialH["contradiction_jaccard"] = v;}const positiveIntKeys: ReadonlyArray<- "concept_gap_min_frequency" | "stale_claim_max_age_days" | "remediation_step_cap"- > = ["concept_gap_min_frequency", "stale_claim_max_age_days", "remediation_step_cap"];+ | "concept_gap_min_frequency"+ | "stale_claim_max_age_days"+ | "remediation_step_cap"+ > = [+ "concept_gap_min_frequency",+ "stale_claim_max_age_days",+ "remediation_step_cap",+ ];for (const key of positiveIntKeys) {if (key in hObj) {const v = hObj[key];if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError("must be a positive integer", `health.${key}`, source);+ throw new BrainConfigError(+ "must be a positive integer",+ `health.${key}`,+ source,+ );}partialH[key] = v;}@@ -1169,7 +1276,8 @@ export function validateBrainConfigDetailed(});}}- health = Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};+ health =+ Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};}// Optional `notes:` block (v0.11.0). Shape:@@ -1183,7 +1291,11 @@ export function validateBrainConfigDetailed(let notes: BrainNotesConfig | undefined;if ("notes" in obj) {const rawNotes = obj["notes"];- if (typeof rawNotes !== "object" || rawNotes === null || Array.isArray(rawNotes)) {+ if (+ typeof rawNotes !== "object" ||+ rawNotes === null ||+ Array.isArray(rawNotes)+ ) {throw new BrainConfigError("notes must be a mapping", "notes", source);}const notesObj = rawNotes as Record<string, unknown>;@@ -1242,7 +1354,65 @@ export function validateBrainConfigDetailed(});}}- notes = Object.keys(partialNotes).length > 0 ? (partialNotes as BrainNotesConfig) : {};+ notes =+ Object.keys(partialNotes).length > 0+ ? (partialNotes as BrainNotesConfig)+ : {};+ }++ // Optional `schema:` block (runtime schema-pack foundation). Shape:+ // schema:+ // preference_types: [research, decision]+ // signal_types: [observation]+ // page_types: [paper]+ // log_event_kinds: [milestone]+ // Absent block leaves cfg.schema undefined; consumers merge built-ins+ // through resolveSchemaVocabulary.+ let schema: BrainSchemaConfig | undefined;+ if ("schema" in obj) {+ const rawSchema = obj["schema"];+ if (+ typeof rawSchema !== "object" ||+ rawSchema === null ||+ Array.isArray(rawSchema)+ ) {+ throw new BrainConfigError("schema must be a mapping", "schema", source);+ }+ const schemaObj = rawSchema as Record<string, unknown>;+ const partialSchema: Partial<+ Record<keyof BrainSchemaConfig, ReadonlyArray<string>>+ > = {};+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ if (!(category in schemaObj)) continue;+ const value = schemaObj[category];+ if (!Array.isArray(value)) {+ throw new BrainConfigError(+ "must be an array of schema tokens",+ `schema.${category}`,+ source,+ );+ }+ partialSchema[category] = value;+ }+ for (const key of Object.keys(schemaObj)) {+ if (!(SCHEMA_VOCAB_CATEGORIES as ReadonlyArray<string>).includes(key)) {+ warnings.push({+ path: source ?? "<config>",+ message: `schema.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }+ try {+ schema = validateSchemaDeclarations(partialSchema) as BrainSchemaConfig;+ } catch (err) {+ if (err instanceof SchemaVocabularyError) {+ const detail = err.message.startsWith(`${err.field}: `)+ ? err.message.slice(err.field.length + 2)+ : err.message;+ throw new BrainConfigError(detail, err.field, source);+ }+ throw err;+ }}// Forward-compat: unknown top-level keys β warning, not error.@@ -1260,6 +1430,7 @@ export function validateBrainConfigDetailed("link_graph","temporal","notes",+ "schema",]);for (const key of Object.keys(obj)) {if (!known.has(key)) {@@ -1295,12 +1466,15 @@ export function validateBrainConfigDetailed(},...(vault !== undefined ? { vault } : {}),...(active !== undefined ? { active } : {}),- ...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),+ ...(disciplineReport !== undefined+ ? { discipline_report: disciplineReport }+ : {}),...(guardrails !== undefined ? { guardrails } : {}),...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),...(temporal !== undefined ? { temporal } : {}),...(notes !== undefined ? { notes } : {}),...(health !== undefined ? { health } : {}),+ ...(schema !== undefined ? { schema } : {}),};return { config, warnings };@@ -1337,13 +1511,25 @@ function mergeBlock(return merged;}-function requirePositiveInteger(field: string, value: unknown, source: string | null): void {+function requirePositiveInteger(+ field: string,+ value: unknown,+ source: string | null,+): void {if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {- throw new BrainConfigError(`must be a positive integer; got ${describe(value)}`, field, source);+ throw new BrainConfigError(+ `must be a positive integer; got ${describe(value)}`,+ field,+ source,+ );}}-function requireNonNegativeInteger(field: string, value: unknown, source: string | null): void {+function requireNonNegativeInteger(+ field: string,+ value: unknown,+ source: string | null,+): void {if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {throw new BrainConfigError(`must be a non-negative integer; got ${describe(value)}`,@@ -1353,9 +1539,22 @@ function requireNonNegativeInteger(field: string, value: unknown, source: string}}-function requireUnitInterval(field: string, value: unknown, source: string | null): void {- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {- throw new BrainConfigError(`must be a number in [0, 1]; got ${describe(value)}`, field, source);+function requireUnitInterval(+ field: string,+ value: unknown,+ source: string | null,+): void {+ if (+ typeof value !== "number" ||+ !Number.isFinite(value) ||+ value < 0 ||+ value > 1+ ) {+ throw new BrainConfigError(+ `must be a number in [0, 1]; got ${describe(value)}`,+ field,+ source,+ );}}@@ -1407,7 +1606,9 @@ export function parseBrainYaml(text: string): ParsedBlock {while (i < lines.length) {const line = lines[i]!;if (line.indent !== 0) {- throw new Error(`line ${line.lineNumber}: unexpected indentation at top level`);+ throw new Error(+ `line ${line.lineNumber}: unexpected indentation at top level`,+ );}const kv = splitKeyValue(line);if (kv.value === "") {@@ -1418,7 +1619,11 @@ export function parseBrainYaml(text: string): ParsedBlock {const child: Record<string, ParsedScalar | ParsedScalar[]> = {};i++;const blockIndent = detectBlockIndent(lines, i);- while (i < lines.length && lines[i]!.indent >= blockIndent && blockIndent > 0) {+ while (+ i < lines.length &&+ lines[i]!.indent >= blockIndent &&+ blockIndent > 0+ ) {const inner = lines[i]!;if (inner.indent !== blockIndent) {throw new Error(@@ -1451,7 +1656,10 @@ export function parseBrainYaml(text: string): ParsedBlock {`(expected ${listIndent} spaces, got ${listLine.indent})`,);}- if (!listLine.content.startsWith("- ") && listLine.content !== "-") {+ if (+ !listLine.content.startsWith("- ") &&+ listLine.content !== "-"+ ) {// If it looks like a `key: value` pair, it's a deeper block β not// supported. Preserve the original error message so existing tests// that assert on the wording keep passing.@@ -1524,7 +1732,8 @@ function splitLines(text: string): Line[] {let content = stripped;if (!/['"]/.test(stripped)) {const hashIdx = stripped.indexOf(" #");- if (hashIdx >= 0) content = stripped.slice(0, hashIdx).replace(/\s+$/, "");+ if (hashIdx >= 0)+ content = stripped.slice(0, hashIdx).replace(/\s+$/, "");}const indent = content.length - content.trimStart().length;out.push({@@ -1551,7 +1760,9 @@ function splitKeyValue(line: Line): KeyValue {}const key = line.content.slice(0, idx).trim();if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {- throw new Error(`line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`);+ throw new Error(+ `line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`,+ );}const value = line.content.slice(idx + 1).trim();return { key, value };@@ -1564,13 +1775,17 @@ function detectBlockIndent(lines: Line[], cursor: number): number {return first.indent;}-function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedScalar[] {+function parseScalar(+ text: string,+ lineNumber: number,+): ParsedScalar | ParsedScalar[] {if (text.startsWith("[") && text.endsWith("]")) {return parseInlineArray(text.slice(1, -1), lineNumber);}if (text.length >= 2 &&- ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))+ ((text.startsWith('"') && text.endsWith('"')) ||+ (text.startsWith("'") && text.endsWith("'")))) {return text.slice(1, -1);}@@ -1592,7 +1807,10 @@ function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedScareturn text;}-function parseInlineArray(innerRaw: string, lineNumber: number): ParsedScalar[] {+function parseInlineArray(+ innerRaw: string,+ lineNumber: number,+): ParsedScalar[] {const inner = innerRaw.trim();if (inner === "") return [];@@ -1625,7 +1843,9 @@ function parseInlineArray(innerRaw: string, lineNumber: number): ParsedScalar[]current += ch;}if (inQuote) {- throw new Error(`line ${lineNumber}: unterminated quoted string in inline array`);+ throw new Error(+ `line ${lineNumber}: unterminated quoted string in inline array`,+ );}out.push(parseInlineArrayItem(current, lineNumber));return out;@@ -1638,7 +1858,9 @@ function parseInlineArrayItem(text: string, lineNumber: number): ParsedScalar {}const parsed = parseScalar(trimmed, lineNumber);if (Array.isArray(parsed)) {- throw new Error(`line ${lineNumber}: nested inline arrays are not supported`);+ throw new Error(+ `line ${lineNumber}: nested inline arrays are not supported`,+ );}return parsed;}diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex 6398713b..ef7ecf3f 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -46,6 +46,11 @@ import {DEFAULT_RELATION_TYPES,type DefaultRelationType,} from "../graph/relation-vocab.ts";+import {+ isKnownSchemaToken,+ validateSchemaToken,+ type BrainSchemaVocabulary,+} from "./schema-vocab.ts";import {brainDirs,preferencePath,@@ -155,6 +160,7 @@ export interface WritePreferenceInput {readonly content_hash?: string;readonly supersedes?: string;readonly aliases?: ReadonlyArray<string>;+ readonly schema_type?: string;readonly memory_layer?: BrainMemoryLayer;readonly memory_branch?: string;readonly related?: ReadonlyArray<string>;@@ -191,6 +197,10 @@ export interface WritePreferenceOptions {readonly overwrite?: boolean;}+export interface ParsePreferenceOptions {+ readonly schemaVocabulary?: BrainSchemaVocabulary;+}+export interface WritePreferenceResult {readonly path: string;readonly id: string;@@ -393,6 +403,12 @@ function preferenceFrontmatter(if (input.aliases && input.aliases.length > 0) {metadata["aliases"] = [...input.aliases];}+ if (input.schema_type?.trim()) {+ metadata["schema_type"] = validateSchemaToken(+ input.schema_type,+ "schema_type",+ );+ }if (input.memory_layer !== undefined) {metadata["memory_layer"] = validateMemoryLayer(input.memory_layer,@@ -582,7 +598,10 @@ export function normalizeDerivedKeys(* (`_status:`, `_applied_count:`, ...); {@link normalizeDerivedKeys}* renames them to the un-prefixed form for downstream readers.*/-export function parsePreference(path: string): BrainPreference {+export function parsePreference(+ path: string,+ options: ParsePreferenceOptions = {},+): BrainPreference {const [rawMeta, _body] = parseFrontmatter(path);const meta = normalizeDerivedKeys(rawMeta);// `_body` is unused for preferences β the body is purely human prose;@@ -654,6 +673,7 @@ export function parsePreference(path: string): BrainPreference {...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }: {}),+ ...spreadSchemaMetadata(meta, path, "preference_types", options),...spreadMemorySemantics(meta, path),...spreadBiTemporal(meta),};@@ -697,6 +717,24 @@ function spreadMemorySemantics(return out;}+function spreadSchemaMetadata(+ meta: Record<string, unknown>,+ path: string,+ category: "preference_types" | "signal_types",+ options: ParsePreferenceOptions,+): { readonly schema_type?: string } {+ const raw = optionalScalarString(meta, "schema_type");+ if (raw === undefined) return {};+ const schemaType = validateSchemaToken(raw, "schema_type");+ const vocab = options.schemaVocabulary;+ if (vocab !== undefined && !isKnownSchemaToken(vocab, category, schemaType)) {+ throw new Error(+ `schema_type ${JSON.stringify(schemaType)} is not declared in ${category} (${path})`,+ );+ }+ return { schema_type: schemaType };+}+function validateMemoryLayer(value: string, path: string): BrainMemoryLayer {if (isBrainMemoryLayer(value)) return value;const allowed = Object.values(BRAIN_MEMORY_LAYER).join(", ");@@ -748,7 +786,10 @@ function spreadBiTemporal(meta: Record<string, unknown>): {* Shares {@link normalizeDerivedKeys} with `parsePreference` so* both forms of Group C frontmatter parse identically.*/-export function parseRetired(path: string): BrainRetired {+export function parseRetired(+ path: string,+ options: ParsePreferenceOptions = {},+): BrainRetired {const [rawMeta] = parseFrontmatter(path);const meta = normalizeDerivedKeys(rawMeta);@@ -814,6 +855,7 @@ export function parseRetired(path: string): BrainRetired {...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }: {}),+ ...spreadSchemaMetadata(meta, path, "preference_types", options),...spreadMemorySemantics(meta, path),...(optionalScalarString(meta, "user_rejected_reason") !== undefined? {diff --git a/src/core/brain/schema-report.ts b/src/core/brain/schema-report.tsnew file mode 100644index 00000000..71854ab3--- /dev/null+++ b/src/core/brain/schema-report.ts@@ -0,0 +1,284 @@+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { listVaultPages } from "../vault.ts";+import { loadBrainConfig } from "./policy.ts";+import { brainDirs, vaultRelative } from "./paths.ts";+import { parsePreference, parseRetired } from "./preference.ts";+import {+ DEFAULT_SCHEMA_VOCAB,+ SCHEMA_VOCAB_CATEGORIES,+ normalizeSchemaToken,+ resolveSchemaVocabulary,+ type BrainSchemaVocabulary,+ type SchemaVocabularyCategory,+} from "./schema-vocab.ts";+import { parseSignal } from "./signal.ts";++export interface SchemaTokenUsage {+ readonly token: string;+ readonly count: number;+}++export type SchemaReportFinding =+ | {+ readonly kind: "unknown-token";+ readonly category: SchemaVocabularyCategory;+ readonly token: string;+ readonly path: string;+ }+ | {+ readonly kind: "unused-declaration";+ readonly category: SchemaVocabularyCategory;+ readonly token: string;+ };++export interface BrainSchemaUsage {+ readonly preference_types: ReadonlyArray<SchemaTokenUsage>;+ readonly signal_types: ReadonlyArray<SchemaTokenUsage>;+ readonly page_types: ReadonlyArray<SchemaTokenUsage>;+ readonly log_event_kinds: ReadonlyArray<SchemaTokenUsage>;+}++export interface BrainSchemaReport {+ readonly schema_version: 1;+ readonly vocabulary: BrainSchemaVocabulary;+ readonly usage: BrainSchemaUsage;+ readonly findings: ReadonlyArray<SchemaReportFinding>;+}++export function buildSchemaReport(vault: string): BrainSchemaReport {+ const cfg = loadBrainConfig(vault);+ const vocabulary = resolveSchemaVocabulary(cfg.schema);+ const usageMaps = emptyUsageMaps();+ const findings: SchemaReportFinding[] = [];++ scanPreferences(vault, vocabulary, usageMaps.preference_types, findings);+ scanSignals(vault, vocabulary, usageMaps.signal_types, findings);+ scanPageTypes(vault, vocabulary, usageMaps.page_types, findings);+ scanLogEventKinds(vault, vocabulary, usageMaps.log_event_kinds, findings);+ addUnusedDeclarationFindings(cfg.schema ?? {}, usageMaps, findings);++ return deepFreezeReport({+ schema_version: 1,+ vocabulary,+ usage: {+ preference_types: freezeUsage(usageMaps.preference_types),+ signal_types: freezeUsage(usageMaps.signal_types),+ page_types: freezeUsage(usageMaps.page_types),+ log_event_kinds: freezeUsage(usageMaps.log_event_kinds),+ },+ findings: Object.freeze(findings.toSorted(compareFindings)),+ });+}++function scanPreferences(+ vault: string,+ vocabulary: BrainSchemaVocabulary,+ counts: Map<string, number>,+ findings: SchemaReportFinding[],+): void {+ const dirs = brainDirs(vault);+ for (const path of listMarkdown(dirs.preferences, "pref-")) {+ const pref = parsePreference(path);+ recordSchemaType(+ vault,+ path,+ "preference_types",+ pref.schema_type,+ vocabulary,+ counts,+ findings,+ );+ }+ for (const path of listMarkdown(dirs.retired, "ret-")) {+ const retired = parseRetired(path);+ recordSchemaType(+ vault,+ path,+ "preference_types",+ retired.schema_type,+ vocabulary,+ counts,+ findings,+ );+ }+}++function scanSignals(+ vault: string,+ vocabulary: BrainSchemaVocabulary,+ counts: Map<string, number>,+ findings: SchemaReportFinding[],+): void {+ const dirs = brainDirs(vault);+ for (const path of listMarkdown(dirs.inbox, "sig-")) {+ const signal = parseSignal(path);+ recordSchemaType(+ vault,+ path,+ "signal_types",+ signal.schema_type,+ vocabulary,+ counts,+ findings,+ );+ }+ for (const path of listMarkdown(dirs.processed, "sig-")) {+ const signal = parseSignal(path);+ recordSchemaType(+ vault,+ path,+ "signal_types",+ signal.schema_type,+ vocabulary,+ counts,+ findings,+ );+ }+}++function scanPageTypes(+ vault: string,+ vocabulary: BrainSchemaVocabulary,+ counts: Map<string, number>,+ findings: SchemaReportFinding[],+): void {+ for (const page of listVaultPages(vault)) {+ const rel = vaultRelative(page.path, vault);+ if (rel === "Brain" || rel.startsWith("Brain/")) continue;+ const raw = page.metadata["schema_type"];+ if (typeof raw !== "string") continue;+ recordSchemaType(+ vault,+ page.path,+ "page_types",+ raw,+ vocabulary,+ counts,+ findings,+ );+ }+}++const LOG_EVENT_HEADER_RE =+ /^##\s+\d{2}:\d{2}:\d{2}\s+([\p{L}][\p{L}\p{N}_-]*)\s*$/u;++function scanLogEventKinds(+ vault: string,+ vocabulary: BrainSchemaVocabulary,+ counts: Map<string, number>,+ findings: SchemaReportFinding[],+): void {+ for (const path of listMarkdown(brainDirs(vault).log, "")) {+ let text: string;+ try {+ text = readFileSync(path, "utf8");+ } catch {+ continue;+ }+ for (const line of text.split(/\r?\n/)) {+ const match = LOG_EVENT_HEADER_RE.exec(line.trim());+ if (!match) continue;+ recordSchemaType(+ vault,+ path,+ "log_event_kinds",+ match[1]!,+ vocabulary,+ counts,+ findings,+ );+ }+ }+}++function recordSchemaType(+ vault: string,+ path: string,+ category: SchemaVocabularyCategory,+ rawToken: string | undefined,+ vocabulary: BrainSchemaVocabulary,+ counts: Map<string, number>,+ findings: SchemaReportFinding[],+): void {+ if (rawToken === undefined) return;+ const token = normalizeSchemaToken(rawToken);+ counts.set(token, (counts.get(token) ?? 0) + 1);+ if (!vocabulary[category].includes(token)) {+ findings.push({+ kind: "unknown-token",+ category,+ token,+ path: vaultRelative(path, vault),+ });+ }+}++function addUnusedDeclarationFindings(+ declarations: Partial<+ Record<SchemaVocabularyCategory, ReadonlyArray<string>>+ >,+ usageMaps: Record<SchemaVocabularyCategory, Map<string, number>>,+ findings: SchemaReportFinding[],+): void {+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ const declared = declarations[category] ?? [];+ const builtin = new Set(DEFAULT_SCHEMA_VOCAB[category]);+ const used = usageMaps[category];+ for (const raw of declared) {+ const token = normalizeSchemaToken(raw);+ if (builtin.has(token)) continue;+ if (!used.has(token)) {+ findings.push({ kind: "unused-declaration", category, token });+ }+ }+ }+}++function listMarkdown(dir: string, prefix: string): string[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir)+ .filter((name) => name.startsWith(prefix) && name.endsWith(".md"))+ .toSorted()+ .map((name) => join(dir, name));+}++function emptyUsageMaps(): Record<+ SchemaVocabularyCategory,+ Map<string, number>+> {+ return {+ preference_types: new Map<string, number>(),+ signal_types: new Map<string, number>(),+ page_types: new Map<string, number>(),+ log_event_kinds: new Map<string, number>(),+ };+}++function freezeUsage(+ counts: Map<string, number>,+): ReadonlyArray<SchemaTokenUsage> {+ return Object.freeze(+ [...counts.entries()]+ .toSorted(([a], [b]) => a.localeCompare(b))+ .map(([token, count]) => Object.freeze({ token, count })),+ );+}++function compareFindings(+ a: SchemaReportFinding,+ b: SchemaReportFinding,+): number {+ return (+ a.kind.localeCompare(b.kind) ||+ a.category.localeCompare(b.category) ||+ a.token.localeCompare(b.token) ||+ ("path" in a ? a.path : "").localeCompare("path" in b ? b.path : "")+ );+}++function deepFreezeReport(report: BrainSchemaReport): BrainSchemaReport {+ Object.freeze(report.usage);+ return Object.freeze(report);+}diff --git a/src/core/brain/schema-vocab.ts b/src/core/brain/schema-vocab.tsnew file mode 100644index 00000000..3a29ba46--- /dev/null+++ b/src/core/brain/schema-vocab.ts@@ -0,0 +1,141 @@+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";++export const SCHEMA_VOCAB_CATEGORIES = Object.freeze([+ "preference_types",+ "signal_types",+ "page_types",+ "log_event_kinds",+] as const);++export type SchemaVocabularyCategory = (typeof SCHEMA_VOCAB_CATEGORIES)[number];++export interface BrainSchemaDeclarations {+ readonly preference_types?: ReadonlyArray<string>;+ readonly signal_types?: ReadonlyArray<string>;+ readonly page_types?: ReadonlyArray<string>;+ readonly log_event_kinds?: ReadonlyArray<string>;+}++export interface BrainSchemaVocabulary {+ readonly preference_types: ReadonlyArray<string>;+ readonly signal_types: ReadonlyArray<string>;+ readonly page_types: ReadonlyArray<string>;+ readonly log_event_kinds: ReadonlyArray<string>;+}++export class SchemaVocabularyError extends Error {+ readonly field: string;+ readonly token: unknown;++ constructor(field: string, token: unknown, message: string) {+ super(`${field}: ${message}`);+ this.name = "SchemaVocabularyError";+ this.field = field;+ this.token = token;+ }+}++const TOKEN_RE = /^[\p{L}][\p{L}\p{N}_-]*$/u;++export const DEFAULT_SCHEMA_VOCAB: BrainSchemaVocabulary = Object.freeze({+ preference_types: Object.freeze(["preference"]),+ signal_types: Object.freeze(["feedback"]),+ page_types: Object.freeze(["note"]),+ log_event_kinds: Object.freeze(Object.values(BRAIN_LOG_EVENT_KIND)),+});++export function normalizeSchemaToken(raw: string): string {+ return raw.normalize("NFC").trim().toLowerCase();+}++export function validateSchemaDeclarations(+ declarations: BrainSchemaDeclarations | undefined | null,+): BrainSchemaDeclarations {+ if (declarations == null) return Object.freeze({});++ const normalized: Partial<+ Record<SchemaVocabularyCategory, ReadonlyArray<string>>+ > = {};+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ const values = declarations[category];+ if (values === undefined) continue;+ if (!Array.isArray(values)) {+ throw new SchemaVocabularyError(+ `schema.${category}`,+ values,+ "must be an array of tokens",+ );+ }+ normalized[category] = Object.freeze(+ values.map((value, index) =>+ validateSchemaToken(value, `schema.${category}[${index}]`),+ ),+ );+ }++ return Object.freeze(normalized) as BrainSchemaDeclarations;+}++export function resolveSchemaVocabulary(+ declarations: BrainSchemaDeclarations | undefined | null = undefined,+): BrainSchemaVocabulary {+ const normalized = validateSchemaDeclarations(declarations);++ return Object.freeze({+ preference_types: mergeCategory(+ DEFAULT_SCHEMA_VOCAB.preference_types,+ normalized.preference_types,+ ),+ signal_types: mergeCategory(+ DEFAULT_SCHEMA_VOCAB.signal_types,+ normalized.signal_types,+ ),+ page_types: mergeCategory(+ DEFAULT_SCHEMA_VOCAB.page_types,+ normalized.page_types,+ ),+ log_event_kinds: mergeCategory(+ DEFAULT_SCHEMA_VOCAB.log_event_kinds,+ normalized.log_event_kinds,+ ),+ });+}++export function isKnownSchemaToken(+ vocab: BrainSchemaVocabulary,+ category: SchemaVocabularyCategory,+ token: string,+): boolean {+ const normalized = normalizeSchemaToken(token);+ return vocab[category].includes(normalized);+}++function mergeCategory(+ builtins: ReadonlyArray<string>,+ declared: ReadonlyArray<string> | undefined,+): ReadonlyArray<string> {+ const seen = new Set<string>();+ const merged: string[] = [];+ for (const token of [...builtins, ...(declared ?? [])]) {+ const normalized = normalizeSchemaToken(token);+ if (seen.has(normalized)) continue;+ seen.add(normalized);+ merged.push(normalized);+ }+ return Object.freeze(merged);+}++export function validateSchemaToken(value: unknown, field: string): string {+ if (typeof value !== "string") {+ throw new SchemaVocabularyError(field, value, "must be a string token");+ }+ const normalized = normalizeSchemaToken(value);+ if (!TOKEN_RE.test(normalized)) {+ throw new SchemaVocabularyError(+ field,+ value,+ "must start with a letter and contain only letters, numbers, underscores, or hyphens",+ );+ }+ return normalized;+}diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 8bbabf84..4bb82fdf 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -29,6 +29,11 @@ import { sanitiseTextField } from "../redactor.ts";import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";import { allocateSlug, brainDirs, validateIsoDate } from "./paths.ts";+import {+ isKnownSchemaToken,+ validateSchemaToken,+ type BrainSchemaVocabulary,+} from "./schema-vocab.ts";import {BRAIN_SIGNAL_SIGN,BRAIN_SIGNAL_SOURCE_TYPE,@@ -74,6 +79,7 @@ export interface WriteSignalInput {* field carries the meaning.*/readonly source_type?: BrainSignalSourceType;+ readonly schema_type?: string;/** Normalised payload hash for idempotency (Β§9 / Β§16). */readonly dedup_hash?: string;/** Session coordinates `<path>#<turn-id>` (Β§16). */@@ -97,6 +103,10 @@ export interface WriteSignalResult {readonly id: string;}+export interface ParseSignalOptions {+ readonly schemaVocabulary?: BrainSchemaVocabulary;+}+const REQUIRED_INPUT_FIELDS: ReadonlyArray<keyof WriteSignalInput> = ["topic","signal",@@ -143,7 +153,10 @@ 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)) {+ 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)}`,);@@ -193,6 +206,12 @@ export function writeSignal() {metadata["source_type"] = sanitised.source_type;}+ if (sanitised.schema_type?.trim()) {+ metadata["schema_type"] = validateSchemaToken(+ sanitised.schema_type,+ "schema_type",+ );+ }if (sanitised.dedup_hash && sanitised.dedup_hash.trim()) {metadata["dedup_hash"] = sanitised.dedup_hash.trim();}@@ -239,9 +258,14 @@ function sanitiseSignalInput(input: WriteSignalInput): WriteSignalInput {singleLine: true,});const scope = input.scope- ? sanitiseTextField(input.scope, { maxLen: SCOPE_MAX_LEN, singleLine: true })+ ? sanitiseTextField(input.scope, {+ maxLen: SCOPE_MAX_LEN,+ singleLine: true,+ }): input.scope;- const raw = input.raw ? sanitiseTextField(input.raw, { maxLen: RAW_MAX_LEN }) : input.raw;+ const raw = input.raw+ ? sanitiseTextField(input.raw, { maxLen: RAW_MAX_LEN })+ : input.raw;const source = input.source? input.source.map((s) =>sanitiseTextField(s, { maxLen: SOURCE_ITEM_MAX_LEN, singleLine: true }),@@ -265,7 +289,10 @@ function sanitiseSignalInput(input: WriteSignalInput): WriteSignalInput {* field. `signal` value mismatch (anything outside positive/negative)* surfaces as a separate, distinguishable error.*/-export function parseSignal(path: string): BrainSignal {+export function parseSignal(+ path: string,+ options: ParseSignalOptions = {},+): BrainSignal {const [meta, body] = parseFrontmatter(path);requireField(meta, "kind");@@ -279,7 +306,10 @@ export function parseSignal(path: string): BrainSignal {const tags = requireStringArray(meta, "tags");const topic = requireString(meta, "topic");const signalValue = requireString(meta, "signal");- if (signalValue !== BRAIN_SIGNAL_SIGN.positive && signalValue !== BRAIN_SIGNAL_SIGN.negative) {+ if (+ signalValue !== BRAIN_SIGNAL_SIGN.positive &&+ signalValue !== BRAIN_SIGNAL_SIGN.negative+ ) {throw new Error(`signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(signalValue)} (${path})`,);@@ -306,7 +336,9 @@ export function parseSignal(path: string): BrainSignal {}for (const item of meta["source"]) {if (typeof item !== "string") {- throw new Error(`signal field 'source' must be an array of strings (${path})`);+ throw new Error(+ `signal field 'source' must be an array of strings (${path})`,+ );}}source = [...(meta["source"] as ReadonlyArray<string>)];@@ -320,10 +352,14 @@ export function parseSignal(path: string): BrainSignal {// silently misdecoding a future or hand-authored payload.const rawCodec = meta["_raw_codec"];if (rawCodec !== undefined && rawCodec !== CODEC_VERSION) {- throw new Error(`signal field '_raw_codec' must be ${JSON.stringify(CODEC_VERSION)} (${path})`);+ throw new Error(+ `signal field '_raw_codec' must be ${JSON.stringify(CODEC_VERSION)} (${path})`,+ );}const raw =- rawSection !== undefined && rawCodec === CODEC_VERSION ? expand(rawSection) : rawSection;+ rawSection !== undefined && rawCodec === CODEC_VERSION+ ? expand(rawSection)+ : rawSection;// Capture-extension optional fields. Absence stays as `undefined`// on the returned object β never coerced to a default, so callers@@ -346,6 +382,20 @@ export function parseSignal(path: string): BrainSignal {}}+ let schema_type: string | undefined;+ if (meta["schema_type"] !== undefined) {+ schema_type = validateSchemaToken(meta["schema_type"], "schema_type");+ const vocab = options.schemaVocabulary;+ if (+ vocab !== undefined &&+ !isKnownSchemaToken(vocab, "signal_types", schema_type)+ ) {+ throw new Error(+ `schema_type ${JSON.stringify(schema_type)} is not declared in signal_types (${path})`,+ );+ }+ }+let dedup_hash: string | undefined;if (meta["dedup_hash"] !== undefined) {const v = meta["dedup_hash"];@@ -379,6 +429,7 @@ export function parseSignal(path: string): BrainSignal {...(source !== undefined ? { source } : {}),...(raw !== undefined ? { raw } : {}),...(source_type !== undefined ? { source_type } : {}),+ ...(schema_type !== undefined ? { schema_type } : {}),...(dedup_hash !== undefined ? { dedup_hash } : {}),...(session_ref !== undefined ? { session_ref } : {}),...readBiTemporal(meta, path),@@ -451,7 +502,10 @@ function composeSignalTags(input: WriteSignalInput): string[] {// 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) {+ 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 ?? []) {@@ -497,7 +551,10 @@ function requireField(meta: Record<string, unknown>, field: string): void {if (!(field in meta) || meta[field] === undefined || meta[field] === null) {throw new Error(`signal missing field: ${field}`);}- if (typeof meta[field] === "string" && (meta[field] as string).trim() === "") {+ if (+ typeof meta[field] === "string" &&+ (meta[field] as string).trim() === ""+ ) {throw new Error(`signal missing field: ${field}`);}}@@ -511,7 +568,10 @@ function requireString(meta: Record<string, unknown>, field: string): string {return v;}-function requireStringArray(meta: Record<string, unknown>, field: string): ReadonlyArray<string> {+function requireStringArray(+ meta: Record<string, unknown>,+ field: string,+): ReadonlyArray<string> {requireField(meta, field);const v = meta[field];if (!Array.isArray(v)) {diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 4466a4ac..86c48479 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -358,6 +358,8 @@ export interface BrainSignal {* semantically equivalent to `live`, never inject a default.*/readonly source_type?: BrainSignalSourceType;+ /** Optional runtime schema taxonomy token. Inert metadata. */+ readonly schema_type?: string;/*** Normalised payload hash anchored to (topic, signal, principle,* scope). Idempotency anchor for `scan-inline` (Β§9) and@@ -450,6 +452,8 @@ export interface BrainPreference {/** Optional wikilink to a retired pref this one replaces. */readonly supersedes?: string;readonly aliases?: ReadonlyArray<string>;+ /** Optional runtime schema taxonomy token. Inert metadata. */+ readonly schema_type?: string;readonly memory_layer?: BrainMemoryLayer;readonly memory_branch?: string;readonly related?: ReadonlyArray<string>;@@ -516,6 +520,8 @@ export interface BrainRetired {readonly confidence_value: number | null;readonly pinned: boolean;readonly aliases?: ReadonlyArray<string>;+ /** Optional runtime schema taxonomy token. Inert metadata. */+ readonly schema_type?: string;readonly memory_layer?: BrainMemoryLayer;readonly memory_branch?: string;readonly related?: ReadonlyArray<string>;@@ -897,6 +903,18 @@ export interface BrainGuardrailConfig {readonly instruction_file_max_lines?: number;}+/**+ * Optional runtime schema vocabulary declarations (v0.25.0 foundation).+ * These are taxonomy tokens, not replacements for operational lifecycle+ * states such as `preference.status` or `apply-evidence` results.+ */+export interface BrainSchemaConfig {+ readonly preference_types?: ReadonlyArray<string>;+ readonly signal_types?: ReadonlyArray<string>;+ readonly page_types?: ReadonlyArray<string>;+ readonly log_event_kinds?: ReadonlyArray<string>;+}+/*** Root of `Brain/_brain.yaml`. `schema_version` is mandatory; unknown* top-level keys are tolerated as forward-compat (logged as a warning by@@ -970,6 +988,11 @@ export interface BrainConfig {* to `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.*/readonly health?: BrainHealthConfig;+ /**+ * Optional runtime schema vocabulary declarations. Absent by default;+ * consumers resolve built-ins through `resolveSchemaVocabulary`.+ */+ readonly schema?: BrainSchemaConfig;}/**diff --git a/tests/cli/brain-schema-cli.test.ts b/tests/cli/brain-schema-cli.test.tsnew file mode 100644index 00000000..ebf8cfe9--- /dev/null+++ b/tests/cli/brain-schema-cli.test.ts@@ -0,0 +1,133 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ writePreference,+ type WritePreferenceInput,+} from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_SIGNAL_SIGN,+} from "../../src/core/brain/types.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-schema-cli-"));+ vault = join(tmp, "vault");+ for (const dir of [+ "preferences",+ "retired",+ "inbox",+ "inbox/processed",+ "log",+ ]) {+ mkdirSync(join(vault, "Brain", dir), { recursive: true });+ }+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ [+ "schema_version: 1",+ "schema:",+ " preference_types: [research, decision]",+ " signal_types: [observation]",+ ].join("\n"),+ "utf8",+ );+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++function basePref(+ slug: string,+ overrides: Partial<WritePreferenceInput> = {},+): WritePreferenceInput {+ return {+ slug,+ topic: "research",+ principle: `Principle for ${slug}`,+ created_at: "2026-05-30T12:00:00Z",+ unconfirmed_until: "2026-06-06T12:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-30T13:00:00Z",+ confidence: BRAIN_CONFIDENCE.low,+ pinned: false,+ ...overrides,+ };+}++function seedSchemaVault(): void {+ writePreference(+ vault,+ basePref("research-pref", {+ schema_type: "research",+ }),+ );+ writeSignal(vault, {+ topic: "research",+ signal: BRAIN_SIGNAL_SIGN.positive,+ agent: "tester",+ principle: "unknown signal schema type",+ created_at: "2026-05-30T12:00:00Z",+ date: "2026-05-30",+ slug: "external",+ schema_type: "external",+ });+}++describe("o2b brain schema", () => {+ test("--json prints the schema report", async () => {+ seedSchemaVault();++ const r = await runCli(["brain", "schema", "--json"], { env: env() });++ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ vocabulary: { preference_types: string[] };+ usage: { signal_types: Array<{ token: string; count: number }> };+ findings: Array<{ kind: string; token: string }>;+ };+ expect(payload.vocabulary.preference_types).toEqual([+ "preference",+ "research",+ "decision",+ ]);+ expect(payload.usage.signal_types).toEqual([+ { token: "external", count: 1 },+ ]);+ expect(payload.findings).toContainEqual(+ expect.objectContaining({ kind: "unknown-token", token: "external" }),+ );+ });++ test("text output summarizes vocabulary, usage, and findings", async () => {+ seedSchemaVault();++ const r = await runCli(["brain", "schema"], { env: env() });++ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("brain schema");+ expect(r.stdout).toContain(+ "preference_types: preference, research, decision",+ );+ expect(r.stdout).toContain("signal_types usage: external x1");+ expect(r.stdout).toContain("[unknown-token] signal_types external");+ expect(r.stdout).toContain(+ "[unused-declaration] preference_types decision",+ );+ });+});diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.tsindex f4a0ddd7..33a86aa4 100644--- a/tests/core/brain.policy.test.ts+++ b/tests/core/brain.policy.test.ts@@ -15,6 +15,7 @@ import {validateBrainConfig,validateBrainConfigDetailed,} from "../../src/core/brain/policy.ts";+import { resolveSchemaVocabulary } from "../../src/core/brain/schema-vocab.ts";let tmp: string;@@ -67,7 +68,10 @@ describe("DEFAULT_BRAIN_CONFIG", () => {describe("validateBrainConfig β happy path", () => {test("accepts the default config", () => {- const config = validateBrainConfig(JSON.parse(JSON.stringify(DEFAULT_BRAIN_CONFIG)), "<test>");+ const config = validateBrainConfig(+ JSON.parse(JSON.stringify(DEFAULT_BRAIN_CONFIG)),+ "<test>",+ );expect(config.schema_version).toBe(1);expect(config.snapshots.retention_count).toBe(10);});@@ -94,6 +98,78 @@ describe("validateBrainConfig β happy path", () => {});});+describe("validateBrainConfig β schema block", () => {+ test("absent schema block keeps the default config unchanged", () => {+ expect(DEFAULT_BRAIN_CONFIG).not.toHaveProperty("schema");++ const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");+ expect(cfg.schema).toBeUndefined();+ expect(resolveSchemaVocabulary(cfg.schema).preference_types).toEqual([+ "preference",+ ]);+ });++ test("accepts inline array declarations and resolves them through schema vocabulary", () => {+ const cfg = validateBrainConfig(+ parseBrainYaml(+ [+ "schema_version: 1",+ "schema:",+ " preference_types: [research, decision]",+ " signal_types: [observation]",+ " page_types: [paper, researcher]",+ " log_event_kinds: [milestone]",+ ].join("\n"),+ ),+ "<schema>",+ );++ expect(cfg.schema?.preference_types).toEqual(["research", "decision"]);+ const vocab = resolveSchemaVocabulary(cfg.schema);+ expect(vocab.preference_types).toEqual([+ "preference",+ "research",+ "decision",+ ]);+ expect(vocab.signal_types).toEqual(["feedback", "observation"]);+ expect(vocab.page_types).toEqual(["note", "paper", "researcher"]);+ expect(vocab.log_event_kinds).toContain("milestone");+ });++ test("rejects invalid schema tokens with a field-named error", () => {+ let thrown: unknown;+ try {+ validateBrainConfig(+ parseBrainYaml(+ "schema_version: 1\nschema:\n preference_types: [research, ../escape]\n",+ ),+ "<schema>",+ );+ } catch (err) {+ thrown = err;+ }++ expect(thrown).toBeInstanceOf(Error);+ const message = (thrown as Error).message;+ expect(message).toContain("schema.preference_types[1]");+ expect(message.match(/schema\.preference_types\[1\]/g)?.length).toBe(1);+ });++ test("unknown schema subkeys warn without failing validation", () => {+ const result = validateBrainConfigDetailed(+ parseBrainYaml(+ "schema_version: 1\nschema:\n preference_types: [research]\n routing_hints: [later]\n",+ ),+ "<schema>",+ );++ expect(result.config.schema?.preference_types).toEqual(["research"]);+ expect(result.warnings.map((warning) => warning.message)).toContain(+ "schema.routing_hints: unknown field ignored (forward-compat)",+ );+ });+});+describe("validateBrainConfig β primary_agent", () => {test("absent β null (default)", () => {const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");@@ -101,7 +177,10 @@ describe("validateBrainConfig β primary_agent", () => {});test("explicit null is accepted", () => {- const cfg = validateBrainConfig({ schema_version: 1, primary_agent: null }, "<test>");+ const cfg = validateBrainConfig(+ { schema_version: 1, primary_agent: null },+ "<test>",+ );expect(cfg.primary_agent).toBeNull();});@@ -125,14 +204,17 @@ describe("validateBrainConfig β primary_agent", () => {test("whitespace-only string rejected", () => {expect(() =>- validateBrainConfig({ schema_version: 1, primary_agent: " " }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, primary_agent: " " },+ "<test>",+ ),).toThrow(/primary_agent/);});test("non-string non-null rejected", () => {- expect(() => validateBrainConfig({ schema_version: 1, primary_agent: 42 }, "<test>")).toThrow(- /primary_agent/,- );+ expect(() =>+ validateBrainConfig({ schema_version: 1, primary_agent: 42 }, "<test>"),+ ).toThrow(/primary_agent/);});});@@ -147,10 +229,18 @@ describe("formatPrimaryAgentYamlValue", () => {});test("rejects values that would need escaping in the tiny YAML parser", () => {- expect(() => formatPrimaryAgentYamlValue("agent\nnext")).toThrow(/disallowed character/);- expect(() => formatPrimaryAgentYamlValue("agent\rnext")).toThrow(/disallowed character/);- expect(() => formatPrimaryAgentYamlValue("agent\\path")).toThrow(/disallowed character/);- expect(() => formatPrimaryAgentYamlValue('agent "quoted"')).toThrow(/disallowed character/);+ expect(() => formatPrimaryAgentYamlValue("agent\nnext")).toThrow(+ /disallowed character/,+ );+ expect(() => formatPrimaryAgentYamlValue("agent\rnext")).toThrow(+ /disallowed character/,+ );+ expect(() => formatPrimaryAgentYamlValue("agent\\path")).toThrow(+ /disallowed character/,+ );+ expect(() => formatPrimaryAgentYamlValue('agent "quoted"')).toThrow(+ /disallowed character/,+ );});});@@ -166,17 +256,26 @@ describe("validateBrainConfig β error cases", () => {});test("unsupported schema_version β error", () => {- expect(() => validateBrainConfig({ schema_version: 99 }, "<test>")).toThrow(/schema_version/);+ expect(() => validateBrainConfig({ schema_version: 99 }, "<test>")).toThrow(+ /schema_version/,+ );});test("non-integer schema_version β error", () => {- expect(() => validateBrainConfig({ schema_version: "1" }, "<test>")).toThrow(/schema_version/);- expect(() => validateBrainConfig({ schema_version: 1.5 }, "<test>")).toThrow(/schema_version/);+ expect(() =>+ validateBrainConfig({ schema_version: "1" }, "<test>"),+ ).toThrow(/schema_version/);+ expect(() =>+ validateBrainConfig({ schema_version: 1.5 }, "<test>"),+ ).toThrow(/schema_version/);});test("negative threshold β error naming the field", () => {try {- validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: -1 } }, "<test>");+ validateBrainConfig(+ { schema_version: 1, dream: { candidate_threshold: -1 } },+ "<test>",+ );throw new Error("should have thrown");} catch (err) {expect(err).toBeInstanceOf(BrainConfigError);@@ -186,25 +285,40 @@ describe("validateBrainConfig β error cases", () => {test("non-integer threshold β error", () => {expect(() =>- validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: 3.5 } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, dream: { candidate_threshold: 3.5 } },+ "<test>",+ ),).toThrow(/positive integer/);});test("zero candidate_threshold β error (must be positive)", () => {expect(() =>- validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: 0 } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, dream: { candidate_threshold: 0 } },+ "<test>",+ ),).toThrow(/positive integer/);});test("snapshots.retention_count must be positive integer", () => {expect(() =>- validateBrainConfig({ schema_version: 1, snapshots: { retention_count: 0 } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, snapshots: { retention_count: 0 } },+ "<test>",+ ),).toThrow(/positive integer/);expect(() =>- validateBrainConfig({ schema_version: 1, snapshots: { retention_count: -5 } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, snapshots: { retention_count: -5 } },+ "<test>",+ ),).toThrow(/positive integer/);expect(() =>- validateBrainConfig({ schema_version: 1, snapshots: { retention_count: 1.5 } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, snapshots: { retention_count: 1.5 } },+ "<test>",+ ),).toThrow(/positive integer/);});@@ -215,7 +329,9 @@ describe("validateBrainConfig β error cases", () => {});test("non-object block β error", () => {- expect(() => validateBrainConfig({ schema_version: 1, dream: 5 }, "<test>")).toThrow(/dream/);+ expect(() =>+ validateBrainConfig({ schema_version: 1, dream: 5 }, "<test>"),+ ).toThrow(/dream/);});test("confidence.low_max_applied = 0 is allowed (non-negative)", () => {@@ -234,8 +350,12 @@ describe("validateBrainConfig β warnings (forward-compat)", () => {"<test>",);expect(result.warnings.length).toBe(2);- expect(result.warnings.map((w) => w.message).join("\n")).toContain("future_field");- expect(result.warnings.map((w) => w.message).join("\n")).toContain("another");+ expect(result.warnings.map((w) => w.message).join("\n")).toContain(+ "future_field",+ );+ expect(result.warnings.map((w) => w.message).join("\n")).toContain(+ "another",+ );expect(result.config.schema_version).toBe(1);});@@ -269,11 +389,18 @@ describe("validateBrainConfig β vault block (v0.10.9)", () => {},"<test>",);- expect(cfg.vault?.ignore_paths).toEqual([".git", "node_modules", "Brain/.snapshots"]);+ expect(cfg.vault?.ignore_paths).toEqual([+ ".git",+ "node_modules",+ "Brain/.snapshots",+ ]);});test("vault.ignore_paths empty array honoured as explicit empty", () => {- const cfg = validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [] } }, "<test>");+ const cfg = validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: [] } },+ "<test>",+ );expect(cfg.vault?.ignore_paths).toEqual([]);});@@ -286,30 +413,44 @@ describe("validateBrainConfig β vault block (v0.10.9)", () => {});test("vault block not a map β BrainConfigError naming the field", () => {- expect(() => validateBrainConfig({ schema_version: 1, vault: 5 }, "<test>")).toThrow(/vault/);+ expect(() =>+ validateBrainConfig({ schema_version: 1, vault: 5 }, "<test>"),+ ).toThrow(/vault/);});test("vault.ignore_paths not an array β BrainConfigError", () => {expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: "not-a-list" } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: "not-a-list" } },+ "<test>",+ ),).toThrow(/vault\.ignore_paths/);});test("non-string entry β BrainConfigError naming the index", () => {expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [".git", 42] } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: [".git", 42] } },+ "<test>",+ ),).toThrow(/vault\.ignore_paths\[1\]/);});test("empty-string entry rejected", () => {expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [" "] } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: [" "] } },+ "<test>",+ ),).toThrow(/non-empty/);});test("entry with newline is rejected", () => {expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["bad\nentry"] } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: ["bad\nentry"] } },+ "<test>",+ ),).toThrow(/vault\.ignore_paths\[0\]/);});@@ -322,7 +463,9 @@ describe("validateBrainConfig β vault block (v0.10.9)", () => {"<test>",);expect(result.config.vault?.ignore_paths).toEqual([".git"]);- expect(result.warnings.some((w) => w.message.includes("unknown_extra"))).toBe(true);+ expect(+ result.warnings.some((w) => w.message.includes("unknown_extra")),+ ).toBe(true);});test("DEFAULT_BRAIN_CONFIG_YAML parses with the vault block populated", () => {@@ -350,10 +493,16 @@ describe("validateBrainConfig β vault block (v0.10.9)", () => {test("entry that normalises to empty (e.g. './' / '/') is rejected", () => {expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["./"] } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: ["./"] } },+ "<test>",+ ),).toThrow(/vault\.ignore_paths\[0\].*empty/);expect(() =>- validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["///"] } }, "<test>"),+ validateBrainConfig(+ { schema_version: 1, vault: { ignore_paths: ["///"] } },+ "<test>",+ ),).toThrow(/vault\.ignore_paths\[0\].*empty/);});@@ -432,10 +581,9 @@ describe("parseBrainYaml", () => {const parsed = parseBrainYaml(`schema_version: 1\nvault:\n ignore_paths: [Drafts, "Drafts/cache"]\n`,);- expect((parsed["vault"] as { ignore_paths: unknown }).ignore_paths).toEqual([- "Drafts",- "Drafts/cache",- ]);+ expect((parsed["vault"] as { ignore_paths: unknown }).ignore_paths).toEqual(+ ["Drafts", "Drafts/cache"],+ );});test("parses one-level indented blocks", () => {@@ -457,10 +605,14 @@ describe("parseBrainYaml", () => {});test("rejects nested blocks deeper than one level", () => {- expect(() => parseBrainYaml(`top:\n middle:\n leaf: 1\n`)).toThrow(/deeper than one level/);+ expect(() => parseBrainYaml(`top:\n middle:\n leaf: 1\n`)).toThrow(+ /deeper than one level/,+ );});test("rejects duplicate top-level key", () => {- expect(() => parseBrainYaml(`schema_version: 1\nschema_version: 2\n`)).toThrow(/duplicate/);+ expect(() =>+ parseBrainYaml(`schema_version: 1\nschema_version: 2\n`),+ ).toThrow(/duplicate/);});});diff --git a/tests/core/brain/schema-metadata.test.ts b/tests/core/brain/schema-metadata.test.tsnew file mode 100644index 00000000..b0221089--- /dev/null+++ b/tests/core/brain/schema-metadata.test.ts@@ -0,0 +1,163 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ moveToRetired,+ parsePreference,+ parseRetired,+ writePreference,+ type WritePreferenceInput,+} from "../../../src/core/brain/preference.ts";+import { resolveSchemaVocabulary } from "../../../src/core/brain/schema-vocab.ts";+import { parseSignal, writeSignal } from "../../../src/core/brain/signal.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_RETIRED_REASON,+ BRAIN_SIGNAL_SIGN,+} from "../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-schema-meta-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function basePref(+ slug: string,+ overrides: Partial<WritePreferenceInput> = {},+): WritePreferenceInput {+ return {+ slug,+ topic: "research",+ principle: `Principle for ${slug}`,+ created_at: "2026-05-30T12:00:00Z",+ unconfirmed_until: "2026-06-06T12:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-30T13:00:00Z",+ confidence: BRAIN_CONFIDENCE.low,+ pinned: false,+ ...overrides,+ };+}++describe("Brain artifact schema metadata", () => {+ test("preference writer omits schema_type unless supplied", () => {+ const res = writePreference(vault, basePref("legacy"));+ const text = readFileSync(res.path, "utf8");++ expect(text).not.toContain("schema_type:");+ expect(parsePreference(res.path).schema_type).toBeUndefined();+ });++ test("preference writer and parser round-trip schema_type", () => {+ const vocab = resolveSchemaVocabulary({ preference_types: ["research"] });+ const res = writePreference(+ vault,+ basePref("custom", {+ schema_type: "Research",+ } as Partial<WritePreferenceInput>),+ );++ expect(readFileSync(res.path, "utf8")).toContain("schema_type: research");+ expect(+ parsePreference(res.path, { schemaVocabulary: vocab }).schema_type,+ ).toBe("research");+ });++ test("preference parser rejects schema_type unknown to a provided vocabulary", () => {+ const path = join(vault, "Brain", "preferences", "pref-unknown.md");+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ "id: pref-unknown",+ "created_at: 2026-05-30T12:00:00Z",+ "_confirmed_at: 2026-05-30T13:00:00Z",+ "unconfirmed_until: 2026-06-06T12:00:00Z",+ "tags: [brain, brain/preference, brain/topic/research]",+ "topic: research",+ "_status: confirmed",+ "principle: unknown schema type",+ "_evidenced_by: []",+ "_applied_count: 0",+ "_violated_count: 0",+ '_last_evidence_at: "null"',+ "_confidence: low",+ '_confidence_value: "null"',+ "pinned: false",+ "schema_type: unknown",+ "---",+ ].join("\n"),+ "utf8",+ );++ const vocab = resolveSchemaVocabulary({ preference_types: ["research"] });+ expect(() => parsePreference(path, { schemaVocabulary: vocab })).toThrow(+ "schema_type",+ );+ });++ test("moveToRetired preserves schema_type metadata", () => {+ const vocab = resolveSchemaVocabulary({ preference_types: ["research"] });+ const res = writePreference(+ vault,+ basePref("retire-me", {+ schema_type: "research",+ } as Partial<WritePreferenceInput>),+ );++ const retired = moveToRetired(+ vault,+ res.path,+ BRAIN_RETIRED_REASON.userRejected,+ {+ now: new Date("2026-06-01T00:00:00Z"),+ retired_by: "[[Brain/log/2026-06-01]]",+ user_rejected_reason: "test",+ },+ );++ expect(+ parseRetired(retired.path, { schemaVocabulary: vocab }).schema_type,+ ).toBe("research");+ });++ test("signal writer and parser round-trip schema_type", () => {+ const vocab = resolveSchemaVocabulary({ signal_types: ["observation"] });+ const res = writeSignal(vault, {+ topic: "research",+ signal: BRAIN_SIGNAL_SIGN.positive,+ agent: "tester",+ principle: "capture observations",+ created_at: "2026-05-30T12:00:00Z",+ date: "2026-05-30",+ slug: "observation",+ schema_type: "Observation",+ });++ expect(readFileSync(res.path, "utf8")).toContain(+ "schema_type: observation",+ );+ expect(parseSignal(res.path, { schemaVocabulary: vocab }).schema_type).toBe(+ "observation",+ );+ });+});diff --git a/tests/core/brain/schema-report.test.ts b/tests/core/brain/schema-report.test.tsnew file mode 100644index 00000000..fd1f7d22--- /dev/null+++ b/tests/core/brain/schema-report.test.ts@@ -0,0 +1,160 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ writePreference,+ type WritePreferenceInput,+} from "../../../src/core/brain/preference.ts";+import { buildSchemaReport } from "../../../src/core/brain/schema-report.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_SIGNAL_SIGN,+} from "../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-schema-report-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox", "processed"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function writeBrainConfig(body: string): void {+ writeFileSync(join(vault, "Brain", "_brain.yaml"), body, "utf8");+}++function basePref(+ slug: string,+ overrides: Partial<WritePreferenceInput> = {},+): WritePreferenceInput {+ return {+ slug,+ topic: "research",+ principle: `Principle for ${slug}`,+ created_at: "2026-05-30T12:00:00Z",+ unconfirmed_until: "2026-06-06T12:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-30T13:00:00Z",+ confidence: BRAIN_CONFIDENCE.low,+ pinned: false,+ ...overrides,+ };+}++describe("buildSchemaReport", () => {+ test("returns resolved vocabulary, usage counts, and lint findings", () => {+ writeBrainConfig(+ [+ "schema_version: 1",+ "schema:",+ " preference_types: [research, decision]",+ " signal_types: [observation]",+ " page_types: [paper, unused-page]",+ " log_event_kinds: [milestone, unused-event]",+ ].join("\n"),+ );+ writePreference(+ vault,+ basePref("research-pref", {+ schema_type: "research",+ }),+ );+ writeSignal(vault, {+ topic: "research",+ signal: BRAIN_SIGNAL_SIGN.positive,+ agent: "tester",+ principle: "unknown signal schema type",+ created_at: "2026-05-30T12:00:00Z",+ date: "2026-05-30",+ slug: "external",+ schema_type: "external",+ });+ mkdirSync(join(vault, "Papers"), { recursive: true });+ writeFileSync(+ join(vault, "Papers", "paper.md"),+ ["---", "title: Paper", "schema_type: paper", "---", "", "Body"].join(+ "\n",+ ),+ "utf8",+ );+ writeFileSync(+ join(vault, "Brain", "log", "2026-05-30.md"),+ [+ "# Brain log β 2026-05-30",+ "",+ "## 12:00:00 milestone",+ "- text: shipped schema report",+ ].join("\n"),+ "utf8",+ );++ const report = buildSchemaReport(vault);++ expect(report.vocabulary.preference_types).toEqual([+ "preference",+ "research",+ "decision",+ ]);+ expect(report.vocabulary.signal_types).toEqual(["feedback", "observation"]);+ expect(report.usage.preference_types).toEqual([+ { token: "research", count: 1 },+ ]);+ expect(report.usage.signal_types).toEqual([+ { token: "external", count: 1 },+ ]);+ expect(report.usage.page_types).toEqual([{ token: "paper", count: 1 }]);+ expect(report.usage.log_event_kinds).toEqual([+ { token: "milestone", count: 1 },+ ]);+ expect(report.findings).toContainEqual({+ kind: "unknown-token",+ category: "signal_types",+ token: "external",+ path: "Brain/inbox/sig-2026-05-30-external.md",+ });+ expect(report.findings).toContainEqual({+ kind: "unused-declaration",+ category: "preference_types",+ token: "decision",+ });+ expect(report.findings).toContainEqual({+ kind: "unused-declaration",+ category: "signal_types",+ token: "observation",+ });+ expect(report.findings).toContainEqual({+ kind: "unused-declaration",+ category: "page_types",+ token: "unused-page",+ });+ expect(report.findings).toContainEqual({+ kind: "unused-declaration",+ category: "log_event_kinds",+ token: "unused-event",+ });+ });++ test("default vault has built-in vocabulary and no findings", () => {+ writeBrainConfig("schema_version: 1\n");++ const report = buildSchemaReport(vault);++ expect(report.vocabulary.preference_types).toEqual(["preference"]);+ expect(report.usage.preference_types).toEqual([]);+ expect(report.findings).toEqual([]);+ expect(Object.isFrozen(report)).toBe(true);+ expect(Object.isFrozen(report.findings)).toBe(true);+ });+});diff --git a/tests/core/brain/schema-vocab.test.ts b/tests/core/brain/schema-vocab.test.tsnew file mode 100644index 00000000..ac268f49--- /dev/null+++ b/tests/core/brain/schema-vocab.test.ts@@ -0,0 +1,106 @@+import { describe, expect, test } from "bun:test";++import {+ DEFAULT_SCHEMA_VOCAB,+ SchemaVocabularyError,+ isKnownSchemaToken,+ normalizeSchemaToken,+ resolveSchemaVocabulary,+ validateSchemaDeclarations,+} from "../../../src/core/brain/schema-vocab.ts";++describe("Brain schema vocabulary", () => {+ test("default vocabulary is frozen and exposes the built-in taxonomy", () => {+ expect(Object.isFrozen(DEFAULT_SCHEMA_VOCAB)).toBe(true);+ expect(Object.isFrozen(DEFAULT_SCHEMA_VOCAB.preference_types)).toBe(true);+ expect(Object.isFrozen(DEFAULT_SCHEMA_VOCAB.signal_types)).toBe(true);+ expect(Object.isFrozen(DEFAULT_SCHEMA_VOCAB.page_types)).toBe(true);+ expect(Object.isFrozen(DEFAULT_SCHEMA_VOCAB.log_event_kinds)).toBe(true);++ expect(DEFAULT_SCHEMA_VOCAB.preference_types).toContain("preference");+ expect(DEFAULT_SCHEMA_VOCAB.signal_types).toContain("feedback");+ expect(DEFAULT_SCHEMA_VOCAB.page_types).toContain("note");+ expect(DEFAULT_SCHEMA_VOCAB.log_event_kinds).toEqual(+ expect.arrayContaining(["dream", "feedback", "note", "import-session"]),+ );+ });++ test("normalizeSchemaToken is NFC, trimmed, and lowercase", () => {+ expect(normalizeSchemaToken(" Research-Note ")).toBe("research-note");+ expect(normalizeSchemaToken("THERAPY_SESSION")).toBe("therapy_session");+ expect(normalizeSchemaToken("Cafe\u0301")).toBe("cafΓ©");+ });++ test("resolveSchemaVocabulary merges declarations after built-ins and de-duplicates", () => {+ const vocab = resolveSchemaVocabulary({+ preference_types: ["research", "Research", "decision"],+ signal_types: ["observation", "feedback"],+ page_types: ["paper", "researcher"],+ log_event_kinds: ["milestone", "note"],+ });++ expect(vocab.preference_types).toEqual([+ "preference",+ "research",+ "decision",+ ]);+ expect(vocab.signal_types).toEqual(["feedback", "observation"]);+ expect(vocab.page_types).toEqual(["note", "paper", "researcher"]);+ expect(vocab.log_event_kinds).toEqual(+ expect.arrayContaining([+ "dream",+ "feedback",+ "note",+ "import-session",+ "milestone",+ ]),+ );+ expect(+ vocab.log_event_kinds.filter((kind) => kind === "note"),+ ).toHaveLength(1);+ expect(Object.isFrozen(vocab)).toBe(true);+ expect(Object.isFrozen(vocab.preference_types)).toBe(true);+ });++ test("isKnownSchemaToken checks a resolved vocabulary category", () => {+ const vocab = resolveSchemaVocabulary({ preference_types: ["research"] });++ expect(isKnownSchemaToken(vocab, "preference_types", "preference")).toBe(+ true,+ );+ expect(isKnownSchemaToken(vocab, "preference_types", "Research")).toBe(+ true,+ );+ expect(isKnownSchemaToken(vocab, "preference_types", "unknown")).toBe(+ false,+ );+ expect(isKnownSchemaToken(vocab, "signal_types", "research")).toBe(false);+ });++ test("validateSchemaDeclarations rejects invalid token shapes with field names", () => {+ expect(() =>+ validateSchemaDeclarations({+ preference_types: ["research", "../escape"],+ }),+ ).toThrow(SchemaVocabularyError);++ try {+ validateSchemaDeclarations({+ preference_types: ["research", "../escape"],+ });+ throw new Error("expected schema validation to fail");+ } catch (err) {+ expect(err).toBeInstanceOf(SchemaVocabularyError);+ expect((err as SchemaVocabularyError).field).toBe(+ "schema.preference_types[1]",+ );+ }++ expect(() =>+ validateSchemaDeclarations({ signal_types: ["two words"] }),+ ).toThrow(/schema.signal_types\[0\]/);+ expect(() => validateSchemaDeclarations({ page_types: [""] })).toThrow(+ /schema.page_types\[0\]/,+ );+ });+});