Skip to content

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

TypeScript

feat: Write-Time Integrity & Governance Suite - schema ontology, tier guard, secret custody, maintenance lane (#76)

Sol Aitken789e3e3f249a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index c1b4e4b7..16c3ab09 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.43.1",
+ "version": "0.44.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index cda714af..c89823c1 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.43.1",
+ "version": "0.44.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4566b2aa..eae982eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,111 @@ 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.44.0] - 2026-06-05
+
+Write-Time Integrity & Governance Suite: every write into the Brain
+passes declared contracts. The schema pack becomes the single
+declarative ontology - controlled-vocabulary labels, link-type
+endpoint constraints, per-type attribute descriptors, and a
+frontmatter field tier map, all additive - with enforcement at each
+feature's existing seam: fail-closed classification whose errors
+teach the declared vocabulary, typed edges blocked at index
+materialization when their endpoint page types violate the declared
+pairs, a tier guard that detects identity-key hand-edits without
+ever write-denying a human, capability-gated secret custody that
+lets an agent use a credential without the value entering its
+context, and a quiet-window lease-guarded lane that keeps heavy
+maintenance off live interactive recall. A vault that declares none
+of the new fields behaves bit-identically. MCP tool count grows
+69 -> 73.
+
+### Added
+
+- **Schema-pack ontology fields.** Four additive fields turn the
+ pack from a flat token list into a real ontology: `labels`
+ (dimension -> fixed enum values), `link_constraints` (link type ->
+ allowed `source->target` page-type pairs), `attributes` (type ->
+ field -> natural-language description), and `frontmatter_tiers`
+ (kind -> field -> tier). All parse, render, and mutate through the
+ existing audited machinery (`o2b brain schema apply` gains
+ `add_label_dimension`, `add_link_constraint`,
+ `set_attribute_field`, `set_frontmatter_tier`, and their inverses,
+ with reference validation and cascade on `remove_type` /
+ `remove_link_type`).
+- **Controlled-vocabulary labels** (`o2b brain label`, MCP
+ `brain_labels`). Assignment is fail-closed - an unknown dimension
+ or value is rejected with the declared vocabulary in the error -
+ single-choice per dimension, persisted as a sorted
+ `labels: [dim/value]` frontmatter array (filterable via
+ `o2b search <q> --property labels=<dim>/<value>`) plus a canonical
+ `label` entity in the registry, so related notes cluster without
+ free-form tag drift.
+- **Link-type endpoint constraints** enforced at index
+ materialization. Each page's declared frontmatter `type` is
+ persisted (index schema v6) and a post-pass recomputes every typed
+ edge's blocked flag from the current pack on every run: violating
+ edges fall back to plain untyped links instead of feeding
+ typed-relation recall, `o2b brain schema lint` (and MCP
+ `schema_inspect` lint) lists each violation, and removing a
+ constraint restores the edges on the next index run without
+ touching files. Fail-open on missing information - undeclared
+ relations and unknown endpoint types always pass.
+- **Per-type attribute fields** (`o2b brain attr`). The note's own
+ frontmatter `type` selects the descriptor set; assigning an
+ undeclared field lists the declared fields WITH their descriptions
+ so the vocabulary teaches itself. One value per field, persisted
+ as a sorted `attributes: [field=value]` frontmatter array;
+ descriptors render in schema explain output as agent guidance. The
+ regex fact extractor is unchanged.
+- **Frontmatter tier guard** (`o2b brain tiers`, MCP `brain_tiers`).
+ Four tiers (identity / system / business / user) with built-in
+ defaults grounded in the fields framework writers actually emit -
+ the preference files' `_`-prefix convention becomes an explicit
+ system-tier rule. `writePreference` merges through the tier model:
+ a hand-added user field survives every framework rewrite, legacy
+ unprefixed Group C keys migrate away, and a changed identity join
+ key throws instead of being silently re-accepted. The index pass
+ snapshots identity fields and stages drift findings the snapshot
+ never absorbs; `tiers check | restore --apply | accept` is the
+ staged repair surface and `brain_doctor` warns with the open
+ count. Unknown kinds resolve everything to user - a human's own
+ vault is never constrained.
+- **Capability-gated secret custody** (`o2b brain secret`, MCP
+ `brain_secrets`). Per-value AES-256-GCM ciphertext (random IV,
+ verified auth tag - tampering fails closed) beside an
+ exclusive-create 0600 keyfile under the vault-local state dir,
+ never synced as vault content. The value enters via stdin or
+ `--from-env` (never argv), no surface returns plaintext, and
+ `run <name> -- cmd...` injects the credential into a subprocess
+ whose command must match the operator-declared glob allowlist -
+ captured output passes through the redactor with the resolved
+ value as a known literal. Every operation lands a no-values audit
+ record in `Brain/log/secret-custody/`. MCP exposes list and run
+ only; storing and removing stays on the operator's CLI. Threat
+ model stated honestly: protects against context leakage, sync
+ exposure, and casual reads - not against root.
+- **Quiet-window maintenance lane** (`o2b brain maintenance`, MCP
+ `brain_maintenance`). Dream + reindex run behind three gates: a
+ tz-aware local-time hour window with midnight wrap (unset = always
+ open), a busy gate over recent recall-telemetry records, and an
+ expiring SQLite lease in a dedicated `maintenance.sqlite` so
+ holding it never contends with the search index writer lock.
+ `--force` bypasses the soft gates but never the lease, tasks run
+ stale-first, every attempt including gate refusals lands in a
+ bounded journal, and a gate skip exits 0 so cron never alarms on a
+ quiet hour.
+
+### Changed
+
+- The search index schema advances to v6 (additive):
+ `documents.page_type`, `documents.tier_snapshot`,
+ `links.relation_blocked`, and the `tier_drift` table - all
+ reindex-safe, existing rows default to neutral values.
+- `redactRawOutput` gains a `literals` option: known secret values
+ are scrubbed verbatim before the pattern passes run.
+- `IndexStats` reports `relationViolations` and `tierDrift` for the
+ materialization post-passes.
+
## [0.43.1] - 2026-06-04
Patch release: the Hermes CLI discovery contract is now actually
@@ -4621,6 +4726,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.44.0]: https://github.com/itechmeat/open-second-brain/compare/v0.43.1...v0.44.0
[0.43.1]: https://github.com/itechmeat/open-second-brain/compare/v0.43.0...v0.43.1
[0.43.0]: https://github.com/itechmeat/open-second-brain/compare/v0.42.0...v0.43.0
[0.42.0]: https://github.com/itechmeat/open-second-brain/compare/v0.41.0...v0.42.0
diff --git a/README.md b/README.md
index a5b25835..64c83e53 100644
--- a/README.md
+++ b/README.md
@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:
These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`). The v0.43.0 surface adds the Entity Truth & Self-Improving Dream Suite: an append-only entity claim ledger under `Brain/truth/` (device-sharded JSONL claim events folded into per-`(entity, aspect)` slots with current value, superseded history, temporal-structural `value_conflict` detection that is always `ask_user`, exact-match quantity aggregation, and `o2b brain truth` / MCP `brain_truth` surfaces), deterministic atomic-fact decomposition (`o2b brain facts decompose`, markdown-structure splitting with an abbreviation guard and optional `--ingest` into the ledger), an actor-framed `quantity` fact family, a name-aware merge guard (`entity-guard` refusal with `--force` bypass) plus an `entity_contamination` deep-synthesis dimension, push-mode cross-agent collision triggers (`agent_collision` kind with cooldown dedup), outcome-tied apply-evidence (`outcome: success|failure|unknown` staging `outcome_regressions` with a deterministic confidence penalty), a markdown-first dead-end registry (`o2b brain dead-end`, MCP `brain_dead_ends` - negative knowledge FTS-recallable beside positive rules), surprisal novelty ranking on `brain_review_candidates` over the existing sqlite-vec index, a weekly `topSource` nomination in the weekly synthesis, and the Brain's first forward-looking fold (`o2b brain foresight`, MCP `brain_foresight` - recurrence cadences project next-due routines, open commitments and questions surface with sources).
+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution). The v0.42.0 surface adds the Time-Aware Recall & Activation Suite: access-reinforced activation (CLI/MCP searches record surfaced documents as hashed one-file-per-access events; a bounded `activation` ranking boost decays stored strength by a content-type half-life table where preferences and decisions never fade; `o2b brain activation status | sweep` inspects and compacts the store), co-access reinforcement edges (habitual companions in the same candidate pool boost each other with a bounded `co_access` reason), dream-stamped `freshness_trend` on preferences (`new | strengthening | stable | weakening | stale` from the evidence time distribution, multiplying the relevance portion of recall), event-time recall discipline (`since`/`until` filters obey declared `valid_from`/`valid_until` validity windows by overlap, with mtime only as the fallback), temporal-bridge traversal (time-scoped queries pull in linked causes and consequences from a padded event-time neighbourhood instead of leaking arbitrary old neighbours), and self-correcting two-pass recall (a zero-candidate evidence-pack query runs exactly one broadened OR retry, reported as `secondPass`). The v0.43.0 surface adds the Entity Truth & Self-Improving Dream Suite: an append-only entity claim ledger under `Brain/truth/` (device-sharded JSONL claim events folded into per-`(entity, aspect)` slots with current value, superseded history, temporal-structural `value_conflict` detection that is always `ask_user`, exact-match quantity aggregation, and `o2b brain truth` / MCP `brain_truth` surfaces), deterministic atomic-fact decomposition (`o2b brain facts decompose`, markdown-structure splitting with an abbreviation guard and optional `--ingest` into the ledger), an actor-framed `quantity` fact family, a name-aware merge guard (`entity-guard` refusal with `--force` bypass) plus an `entity_contamination` deep-synthesis dimension, push-mode cross-agent collision triggers (`agent_collision` kind with cooldown dedup), outcome-tied apply-evidence (`outcome: success|failure|unknown` staging `outcome_regressions` with a deterministic confidence penalty), a markdown-first dead-end registry (`o2b brain dead-end`, MCP `brain_dead_ends` - negative knowledge FTS-recallable beside positive rules), surprisal novelty ranking on `brain_review_candidates` over the existing sqlite-vec index, a weekly `topSource` nomination in the weekly synthesis, and the Brain's first forward-looking fold (`o2b brain foresight`, MCP `brain_foresight` - recurrence cadences project next-due routines, open commitments and questions surface with sources). The v0.44.0 surface adds the Write-Time Integrity & Governance Suite: schema-pack ontology fields (controlled-vocabulary `labels`, per-link-type `link_constraints` endpoint pairs, per-type `attributes` descriptors, and a `frontmatter_tiers` map - all additive with audited mutations), fail-closed label classification (`o2b brain label`, MCP `brain_labels` - unknown dimensions and values are rejected with the declared vocabulary, persisted as a filterable frontmatter array plus a canonical label entity), link-type endpoint constraints enforced at index materialization (violating typed edges fall back to untyped links, surfaced by `schema lint` and restored automatically when the constraint is removed), per-type attribute fields whose validation errors teach the declared vocabulary (`o2b brain attr`), a four-level frontmatter tier guard (identity/system/business/user with built-in framework defaults, a tier-respecting merge in framework writers, index-time identity-drift detection that never absorbs a hand-edit, and the staged `o2b brain tiers check | restore | accept` repair surface, MCP `brain_tiers`), capability-gated secret custody (`o2b brain secret set | list | rm | run`, MCP `brain_secrets` - per-value AES-256-GCM ciphertext under the vault-local state dir, stdin-only ingestion, allowlist-gated subprocess env injection with redacted output, and a no-values audit trail in `Brain/log/secret-custody/`), and a quiet-window lease-guarded maintenance lane (`o2b brain maintenance run | status`, MCP `brain_maintenance` - a tz-aware hour window, a recall-telemetry busy gate, an expiring SQLite lease no second worker can grab, stale-first task ordering, and a bounded journal of every attempt including gate refusals).
## CLI
diff --git a/docs/brainstorm/write-time-integrity-governance/cli-output/claude.md b/docs/brainstorm/write-time-integrity-governance/cli-output/claude.md
new file mode 100644
index 00000000..4c27701b
--- /dev/null
+++ b/docs/brainstorm/write-time-integrity-governance/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Unified Write-Contract Gateway
+- **Approach**: Funnel every Brain write through a single `validateWrite()` contract gateway that composes pluggable validators (tier guard, enum vocabulary, link-endpoint constraints, attribute hints) and enforces fail-closed semantics with one shared audit trail. Secret custody is a sibling "resolve-but-never-return" capability resolver invoked outside the write path; the maintenance lane is a separate scheduler. All six features hang off two cross-cutting spines.
+- **Trade-offs**:
+ - Pro: one enforcement point with consistent fail-closed behaviour and a single, uniform diagnostic/audit stream.
+ - Pro: new contracts (future epics) register once and apply everywhere.
+ - Con: directly courts the explicitly-forbidden "governance framework" over-abstraction.
+ - Con: retrofitting every existing write call site is invasive and threatens the bit-identical neutral-default guarantee across a wide blast radius.
+ - Con: couples the capture hot path to a generalized validator chain, risking the "capture stays fast" constraint.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: Schema-Pack-Centric Ontology + Two Satellites
+- **Approach**: Promote the schema pack to the single declarative ontology via additive version bump — adding a tier map (T1), controlled-vocab enums (T3), per-link source/target pairs (T4), and per-type attribute descriptors (T5) — while enforcement stays at each feature's existing seam (frontmatter merge, ranker/extractor, relation-polarity, fact-extract), all reading the same pack. Secret custody (T2) and the quiet-window maintenance lane (T6) ship as standalone modules reusing only existing conventions (node:crypto, JSONL ledger discipline, `discipline/window.ts` math). Three of six tasks collapse onto one config surface without a new runtime layer.
+- **Trade-offs**:
+ - Pro: leverages existing `schema-pack`/`schema-mutate`/`schema-vocab` machinery — the shared surface genuinely "pays for itself" and turns a flat token list into a real ontology.
+ - Pro: hot path untouched; expensive validation stays in explicit verbs/dream; neutral defaults trivially preserved (empty pack fields = old behaviour).
+ - Pro: per-task landability and additive versioning fit the v0.43.0 format-stability constraint.
+ - Con: schema pack grows broad; four enforcement seams remain physically separate even though they share one source of truth.
+ - Con: one coordinated schema version bump must serve four features, needing care to stay additive.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Six Fully Independent Modules
+- **Approach**: Each task is a self-contained core module + CLI verb + MCP tool + tests touching only its named seam, with zero coordination layer. Tier guard, enums, link constraints, and attribute hints each extend their respective files independently (the three schema features each add their own additive field in isolation); secret store and maintenance lane stand alone.
+- **Trade-offs**:
+ - Pro: minimal risk, maximal composability, easiest per-task land/revert, smallest blast radius.
+ - Pro: neutral-default guarantee is almost free per feature.
+ - Con: duplicated write-time validation plumbing across T3/T4/T5.
+ - Con: three tasks mutate the schema pack with no shared discipline — invites drift and fragmented enum/constraint/attribute handling.
+ - Con: no consistent fail-closed or audit story; misses the natural synergy of the three schema-driven features.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 2
+**Rationale**: It captures the real synergy — tasks 3, 4, 5, and 1 are all declarations that belong in the schema pack, which already exists and so avoids the forbidden framework layer while still giving a single source of truth. Enforcement at the proven existing seams keeps the capture hot path fast and makes the bit-identical neutral-default guarantee easy to pin with tests, and leaving secret custody and the maintenance lane as independent satellites honours their genuine orthogonality rather than forcing all six into the over-abstraction that sinks Variant 1 or the duplication/drift that weakens Variant 3.
diff --git a/docs/brainstorm/write-time-integrity-governance/cli-output/prompt.md b/docs/brainstorm/write-time-integrity-governance/cli-output/prompt.md
new file mode 100644
index 00000000..6b01805c
--- /dev/null
+++ b/docs/brainstorm/write-time-integrity-governance/cli-output/prompt.md
@@ -0,0 +1,110 @@
+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
+
+Epic "Write-Time Integrity & Governance Suite" for Open Second Brain (~v0.44.0). Six kanban tasks ship as one release. Theme: every write into the Brain passes declared contracts.
+
+## Task 1 (t_3f92d3f1, p4): Tiered frontmatter field protection (system vs business vs user-editable)
+
+Upstream EverOS gives every markdown file a 4-tier frontmatter chassis (L1 read-only id/type/schema_version, L2 system, L3 business, L4 user) so direct hand-edits in Obsidian/Vim cannot clobber framework-owned join keys; writers merge frontmatter respecting tier protection on every append.
+
+OSB writes frontmatter atomically and detects content-hash drift, but has no tier model declaring which frontmatter fields a human may safely edit vs which are framework-owned join keys. In a Syncthing-shared Obsidian vault that humans edit directly, a tier guard would prevent silent corruption of ids/scopes the index depends on.
+
+Codegraph hints: writeFrontmatterAtomic in src/core/vault.ts:173 (atomic write, exclusive-create semantics); src/core/brain/content-hash.ts drift checks exist; no per-field tier-protection layer.
+
+## Task 2 (t_0b134404, p4): Capability-gated secret custody store the agent uses but cannot read
+
+Upstream Signet stores secrets encrypted-at-rest (per-value ciphertext, 0600) behind a privileged plugin. The agent never receives decrypted values: the daemon resolves a secret internally and either uses it directly in an API call or injects it into a subprocess env the agent cannot inspect. Every operation emits audited diagnostics (secret.resolved_for_exec, secret.exec_started) with values never logged; routes are capability-gated.
+
+OSB redacts secrets out of memory (src/core/redactor.ts removes secrets, never resolves them) but has no positive custody path - nothing lets an OSB-driven agent USE a credential (an embedding key, a deploy token) without the value entering its context. A capability-gated, audited secret store under Brain/ would extend OSB's governance-first thesis from redaction to safe use, complementing Pay Memory's spend governance (src/core/pay-memory/ is spend approval, not credential custody).
+
+## Task 3 (t_7a41f42d, p3): Controlled-vocabulary entity labels enforced at write time
+
+Upstream Hindsight lets a memory bank define a fixed vocabulary of classification dimensions (e.g. priority with enum values low/medium/high/urgent) at config level. At retain time the extractor is forced to pick an allowed value, stored as a canonical entity like 'priority:urgent'. Labels become graph entities that cluster related memories and, when flagged, filterable tags.
+
+OSB has free-form entity extraction and entity-match ranking but no operator-defined controlled vocabulary enforced at write time. A schema-pack-driven enum the extractor must choose from would give deterministic filterable tags (domain, sensitivity, lifecycle-stage) and natural clustering, fixing same-concept-three-spellings fragmentation.
+
+Codegraph hints: src/core/search/ranker.ts:34-41 entityMatchByChunk (free-form entity layer only); schema-pack types exist but do not enforce enums at write time.
+
+## Task 4 (t_15453235, p3): Schema-enforced source/target type constraints for link types
+
+Extend the schema pack so each declared link_type carries allowed (source_type, target_type) pairs, and the extractor/validator refuses to materialize a typed relation whose endpoints violate those constraints. OSB currently declares link_types and an open relation vocabulary with fixed polarity, but never restricts which page/entity types a given relation may connect. Turns the schema pack from a flat token list into a real ontology, blocking nonsense edges (e.g. a depends_on from a preference to a payment receipt) at write time and making typed-relation recall trustworthy by construction.
+
+Codegraph hints: src/core/brain/schema-pack.ts:14-22 (SchemaPack interface, no source/target field); src/core/brain/schema-mutate.ts (add_link_type/remove_link_type only); src/core/search/relation-polarity.ts:34,171-225 (open vocabulary, endpoints unconstrained).
+
+## Task 5 (t_f5633190, p1): Per-type attribute fields with descriptions guiding fact extraction
+
+Let an extractable schema type declare a small set of typed attribute fields (e.g. status, category, proficiency) with natural-language descriptions that steer the fact extractor toward populating those fields, instead of capturing only a flat span. OSB's regex fact-extraction captures whole spans into fact-family signals with no structured attributes; per-type attribute hints would let domain-specific terminology and structured values be captured and later filtered.
+
+Codegraph hints: src/core/brain/fact-extract.ts:30-80 (FAMILY_PATTERNS, ExtractedFact has only family/text/line); src/core/brain/schema-pack.ts:20,43-45 (extractable is a token list, no field descriptors).
+
+## Task 6 (t_166d1226, p3): Quiet-window, lease-guarded heavy maintenance lane
+
+Upstream ClawMem runs a second consolidation worker only inside a configurable hour window and only when interactive query-rate is low, scoped exclusively via DB-backed worker leases (no double-run across processes), stale-first selection, journaling every attempt in maintenance_runs for operator visibility.
+
+OSB's dream/maintenance fires from cron with no contention awareness or lease, so a heavy pass can overlap an interactive recall on the same vault. A query-rate-gated, lease-guarded quiet-window lane would schedule expensive synthesis/reindex without competing with live agent turns, with an auditable run journal.
+
+Codegraph hints: src/core/brain/dream.ts (cron-triggered, no lease/quiet-window/query-rate gate); src/core/discipline/window.ts:53 has timezone window math but not applied to workers; no worker-lease/maintenance-runs equivalent.
+
+# Project context
+
+Open Second Brain: TypeScript on Bun, second brain for AI agents over Obsidian-compatible Markdown vaults plus SQLite (FTS5 + sqlite-vec) index. CLI (`o2b brain <verb>`), MCP server (69 tools), python Hermes plugin. Markdown files are authority; SQLite/state.json files are recomputable caches.
+
+Recent commits:
+3a2d2c7 chore(release): v0.43.1
+db22f43 fix(hermes): root cli.py shim completes the upstream CLI discovery contract
+a0054dd feat: Entity Truth & Self-Improving Dream Suite - claim ledger, outcome-aware dream, foresight (#74)
+b16c37d feat: Time-Aware Recall & Activation Suite - usage-aware ranking, event-time recall, two-pass recovery (#73)
+c3a2fcc feat: Agent Write Contract Suite - write sessions, decision panel, backend boundary, shared namespace (#72)
+7733f20 feat: Project History Suite - git history memory, ADR mining, architecture notes, query telemetry (#71)
+8e8c0bc feat: Memory Observability Suite - versioned continuity contract, lazy telemetry, ATOF/ATIF export, recall benchmark (#70)
+eb56c9f feat: Workspace Insight Suite - project pointers, cross-vault recall, trigger queue, proactive synthesis (#69)
+707197a feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)
+eda202d feat: Embedding Provider Suite - local embedder, provider registry, cost gate, RRF fusion (#67)
+dee5ab7 feat: Memory Integrity Suite - canonical entities, conflict-free log shards, capture boundaries, fact extraction (#66)
+
+Related files:
+- src/core/vault.ts (writeFrontmatter, writeFrontmatterAtomic, parseFrontmatterText)
+- src/core/brain/content-hash.ts (drift detection)
+- src/core/brain/schema-pack.ts, src/core/brain/schema-vocab.ts, src/core/brain/schema-mutate.ts (schema pack: declarations, aliases, prefixes, link_types, extractable, expert_routing; mutation verbs)
+- src/core/search/relation-polarity.ts (typed-relation vocabulary, fixed polarity)
+- src/core/brain/fact-extract.ts (FAMILY_PATTERNS regex families incl. quantity; ExtractedFact {family, text, line})
+- src/core/brain/entities/registry.ts (canonical entity registry upsert/relate)
+- src/core/redactor.ts (SECRET_KEYS, redactRawOutput - removal only)
+- src/core/pay-memory/ (approval workflow, receipts, policy check - the governance precedent)
+- src/core/brain/dream.ts (2226 lines, cron-fired learning pass; DreamRunSummary)
+- src/core/brain/triggers/ (trigger queue with cooldown dedup, push-mode findings)
+- src/core/discipline/window.ts (tz-aware window math, currently only for daily digest)
+- src/core/brain/truth/ (v0.43.0 claim ledger: append-only JSONL shards folding to state.json - the storage discipline precedent)
+- src/cli/brain/verbs/ + src/mcp/brain-tools.ts (CLI verb / MCP tool registration patterns)
+
+Conventions:
+- Deterministic, bounded, fail-closed core; no model calls in core paths; provider-dependent work is optional and degrades cleanly.
+- Markdown-first: durable state is human-readable .md with frontmatter; derived caches recomputable; append-only JSONL ledgers with explicit sweep where event history matters.
+- Neutral defaults: a vault without the new config/data must behave bit-identically to the previous release (pinned by tests).
+- Nothing auto-resolves silently: conflicts and destructive decisions stage as ask_user findings or require explicit flags (--force / bypass options).
+- Every new capability ships as: core module + CLI verb + MCP tool + tests (bun test) + docs.
+- TDD with atomic conventional commits; oxlint/oxfmt baseline; TypeScript strict, no `as` cast crutches.
+
+Constraints:
+- Do not change existing public APIs or break the v0.43.0 truth-ledger / schema-pack file formats (additive schema versioning only).
+- No new heavyweight external dependencies; encryption must come from the platform (node:crypto). No daemon processes - OSB is CLI/MCP invoked; "the agent cannot read the secret" must be designed within that constraint honestly (threat model: protect against accidental context leakage and casual reads, document what root/same-user access can still do).
+- The capture hot path must stay fast; expensive validation belongs in explicit verbs or the dream/maintenance lane.
+- Single PR ~50-70 files; six features must compose without a shared over-abstraction (no "governance framework" layer unless it genuinely pays for itself).
+
+# 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/write-time-integrity-governance/design.md b/docs/brainstorm/write-time-integrity-governance/design.md
new file mode 100644
index 00000000..9e97e524
--- /dev/null
+++ b/docs/brainstorm/write-time-integrity-governance/design.md
@@ -0,0 +1,64 @@
+# Write-Time Integrity & Governance Suite - declared contracts for every Brain write
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+The Brain accepts writes from humans (Obsidian/Vim over Syncthing), agents (CLI/MCP), and its own maintenance passes, but almost nothing about those writes is declared: any frontmatter field can be hand-edited including framework-owned join keys, entity labels are free-form strings that fragment ("High" / "high" / "important"), typed relations connect any two page types, fact extraction captures flat spans with no structured attributes, credentials can only be redacted out of memory but never safely used, and the heavy dream/reindex pass can land on top of a live interactive recall. Each gap is a different face of one missing idea: write-time contracts.
+
+## Scope
+
+- **Schema pack as the single declarative ontology** (additive fields, schema-pack format version stays compatible):
+ - `frontmatter_tiers` - per-kind field tier map (t_3f92d3f1, p4)
+ - `labels` - controlled-vocabulary enum dimensions (t_7a41f42d, p3)
+ - `link_constraints` - allowed (source_type, target_type) pairs per link_type (t_15453235, p3)
+ - `attributes` - per-extractable-type attribute fields with natural-language descriptions (t_f5633190, p1)
+- **Tier guard**: deterministic tier model (L1 identity / L2 system / L3 business / L4 user) with built-in defaults for framework kinds, a tier-respecting frontmatter merge helper used by framework writers, and an index-baseline drift check that stages L1/L2 violations as ask_user findings with explicit restore.
+- **Secret custody satellite** (t_0b134404, p4): AES-256-GCM per-value ciphertext store under the vault's local state dir, 0600 keyfile, set/list/rm/run surface where `run` injects the secret into a subprocess env and pipes output through the redactor; per-secret exec allowlist declared at set time; full no-values audit trail.
+- **Quiet-window maintenance lane satellite** (t_166d1226, p3): `o2b brain maintenance run` gates on (a) configured local-time window, (b) recent interactive query rate from existing recall telemetry, (c) a SQLite-backed expiring worker lease; runs registered heavy tasks stale-first and journals every attempt.
+- CLI verbs + MCP tools + tests + docs for each capability.
+
+## Out of scope
+
+- Any shared "validateWrite gateway" or governance framework layer (consultant Variant 1 - explicitly rejected).
+- LLM-driven extraction: `attributes` descriptors steer agents and validate agent-supplied values; the deterministic core never calls a model.
+- OS keychain integration and protection against same-user root processes (threat model documented instead).
+- Retroactive re-typing of existing relations or migration of existing labels (lint surfaces violations; nothing rewrites history silently).
+- Daemonized watchers; everything stays CLI/MCP invoked.
+
+## Chosen approach
+
+Consultant Variant 2 (Schema-Pack-Centric Ontology + Two Satellites), accepted without override. The four declarative features (tiers, labels, link constraints, attributes) become additive schema-pack fields parsed by the existing `schema-pack.ts` / `schema-vocab.ts` / `schema-mutate.ts` machinery, while enforcement stays at each feature's existing seam: the frontmatter merge in brain writers, the entity/label write path, `relation-polarity.ts` typed-edge materialization, and capture-time attribute validation. Secret custody and the maintenance lane are standalone modules that reuse only existing conventions (node:crypto, append-only JSONL + explicit sweep, `discipline/window.ts` timezone math, recall telemetry). No new runtime layer; a vault whose schema pack declares none of the new fields behaves bit-identically.
+
+## Design decisions
+
+- **Tier semantics (OSB mapping of EverOS L1-L4)**: L1 `identity` (id/kind/schema-version join keys - framework-owned, hand-edit = corruption), L2 `system` (framework-written timestamps/counters - hand-edit = drift), L3 `business` (agent-written domain fields via verbs), L4 `user` (freely editable). Built-in `DEFAULT_TIER_MAP` covers framework kinds (brain-preference, brain-active, brain-dead-end, signals, receipts...); `frontmatter_tiers` in the schema pack extends/overrides per kind. Unknown kinds and undeclared fields default to L4 - never block a user's own vault.
+- **Tier enforcement is two-sided but never a write-deny on humans**: (a) framework writers merge through `mergeFrontmatterTiered()` so they cannot clobber L4 fields a human added and cannot silently accept hand-edits to L1; (b) `o2b brain tiers check` compares each file's L1/L2 fields against the last-indexed baseline already stored in SQLite and stages mismatches as findings (`ask_user`), restorable via `--apply` per finding. Humans keep full file ownership; the framework detects and offers repair instead of fighting the editor.
+- **Secrets live outside synced markdown**: ciphertext store + keyfile under the vault-local state dir (alongside `brain.sqlite`), never under `Brain/`. Honest threat model in docs: protects against secret values entering agent context, vault sync/export leakage, and casual reads; does NOT protect against root or same-user processes (no daemon, no TPM - platform constraint).
+- **Capability = exec allowlist declared at set time**: `o2b brain secret set NAME --allow "curl *" --env-var API_KEY` (value via stdin or env, never argv). `secret run NAME -- cmd...` refuses commands not matching the allowlist; MCP `brain_secrets` exposes list/exists/run (run still allowlist-gated), never get. Subprocess stdout/stderr pass through `redactRawOutput` extended with the resolved value before reaching the caller.
+- **Audit trail follows the log discipline**: every secret operation appends a no-values line to `Brain/log/<date>.md` + JSONL sidecar (`secret_set`, `secret_resolved_for_exec`, `secret_exec_denied`...), making custody auditable from inside the vault without exposing material.
+- **Label canonical form** is `label:<dimension>:<value>` written into the entity registry and a `labels` frontmatter map; validation is fail-closed (`unknown dimension` / `value not in vocabulary` reject the assignment with the allowed list in the error). Search gains a deterministic `label:` filter.
+- **Link constraints constrain materialization, not authoring**: a typed relation whose endpoint kinds violate `link_constraints` falls back to an untyped link and surfaces in `schema_lint` with the violated pair; existing edges are linted, never deleted.
+- **Attributes are agent guidance + validation, not extraction magic**: descriptors render into the agent-facing schema surfaces (`schema_explain_type`, capture instructions) and validate agent-supplied `--attr field=value` pairs at capture; regex fact-extract is unchanged.
+- **Lease is SQLite, not a lockfile**: `INSERT ... ON CONFLICT` claim with expiry timestamp in `brain.sqlite` survives crashes (expired leases are reclaimable) and is visible cross-process (CLI + MCP). Query-rate gate reuses the existing recall-telemetry counters (last N minutes threshold); window gate generalizes `discipline/window.ts` local-time math to an `[start_hour, end_hour)` daily window.
+- **Maintenance journal is bounded JSONL** (`maintenance-runs.jsonl`, newest-N explicit sweep) plus a `maintenance status` verb; every attempt is journaled including gate-refusals (`skipped:window`, `skipped:busy`, `skipped:lease`).
+- **One coordinated schema-pack change**: all four new fields land in a single parser/renderer/mutate change set with one round-trip test (parse -> render -> parse identity), avoiding four divergent mini-formats.
+
+## File changes
+
+New core: `src/core/brain/frontmatter-tiers.ts`, `src/core/brain/secrets/{store,crypto,exec,audit}.ts`, `src/core/brain/maintenance/{lease,lane,journal}.ts`, `src/core/brain/labels.ts`.
+Extended core: `schema-pack.ts`, `schema-vocab.ts` (if shared validation helpers move), `schema-mutate.ts`, `src/core/search/relation-polarity.ts`, `src/core/brain/fact-extract.ts` (attr validation only), `src/core/redactor.ts` (value-set extension hook), `src/core/search/search.ts` (label filter), doctor/lint integration points.
+New CLI verbs: `tiers`, `secret`, `label`, `maintenance` (+ schema verb extensions); registered in the 5 standard places.
+New MCP tools: `brain_tiers`, `brain_secrets`, `brain_labels`, `brain_maintenance` (or folded ops where a surface already exists) with previewBudget + pinned-list/count updates in `tests/mcp/mcp.test.ts`.
+Tests: per-module unit suites, CLI suites, MCP suite, one cross-feature e2e integration test.
+Docs: README surface sentence, CHANGELOG `[0.44.0]`, `docs/cli-reference.md`, `docs/how-it-works.md` chapter.
+
+## Risks and open questions
+
+- **Index baseline coverage for tier drift**: the check can only compare fields the indexer already persists; if some L1 fields are not in SQLite today, the indexer gains them additively (risk: index schema migration - keep additive and recomputable).
+- **`.open-second-brain/` sync exposure**: if an operator syncs the state dir, the keyfile travels with the ciphertext. Docs must state the assumption (state dir is machine-local, as for `brain.sqlite`) and `brain_doctor` gains a permissions check (keyfile 0600).
+- **Allowlist bypass creativity**: `--allow "bash *"` defeats the gate; docs recommend narrow patterns and the audit trail records the exact command line (values excluded).
+- **Query-rate gate cold start**: a vault with no telemetry treats rate as zero (lane runs); acceptable because the window + lease gates still hold.
+- **Schema pack growth**: four new fields in one release; mitigated by the single coordinated change set + round-trip property test.
diff --git a/docs/brainstorm/write-time-integrity-governance/plan.md b/docs/brainstorm/write-time-integrity-governance/plan.md
new file mode 100644
index 00000000..f2c2606e
--- /dev/null
+++ b/docs/brainstorm/write-time-integrity-governance/plan.md
@@ -0,0 +1,103 @@
+# Write-Time Integrity & Governance Suite - implementation plan
+
+Feature branch: `feat/write-time-integrity-governance`. TDD per task, one atomic conventional commit per task, formatter + linter green before every commit.
+
+## Tasks
+
+### Task 1: Schema pack ontology fields (foundation)
+- **Files**: `src/core/brain/schema-pack.ts`, `src/core/brain/schema-mutate.ts`, `tests/core/brain/schema-pack-ontology.test.ts` (new), existing schema-pack/mutate tests extended
+- **What**: additive parsing + rendering + freezing for `frontmatter_tiers` (kind -> field -> tier), `labels` (dimension -> enum values), `link_constraints` (link_type -> list of `source->target` pairs), `attributes` (type -> field -> description). Mutation ops `add_label_dimension`, `remove_label_dimension`, `add_link_constraint`, `remove_link_constraint`, `set_attribute_field`, `remove_attribute_field`, `set_frontmatter_tier`, `remove_frontmatter_tier`. Round-trip property: parse(render(pack)) deep-equals pack for all new fields; empty fields render nothing (neutral default pinned).
+- **Acceptance**: round-trip test green; a config without new fields parses to empty frozen structures; invalid tokens/tiers/pairs fail closed with path-qualified errors.
+- **Depends on**: none
+
+### Task 2: Controlled-vocabulary labels (t_7a41f42d)
+- **Files**: `src/core/brain/labels.ts` (new), `src/core/search/search.ts` (label filter), `src/core/brain/entities/registry.ts` (canonical label entities), `src/cli/brain/verbs/label.ts` (new), `tests/core/brain/labels.test.ts`, `tests/cli/brain-label.test.ts`
+- **What**: `validateLabelAssignment(pack, dimension, value)` fail-closed with allowed-list errors; `assignLabel(vault, path, dimension, value)` writes frontmatter `labels` map + `label:<dim>:<value>` registry entity; `o2b brain label <path> <dim>=<value>` + `--remove`; deterministic `label:<dim>=<value>` search filter.
+- **Acceptance**: unknown dimension/value rejected with vocabulary in message; assignment idempotent; search filter returns only labeled notes; vault without `labels` config behaves bit-identically (pinned).
+- **Depends on**: Task 1
+
+### Task 3: Link-type endpoint constraints (t_15453235)
+- **Files**: `src/core/search/relation-polarity.ts`, schema-lint integration (`src/core/brain/schema-lint.ts` or existing lint module), `tests/core/search/link-constraints.test.ts`
+- **What**: typed-relation materialization consults `link_constraints`; a violating relation falls back to an untyped link (never dropped) and `schema_lint` reports each violation with the declared pairs. No constraints declared = exact current behavior.
+- **Acceptance**: violating edge is untyped + linted; conforming edge typed as today; empty-constraints snapshot test byte-identical.
+- **Depends on**: Task 1
+
+### Task 4: Per-type attribute fields (t_f5633190)
+- **Files**: `src/core/brain/fact-extract.ts` (attr validation helper only), schema explain surface (`src/mcp/` schema_explain_type handler), capture verb attr support, `tests/core/brain/attributes.test.ts`
+- **What**: `validateAttributes(pack, type, attrs)` fail-closed (unknown field lists declared fields + descriptions); `--attr field=value` on the capture path stores a structured `attributes` map; `schema_explain_type` renders descriptors so agents see the vocabulary.
+- **Acceptance**: undeclared field rejected with guidance; declared attrs persist and round-trip; no `attributes` config = no behavior change.
+- **Depends on**: Task 1
+
+### Task 5: Frontmatter tier model + merge guard (t_3f92d3f1, part 1)
+- **Files**: `src/core/brain/frontmatter-tiers.ts` (new: `TIER_LEVELS`, `DEFAULT_TIER_MAP`, `resolveFieldTier`, `mergeFrontmatterTiered`), `tests/core/brain/frontmatter-tiers.test.ts`
+- **What**: tier resolution (pack override > built-in default > L4); `mergeFrontmatterTiered(existing, incoming, {kind, pack})` - framework writes preserve L4 fields they do not own and refuse to overwrite L1 with changed values unless `acceptIdentity: true`; pure function, exhaustive unit tests.
+- **Acceptance**: L4 user field survives framework rewrite; L1 hand-edit is not silently re-accepted by a framework write; unknown kind = everything L4 = current merge semantics.
+- **Depends on**: Task 1
+
+### Task 6: Tier drift check + repair verb (t_3f92d3f1, part 2)
+- **Files**: `src/cli/brain/verbs/tiers.ts` (new), indexer baseline additions if needed (`src/core/search/store.ts`), doctor integration, `tests/cli/brain-tiers.test.ts`
+- **What**: `o2b brain tiers check` compares each indexed file's L1/L2 fields against the last-indexed baseline; mismatches stage findings (`ask_user`) listing field/expected/actual; `o2b brain tiers restore <path> [--field f] --apply` restores from baseline; `brain_doctor` surfaces count. Framework writers (preference, dead-end, truth ingest writers) switch to `mergeFrontmatterTiered`.
+- **Acceptance**: hand-edited `id` detected with expected/actual; restore round-trips; clean vault = zero findings; doctor neutral when no drift.
+- **Depends on**: Task 5
+
+### Task 7: Secret custody store + crypto (t_0b134404, part 1)
+- **Files**: `src/core/brain/secrets/crypto.ts`, `src/core/brain/secrets/store.ts`, `src/core/brain/secrets/audit.ts` (new), `tests/core/brain/secrets/store.test.ts`
+- **What**: AES-256-GCM per-value ciphertext (node:crypto, random IV per value, auth tag verified), keyfile 0600 auto-created under the vault-local state dir; store file with per-secret metadata `{name, env_var, allow (exec patterns), created_at, last_used_at}`; `setSecret`/`listSecrets` (names+metadata only)/`removeSecret`; no API returns plaintext; audit appender writes no-values events to the daily log + JSONL sidecar.
+- **Acceptance**: set/list/rm round-trip without plaintext exposure in any return value or thrown error; tampered ciphertext fails closed; keyfile created 0600; audit lines contain name + event, never value.
+- **Depends on**: none
+
+### Task 8: Secret exec + CLI + redaction (t_0b134404, part 2)
+- **Files**: `src/core/brain/secrets/exec.ts`, `src/cli/brain/verbs/secret.ts` (new), `src/core/redactor.ts` (runtime value-set extension), `tests/core/brain/secrets/exec.test.ts`, `tests/cli/brain-secret.test.ts`
+- **What**: `runWithSecret(vault, name, argv)` - allowlist match (glob on the joined command), spawn with `{...env, [env_var]: value}`, stdout/stderr passed through `redactRawOutput` extended with the resolved value, exit code propagated; `o2b brain secret set|list|rm|run` (value via stdin or `--from-env`, never argv); denial audited as `secret_exec_denied`.
+- **Acceptance**: allowlisted command sees the env var; non-matching command refused + audited; output containing the value reaches the caller redacted; value absent from o2b's own argv/env after run.
+- **Depends on**: Task 7
+
+### Task 9: Maintenance lease + gates (t_166d1226, part 1)
+- **Files**: `src/core/brain/maintenance/lease.ts`, `src/core/brain/maintenance/lane.ts` (new), `src/core/discipline/window.ts` (generalized daily window helper), `tests/core/brain/maintenance/lease.test.ts`, `tests/core/brain/maintenance/lane.test.ts`
+- **What**: SQLite expiring lease (`acquireLease(db, worker, ttl)` via INSERT ON CONFLICT, reclaim on expiry, `releaseLease`); `dailyWindowContains(now, {startHour, endHour, tz})`; query-rate gate over existing recall-telemetry counters (`interactive queries in last N min < threshold`); `evaluateGates()` returns `run | skipped:window | skipped:busy | skipped:lease`.
+- **Acceptance**: second worker cannot acquire a live lease but can reclaim an expired one; window math correct across tz/midnight-wrap; busy vault skips; no telemetry = rate 0.
+- **Depends on**: none
+
+### Task 10: Maintenance journal + verb (t_166d1226, part 2)
+- **Files**: `src/core/brain/maintenance/journal.ts`, `src/cli/brain/verbs/maintenance.ts` (new), `tests/cli/brain-maintenance.test.ts`
+- **What**: bounded JSONL journal (newest-N sweep) recording every attempt incl. gate-refusals; `o2b brain maintenance run [--force]` (force bypasses window+busy, never the lease) executing registered heavy tasks stale-first (initially: dream, reindex), `maintenance status` (lease holder, last runs, next window).
+- **Acceptance**: every attempt journaled with gate verdict; `--force` honors lease; status renders journal + lease.
+- **Depends on**: Task 9
+
+### Task 11: MCP tools + registry pins
+- **Files**: `src/mcp/brain-tools.ts`, `tests/mcp/mcp.test.ts`, `tests/mcp/brain-governance.test.ts` (new)
+- **What**: `brain_labels` (assign/remove/list ops), `brain_tiers` (check/restore), `brain_secrets` (list/run - no set/get over MCP), `brain_maintenance` (run/status); previewBudget on each; pinned sorted tool list + stdio count 69 -> 73 updated.
+- **Acceptance**: MCP suite green incl. updated pins; INVALID_PARAMS guards mirror CLI usage errors.
+- **Depends on**: Tasks 2, 6, 8, 10
+
+### Task 12: E2E integration + docs
+- **Files**: `tests/e2e/write-time-governance.integration.test.ts` (new), `README.md`, `CHANGELOG.md` (`[0.44.0]`), `docs/cli-reference.md`, `docs/how-it-works.md`
+- **What**: one vault exercising: declare ontology -> assign labels -> constraint-violating link linted -> attr validation -> hand-edit L1 -> tiers check finds + restores -> secret set/run with redacted output -> maintenance run inside/outside window. Docs per phase-5 conventions.
+- **Acceptance**: e2e green; docs build; CHANGELOG entry complete with compare link.
+- **Depends on**: all
+
+## Implementation deviations (documented during phase 2)
+
+- **Task 4 host surface**: attribute assignment ships as its own verb
+ `o2b brain attr <path> <field>=<value>` mirroring `label`, not as a
+ `--attr` flag on a capture verb - no single capture verb writes
+ typed pages today, and the note's own frontmatter `type` selecting
+ the descriptor set is the cleaner contract.
+- **Task 6 baseline**: the drift baseline is an index-time
+ `tier_snapshot` per document (seeded on first index, identity
+ fields never absorbed on later runs) rather than comparing against
+ fields "already stored in SQLite" - the index never persisted
+ frontmatter values before v6. Only identity-tier changes stage
+ findings; system-tier fields mutate legitimately on every
+ framework write and would false-positive on each dream run.
+- **Task 9 window math**: the daily window helper lives in
+ `maintenance/lane.ts` (Intl-based local hour); `discipline/window.ts`
+ stays untouched - its yesterday-interval contract is unrelated to
+ an hour-window predicate.
+- **Task 10/CLI**: the window is configured per invocation
+ (`--window H-H --tz ZONE` on the cron command line), not via a new
+ config key - explicit at the call site, neutral default preserved.
+- **Task 11**: no `brain_attr` MCP tool - descriptors already reach
+ agents through schema explain output, and attribute writes stay on
+ the CLI alongside `label`'s MCP counterpart covering the
+ classification use case.
diff --git a/docs/brainstorm/write-time-integrity-governance/variants.md b/docs/brainstorm/write-time-integrity-governance/variants.md
new file mode 100644
index 00000000..da84ac4d
--- /dev/null
+++ b/docs/brainstorm/write-time-integrity-governance/variants.md
@@ -0,0 +1,51 @@
+# Write-Time Integrity & Governance Suite - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), primary path, exit 0, 3 parseable variants. Fallback (Codex) not needed. Prompt: `cli-output/prompt.md`, raw output: `cli-output/claude.md`.
+
+## Variants (consultant verbatim)
+
+### Variant 1: Unified Write-Contract Gateway
+- **Approach**: Funnel every Brain write through a single `validateWrite()` contract gateway that composes pluggable validators (tier guard, enum vocabulary, link-endpoint constraints, attribute hints) and enforces fail-closed semantics with one shared audit trail. Secret custody is a sibling "resolve-but-never-return" capability resolver invoked outside the write path; the maintenance lane is a separate scheduler. All six features hang off two cross-cutting spines.
+- **Trade-offs**:
+ - Pro: one enforcement point with consistent fail-closed behaviour and a single, uniform diagnostic/audit stream.
+ - Pro: new contracts (future epics) register once and apply everywhere.
+ - Con: directly courts the explicitly-forbidden "governance framework" over-abstraction.
+ - Con: retrofitting every existing write call site is invasive and threatens the bit-identical neutral-default guarantee across a wide blast radius.
+ - Con: couples the capture hot path to a generalized validator chain, risking the "capture stays fast" constraint.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: Schema-Pack-Centric Ontology + Two Satellites
+- **Approach**: Promote the schema pack to the single declarative ontology via additive version bump - adding a tier map (T1), controlled-vocab enums (T3), per-link source/target pairs (T4), and per-type attribute descriptors (T5) - while enforcement stays at each feature's existing seam (frontmatter merge, ranker/extractor, relation-polarity, fact-extract), all reading the same pack. Secret custody (T2) and the quiet-window maintenance lane (T6) ship as standalone modules reusing only existing conventions (node:crypto, JSONL ledger discipline, `discipline/window.ts` math). Three of six tasks collapse onto one config surface without a new runtime layer.
+- **Trade-offs**:
+ - Pro: leverages existing `schema-pack`/`schema-mutate`/`schema-vocab` machinery - the shared surface genuinely "pays for itself" and turns a flat token list into a real ontology.
+ - Pro: hot path untouched; expensive validation stays in explicit verbs/dream; neutral defaults trivially preserved (empty pack fields = old behaviour).
+ - Pro: per-task landability and additive versioning fit the v0.43.0 format-stability constraint.
+ - Con: schema pack grows broad; four enforcement seams remain physically separate even though they share one source of truth.
+ - Con: one coordinated schema version bump must serve four features, needing care to stay additive.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Six Fully Independent Modules
+- **Approach**: Each task is a self-contained core module + CLI verb + MCP tool + tests touching only its named seam, with zero coordination layer. Tier guard, enums, link constraints, and attribute hints each extend their respective files independently (the three schema features each add their own additive field in isolation); secret store and maintenance lane stand alone.
+- **Trade-offs**:
+ - Pro: minimal risk, maximal composability, easiest per-task land/revert, smallest blast radius.
+ - Pro: neutral-default guarantee is almost free per feature.
+ - Con: duplicated write-time validation plumbing across T3/T4/T5.
+ - Con: three tasks mutate the schema pack with no shared discipline - invites drift and fragmented enum/constraint/attribute handling.
+ - Con: no consistent fail-closed or audit story; misses the natural synergy of the three schema-driven features.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Consultant recommendation: Variant 2
+**Rationale (verbatim)**: It captures the real synergy - tasks 3, 4, 5, and 1 are all declarations that belong in the schema pack, which already exists and so avoids the forbidden framework layer while still giving a single source of truth. Enforcement at the proven existing seams keeps the capture hot path fast and makes the bit-identical neutral-default guarantee easy to pin with tests, and leaving secret custody and the maintenance lane as independent satellites honours their genuine orthogonality rather than forcing all six into the over-abstraction that sinks Variant 1 or the duplication/drift that weakens Variant 3.
+
+## Orchestrator decision
+
+Variant 2 accepted without override. Project-context confirmation beyond the consultant's reasoning:
+
+1. The schema pack already has exactly the needed lifecycle (parse -> freeze -> render -> mutate -> lint) proven across three prior releases; adding four additive fields rides battle-tested machinery instead of inventing parallel config surfaces (Variant 3's drift risk is real - the v0.43.0 cycle showed how much discipline one shared format needs).
+2. Variant 1 contradicts a hard brief constraint ("no governance framework layer unless it genuinely pays for itself") and would touch every writer call site, blowing both the bit-identical guarantee and the 50-70 file target.
+3. The two satellites match precedents: secrets follow the Pay Memory governance + activation-store storage discipline; the maintenance lane reuses `discipline/window.ts` and the #71 recall-telemetry counters - no new abstractions anywhere.
+
+Containment refinements documented in `design.md`: tier guard never write-denies humans (detect + staged repair instead), secrets keyfile threat model stated honestly, `--force` on maintenance bypasses soft gates but never the lease.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 1104c7c5..0d8acfb0 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -197,6 +197,18 @@ o2b brain foresight [--horizon-days N] [--write] - forward projection:
Claims live as device-sharded append-only JSONL under `Brain/truth/` with a recomputable `state.json` fold - deleting the cache loses nothing. The merge guard rides `o2b brain merge` (an `entity-guard` refusal when the two preferences anchor disjoint people/orgs; `--force` bypasses). `o2b brain apply-evidence` accepts `--outcome success|failure|unknown`; the dream pass stages `outcome_regressions` with a deterministic confidence penalty when applied events carry repeated failures. `brain_review_candidates` annotates inbox signals with `signal_novelty` when the vault has indexed embeddings.
+### Write-time integrity and governance (since v0.44.0)
+
+```text
+o2b brain label <path> <dimension>=<value> | --remove <dimension> | --show - controlled-vocabulary classification; fail-closed against the schema pack's labels field
+o2b brain attr <path> <field>=<value> | --remove <field> | --show - per-type attribute fields; an undeclared field error lists the declared fields WITH descriptions
+o2b brain tiers check | restore <path> [--field F] --apply | accept <path> [--field F] - staged repair for identity-tier frontmatter hand-edits
+o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> - capability-gated custody; the value enters via stdin, never argv
+o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] - quiet-window lease-guarded lane for dream + reindex
+```
+
+The schema pack gains four additive ontology fields (`labels`, `link_constraints`, `attributes`, `frontmatter_tiers`) with audited mutations through `o2b brain schema apply`. Link constraints enforce at index materialization: a typed edge whose endpoint page types violate the declared pairs falls back to an untyped link, `o2b brain schema lint` lists each violation, and removing the constraint restores the edges on the next index run. Tier drift detection rides the same index pass - the snapshot keeps the expected value, so reindexes never absorb a hand-edit, and `brain_doctor` warns with the open count. Filter labelled recall with `o2b search <q> --property labels=<dim>/<value>`. Secrets protect against context leakage and vault sync exposure, not against root; every custody operation lands a no-values record in `Brain/log/secret-custody/`. A maintenance gate skip exits 0 so cron never alarms on a quiet hour.
+
## Vault scope
Single exclusion policy for every vault walker.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index a595f734..9dd7c1e6 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -965,6 +965,20 @@ The Brain recorded facts but had no notion of which one is true NOW: two contrad
**The self-improving dream.** Apply-evidence events now optionally carry a downstream outcome (`success | failure | unknown`); a rule whose applied events keep co-occurring with failures looks confirmed while actively hurting, so the dream refresh stages an `outcome_regressions` finding with a deterministic confidence penalty - staged for the operator, never silently retired. Failed approaches persist as markdown dead-ends (`Brain/dead-ends/`) that FTS indexes like any note, so recall surfaces "avoid X" beside "prefer Y". Inbox signals rank by surprisal - mean embedding distance to their nearest indexed neighbours, computed over the existing sqlite-vec index with zero provider calls - so review attention lands on genuinely new signals first. The weekly synthesis nominates the single most-developable note of the window, and the foresight fold projects forward for the first time: recurrence cadences yield next-due dates, recent open commitments and questions surface with sources, and an empty vault folds to an empty envelope.
+## Write-time integrity and governance (since v0.44.0)
+
+Until now almost nothing about a write into the Brain was declared: any frontmatter field could be hand-edited including the join keys the index depends on, labels were free-form strings that fragment, typed relations connected any two page types, credentials could only be redacted out of memory but never safely used, and the heavy dream/reindex pass could land on top of a live interactive recall. The Write-Time Integrity & Governance Suite makes the schema pack the single declarative ontology and enforces each contract at its existing seam - no new framework layer.
+
+**The ontology lives in the schema pack.** Four additive fields - `labels` (controlled-vocabulary dimensions with fixed enum values), `link_constraints` (allowed `source->target` page-type pairs per link type), `attributes` (per-type fields with natural-language descriptions), and `frontmatter_tiers` (per-kind field tier overrides) - parse, render, and mutate through the same audited machinery the schema pack always had. A vault that declares none of them behaves bit-identically.
+
+**Enforcement at the seam, fail-closed with guidance.** Label assignment rejects an unknown dimension or value WITH the declared vocabulary in the error; attribute validation lists the declared fields with their descriptions, so the error message teaches the domain language instead of just refusing. Link constraints enforce at index materialization: each page's declared `type` is persisted, a post-pass recomputes every typed edge's blocked flag from the current pack on every run - a violating edge falls back to an untyped link instead of feeding typed-relation recall, schema lint lists each violation, and removing the constraint restores the edges without touching any file.
+
+**The tier guard never fights the editor.** Four tiers (identity / system / business / user) map onto the fields framework writers actually emit; the preference files' `_`-prefix convention becomes an explicit system-tier rule. Framework rewrites merge through the tier model - a field a human added by hand survives, and a changed identity join key throws instead of being silently re-accepted - while hand-edits in Obsidian or Vim are never write-denied: the index pass snapshots identity fields, stages a drift finding the snapshot never absorbs, and the operator resolves it through `tiers check | restore | accept`. The doctor warns with the open count.
+
+**Custody, not just redaction.** Secrets live as per-value AES-256-GCM ciphertext beside a 0600 keyfile in the vault-local state dir - never synced as vault content, never returned by any surface. An agent uses a credential by running an allowlisted command with the value injected into the subprocess env; captured output comes back with the value scrubbed as a known literal, the material enters only via the operator's stdin, and every operation lands a no-values audit record under `Brain/log/secret-custody/`. The threat model is stated honestly: this protects against context leakage, sync exposure, and casual reads - not against root.
+
+**Heavy work waits its turn.** The maintenance lane runs dream and reindex behind three gates: a tz-aware local-time window, a busy gate over recent recall telemetry, and an expiring SQLite lease in its own database so holding it never contends with the search index writer lock. Force bypasses the soft gates but never the lease, tasks run stale-first, and every attempt - including each gate refusal - lands in a bounded journal, because a lane you cannot audit is a lane you cannot trust.
+
## Safety properties
These are invariants of the system, not configuration to enable.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 693d4376..f8cba9a9 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.43.1",
+ "version": "0.44.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 6d76116c..8b950784 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.43.1",
+ "version": "0.44.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.yaml
index d9167eec..3ab85f7b 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.43.1"
+version: "0.44.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 494e85c6..93e0d513 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.43.1",
+ "version": "0.44.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index d9167eec..3ab85f7b 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.43.1"
+version: "0.44.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index e6a9340a..f16a272b 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.43.1"
+version = "0.44.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.ts
index da212cc2..d6351eb4 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -37,6 +37,11 @@ import {
cmdBrainFacts,
cmdBrainDeadEnd,
cmdBrainForesight,
+ cmdBrainLabel,
+ cmdBrainAttr,
+ cmdBrainTiers,
+ cmdBrainSecret,
+ cmdBrainMaintenance,
cmdBrainAudit,
cmdBrainMorningBrief,
cmdBrainCodec,
@@ -179,6 +184,16 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainDeadEnd(rest);
case "foresight":
return await cmdBrainForesight(rest);
+ case "label":
+ return await cmdBrainLabel(rest);
+ case "attr":
+ return await cmdBrainAttr(rest);
+ case "tiers":
+ return await cmdBrainTiers(rest);
+ case "secret":
+ return await cmdBrainSecret(rest);
+ case "maintenance":
+ return await cmdBrainMaintenance(rest);
case "audit":
return await cmdBrainAudit(rest);
case "morning-brief":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 978d204e..0d5413fe 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -44,6 +44,11 @@ Brain verbs (observing memory):
facts Decompose text into atomic assertions (--ingest to ledger)
dead-end Negative-knowledge registry: record and list failed approaches
foresight Forward projection: routines coming due, open commitments and questions
+ label Controlled-vocabulary classification: assign, remove, show note labels
+ attr Typed-page attribute fields: assign, remove, show (schema-pack declared)
+ tiers Frontmatter tier guard: check identity-field drift, restore or accept
+ secret Capability-gated secret custody: set, list, rm, run (use w/o exposure)
+ maintenance Quiet-window, lease-guarded lane for heavy passes (dream, reindex)
audit Render a preference's full mutation audit trail
morning-brief Session-start summary: top prefs, open questions, recent notes
codec Compress/expand session prose with the deterministic codec (stdin/--in)
@@ -244,6 +249,46 @@ export const VERB_HELP: Record<string, string> = {
"recurring routines coming due within the horizon (cadence arithmetic, soonest\n" +
"first), recent open commitments, and open questions - every item carries\n" +
"deterministic sources. --write persists Brain/foresight/<date>.md.\n",
+ label:
+ "usage: o2b brain label <path> <dimension>=<value> | --remove <dimension> | --show [--agent N] [--vault <path>] [--json]\n" +
+ "Controlled-vocabulary classification against the schema pack's labels\n" +
+ "field. Assignments are fail-closed - unknown dimensions and values are\n" +
+ "rejected with the declared vocabulary - single-choice per dimension, and\n" +
+ "persist as a sorted labels frontmatter array plus a canonical label\n" +
+ "entity. Filter recall with: o2b search <q> --property labels=<dim>/<value>.\n",
+ attr:
+ "usage: o2b brain attr <path> <field>=<value> | --remove <field> | --show [--vault <path>] [--json]\n" +
+ "Per-type attribute fields declared in the schema pack's attributes map.\n" +
+ "The note's own frontmatter type selects the descriptor set; assigning an\n" +
+ "undeclared field is rejected with the declared fields and their\n" +
+ "natural-language descriptions. One value per field, persisted as a sorted\n" +
+ "attributes frontmatter array (filterable via --property attributes=<f>=<v>).\n",
+ tiers:
+ "usage: o2b brain tiers check | restore <path> [--field F] [--apply] | accept <path> [--field F] [--vault <path>] [--json]\n" +
+ "Frontmatter tier guard over framework-kind files. The index post-pass\n" +
+ "snapshots identity/system fields and stages a finding when an identity\n" +
+ "join key (kind, id, entity_id, category) changes by hand - the snapshot\n" +
+ "keeps the expected value, so reindexes never absorb the edit. check\n" +
+ "lists open findings; restore writes the expected value back (--apply);\n" +
+ "accept adopts the hand-edit as the new baseline. Nothing auto-resolves.\n",
+ secret:
+ "usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] | list | rm <name> | run <name> [--agent N] [--vault <path>] [--json] -- <command...>\n" +
+ "Capability-gated secret custody under the vault-local state dir:\n" +
+ "per-value AES-256-GCM ciphertext, 0600 keyfile, no surface ever prints\n" +
+ "the value. set reads the value from stdin or --from-env (never argv);\n" +
+ "run injects it as the declared env var into a subprocess whose command\n" +
+ "matches the allowlist declared at set time, and the captured output is\n" +
+ "redacted before it reaches the caller. Every operation lands a\n" +
+ "no-values record in Brain/log/secret-custody/. Protects against\n" +
+ "context leakage and vault sync exposure - not against root.\n",
+ maintenance:
+ "usage: o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]\n" +
+ "Quiet-window, lease-guarded lane for heavy passes. run gates on the\n" +
+ "local-time window (unset = always open), recent interactive query-rate\n" +
+ "from recall telemetry, and an expiring SQLite lease no second worker\n" +
+ "can grab, then executes dream + reindex stale-first. --force bypasses\n" +
+ "the soft gates but never the lease. Every attempt - including gate\n" +
+ "refusals - lands in a bounded journal; status renders lease + journal.\n",
audit:
"usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +
"Render a preference's full mutation audit trail (create / promote /\n" +
diff --git a/src/cli/brain/verbs/attr.ts b/src/cli/brain/verbs/attr.ts
new file mode 100644
index 00000000..38fe3c49
--- /dev/null
+++ b/src/cli/brain/verbs/attr.ts
@@ -0,0 +1,100 @@
+/**
+ * `o2b brain attr <path> <field>=<value> | --remove <field> | --show`
+ * (t_f5633190): per-type attribute fields. The note's own frontmatter
+ * `type` selects the schema pack's declared descriptor set; assigning
+ * an undeclared field is rejected with the declared fields AND their
+ * natural-language descriptions, so the vocabulary teaches itself.
+ *
+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage
+ * errors.
+ */
+
+import {
+ assignNoteAttribute,
+ AttributeVocabularyError,
+ readAttributes,
+ removeNoteAttribute,
+} from "../../../core/brain/attributes.ts";
+import { loadSchemaPack } from "../../../core/brain/schema-pack.ts";
+import { resolveNotePath } from "../../../core/brain/note-path.ts";
+import { defaultConfigPath } from "../../../core/config.ts";
+import { parseFrontmatter } from "../../../core/vault.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain attr <path> <field>=<value> | " +
+ "o2b brain attr <path> --remove <field> | " +
+ "o2b brain attr <path> --show [--vault <path>] [--json]";
+
+export async function cmdBrainAttr(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ remove: { type: "string" },
+ show: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const asJson = flags["json"] === true;
+ const relPath = positional[0];
+ const assignment = positional[1];
+ const remove = flags["remove"] as string | undefined;
+ const show = flags["show"] === true;
+ const modes = [assignment !== undefined, remove !== undefined, show].filter(Boolean).length;
+ if (!relPath || modes !== 1) {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ try {
+ if (show) {
+ const [metadata] = parseFrontmatter(resolveNotePath(vault, relPath));
+ const attributes = readAttributes(metadata);
+ if (asJson) okJson({ path: relPath, attributes });
+ else {
+ const entries = Object.entries(attributes);
+ ok(
+ `attributes: ${entries.length === 0 ? "(none)" : entries.map(([f, v]) => `${f}=${v}`).join(", ")}`,
+ );
+ }
+ return 0;
+ }
+
+ const pack = loadSchemaPack(vault);
+ if (remove !== undefined) {
+ const result = removeNoteAttribute(vault, relPath, { field: remove });
+ if (asJson) okJson({ ...result });
+ else if (result.removed) ok(`attribute removed: ${remove}`);
+ else ok(`attribute not present: ${remove}`);
+ return 0;
+ }
+
+ const eq = assignment!.indexOf("=");
+ if (eq <= 0 || eq === assignment!.length - 1) {
+ process.stderr.write(`brain attr: assignment must be <field>=<value>\n${USAGE}\n`);
+ return 2;
+ }
+ const result = assignNoteAttribute(vault, relPath, {
+ field: assignment!.slice(0, eq),
+ value: assignment!.slice(eq + 1),
+ pack,
+ });
+ if (asJson) okJson({ ...result });
+ else {
+ ok(`attributes: ${result.attributes.join(", ")}${result.changed ? "" : " (unchanged)"}`);
+ }
+ return 0;
+ } catch (exc) {
+ if (exc instanceof AttributeVocabularyError) {
+ process.stderr.write(`brain attr: ${exc.message}\n`);
+ return 2;
+ }
+ const message = `attr failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.ts
index b0e51f7d..db5615fd 100644
--- a/src/cli/brain/verbs/doctor.ts
+++ b/src/cli/brain/verbs/doctor.ts
@@ -1,4 +1,5 @@
import { defaultConfigPath } from "../../../core/config.ts";
+import { resolveSearchConfig } from "../../../core/search/index.ts";
import { runDoctor } from "../../../core/brain/doctor.ts";
import {
applyRemediation,
@@ -21,7 +22,10 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {
let result;
try {
- result = runDoctor(vault, { strict: Boolean(flags["strict"]) });
+ result = runDoctor(vault, {
+ strict: Boolean(flags["strict"]),
+ dbPath: resolveSearchConfig({ vault, configPath: config ?? undefined }).dbPath,
+ });
} catch (exc) {
return fail(`doctor failed: ${(exc as Error).message ?? exc}`);
}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 8d9e028b..eada1f97 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -24,6 +24,11 @@ export { cmdBrainTruth } from "./truth.ts";
export { cmdBrainFacts } from "./facts.ts";
export { cmdBrainDeadEnd } from "./dead-end.ts";
export { cmdBrainForesight } from "./foresight.ts";
+export { cmdBrainLabel } from "./label.ts";
+export { cmdBrainAttr } from "./attr.ts";
+export { cmdBrainTiers } from "./tiers.ts";
+export { cmdBrainSecret } from "./secret.ts";
+export { cmdBrainMaintenance } from "./maintenance.ts";
export { cmdBrainAudit } from "./audit.ts";
export { cmdBrainMorningBrief } from "./morning-brief.ts";
export { cmdBrainCodec } from "./codec.ts";
diff --git a/src/cli/brain/verbs/label.ts b/src/cli/brain/verbs/label.ts
new file mode 100644
index 00000000..133211a0
--- /dev/null
+++ b/src/cli/brain/verbs/label.ts
@@ -0,0 +1,103 @@
+/**
+ * `o2b brain label <path> <dimension>=<value> | --remove <dimension> | --show`
+ * (t_7a41f42d): controlled-vocabulary classification. Assignments are
+ * validated fail-closed against the schema pack's `labels` field -
+ * unknown dimensions and values are rejected with the declared
+ * vocabulary - and stored as a sorted `labels` frontmatter array plus
+ * a canonical `label` entity.
+ *
+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage
+ * errors.
+ */
+
+import {
+ assignNoteLabel,
+ LabelVocabularyError,
+ readLabels,
+ removeNoteLabel,
+} from "../../../core/brain/labels.ts";
+import { loadSchemaPack } from "../../../core/brain/schema-pack.ts";
+import { resolveNotePath } from "../../../core/brain/note-path.ts";
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { parseFrontmatter } from "../../../core/vault.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain label <path> <dimension>=<value> | " +
+ "o2b brain label <path> --remove <dimension> | " +
+ "o2b brain label <path> --show [--agent N] [--vault <path>] [--json]";
+
+export async function cmdBrainLabel(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ remove: { type: "string" },
+ show: { type: "boolean" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const asJson = flags["json"] === true;
+ const relPath = positional[0];
+ const assignment = positional[1];
+ const remove = flags["remove"] as string | undefined;
+ const show = flags["show"] === true;
+ const modes = [assignment !== undefined, remove !== undefined, show].filter(Boolean).length;
+ if (!relPath || modes !== 1) {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ try {
+ if (show) {
+ const [metadata] = parseFrontmatter(resolveNotePath(vault, relPath));
+ const labels = readLabels(metadata);
+ if (asJson) okJson({ path: relPath, labels });
+ else {
+ ok(`labels: ${labels.length === 0 ? "(none)" : labels.join(", ")}`);
+ }
+ return 0;
+ }
+
+ const pack = loadSchemaPack(vault);
+ if (remove !== undefined) {
+ const result = removeNoteLabel(vault, relPath, { dimension: remove, pack });
+ if (asJson) okJson({ ...result });
+ else if (result.removed) ok(`label removed: ${remove} (now: ${renderSet(result.labels)})`);
+ else ok(`label not present: ${remove}`);
+ return 0;
+ }
+
+ const eq = assignment!.indexOf("=");
+ if (eq <= 0 || eq === assignment!.length - 1) {
+ process.stderr.write(`brain label: assignment must be <dimension>=<value>\n${USAGE}\n`);
+ return 2;
+ }
+ const result = assignNoteLabel(vault, relPath, {
+ dimension: assignment!.slice(0, eq),
+ value: assignment!.slice(eq + 1),
+ pack,
+ agent: (flags["agent"] as string | undefined)?.trim() || resolveAgentName(config),
+ now: new Date(),
+ });
+ if (asJson) okJson({ ...result });
+ else ok(`labels: ${renderSet(result.labels)}${result.changed ? "" : " (unchanged)"}`);
+ return 0;
+ } catch (exc) {
+ if (exc instanceof LabelVocabularyError) {
+ process.stderr.write(`brain label: ${exc.message}\n`);
+ return 2;
+ }
+ const message = `label failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
+
+function renderSet(labels: ReadonlyArray<string>): string {
+ return labels.length === 0 ? "(none)" : labels.join(", ");
+}
diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.ts
new file mode 100644
index 00000000..82f285d9
--- /dev/null
+++ b/src/cli/brain/verbs/maintenance.ts
@@ -0,0 +1,148 @@
+/**
+ * `o2b brain maintenance <run|status>` (t_166d1226): the quiet-window
+ * lane for heavy passes. `run` gates on the local-time window
+ * (--window H-H, unset = always open), recent interactive query-rate,
+ * and the expiring SQLite lease, then executes dream + reindex
+ * stale-first; --force bypasses the soft gates but never the lease.
+ * `status` renders the lease holder and recent journal. Designed as
+ * the cron entry point: a dead dashboard hour surfaces as
+ * skipped:window in the journal instead of a contended vault.
+ *
+ * Exit codes: 0 on success (including a gate skip - cron must not
+ * alarm on a quiet hour), 1 on an operational failure, 2 on usage
+ * errors.
+ */
+
+import { dream } from "../../../core/brain/dream.ts";
+import { currentLease, MAINTENANCE_LEASE_NAME } from "../../../core/brain/maintenance/lease.ts";
+import {
+ MAINTENANCE_BUSY_MINUTES,
+ MAINTENANCE_BUSY_THRESHOLD,
+ runMaintenance,
+ type DailyWindow,
+} from "../../../core/brain/maintenance/lane.ts";
+import { listJournal } from "../../../core/brain/maintenance/journal.ts";
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { indexVault, resolveSearchConfig } from "../../../core/search/index.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] " +
+ "[--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]";
+
+export async function cmdBrainMaintenance(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ force: { type: "boolean" },
+ window: { type: "string" },
+ tz: { type: "string" },
+ "busy-minutes": { type: "string" },
+ "busy-threshold": { type: "string" },
+ limit: { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const op = positional[0];
+ const asJson = flags["json"] === true;
+ if (op !== "run" && op !== "status") {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const now = new Date();
+
+ try {
+ if (op === "status") {
+ const limitRaw = flags["limit"] as string | undefined;
+ const limit = limitRaw !== undefined ? Number(limitRaw) : 10;
+ if (!Number.isInteger(limit) || limit < 1) {
+ process.stderr.write("brain maintenance status: --limit must be a positive integer\n");
+ return 2;
+ }
+ const lease = currentLease(vault, { name: MAINTENANCE_LEASE_NAME, now });
+ const journal = listJournal(vault, limit);
+ if (asJson) okJson({ lease, journal });
+ else {
+ ok(lease === null ? "lease: free" : `lease: ${lease.holder} until ${lease.expiresAt}`);
+ ok(`journal (${journal.length} recent):`);
+ for (const e of journal) {
+ ok(` ${e.ts} ${e.verdict}${e.task ? ` ${e.task} ${e.ok ? "ok" : "FAILED"}` : ""}`);
+ }
+ }
+ return 0;
+ }
+
+ let window: DailyWindow | undefined;
+ const windowRaw = flags["window"] as string | undefined;
+ if (windowRaw !== undefined) {
+ const match = /^(\d{1,2})-(\d{1,2})$/.exec(windowRaw.trim());
+ const startHour = match ? Number(match[1]) : Number.NaN;
+ const endHour = match ? Number(match[2]) : Number.NaN;
+ if (!match || startHour > 23 || endHour > 23) {
+ process.stderr.write(
+ `brain maintenance run: --window must be H-H with hours 0..23, got: ${windowRaw}\n`,
+ );
+ return 2;
+ }
+ window = { startHour, endHour, tz: (flags["tz"] as string | undefined) ?? "UTC" };
+ }
+ const busyMinutes = numberFlag(flags["busy-minutes"], MAINTENANCE_BUSY_MINUTES);
+ const busyThreshold = numberFlag(flags["busy-threshold"], MAINTENANCE_BUSY_THRESHOLD);
+ if (busyMinutes === null || busyThreshold === null) {
+ process.stderr.write(
+ "brain maintenance run: --busy-minutes/--busy-threshold must be positive integers\n",
+ );
+ return 2;
+ }
+
+ const holder =
+ ((flags["agent"] as string | undefined)?.trim() || resolveAgentName(config)) +
+ `@${process.pid}`;
+ const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
+ const result = await runMaintenance(vault, {
+ now,
+ holder,
+ force: flags["force"] === true,
+ ...(window !== undefined ? { window } : {}),
+ busy: { minutes: busyMinutes, threshold: busyThreshold },
+ tasks: [
+ {
+ name: "dream",
+ run: async () => {
+ dream(vault, { now });
+ },
+ },
+ {
+ name: "reindex",
+ run: async () => {
+ await indexVault(searchConfig);
+ },
+ },
+ ],
+ });
+
+ if (asJson) okJson({ verdict: result.verdict, tasks: result.tasks });
+ else {
+ ok(`maintenance: ${result.verdict}`);
+ for (const t of result.tasks) {
+ ok(` ${t.name}: ${t.ok ? "ok" : `FAILED (${t.error})`} in ${t.duration_ms}ms`);
+ }
+ }
+ return result.tasks.some((t) => !t.ok) ? 1 : 0;
+ } catch (exc) {
+ const message = `maintenance ${op} failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
+
+function numberFlag(raw: unknown, fallback: number): number | null {
+ if (raw === undefined) return fallback;
+ const value = Number(raw);
+ return Number.isInteger(value) && value > 0 ? value : null;
+}
diff --git a/src/cli/brain/verbs/schema.ts b/src/cli/brain/verbs/schema.ts
index e23eba10..e038d15c 100644
--- a/src/cli/brain/verbs/schema.ts
+++ b/src/cli/brain/verbs/schema.ts
@@ -1,4 +1,5 @@
import { defaultConfigPath } from "../../../core/config.ts";
+import { resolveSearchConfig } from "../../../core/search/index.ts";
import {
applySchemaAdminMutations,
buildSchemaGraph,
@@ -65,7 +66,13 @@ export async function cmdBrainSchema(argv: string[]): Promise<number> {
case "stats":
return writeResult(buildSchemaStats(vault), Boolean(flags["json"]), renderGenericText);
case "lint":
- return writeResult(buildSchemaLint(vault), Boolean(flags["json"]), renderGenericText);
+ return writeResult(
+ buildSchemaLint(vault, {
+ dbPath: resolveSearchConfig({ vault, configPath: config ?? undefined }).dbPath,
+ }),
+ Boolean(flags["json"]),
+ renderGenericText,
+ );
case "graph":
return writeResult(buildSchemaGraph(vault), Boolean(flags["json"]), renderGenericText);
case "explain": {
@@ -152,5 +159,12 @@ function renderFinding(finding: SchemaReportFinding): string {
if (finding.kind === "unknown-token") {
return `[unknown-token] ${finding.category} ${finding.token} (${finding.path})`;
}
+ if (finding.kind === "link-constraint-violation") {
+ return (
+ `[link-constraint-violation] ${finding.relation} ` +
+ `${finding.source_type ?? "?"}->${finding.target_type ?? "?"} ` +
+ `(${finding.source} -> ${finding.target})`
+ );
+ }
return `[unused-declaration] ${finding.category} ${finding.token}`;
}
diff --git a/src/cli/brain/verbs/secret.ts b/src/cli/brain/verbs/secret.ts
new file mode 100644
index 00000000..5a2b014f
--- /dev/null
+++ b/src/cli/brain/verbs/secret.ts
@@ -0,0 +1,136 @@
+/**
+ * `o2b brain secret <set|list|rm|run>` (t_0b134404): capability-gated
+ * secret custody. `set` ingests the value from stdin or --from-env -
+ * NEVER from argv, where it would land in shell history and process
+ * lists; `list` shows metadata only; `run <name> -- cmd...` injects
+ * the secret into an allowlisted subprocess env and returns redacted
+ * output. No surface ever prints the value.
+ *
+ * Exit codes: 0 on success (run: the subprocess exit code), 1 on an
+ * operational failure, 2 on usage errors.
+ */
+
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { runWithSecret, SecretExecDeniedError } from "../../../core/brain/secrets/exec.ts";
+import { listSecrets, removeSecret, setSecret } from "../../../core/brain/secrets/store.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] [--vault <path>] [--json] | " +
+ "list [--vault <path>] [--json] | rm <name> [--vault <path>] | " +
+ "run <name> [--agent N] [--vault <path>] [--json] -- <command...>";
+
+export async function cmdBrainSecret(argv: string[]): Promise<number> {
+ // `run <name> -- cmd...`: everything after `--` belongs to the
+ // subprocess verbatim and must not be flag-parsed.
+ const dashDash = argv.indexOf("--");
+ const ownArgs = dashDash >= 0 ? argv.slice(0, dashDash) : argv;
+ const commandArgs = dashDash >= 0 ? argv.slice(dashDash + 1) : [];
+
+ const { flags, positional } = parse(ownArgs, {
+ vault: { type: "string" },
+ "env-var": { type: "string" },
+ allow: { type: "string-array" },
+ "from-env": { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const op = positional[0];
+ const asJson = flags["json"] === true;
+ if (op !== "set" && op !== "list" && op !== "rm" && op !== "run") {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+ const name = positional[1];
+ if (op !== "list" && !name) {
+ process.stderr.write(`brain secret ${op}: a secret name is required\n${USAGE}\n`);
+ return 2;
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined)?.trim() || resolveAgentName(config);
+ const now = new Date();
+
+ try {
+ switch (op) {
+ case "set": {
+ const fromEnv = flags["from-env"] as string | undefined;
+ let value: string;
+ if (fromEnv !== undefined) {
+ const fromEnvValue = process.env[fromEnv];
+ if (fromEnvValue === undefined || fromEnvValue.length === 0) {
+ process.stderr.write(`brain secret set: env var ${fromEnv} is unset or empty\n`);
+ return 2;
+ }
+ value = fromEnvValue;
+ } else {
+ value = (await Bun.stdin.text()).replace(/\r?\n$/, "");
+ if (value.trim().length === 0) {
+ process.stderr.write(
+ `brain secret set: pipe the value via stdin or pass --from-env SRC\n`,
+ );
+ return 2;
+ }
+ }
+ const metadata = setSecret(vault, {
+ name: name!,
+ value,
+ ...(typeof flags["env-var"] === "string" ? { envVar: flags["env-var"] as string } : {}),
+ allow: (flags["allow"] as string[] | undefined) ?? [],
+ agent,
+ now,
+ });
+ if (asJson) okJson({ ...metadata });
+ else ok(`secret stored: ${metadata.name} (env: ${metadata.env_var})`);
+ return 0;
+ }
+ case "list": {
+ const secrets = listSecrets(vault);
+ if (asJson) okJson({ secrets });
+ else {
+ ok(`secrets: ${secrets.length}`);
+ for (const s of secrets) {
+ ok(
+ ` ${s.name} env: ${s.env_var} allow: ${s.allow.length === 0 ? "(exec denied)" : s.allow.join(", ")}`,
+ );
+ }
+ }
+ return 0;
+ }
+ case "rm": {
+ const removed = removeSecret(vault, name!, { agent, now });
+ if (!removed) return fail(`secret rm: unknown secret "${name}"`);
+ if (asJson) okJson({ removed: name });
+ else ok(`secret removed: ${name}`);
+ return 0;
+ }
+ case "run": {
+ if (commandArgs.length === 0) {
+ process.stderr.write(`brain secret run: a command is required after --\n${USAGE}\n`);
+ return 2;
+ }
+ const result = await runWithSecret(vault, name!, commandArgs, { agent, now });
+ if (asJson) {
+ okJson({ exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr });
+ } else {
+ if (result.stdout.length > 0) process.stdout.write(result.stdout);
+ if (result.stderr.length > 0) process.stderr.write(result.stderr);
+ }
+ return result.exitCode;
+ }
+ }
+ return 2;
+ } catch (exc) {
+ if (exc instanceof SecretExecDeniedError) {
+ process.stderr.write(`brain secret: ${exc.message}\n`);
+ return 2;
+ }
+ const message = `secret ${op} failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
diff --git a/src/cli/brain/verbs/tiers.ts b/src/cli/brain/verbs/tiers.ts
new file mode 100644
index 00000000..05b89bfb
--- /dev/null
+++ b/src/cli/brain/verbs/tiers.ts
@@ -0,0 +1,156 @@
+/**
+ * `o2b brain tiers <check|restore|accept>` (t_3f92d3f1): the staged
+ * repair surface for identity-tier frontmatter hand-edits the index
+ * post-pass detected. `check` lists open findings (read-only),
+ * `restore <path> --apply` writes the expected value back into the
+ * file, `accept <path>` adopts the hand-edit as the new truth -
+ * nothing auto-resolves, the operator stays the judge.
+ *
+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage
+ * errors.
+ */
+
+import { join } from "node:path";
+import { existsSync } from "node:fs";
+
+import { resolveSearchConfig } from "../../../core/search/index.ts";
+import { Store } from "../../../core/search/store.ts";
+import { parseFrontmatter, writeFrontmatterAtomic } from "../../../core/vault.ts";
+import { defaultConfigPath } from "../../../core/config.ts";
+import type { FrontmatterMap } from "../../../core/types.ts";
+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain tiers check | " +
+ "o2b brain tiers restore <path> [--field F] [--apply] | " +
+ "o2b brain tiers accept <path> [--field F] [--vault <path>] [--json]";
+
+export async function cmdBrainTiers(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ field: { type: "string" },
+ apply: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const op = positional[0];
+ const asJson = flags["json"] === true;
+ if (op !== "check" && op !== "restore" && op !== "accept") {
+ process.stderr.write(`${USAGE}\n`);
+ return 2;
+ }
+ const relPath = positional[1];
+ if ((op === "restore" || op === "accept") && !relPath) {
+ process.stderr.write(`brain tiers ${op}: a vault-relative path is required\n${USAGE}\n`);
+ return 2;
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });
+ const field = (flags["field"] as string | undefined)?.trim();
+
+ try {
+ if (op === "check") {
+ // Fail-soft: a vault that was never indexed has no snapshots
+ // and therefore no drift - not an error.
+ if (!existsSync(searchConfig.dbPath)) {
+ if (asJson) okJson({ findings: [] });
+ else ok("tier drift: 0 open finding(s)");
+ return 0;
+ }
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ const findings = store.listTierDrift();
+ if (asJson) {
+ okJson({ findings });
+ } else {
+ ok(`tier drift: ${findings.length} open finding(s)`);
+ for (const f of findings) {
+ ok(
+ ` ${f.path} ${f.field}: expected ${render(f.expected)}, actual ${render(f.actual)}`,
+ );
+ }
+ if (findings.length > 0) {
+ ok("resolve with: o2b brain tiers restore <path> --apply (or accept <path>)");
+ }
+ }
+ return 0;
+ } finally {
+ await store.close();
+ }
+ }
+
+ const store = await Store.open(searchConfig, { mode: "write" });
+ try {
+ const docId = store.getDocumentIdByPath(relPath!);
+ if (docId === null) return fail(`tiers ${op}: not indexed: ${relPath}`);
+ const rows = store
+ .listTierDrift()
+ .filter((r) => r.documentId === docId && (field === undefined || r.field === field));
+ if (rows.length === 0) {
+ return fail(`tiers ${op}: no open drift for ${relPath}${field ? ` field ${field}` : ""}`);
+ }
+
+ if (op === "restore") {
+ if (flags["apply"] !== true) {
+ if (asJson) okJson({ would_restore: rows, applied: false });
+ else {
+ for (const r of rows) {
+ ok(
+ `would restore ${r.path} ${r.field}: ${render(r.actual)} -> ${render(r.expected)}`,
+ );
+ }
+ ok("re-run with --apply to write");
+ }
+ return 0;
+ }
+ const path = join(vault, relPath!);
+ const [metadata, body] = parseFrontmatter(path);
+ const next: FrontmatterMap = { ...metadata };
+ for (const r of rows) {
+ next[r.field] = asFrontmatterValue(r.expected, r.field);
+ }
+ writeFrontmatterAtomic(path, next, body, { overwrite: true });
+ for (const r of rows) store.clearTierDrift(docId, r.field);
+ if (asJson) okJson({ restored: rows.map((r) => r.field), path: relPath });
+ else ok(`restored ${rows.length} field(s) in ${relPath}`);
+ return 0;
+ }
+
+ // accept: the hand-edit becomes the new snapshot truth.
+ const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };
+ for (const r of rows) {
+ snapshot[r.field] = r.actual;
+ store.clearTierDrift(docId, r.field);
+ }
+ store.setTierSnapshot(docId, snapshot);
+ if (asJson) okJson({ accepted: rows.map((r) => r.field), path: relPath });
+ else ok(`accepted ${rows.length} field(s) as the new baseline in ${relPath}`);
+ return 0;
+ } finally {
+ await store.close();
+ }
+ } catch (exc) {
+ const message = `tiers ${op} failed: ${(exc as Error).message ?? exc}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
+
+function render(value: unknown): string {
+ return JSON.stringify(value);
+}
+
+/** Narrow a snapshot value to the shapes frontmatter can carry. */
+function asFrontmatterValue(value: unknown, field: string): FrontmatterMap[string] {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ return value;
+ }
+ if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {
+ return value;
+ }
+ throw new Error(`snapshot value for "${field}" is not a frontmatter scalar or string array`);
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 32f5c35b..c2473f86 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -118,6 +118,11 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("facts", "Decompose text into atomic assertions"),
command("dead-end", "Record or list failed approaches"),
command("foresight", "Render forward-looking projection"),
+ command("label", "Assign, remove, or show controlled-vocabulary labels"),
+ command("attr", "Assign, remove, or show typed-page attribute fields"),
+ command("tiers", "Check, restore, or accept identity-field drift"),
+ command("secret", "Capability-gated secret custody: set, list, rm, run"),
+ command("maintenance", "Quiet-window, lease-guarded heavy maintenance lane"),
command("audit", "Render mutation audit trail"),
command("morning-brief", "Render session-start summary"),
command("codec", "Compress or expand session prose"),
diff --git a/src/core/brain/attributes.ts b/src/core/brain/attributes.ts
new file mode 100644
index 00000000..391103ec
--- /dev/null
+++ b/src/core/brain/attributes.ts
@@ -0,0 +1,193 @@
+/**
+ * Per-type attribute fields (write-time-integrity-governance).
+ *
+ * The schema pack's `attributes` field declares, per page type, a
+ * small set of fields with natural-language descriptions. The
+ * descriptions are agent guidance, not extraction magic: they render
+ * in schema explain output so an agent capturing a typed page knows
+ * the domain vocabulary, and validation is fail-closed - assigning an
+ * undeclared field lists the declared fields WITH their descriptions
+ * so the caller can self-correct. Values persist as a sorted
+ * `attributes: [field=value]` frontmatter array, filterable through
+ * the existing `--property` post-rank search filter. The regex fact
+ * extractor is unchanged.
+ */
+
+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { resolveNotePath } from "./note-path.ts";
+import { normalizeSchemaToken } from "./schema-vocab.ts";
+import type { SchemaPack } from "./schema-pack.ts";
+
+export class AttributeVocabularyError extends Error {
+ readonly type: string;
+ readonly declared: Readonly<Record<string, string>>;
+
+ constructor(type: string, declared: Readonly<Record<string, string>>, message: string) {
+ super(message);
+ this.name = "AttributeVocabularyError";
+ this.type = type;
+ this.declared = declared;
+ }
+}
+
+export interface AttributeAssignment {
+ readonly type: string;
+ readonly field: string;
+ readonly value: string;
+}
+
+export interface AssignNoteAttributeOptions {
+ readonly field: string;
+ readonly value: string;
+ readonly pack: SchemaPack;
+}
+
+export interface RemoveNoteAttributeOptions {
+ readonly field: string;
+}
+
+export interface NoteAttributeResult {
+ /** Vault-relative path of the note. */
+ readonly path: string;
+ /** The note's full `field=value` set after the operation, sorted. */
+ readonly attributes: ReadonlyArray<string>;
+ /** Whether the file content changed. */
+ readonly changed: boolean;
+}
+
+export interface RemoveNoteAttributeResult extends NoteAttributeResult {
+ /** Whether the field was present before removal. */
+ readonly removed: boolean;
+}
+
+/**
+ * Validate one assignment against the declared descriptors.
+ * Fail-closed both ways: a type with no declared attributes names the
+ * types that have them; an undeclared field lists the declared fields
+ * with their descriptions - the descriptions ARE the guidance.
+ */
+export function validateAttributeAssignment(
+ pack: SchemaPack,
+ type: string,
+ field: string,
+ value: string,
+): AttributeAssignment {
+ const normalizedType = normalizeSchemaToken(type);
+ const declared = pack.attributes[normalizedType];
+ if (declared === undefined) {
+ const types = Object.keys(pack.attributes);
+ throw new AttributeVocabularyError(
+ normalizedType,
+ {},
+ types.length === 0
+ ? "no attribute fields are declared in the schema pack"
+ : `type "${normalizedType}" declares no attributes - declared attribute types: ${types.join(", ")}`,
+ );
+ }
+ const normalizedField = normalizeSchemaToken(field);
+ if (declared[normalizedField] === undefined) {
+ const fields = Object.entries(declared)
+ .map(([name, description]) => `${name} (${description})`)
+ .join(", ");
+ throw new AttributeVocabularyError(
+ normalizedType,
+ declared,
+ `attribute "${normalizedField}" is not declared for type "${normalizedType}" - declared fields: ${fields}`,
+ );
+ }
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ throw new AttributeVocabularyError(
+ normalizedType,
+ declared,
+ "attribute value must not be empty",
+ );
+ }
+ if (/[\r\n]/.test(value)) {
+ throw new AttributeVocabularyError(
+ normalizedType,
+ declared,
+ "attribute value must be a single line",
+ );
+ }
+ if (trimmed.includes(",")) {
+ throw new AttributeVocabularyError(
+ normalizedType,
+ declared,
+ "attribute value must not contain a comma (it breaks the inline frontmatter array)",
+ );
+ }
+ return { type: normalizedType, field: normalizedField, value: trimmed };
+}
+
+/**
+ * Assign one attribute to a typed note. The note's own frontmatter
+ * `type` selects the descriptor set; validation runs before any write
+ * so an invalid assignment never touches the file. One value per
+ * field - reassignment replaces.
+ */
+export function assignNoteAttribute(
+ vault: string,
+ relPath: string,
+ opts: AssignNoteAttributeOptions,
+): NoteAttributeResult {
+ const path = resolveNotePath(vault, relPath);
+ const [metadata, body] = parseFrontmatter(path);
+ const rawType = metadata["type"];
+ if (typeof rawType !== "string" || normalizeSchemaToken(rawType).length === 0) {
+ throw new Error(`note declares no type in frontmatter: ${relPath}`);
+ }
+ const assignment = validateAttributeAssignment(opts.pack, rawType, opts.field, opts.value);
+ const existing = readAttributeEntries(metadata);
+ const kept = existing.filter((entry) => !entry.startsWith(`${assignment.field}=`));
+ const next = [...kept, `${assignment.field}=${assignment.value}`].toSorted((a, b) =>
+ a.localeCompare(b),
+ );
+ const changed = !sameEntries(existing, next);
+ if (changed) {
+ writeFrontmatterAtomic(path, { ...metadata, attributes: next }, body, { overwrite: true });
+ }
+ return { path: relPath, attributes: next, changed };
+}
+
+/** Remove a field's attribute from a note. */
+export function removeNoteAttribute(
+ vault: string,
+ relPath: string,
+ opts: RemoveNoteAttributeOptions,
+): RemoveNoteAttributeResult {
+ const field = normalizeSchemaToken(opts.field);
+ const path = resolveNotePath(vault, relPath);
+ const [metadata, body] = parseFrontmatter(path);
+ const existing = readAttributeEntries(metadata);
+ const next = existing.filter((entry) => !entry.startsWith(`${field}=`));
+ const removed = next.length !== existing.length;
+ if (removed) {
+ const nextMetadata = { ...metadata };
+ if (next.length > 0) nextMetadata["attributes"] = next;
+ else delete nextMetadata["attributes"];
+ writeFrontmatterAtomic(path, nextMetadata, body, { overwrite: true });
+ }
+ return { path: relPath, attributes: next, changed: removed, removed };
+}
+
+/** Parse a note's `attributes` array into a `field -> value` record. */
+export function readAttributes(metadata: Record<string, unknown>): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readAttributeEntries(metadata)) {
+ const eq = entry.indexOf("=");
+ if (eq <= 0) continue;
+ out[entry.slice(0, eq)] = entry.slice(eq + 1);
+ }
+ return out;
+}
+
+function readAttributeEntries(metadata: Record<string, unknown>): string[] {
+ const raw = metadata["attributes"];
+ if (!Array.isArray(raw)) return [];
+ return raw.filter((entry): entry is string => typeof entry === "string");
+}
+
+function sameEntries(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
+ return left.length === right.length && left.every((entry, index) => entry === right[index]);
+}
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 3706acb1..9df50dc2 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -45,6 +45,7 @@ import { buildBacklinkIndex } from "./backlinks.ts";
import { buildEntityIndex } from "./entities/index-builder.ts";
import { buildCaptureBoundary } from "./capture-boundary.ts";
import { verifyContentHash } from "./content-hash.ts";
+import { readTierDriftCount } from "./frontmatter-tiers.ts";
import { scanDanglingWorkruns } from "./dream-workrun.ts";
import { parseLogDayFile } from "./log.ts";
import {
@@ -115,6 +116,12 @@ export interface RunDoctorOptions {
* Tests pin this for determinism.
*/
readonly now?: Date;
+ /**
+ * Search-index path for index-backed checks
+ * (write-time-integrity-governance: staged tier-drift findings).
+ * Fail-soft: a missing index or pre-v6 schema simply skips them.
+ */
+ readonly dbPath?: string;
/**
* Optional precomputed dream summary (v0.10.16). When supplied,
* the doctor runs the verification-delta helper and folds the
@@ -251,6 +258,21 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
checkPreferences(vault, issues, idIndex, knownBasenames);
checkRetired(vault, issues, idIndex, knownBasenames);
+ // Tier guard (write-time-integrity-governance): staged identity
+ // hand-edits the index post-pass detected. Fail-soft index read.
+ if (opts.dbPath !== undefined) {
+ const driftCount = readTierDriftCount(opts.dbPath);
+ if (driftCount > 0) {
+ issues.push({
+ severity: "warning",
+ code: "tier-drift",
+ message:
+ `${driftCount} identity-field hand-edit(s) staged - ` +
+ "review with: o2b brain tiers check",
+ });
+ }
+ }
+
// Duplicate-id reporting after every file has been indexed.
for (const [id, paths] of idIndex.entries()) {
if (paths.length > 1) {
diff --git a/src/core/brain/frontmatter-tiers.ts b/src/core/brain/frontmatter-tiers.ts
new file mode 100644
index 00000000..5f1eaf19
--- /dev/null
+++ b/src/core/brain/frontmatter-tiers.ts
@@ -0,0 +1,223 @@
+/**
+ * Tiered frontmatter field protection (write-time-integrity-governance).
+ *
+ * Four tiers, EverOS-inspired, mapped onto Open Second Brain's
+ * existing conventions:
+ *
+ * - `identity` - framework-owned join keys (`kind`, `id`,
+ * `entity_id`, an entity's `category`). A hand-edit here corrupts
+ * the joins the index and registry depend on.
+ * - `system` - framework-written bookkeeping: timestamps,
+ * counters, lifecycle status. The `_`-prefixed preference fields
+ * already follow this convention informally; the tier model makes
+ * it explicit.
+ * - `business` - domain fields agents write through verbs.
+ * - `user` - freely editable; everything undeclared.
+ *
+ * Resolution order: schema-pack `frontmatter_tiers` override >
+ * built-in framework defaults > `user`. Unknown kinds resolve every
+ * field to `user`, so a human's own vault is never constrained.
+ *
+ * The guard never write-denies humans: framework writers merge
+ * through `mergeFrontmatterTiered` (preserve user fields they do not
+ * own, refuse to change identity values), and the drift check
+ * (`o2b brain tiers check`) detects hand-edits against the indexed
+ * baseline and stages repair - it does not fight the editor.
+ */
+
+import { Database } from "bun:sqlite";
+import { existsSync } from "node:fs";
+
+import { FRONTMATTER_TIERS, type FrontmatterTier, type SchemaPack } from "./schema-pack.ts";
+
+export { FRONTMATTER_TIERS };
+export type { FrontmatterTier };
+
+/** Thrown when a merge would change an identity join key. */
+export class FrontmatterTierConflictError extends Error {
+ readonly field: string;
+ readonly existingValue: unknown;
+ readonly incomingValue: unknown;
+
+ constructor(field: string, existingValue: unknown, incomingValue: unknown) {
+ super(
+ `identity field "${field}" cannot change in a framework write: ` +
+ `${JSON.stringify(existingValue)} -> ${JSON.stringify(incomingValue)} ` +
+ `(pass acceptIdentity for an explicit migration)`,
+ );
+ this.name = "FrontmatterTierConflictError";
+ this.field = field;
+ this.existingValue = existingValue;
+ this.incomingValue = incomingValue;
+ }
+}
+
+/**
+ * Built-in tier defaults for framework-owned kinds, grounded in the
+ * fields the writers actually emit (preference.ts, entities/registry,
+ * signal.ts, dead-ends.ts). Fields not listed here fall through to
+ * the `_`-prefix system rule, then to `user`.
+ */
+export const DEFAULT_TIER_MAP: Readonly<Record<string, Readonly<Record<string, FrontmatterTier>>>> =
+ Object.freeze({
+ "brain-preference": Object.freeze<Record<string, FrontmatterTier>>({
+ kind: "identity",
+ id: "identity",
+ created_at: "system",
+ unconfirmed_until: "system",
+ topic: "business",
+ principle: "business",
+ scope: "business",
+ tags: "business",
+ aliases: "business",
+ supersedes: "business",
+ // Legacy unprefixed Group C names (pre-§24). System tier so a
+ // tier-merging rewrite drops them instead of preserving a stale
+ // copy beside the `_`-prefixed field the writer emits today.
+ status: "system",
+ confirmed_at: "system",
+ evidenced_by: "system",
+ applied_count: "system",
+ violated_count: "system",
+ last_evidence_at: "system",
+ confidence: "system",
+ confidence_value: "system",
+ }),
+ "brain-retired": Object.freeze<Record<string, FrontmatterTier>>({
+ kind: "identity",
+ id: "identity",
+ created_at: "system",
+ retired_at: "system",
+ }),
+ "brain-signal": Object.freeze<Record<string, FrontmatterTier>>({
+ kind: "identity",
+ id: "identity",
+ created_at: "system",
+ agent: "system",
+ topic: "business",
+ signal: "business",
+ scope: "business",
+ }),
+ "brain-entity": Object.freeze<Record<string, FrontmatterTier>>({
+ kind: "identity",
+ entity_id: "identity",
+ category: "identity",
+ created_at: "system",
+ updated_at: "system",
+ status: "system",
+ source_agent: "system",
+ name: "business",
+ aliases: "business",
+ confidence: "business",
+ }),
+ "brain-dead-end": Object.freeze<Record<string, FrontmatterTier>>({
+ kind: "identity",
+ id: "identity",
+ created_at: "system",
+ agent: "system",
+ }),
+ });
+
+/**
+ * Resolve one field's tier: pack override > built-in default >
+ * `_`-prefix system rule (framework kinds only) > `user`.
+ */
+export function resolveFieldTier(pack: SchemaPack, kind: string, field: string): FrontmatterTier {
+ const packKind = pack.frontmatter_tiers[kind];
+ const override = packKind?.[field];
+ if (override !== undefined) return override;
+ const isFrameworkKind = DEFAULT_TIER_MAP[kind] !== undefined || packKind !== undefined;
+ if (!isFrameworkKind) return "user";
+ const builtin = DEFAULT_TIER_MAP[kind]?.[field];
+ if (builtin !== undefined) return builtin;
+ if (field.startsWith("_")) return "system";
+ return "user";
+}
+
+/**
+ * Every field of a kind with a declared non-`user` tier (pack
+ * overrides merged over built-ins). The drift check walks this map;
+ * `user`-tier overrides are omitted because they need no protection.
+ */
+export function tieredFieldsForKind(
+ pack: SchemaPack,
+ kind: string,
+): Record<string, FrontmatterTier> {
+ const out: Record<string, FrontmatterTier> = {};
+ for (const [field, tier] of Object.entries(DEFAULT_TIER_MAP[kind] ?? {})) out[field] = tier;
+ for (const [field, tier] of Object.entries(pack.frontmatter_tiers[kind] ?? {})) {
+ if (tier === "user") delete out[field];
+ else out[field] = tier;
+ }
+ return out;
+}
+
+export interface MergeFrontmatterTieredOptions {
+ /** The file's framework kind (the writer knows what it writes). */
+ readonly kind: string;
+ readonly pack: SchemaPack;
+ /**
+ * Allow an identity value to change - explicit migrations only
+ * (rename, re-id). Never set this on a routine update write.
+ */
+ readonly acceptIdentity?: boolean;
+}
+
+/**
+ * Tier-respecting frontmatter merge for framework writers. Incoming
+ * (framework) values win field-by-field; existing-only fields are
+ * preserved when their tier is `user` - a field a human added by hand
+ * survives every framework rewrite - and DROPPED otherwise: a
+ * framework-owned field the writer no longer emits is a deliberate
+ * migration (e.g. legacy unprefixed names), not user data. A changed
+ * identity value throws unless `acceptIdentity` marks an explicit
+ * migration. Unknown kinds have no non-`user` fields, so the merge
+ * degrades to a plain spread.
+ */
+export function mergeFrontmatterTiered<V>(
+ existing: Readonly<Record<string, V>>,
+ incoming: Readonly<Record<string, V>>,
+ opts: MergeFrontmatterTieredOptions,
+): Record<string, V> {
+ if (opts.acceptIdentity !== true) {
+ for (const [field, incomingValue] of Object.entries(incoming)) {
+ if (resolveFieldTier(opts.pack, opts.kind, field) !== "identity") continue;
+ if (!(field in existing)) continue;
+ const existingValue = existing[field];
+ if (!sameScalar(existingValue, incomingValue)) {
+ throw new FrontmatterTierConflictError(field, existingValue, incomingValue);
+ }
+ }
+ }
+ const merged: Record<string, V> = {};
+ for (const [field, value] of Object.entries(existing)) {
+ if (field in incoming) continue;
+ if (resolveFieldTier(opts.pack, opts.kind, field) === "user") merged[field] = value;
+ }
+ return Object.assign(merged, incoming);
+}
+
+function sameScalar(left: unknown, right: unknown): boolean {
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return left.length === right.length && left.every((v, i) => sameScalar(v, right[i]));
+ }
+ return left === right;
+}
+
+/**
+ * Count the staged tier-drift findings straight from the index
+ * database (doctor surface). Read-only, fail-soft: a missing index
+ * file, a pre-v6 schema, or any read error counts as zero.
+ */
+export function readTierDriftCount(dbPath: string): number {
+ if (!existsSync(dbPath)) return 0;
+ let db: Database | null = null;
+ try {
+ db = new Database(dbPath, { readonly: true });
+ return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM tier_drift").get()?.n ?? 0;
+ } catch {
+ return 0;
+ } finally {
+ db?.close();
+ }
+}
diff --git a/src/core/brain/labels.ts b/src/core/brain/labels.ts
new file mode 100644
index 00000000..01b3ce6b
--- /dev/null
+++ b/src/core/brain/labels.ts
@@ -0,0 +1,184 @@
+/**
+ * Controlled-vocabulary labels (write-time-integrity-governance).
+ *
+ * The schema pack declares label dimensions with a fixed enum of
+ * allowed values (`schema.labels`); this module is the write-time
+ * enforcement seam. Assignment is fail-closed - an unknown dimension
+ * or value is rejected with the declared vocabulary in the error -
+ * and classification is single-choice: one value per dimension per
+ * note. Labels persist as a sorted `labels: [dim/value]` frontmatter
+ * array (filterable through the existing `--property` post-rank
+ * filter) plus a canonical `label` entity in the registry so related
+ * notes cluster without free-form tag drift.
+ */
+
+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { resolveNotePath } from "./note-path.ts";
+import { normalizeSchemaToken } from "./schema-vocab.ts";
+import { upsertEntity } from "./entities/registry.ts";
+import type { SchemaPack } from "./schema-pack.ts";
+
+export const LABEL_ENTITY_CATEGORY = "label";
+
+export class LabelVocabularyError extends Error {
+ readonly dimension: string;
+ readonly allowed: ReadonlyArray<string>;
+
+ constructor(dimension: string, allowed: ReadonlyArray<string>, message: string) {
+ super(message);
+ this.name = "LabelVocabularyError";
+ this.dimension = dimension;
+ this.allowed = allowed;
+ }
+}
+
+export interface LabelAssignment {
+ readonly dimension: string;
+ readonly value: string;
+ /** Canonical `dimension/value` form stored in frontmatter. */
+ readonly token: string;
+}
+
+export interface AssignNoteLabelOptions {
+ readonly dimension: string;
+ readonly value: string;
+ readonly pack: SchemaPack;
+ /** Agent identity stamped on the canonical label entity. */
+ readonly agent: string;
+ /** Injected clock for deterministic registry stamps. */
+ readonly now: Date;
+}
+
+export interface RemoveNoteLabelOptions {
+ readonly dimension: string;
+ readonly pack: SchemaPack;
+}
+
+export interface NoteLabelResult {
+ /** Vault-relative path of the labelled note. */
+ readonly path: string;
+ /** The note's full label set after the operation, sorted. */
+ readonly labels: ReadonlyArray<string>;
+ /** Whether the file content changed. */
+ readonly changed: boolean;
+}
+
+export interface RemoveNoteLabelResult extends NoteLabelResult {
+ /** Whether the dimension was present before removal. */
+ readonly removed: boolean;
+}
+
+/** Render the canonical `dimension/value` label form. */
+export function labelToken(dimension: string, value: string): string {
+ return `${dimension}/${value}`;
+}
+
+/**
+ * Validate one assignment against the declared vocabulary.
+ * Fail-closed: unknown dimensions and values throw with the declared
+ * alternatives listed, so a caller (or its operator) can self-correct.
+ */
+export function validateLabelAssignment(
+ pack: SchemaPack,
+ dimension: string,
+ value: string,
+): LabelAssignment {
+ const dimensions = Object.keys(pack.labels);
+ if (dimensions.length === 0) {
+ throw new LabelVocabularyError(
+ normalizeSchemaToken(dimension),
+ [],
+ "no label dimensions are declared in the schema pack",
+ );
+ }
+ const normalizedDimension = normalizeSchemaToken(dimension);
+ const allowed = pack.labels[normalizedDimension];
+ if (allowed === undefined) {
+ throw new LabelVocabularyError(
+ normalizedDimension,
+ dimensions,
+ `unknown label dimension "${normalizedDimension}" - declared dimensions: ${dimensions.join(", ")}`,
+ );
+ }
+ const normalizedValue = normalizeSchemaToken(value);
+ if (!allowed.includes(normalizedValue)) {
+ throw new LabelVocabularyError(
+ normalizedDimension,
+ allowed,
+ `label ${normalizedDimension}="${normalizedValue}" is not in the vocabulary - allowed values: ${allowed.join(", ")}`,
+ );
+ }
+ return {
+ dimension: normalizedDimension,
+ value: normalizedValue,
+ token: labelToken(normalizedDimension, normalizedValue),
+ };
+}
+
+/**
+ * Assign one label to a note: validates against the pack, replaces
+ * any existing value of the same dimension (single-choice), writes a
+ * sorted `labels` frontmatter array atomically, and registers the
+ * canonical `label` entity. Validation runs before any I/O so an
+ * invalid assignment never touches the file.
+ */
+export function assignNoteLabel(
+ vault: string,
+ relPath: string,
+ opts: AssignNoteLabelOptions,
+): NoteLabelResult {
+ const assignment = validateLabelAssignment(opts.pack, opts.dimension, opts.value);
+ const path = resolveNotePath(vault, relPath);
+ const [metadata, body] = parseFrontmatter(path);
+ const existing = readLabels(metadata);
+ const kept = existing.filter((token) => !token.startsWith(`${assignment.dimension}/`));
+ const next = [...kept, assignment.token].toSorted((a, b) => a.localeCompare(b));
+ const changed = !sameLabels(existing, next);
+ if (changed) {
+ const nextMetadata = { ...metadata, labels: next };
+ writeFrontmatterAtomic(path, nextMetadata, body, { overwrite: true });
+ }
+ upsertEntity(vault, {
+ category: LABEL_ENTITY_CATEGORY,
+ name: assignment.token,
+ agent: opts.agent,
+ now: opts.now,
+ });
+ return { path: relPath, labels: next, changed };
+}
+
+/**
+ * Remove a dimension's label from a note. The canonical label entity
+ * stays in the registry - other notes may still carry the label, and
+ * an orphaned label entity is harmless vocabulary, not corruption.
+ */
+export function removeNoteLabel(
+ vault: string,
+ relPath: string,
+ opts: RemoveNoteLabelOptions,
+): RemoveNoteLabelResult {
+ const dimension = normalizeSchemaToken(opts.dimension);
+ const path = resolveNotePath(vault, relPath);
+ const [metadata, body] = parseFrontmatter(path);
+ const existing = readLabels(metadata);
+ const next = existing.filter((token) => !token.startsWith(`${dimension}/`));
+ const removed = next.length !== existing.length;
+ if (removed) {
+ const nextMetadata = { ...metadata };
+ if (next.length > 0) nextMetadata["labels"] = next;
+ else delete nextMetadata["labels"];
+ writeFrontmatterAtomic(path, nextMetadata, body, { overwrite: true });
+ }
+ return { path: relPath, labels: next, changed: removed, removed };
+}
+
+/** Read the validated string entries of a note's `labels` array. */
+export function readLabels(metadata: Record<string, unknown>): string[] {
+ const raw = metadata["labels"];
+ if (!Array.isArray(raw)) return [];
+ return raw.filter((entry): entry is string => typeof entry === "string");
+}
+
+function sameLabels(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
+ return left.length === right.length && left.every((token, index) => token === right[index]);
+}
diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.ts
new file mode 100644
index 00000000..93204d03
--- /dev/null
+++ b/src/core/brain/maintenance/journal.ts
@@ -0,0 +1,78 @@
+/**
+ * Maintenance run journal (write-time-integrity-governance,
+ * t_166d1226): bounded append-only JSONL in the vault-local state
+ * dir. Every attempt lands here - including gate refusals - so the
+ * operator can see WHY the quiet-window lane did or did not run
+ * without trusting silence. Newest-N retention with an explicit
+ * sweep on append, matching the activation-store discipline.
+ */
+
+import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { mkdirSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+export const MAINTENANCE_JOURNAL_CAP = 500;
+
+export type MaintenanceVerdict = "run" | "skipped:window" | "skipped:busy" | "skipped:lease";
+
+export interface MaintenanceJournalEntry {
+ readonly ts: string;
+ readonly holder: string;
+ readonly verdict: MaintenanceVerdict;
+ /** Present on per-task rows; absent on gate-refusal rows. */
+ readonly task?: string;
+ readonly ok?: boolean;
+ readonly duration_ms?: number;
+ readonly error?: string;
+}
+
+function journalPath(vault: string): string {
+ return join(vault, ".open-second-brain", "maintenance-runs.jsonl");
+}
+
+export function appendJournal(vault: string, entry: MaintenanceJournalEntry): void {
+ const path = journalPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ // O_APPEND, one line per call: concurrent gate-refusal writers
+ // (which run BEFORE the lease is held) interleave instead of
+ // overwriting each other through a read-modify-rewrite race. The
+ // cap is enforced separately by `sweepJournal`, which runMaintenance
+ // calls while it holds the lease - the only safe rewrite point.
+ appendFileSync(path, JSON.stringify(entry) + "\n");
+}
+
+/** Trim the journal to the newest `cap` lines. Lease-holder only. */
+export function sweepJournal(vault: string, cap: number = MAINTENANCE_JOURNAL_CAP): void {
+ const path = journalPath(vault);
+ const lines = readLines(path);
+ if (lines.length <= cap) return;
+ const kept = lines.slice(lines.length - cap);
+ const tmp = `${path}.tmp`;
+ writeFileSync(tmp, kept.join("\n") + "\n");
+ renameSync(tmp, path);
+}
+
+/** Journal entries, newest first. Unparseable lines are skipped. */
+export function listJournal(vault: string, limit?: number): MaintenanceJournalEntry[] {
+ const lines = readLines(journalPath(vault));
+ const out: MaintenanceJournalEntry[] = [];
+ for (const line of lines) {
+ try {
+ const parsed: unknown = JSON.parse(line);
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
+ out.push(parsed as MaintenanceJournalEntry);
+ }
+ } catch {
+ // Fail-soft: a torn line never breaks the journal read.
+ }
+ }
+ out.reverse();
+ return limit !== undefined ? out.slice(0, Math.max(0, limit)) : out;
+}
+
+function readLines(path: string): string[] {
+ if (!existsSync(path)) return [];
+ return readFileSync(path, "utf8")
+ .split("\n")
+ .filter((line) => line.trim().length > 0);
+}
diff --git a/src/core/brain/maintenance/lane.ts b/src/core/brain/maintenance/lane.ts
new file mode 100644
index 00000000..9c8be873
--- /dev/null
+++ b/src/core/brain/maintenance/lane.ts
@@ -0,0 +1,181 @@
+/**
+ * Quiet-window maintenance lane (write-time-integrity-governance,
+ * t_166d1226). Heavy passes (dream, reindex) run through three gates:
+ *
+ * 1. window - a configured local-time hour window (tz-aware,
+ * midnight wrap supported); unconfigured = always open.
+ * 2. busy - recent interactive query-rate from the existing
+ * recall-telemetry continuity records; a vault without
+ * telemetry counts as quiet.
+ * 3. lease - the expiring SQLite lease; never bypassable, even
+ * with --force, because two concurrent heavy passes on
+ * one vault is the exact failure this lane exists to
+ * prevent.
+ *
+ * `--force` bypasses the soft gates (window, busy) for an operator
+ * who wants the pass NOW; tasks run stale-first (least-recently
+ * succeeded first, never-run before everything) and every attempt is
+ * journaled.
+ */
+
+import { listRecallTelemetry } from "../recall-telemetry.ts";
+import { acquireLease, MAINTENANCE_LEASE_NAME, releaseLease } from "./lease.ts";
+import { appendJournal, listJournal, sweepJournal, type MaintenanceVerdict } from "./journal.ts";
+
+/** Default lease TTL: generous enough for a full reindex + dream. */
+export const MAINTENANCE_LEASE_TTL_MS = 30 * 60 * 1000;
+/** Default busy gate: this many queries in the window means busy. */
+export const MAINTENANCE_BUSY_THRESHOLD = 5;
+/** Default busy lookback window in minutes. */
+export const MAINTENANCE_BUSY_MINUTES = 10;
+
+export interface DailyWindow {
+ /** Local hour [0..23] the window opens (inclusive). */
+ readonly startHour: number;
+ /** Local hour [0..23] the window closes (exclusive). */
+ readonly endHour: number;
+ readonly tz: string;
+}
+
+export interface BusyGate {
+ readonly minutes: number;
+ readonly threshold: number;
+}
+
+export interface EvaluateGatesOptions {
+ readonly now: Date;
+ /** Absent = the window gate is always open (neutral default). */
+ readonly window?: DailyWindow;
+ readonly busy?: BusyGate;
+}
+
+export interface MaintenanceTask {
+ readonly name: string;
+ readonly run: () => Promise<void>;
+}
+
+export interface RunMaintenanceOptions extends EvaluateGatesOptions {
+ readonly holder: string;
+ readonly tasks: ReadonlyArray<MaintenanceTask>;
+ /** Bypass window and busy gates - never the lease. */
+ readonly force?: boolean;
+ readonly leaseTtlMs?: number;
+}
+
+export interface MaintenanceTaskResult {
+ readonly name: string;
+ readonly ok: boolean;
+ readonly duration_ms: number;
+ readonly error?: string;
+}
+
+export interface RunMaintenanceResult {
+ readonly verdict: MaintenanceVerdict;
+ readonly tasks: ReadonlyArray<MaintenanceTaskResult>;
+}
+
+/** True when `now` falls inside the local-time window (wrap-aware). */
+export function dailyWindowContains(now: Date, window: DailyWindow): boolean {
+ const hour = Number(
+ new Intl.DateTimeFormat("en-CA", {
+ timeZone: window.tz,
+ hour: "2-digit",
+ hourCycle: "h23",
+ }).format(now),
+ );
+ if (window.startHour === window.endHour) return true; // degenerate: always open
+ if (window.startHour < window.endHour) {
+ return hour >= window.startHour && hour < window.endHour;
+ }
+ // Midnight wrap: 22-04 means [22..24) plus [0..4).
+ return hour >= window.startHour || hour < window.endHour;
+}
+
+/** Evaluate the soft gates; the lease is checked at run time. */
+export function evaluateGates(vault: string, opts: EvaluateGatesOptions): MaintenanceVerdict {
+ if (opts.window !== undefined && !dailyWindowContains(opts.now, opts.window)) {
+ return "skipped:window";
+ }
+ const busy = opts.busy ?? {
+ minutes: MAINTENANCE_BUSY_MINUTES,
+ threshold: MAINTENANCE_BUSY_THRESHOLD,
+ };
+ const since = new Date(opts.now.getTime() - busy.minutes * 60_000).toISOString();
+ const recent = listRecallTelemetry(vault, { since });
+ if (recent.length >= busy.threshold) return "skipped:busy";
+ return "run";
+}
+
+/**
+ * Run the registered heavy tasks through the gates. Tasks execute
+ * stale-first: least-recently succeeded first (from the journal),
+ * never-run before everything, so a task that keeps failing or got
+ * starved naturally floats to the front.
+ */
+export async function runMaintenance(
+ vault: string,
+ opts: RunMaintenanceOptions,
+): Promise<RunMaintenanceResult> {
+ const nowIso = opts.now.toISOString();
+ if (opts.force !== true) {
+ const verdict = evaluateGates(vault, opts);
+ if (verdict !== "run") {
+ appendJournal(vault, { ts: nowIso, holder: opts.holder, verdict });
+ return { verdict, tasks: [] };
+ }
+ }
+
+ const ttl = opts.leaseTtlMs ?? MAINTENANCE_LEASE_TTL_MS;
+ if (!acquireLease(vault, { holder: opts.holder, ttlMs: ttl, now: opts.now })) {
+ appendJournal(vault, { ts: nowIso, holder: opts.holder, verdict: "skipped:lease" });
+ return { verdict: "skipped:lease", tasks: [] };
+ }
+
+ try {
+ const ordered = orderStaleFirst(vault, opts.tasks);
+ const results: MaintenanceTaskResult[] = [];
+ for (const task of ordered) {
+ const startedAt = Date.now();
+ let ok = true;
+ let error: string | undefined;
+ try {
+ // Sequential by design: the lane exists to serialize heavy work.
+ // eslint-disable-next-line no-await-in-loop
+ await task.run();
+ } catch (exc) {
+ ok = false;
+ error = exc instanceof Error ? exc.message : String(exc);
+ }
+ const duration = Date.now() - startedAt;
+ results.push({ name: task.name, ok, duration_ms: duration, ...(error ? { error } : {}) });
+ appendJournal(vault, {
+ ts: nowIso,
+ holder: opts.holder,
+ verdict: "run",
+ task: task.name,
+ ok,
+ duration_ms: duration,
+ ...(error ? { error } : {}),
+ });
+ }
+ // The cap rewrite happens only here, while the lease is held -
+ // the one point where no other writer can race the journal.
+ sweepJournal(vault);
+ return { verdict: "run", tasks: results };
+ } finally {
+ releaseLease(vault, { holder: opts.holder, name: MAINTENANCE_LEASE_NAME });
+ }
+}
+
+function orderStaleFirst(vault: string, tasks: ReadonlyArray<MaintenanceTask>): MaintenanceTask[] {
+ const lastSuccess = new Map<string, string>();
+ for (const entry of listJournal(vault)) {
+ if (entry.task === undefined || entry.ok !== true) continue;
+ if (!lastSuccess.has(entry.task)) lastSuccess.set(entry.task, entry.ts); // newest-first list
+ }
+ return [...tasks].toSorted((a, b) => {
+ const aTs = lastSuccess.get(a.name) ?? "";
+ const bTs = lastSuccess.get(b.name) ?? "";
+ return aTs.localeCompare(bTs);
+ });
+}
diff --git a/src/core/brain/maintenance/lease.ts b/src/core/brain/maintenance/lease.ts
new file mode 100644
index 00000000..b50e9b7a
--- /dev/null
+++ b/src/core/brain/maintenance/lease.ts
@@ -0,0 +1,119 @@
+/**
+ * Expiring maintenance lease (write-time-integrity-governance,
+ * t_166d1226). A tiny dedicated SQLite database in the vault-local
+ * state dir - deliberately NOT brain.sqlite, so holding the lease
+ * never contends with the search index writer lock - holds one row
+ * per lease name. Acquisition is a single conditional upsert, so two
+ * workers racing across processes cannot both win; a crashed worker's
+ * lease frees itself by expiry, never by manual cleanup.
+ */
+
+import { Database } from "bun:sqlite";
+import { mkdirSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+export const MAINTENANCE_LEASE_NAME = "maintenance";
+
+export interface AcquireLeaseOptions {
+ readonly name?: string;
+ readonly holder: string;
+ readonly ttlMs: number;
+ readonly now: Date;
+}
+
+export interface ReleaseLeaseOptions {
+ readonly name?: string;
+ readonly holder: string;
+}
+
+export interface LeaseState {
+ readonly name: string;
+ readonly holder: string;
+ readonly expiresAt: string;
+}
+
+function leaseDbPath(vault: string): string {
+ return join(vault, ".open-second-brain", "maintenance.sqlite");
+}
+
+function openLeaseDb(vault: string): Database {
+ const path = leaseDbPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ const db = new Database(path);
+ db.exec("PRAGMA journal_mode = WAL");
+ db.exec("PRAGMA busy_timeout = 5000");
+ db.exec(
+ "CREATE TABLE IF NOT EXISTS leases (" +
+ " name TEXT PRIMARY KEY," +
+ " holder TEXT NOT NULL," +
+ " expires_at TEXT NOT NULL" +
+ ")",
+ );
+ return db;
+}
+
+/**
+ * Try to take the lease. True when this holder now owns it - either
+ * it was free, expired, or already ours (re-entrant renew).
+ */
+export function acquireLease(vault: string, opts: AcquireLeaseOptions): boolean {
+ if (!Number.isFinite(opts.ttlMs) || opts.ttlMs <= 0) {
+ // A non-positive TTL would mint an already-expired lease and every
+ // contender would acquire at once - silent loss of mutual exclusion.
+ throw new Error(`lease ttlMs must be a positive number, got ${opts.ttlMs}`);
+ }
+ const name = opts.name ?? MAINTENANCE_LEASE_NAME;
+ const nowIso = opts.now.toISOString();
+ const expiresAt = new Date(opts.now.getTime() + opts.ttlMs).toISOString();
+ const db = openLeaseDb(vault);
+ try {
+ db.run(
+ "INSERT INTO leases(name, holder, expires_at) VALUES (?, ?, ?) " +
+ "ON CONFLICT(name) DO UPDATE SET holder = excluded.holder, expires_at = excluded.expires_at " +
+ "WHERE leases.expires_at < ? OR leases.holder = excluded.holder",
+ [name, opts.holder, expiresAt, nowIso],
+ );
+ const row = db
+ .query<{ holder: string }, [string]>("SELECT holder FROM leases WHERE name = ?")
+ .get(name);
+ return row?.holder === opts.holder;
+ } finally {
+ db.close();
+ }
+}
+
+/** Release the lease; only the current holder may. */
+export function releaseLease(vault: string, opts: ReleaseLeaseOptions): boolean {
+ const name = opts.name ?? MAINTENANCE_LEASE_NAME;
+ const db = openLeaseDb(vault);
+ try {
+ db.run("DELETE FROM leases WHERE name = ? AND holder = ?", [name, opts.holder]);
+ const gone = db
+ .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM leases WHERE name = ?")
+ .get(name);
+ return (gone?.n ?? 0) === 0;
+ } finally {
+ db.close();
+ }
+}
+
+/** The live lease, or null when free or expired. */
+export function currentLease(
+ vault: string,
+ opts: { readonly name?: string; readonly now?: Date } = {},
+): LeaseState | null {
+ const name = opts.name ?? MAINTENANCE_LEASE_NAME;
+ const now = opts.now ?? new Date();
+ const db = openLeaseDb(vault);
+ try {
+ const row = db
+ .query<{ name: string; holder: string; expires_at: string }, [string]>(
+ "SELECT name, holder, expires_at FROM leases WHERE name = ?",
+ )
+ .get(name);
+ if (!row || row.expires_at < now.toISOString()) return null;
+ return { name: row.name, holder: row.holder, expiresAt: row.expires_at };
+ } finally {
+ db.close();
+ }
+}
diff --git a/src/core/brain/note-path.ts b/src/core/brain/note-path.ts
new file mode 100644
index 00000000..094df6a2
--- /dev/null
+++ b/src/core/brain/note-path.ts
@@ -0,0 +1,44 @@
+/**
+ * Vault-contained note path resolution (write-time-integrity-
+ * governance). One guard shared by every governance surface that
+ * reads or writes a caller-supplied vault-relative path (labels,
+ * attributes, their CLI/MCP show branches, tier restore): lexical
+ * containment first, then symlink canonicalization - a symlink
+ * inside the vault pointing outside it must not pass.
+ */
+
+import { existsSync, realpathSync } from "node:fs";
+import { resolve, sep } from "node:path";
+
+export interface ResolveNotePathOptions {
+ /** When true (default), a missing file is an error. */
+ readonly mustExist?: boolean;
+}
+
+/**
+ * Resolve `relPath` against the vault root, refusing lexical
+ * traversal and symlink escapes. Returns the canonical absolute path.
+ */
+export function resolveNotePath(
+ vault: string,
+ relPath: string,
+ opts: ResolveNotePathOptions = {},
+): string {
+ const vaultRoot = resolve(vault);
+ const path = resolve(vaultRoot, relPath);
+ if (path !== vaultRoot && !path.startsWith(vaultRoot + sep)) {
+ throw new Error(`note path resolves outside the vault: ${relPath}`);
+ }
+ if (!existsSync(path)) {
+ if (opts.mustExist === false) return path;
+ throw new Error(`note does not exist: ${relPath}`);
+ }
+ // Canonicalize both sides: a symlinked vault root is fine, a
+ // symlinked NOTE that escapes the canonical root is not.
+ const realRoot = realpathSync(vaultRoot);
+ const realPath = realpathSync(path);
+ if (realPath !== realRoot && !realPath.startsWith(realRoot + sep)) {
+ throw new Error(`note path resolves outside the vault via a symlink: ${relPath}`);
+ }
+ return realPath;
+}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 574c7057..ff312bfd 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -38,6 +38,8 @@ import { basename, dirname, join } from "node:path";
import type { FrontmatterMap } from "../types.ts";
import { formatFrontmatter, parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { FrontmatterTierConflictError, mergeFrontmatterTiered } from "./frontmatter-tiers.ts";
+import { loadSchemaPack } from "./schema-pack.ts";
import { DEFAULT_RELATION_TYPES, type DefaultRelationType } from "../graph/relation-vocab.ts";
import {
isKnownSchemaToken,
@@ -274,15 +276,30 @@ export function writePreference(
const path = preferencePath(vault, slug);
const id = `pref-${slug}`;
- const metadata = preferenceFrontmatter(input, id);
+ let metadata = preferenceFrontmatter(input, id);
const body = renderPreferenceBody(input);
- // Content-level idempotency: skip the rename when the file would be
- // byte-identical. Keeps the dream invariant "a no-op rerun must not
- // rewrite preference files" even after v0.10.1 expanded what dream
- // recomputes per pass (evidence slices), and it spares Syncthing
- // peers from spurious sync events.
if (options.overwrite && existsSync(path)) {
+ // Tier guard (write-time-integrity-governance): rewrites merge
+ // through the tier model so a user-tier field a human added by
+ // hand survives, framework-owned legacy keys the writer no longer
+ // emits are dropped, and a changed identity join key throws
+ // instead of being silently re-accepted. An unreadable existing
+ // file or schema pack falls back to the plain framework write.
+ try {
+ const [existingMeta] = parseFrontmatter(path);
+ metadata = mergeFrontmatterTiered(existingMeta, metadata, {
+ kind: "brain-preference",
+ pack: loadSchemaPack(vault),
+ });
+ } catch (exc) {
+ if (exc instanceof FrontmatterTierConflictError) throw exc;
+ }
+ // Content-level idempotency: skip the rename when the file would
+ // be byte-identical. Keeps the dream invariant "a no-op rerun
+ // must not rewrite preference files" even after v0.10.1 expanded
+ // what dream recomputes per pass (evidence slices), and it spares
+ // Syncthing peers from spurious sync events.
try {
const next = formatFrontmatter(metadata, body);
const prev = readFileSync(path, "utf8");
diff --git a/src/core/brain/schema-admin.ts b/src/core/brain/schema-admin.ts
index 3431306d..1bfb4252 100644
--- a/src/core/brain/schema-admin.ts
+++ b/src/core/brain/schema-admin.ts
@@ -1,10 +1,16 @@
import { brainConfigPath } from "./paths.ts";
+import { linkConstraintAllows, readBlockedRelationRows } from "../search/link-constraints.ts";
import {
buildSchemaReport,
type BrainSchemaReport,
type SchemaReportFinding,
} from "./schema-report.ts";
-import { loadSchemaPack, type SchemaPack } from "./schema-pack.ts";
+import {
+ FRONTMATTER_TIERS,
+ loadSchemaPack,
+ type FrontmatterTier,
+ type SchemaPack,
+} from "./schema-pack.ts";
import {
applySchemaMutations,
type ApplySchemaMutationsResult,
@@ -61,6 +67,12 @@ export interface SchemaExplanation {
readonly link_type: boolean;
readonly extractable: boolean;
readonly expert: string | null;
+ /**
+ * Declared attribute fields for this type with their natural-language
+ * descriptions (write-time-integrity-governance) - the vocabulary an
+ * agent should populate when capturing this type.
+ */
+ readonly attributes: Readonly<Record<string, string>>;
}
export interface SchemaOrphanReport {
@@ -116,10 +128,37 @@ export function buildSchemaStats(vault: string): SchemaStats {
};
}
-export function buildSchemaLint(vault: string): {
+export function buildSchemaLint(
+ vault: string,
+ opts: { readonly dbPath?: string } = {},
+): {
findings: ReadonlyArray<SchemaReportFinding>;
} {
- return { findings: buildSchemaReport(vault).findings };
+ const findings: SchemaReportFinding[] = [...buildSchemaReport(vault).findings];
+ if (opts.dbPath !== undefined) {
+ // Link-constraint enforcement happens in the indexer's
+ // materialization post-pass; lint reads the blocked edges back
+ // from the index (fail-soft: no index file = no findings) and
+ // re-checks each one against the CURRENT pack, so a `schema
+ // apply` that removed or relaxed a constraint stops reporting
+ // stale violations immediately - the next index run unblocks the
+ // edges themselves.
+ const constraints = loadSchemaPack(vault).link_constraints;
+ for (const row of readBlockedRelationRows(opts.dbPath)) {
+ if (linkConstraintAllows(constraints, row.relation, row.sourceType, row.targetType)) {
+ continue; // stale flag; the next index run clears it
+ }
+ findings.push({
+ kind: "link-constraint-violation",
+ relation: row.relation,
+ source: row.sourcePath,
+ target: row.targetPath,
+ source_type: row.sourceType,
+ target_type: row.targetType,
+ });
+ }
+ }
+ return { findings };
}
export function buildSchemaGraph(vault: string): SchemaGraph {
@@ -197,6 +236,7 @@ export function explainSchemaToken(vault: string, rawToken: string): SchemaExpla
link_type: pack.link_types.includes(token),
extractable: pack.extractable.includes(token),
expert: pack.expert_routing[token] ?? null,
+ attributes: pack.attributes[token] ?? {},
};
}
@@ -294,11 +334,58 @@ function coerceSchemaMutation(value: unknown): SchemaMutation {
throw new Error("mutation.expert must be a string or null");
return { op, token: readString(value, "token"), expert };
}
+ case "add_label_dimension":
+ return {
+ op,
+ dimension: readString(value, "dimension"),
+ values: readStringArray(value, "values"),
+ };
+ case "remove_label_dimension":
+ return { op, dimension: readString(value, "dimension") };
+ case "add_link_constraint":
+ case "remove_link_constraint":
+ return {
+ op,
+ link_type: readString(value, "link_type"),
+ source: readString(value, "source"),
+ target: readString(value, "target"),
+ };
+ case "set_attribute_field":
+ return {
+ op,
+ type: readString(value, "type"),
+ field: readString(value, "field"),
+ description: readString(value, "description"),
+ };
+ case "remove_attribute_field":
+ return { op, type: readString(value, "type"), field: readString(value, "field") };
+ case "set_frontmatter_tier": {
+ const tier = readString(value, "tier");
+ if (!(FRONTMATTER_TIERS as ReadonlyArray<string>).includes(tier)) {
+ throw new Error(`mutation.tier must be one of ${FRONTMATTER_TIERS.join(", ")}`);
+ }
+ return {
+ op,
+ kind: readString(value, "kind"),
+ field: readString(value, "field"),
+ tier: tier as FrontmatterTier,
+ };
+ }
+ case "remove_frontmatter_tier":
+ return { op, kind: readString(value, "kind"), field: readString(value, "field") };
default:
throw new Error(`unsupported schema mutation op: ${op}`);
}
}
+function readStringArray(value: Record<string, unknown>, key: string): string[] {
+ const raw = value[key];
+ if (!Array.isArray(raw) || !raw.every((item): item is string => typeof item === "string")) {
+ throw new Error(`mutation.${key} must be an array of strings`);
+ }
+ return raw;
+}
+
function readCategory(value: Record<string, unknown>): SchemaVocabularyCategory {
const raw = readString(value, "category");
if (!(SCHEMA_VOCAB_CATEGORIES as ReadonlyArray<string>).includes(raw)) {
diff --git a/src/core/brain/schema-mutate.ts b/src/core/brain/schema-mutate.ts
index 375bcd04..fe33eaf5 100644
--- a/src/core/brain/schema-mutate.ts
+++ b/src/core/brain/schema-mutate.ts
@@ -10,6 +10,9 @@ import {
renderSchemaBlock,
replaceSchemaBlock,
schemaPackTokens,
+ validateEndpointPair,
+ FRONTMATTER_TIERS,
+ type FrontmatterTier,
type SchemaPack,
} from "./schema-pack.ts";
import {
@@ -56,6 +59,40 @@ export type SchemaMutation =
readonly op: "set_expert_routing";
readonly token: string;
readonly expert: string | null;
+ }
+ | {
+ readonly op: "add_label_dimension";
+ readonly dimension: string;
+ readonly values: ReadonlyArray<string>;
+ }
+ | { readonly op: "remove_label_dimension"; readonly dimension: string }
+ | {
+ readonly op: "add_link_constraint" | "remove_link_constraint";
+ readonly link_type: string;
+ readonly source: string;
+ readonly target: string;
+ }
+ | {
+ readonly op: "set_attribute_field";
+ readonly type: string;
+ readonly field: string;
+ readonly description: string;
+ }
+ | {
+ readonly op: "remove_attribute_field";
+ readonly type: string;
+ readonly field: string;
+ }
+ | {
+ readonly op: "set_frontmatter_tier";
+ readonly kind: string;
+ readonly field: string;
+ readonly tier: FrontmatterTier;
+ }
+ | {
+ readonly op: "remove_frontmatter_tier";
+ readonly kind: string;
+ readonly field: string;
};
export interface ApplySchemaMutationsOptions {
@@ -78,6 +115,10 @@ interface MutableSchemaPack {
link_types: string[];
extractable: string[];
expert_routing: Record<string, string>;
+ labels: Record<string, string[]>;
+ link_constraints: Record<string, string[]>;
+ attributes: Record<string, Record<string, string>>;
+ frontmatter_tiers: Record<string, Record<string, FrontmatterTier>>;
}
export async function applySchemaMutations(
@@ -147,6 +188,7 @@ function applyOne(pack: MutableSchemaPack, mutation: SchemaMutation): void {
}
removeValue(pack.extractable, token);
delete pack.expert_routing[token];
+ delete pack.attributes[token];
return;
}
case "update_type": {
@@ -165,6 +207,18 @@ function applyOne(pack: MutableSchemaPack, mutation: SchemaMutation): void {
pack.expert_routing[next] = pack.expert_routing[token]!;
delete pack.expert_routing[token];
}
+ if (pack.attributes[token]) {
+ pack.attributes[next] = pack.attributes[token]!;
+ delete pack.attributes[token];
+ }
+ for (const [linkType, pairs] of Object.entries(pack.link_constraints)) {
+ pack.link_constraints[linkType] = pairs.map((pair) => {
+ const [source, target] = pair.split("->");
+ const nextSource = source === token ? next : source!;
+ const nextTarget = target === token ? next : target!;
+ return `${nextSource}->${nextTarget}`;
+ });
+ }
return;
}
case "add_alias": {
@@ -200,6 +254,7 @@ function applyOne(pack: MutableSchemaPack, mutation: SchemaMutation): void {
case "remove_link_type": {
const token = validateSchemaToken(mutation.token, "schema.link_types");
removeValue(pack.link_types, token);
+ delete pack.link_constraints[token];
return;
}
case "set_extractable": {
@@ -220,6 +275,87 @@ function applyOne(pack: MutableSchemaPack, mutation: SchemaMutation): void {
}
return;
}
+ case "add_label_dimension": {
+ const dimension = validateSchemaToken(mutation.dimension, "schema.labels");
+ const values = mutation.values.map((value, index) =>
+ validateSchemaToken(value, `schema.labels.${dimension}[${index}]`),
+ );
+ if (values.length === 0) {
+ throw new Error(`schema.labels.${dimension}: at least one value is required`);
+ }
+ pack.labels[dimension] = pack.labels[dimension] ?? [];
+ for (const value of values) addUnique(pack.labels[dimension]!, value);
+ return;
+ }
+ case "remove_label_dimension": {
+ const dimension = validateSchemaToken(mutation.dimension, "schema.labels");
+ delete pack.labels[dimension];
+ return;
+ }
+ case "add_link_constraint": {
+ const linkType = validateSchemaToken(mutation.link_type, "schema.link_constraints");
+ const pair = validateEndpointPair(
+ `${mutation.source}->${mutation.target}`,
+ `schema.link_constraints.${linkType}`,
+ );
+ pack.link_constraints[linkType] = pack.link_constraints[linkType] ?? [];
+ addUnique(pack.link_constraints[linkType]!, pair);
+ return;
+ }
+ case "remove_link_constraint": {
+ const linkType = validateSchemaToken(mutation.link_type, "schema.link_constraints");
+ const pair = validateEndpointPair(
+ `${mutation.source}->${mutation.target}`,
+ `schema.link_constraints.${linkType}`,
+ );
+ removeValue(pack.link_constraints[linkType] ?? [], pair);
+ if ((pack.link_constraints[linkType]?.length ?? 0) === 0) {
+ delete pack.link_constraints[linkType];
+ }
+ return;
+ }
+ case "set_attribute_field": {
+ const type = validateSchemaToken(mutation.type, "schema.attributes");
+ const field = validateSchemaToken(mutation.field, `schema.attributes.${type}`);
+ const description = mutation.description.trim();
+ if (description.length === 0) {
+ throw new Error(`schema.attributes.${type}.${field}: description must not be empty`);
+ }
+ if (/[\r\n]/.test(mutation.description)) {
+ throw new Error(`schema.attributes.${type}.${field}: description must be a single line`);
+ }
+ pack.attributes[type] = pack.attributes[type] ?? {};
+ pack.attributes[type]![field] = description;
+ return;
+ }
+ case "remove_attribute_field": {
+ const type = validateSchemaToken(mutation.type, "schema.attributes");
+ const field = validateSchemaToken(mutation.field, `schema.attributes.${type}`);
+ delete pack.attributes[type]?.[field];
+ if (Object.keys(pack.attributes[type] ?? {}).length === 0) delete pack.attributes[type];
+ return;
+ }
+ case "set_frontmatter_tier": {
+ const kind = validateSchemaToken(mutation.kind, "schema.frontmatter_tiers");
+ const field = validateSchemaToken(mutation.field, `schema.frontmatter_tiers.${kind}`);
+ if (!FRONTMATTER_TIERS.includes(mutation.tier)) {
+ throw new Error(
+ `schema.frontmatter_tiers.${kind}.${field}: tier must be one of ${FRONTMATTER_TIERS.join(", ")}`,
+ );
+ }
+ pack.frontmatter_tiers[kind] = pack.frontmatter_tiers[kind] ?? {};
+ pack.frontmatter_tiers[kind]![field] = mutation.tier;
+ return;
+ }
+ case "remove_frontmatter_tier": {
+ const kind = validateSchemaToken(mutation.kind, "schema.frontmatter_tiers");
+ const field = validateSchemaToken(mutation.field, `schema.frontmatter_tiers.${kind}`);
+ delete pack.frontmatter_tiers[kind]?.[field];
+ if (Object.keys(pack.frontmatter_tiers[kind] ?? {}).length === 0) {
+ delete pack.frontmatter_tiers[kind];
+ }
+ return;
+ }
}
}
@@ -236,6 +372,10 @@ function clonePack(pack: SchemaPack): MutableSchemaPack {
link_types: [...pack.link_types],
extractable: [...pack.extractable],
expert_routing: { ...pack.expert_routing },
+ labels: mapArrayRecord(pack.labels),
+ link_constraints: mapArrayRecord(pack.link_constraints),
+ attributes: mapNestedRecord(pack.attributes),
+ frontmatter_tiers: mapNestedRecord(pack.frontmatter_tiers),
};
}
@@ -250,6 +390,10 @@ function freezeMutable(input: MutableSchemaPack): SchemaPack {
link_types: Object.freeze([...input.link_types]),
extractable: Object.freeze([...input.extractable]),
expert_routing: Object.freeze({ ...input.expert_routing }),
+ labels: freezeArrayRecord(input.labels),
+ link_constraints: freezeArrayRecord(input.link_constraints),
+ attributes: freezeNestedRecord(input.attributes),
+ frontmatter_tiers: freezeNestedRecord(input.frontmatter_tiers),
}),
);
}
@@ -270,6 +414,32 @@ function validateSchemaPackReferences(pack: SchemaPack): void {
throw new Error(`schema.expert_routing.${token}: token is not declared`);
}
}
+ for (const linkType of Object.keys(pack.link_constraints)) {
+ if (!pack.link_types.includes(linkType)) {
+ throw new Error(`schema.link_constraints.${linkType}: link type is not declared`);
+ }
+ }
+ for (const type of Object.keys(pack.attributes)) {
+ if (!tokens.has(type)) {
+ throw new Error(`schema.attributes.${type}: token is not declared`);
+ }
+ }
+}
+
+function mapNestedRecord<T extends string>(
+ record: Readonly<Record<string, Readonly<Record<string, T>>>>,
+): Record<string, Record<string, T>> {
+ const out: Record<string, Record<string, T>> = {};
+ for (const [key, inner] of Object.entries(record)) out[key] = { ...inner };
+ return out;
+}
+
+function freezeNestedRecord<T extends string>(
+ record: Record<string, Record<string, T>>,
+): Readonly<Record<string, Readonly<Record<string, T>>>> {
+ const out: Record<string, Readonly<Record<string, T>>> = {};
+ for (const [key, inner] of Object.entries(record)) out[key] = Object.freeze({ ...inner });
+ return Object.freeze(out);
}
function pruneDeclarations(
diff --git a/src/core/brain/schema-pack.ts b/src/core/brain/schema-pack.ts
index c9c27d1b..88b016db 100644
--- a/src/core/brain/schema-pack.ts
+++ b/src/core/brain/schema-pack.ts
@@ -19,8 +19,26 @@ export interface SchemaPack {
readonly link_types: ReadonlyArray<string>;
readonly extractable: ReadonlyArray<string>;
readonly expert_routing: Readonly<Record<string, string>>;
+ /** Controlled-vocabulary label dimensions: dimension -> allowed values. */
+ readonly labels: Readonly<Record<string, ReadonlyArray<string>>>;
+ /** Allowed endpoint pairs per link type, each stored as `source->target`. */
+ readonly link_constraints: Readonly<Record<string, ReadonlyArray<string>>>;
+ /** Per-type attribute descriptors: type -> field -> description. */
+ readonly attributes: Readonly<Record<string, Readonly<Record<string, string>>>>;
+ /** Frontmatter tier overrides: kind -> field -> tier. */
+ readonly frontmatter_tiers: Readonly<Record<string, Readonly<Record<string, FrontmatterTier>>>>;
}
+/**
+ * Four-level frontmatter field tier model (EverOS-inspired):
+ * `identity` - framework-owned join keys (hand-edit = corruption);
+ * `system` - framework-written bookkeeping (hand-edit = drift);
+ * `business` - agent-written domain fields; `user` - freely editable.
+ */
+export const FRONTMATTER_TIERS = Object.freeze(["identity", "system", "business", "user"] as const);
+
+export type FrontmatterTier = (typeof FRONTMATTER_TIERS)[number];
+
export function loadSchemaPack(vault: string): SchemaPack {
const path = brainConfigPath(vault);
const text = existsSync(path) ? readFileSync(path, "utf8") : "schema_version: 1\n";
@@ -49,6 +67,25 @@ export function parseSchemaPack(configText: string): SchemaPack {
"schema.expert_routing",
false,
);
+ const labels = parseMapListField(lines, "labels", "schema.labels");
+ const linkConstraints = parseMapListField(
+ lines,
+ "link_constraints",
+ "schema.link_constraints",
+ validateEndpointPair,
+ );
+ const attributes = parseCompoundMapField(
+ lines,
+ "attributes",
+ "schema.attributes",
+ validateAttributeDescription,
+ );
+ const frontmatterTiers = parseCompoundMapField(
+ lines,
+ "frontmatter_tiers",
+ "schema.frontmatter_tiers",
+ validateFrontmatterTier,
+ );
return freezeSchemaPack({
declarations,
@@ -58,9 +95,41 @@ export function parseSchemaPack(configText: string): SchemaPack {
link_types: unique(linkTypes),
extractable: unique(extractable),
expert_routing: expertRouting,
+ labels,
+ link_constraints: linkConstraints,
+ attributes,
+ frontmatter_tiers: frontmatterTiers,
});
}
+/** Validate and normalize a `source->target` endpoint pair value. */
+export function validateEndpointPair(value: string, field: string): string {
+ const arrow = value.indexOf("->");
+ if (arrow < 0) {
+ throw new Error(`${field}: "${value}" must be a source->target pair of schema tokens`);
+ }
+ const source = validateSchemaToken(value.slice(0, arrow), field);
+ const target = validateSchemaToken(value.slice(arrow + 2), field);
+ return `${source}->${target}`;
+}
+
+function validateAttributeDescription(value: string, field: string): string {
+ // Raw value checked for line breaks (same contract as the mutation
+ // op in schema-mutate.ts); the trimmed form is what gets stored.
+ if (/[\r\n]/.test(value)) throw new Error(`${field}: description must be a single line`);
+ const trimmed = value.trim();
+ if (trimmed.length === 0) throw new Error(`${field}: description must not be empty`);
+ return trimmed;
+}
+
+function validateFrontmatterTier(value: string, field: string): FrontmatterTier {
+ const normalized = value.trim().toLowerCase();
+ if (!(FRONTMATTER_TIERS as ReadonlyArray<string>).includes(normalized)) {
+ throw new Error(`${field}: tier must be one of ${FRONTMATTER_TIERS.join(", ")}`);
+ }
+ return normalized as FrontmatterTier;
+}
+
export function renderSchemaBlock(pack: SchemaPack): string {
const lines = ["schema:"];
for (const category of SCHEMA_VOCAB_CATEGORIES) {
@@ -74,6 +143,10 @@ export function renderSchemaBlock(pack: SchemaPack): string {
renderList(lines, "link_types", pack.link_types);
renderList(lines, "extractable", pack.extractable);
renderMapScalar(lines, "expert_routing", pack.expert_routing);
+ renderMapList(lines, "labels", pack.labels);
+ renderMapList(lines, "link_constraints", pack.link_constraints);
+ renderCompoundMap(lines, "attributes", pack.attributes);
+ renderCompoundMap(lines, "frontmatter_tiers", pack.frontmatter_tiers);
if (lines.length === 1) lines.push(" {}");
return lines.join("\n") + "\n";
}
@@ -138,9 +211,10 @@ function parseMapListField(
lines: ReadonlyArray<string>,
key: string,
field: string,
+ validateValue: (value: string, field: string) => string = validateSchemaToken,
): Record<string, ReadonlyArray<string>> {
const start = findField(lines, key);
- if (start < 0) return {};
+ if (start < 0) return freezeRecord({});
const out: Record<string, string[]> = {};
for (let index = start + 1; index < lines.length; index++) {
const line = lines[index]!;
@@ -149,9 +223,9 @@ function parseMapListField(
if (flat) {
const [rawToken, rawAlias] = splitPair(flat[1]!);
const token = validateSchemaToken(rawToken, `${field}.${rawToken}`);
- const alias = validateSchemaToken(rawAlias, `${field}.${token}`);
+ const alias = validateValue(rawAlias, `${field}.${token}`);
out[token] = out[token] ?? [];
- out[token]!.push(alias);
+ if (!out[token]!.includes(alias)) out[token]!.push(alias);
continue;
}
const entry = /^ ([^:]+):\s*(.*)$/.exec(line);
@@ -160,14 +234,45 @@ function parseMapListField(
const rest = entry[2]!.trim();
const values = rest.startsWith("[") ? parseInlineList(rest) : collectNestedList(lines, index);
out[token] = unique(
- values.map((value, valueIndex) =>
- validateSchemaToken(value, `${field}.${token}[${valueIndex}]`),
- ),
+ values.map((value, valueIndex) => validateValue(value, `${field}.${token}[${valueIndex}]`)),
);
}
return freezeRecord(out);
}
+/**
+ * Parse a `- outer.inner=value` map-of-maps field. The compound key is
+ * split on its first `.`; both halves must be schema tokens, the value
+ * is checked by `validateValue` (free text stays untouched beyond it).
+ */
+function parseCompoundMapField<T extends string>(
+ lines: ReadonlyArray<string>,
+ key: string,
+ field: string,
+ validateValue: (value: string, field: string) => T,
+): Readonly<Record<string, Readonly<Record<string, T>>>> {
+ const start = findField(lines, key);
+ if (start < 0) return Object.freeze({});
+ const out: Record<string, Record<string, T>> = {};
+ for (let index = start + 1; index < lines.length; index++) {
+ const line = lines[index]!;
+ if (/^ \S/.test(line)) break;
+ const flat = /^ -\s+(.+?)\s*$/.exec(line);
+ if (!flat) continue;
+ const [rawKey, rawValue] = splitPair(flat[1]!);
+ const dot = rawKey.indexOf(".");
+ if (dot <= 0 || dot === rawKey.length - 1) {
+ throw new Error(`${field}: "${rawKey}" must use a compound type.field key`);
+ }
+ const outer = validateSchemaToken(rawKey.slice(0, dot), `${field}.${rawKey}`);
+ const inner = validateSchemaToken(rawKey.slice(dot + 1), `${field}.${outer}`);
+ const value = validateValue(rawValue, `${field}.${outer}.${inner}`);
+ out[outer] = out[outer] ?? {};
+ out[outer]![inner] = value;
+ }
+ return freezeNestedRecord(out);
+}
+
function parseMapScalarField(
lines: ReadonlyArray<string>,
key: string,
@@ -266,6 +371,21 @@ function renderMapScalar(
for (const [name, value] of entries) lines.push(` - ${name}=${value}`);
}
+function renderCompoundMap(
+ lines: string[],
+ key: string,
+ values: Readonly<Record<string, Readonly<Record<string, string>>>>,
+): void {
+ const outers = Object.entries(values).toSorted(([left], [right]) => left.localeCompare(right));
+ const rendered: string[] = [];
+ for (const [outer, fields] of outers) {
+ const inners = Object.entries(fields).toSorted(([left], [right]) => left.localeCompare(right));
+ for (const [inner, value] of inners) rendered.push(` - ${outer}.${inner}=${value}`);
+ }
+ if (rendered.length === 0) return;
+ lines.push(` ${key}:`, ...rendered);
+}
+
function splitPair(raw: string): [string, string] {
const index = raw.indexOf("=");
if (index < 0) return [raw, ""];
@@ -283,6 +403,10 @@ function freezeSchemaPack(
link_types: Object.freeze([...input.link_types]),
extractable: Object.freeze([...input.extractable]),
expert_routing: input.expert_routing,
+ labels: input.labels,
+ link_constraints: input.link_constraints,
+ attributes: input.attributes,
+ frontmatter_tiers: input.frontmatter_tiers,
});
}
@@ -290,6 +414,14 @@ function freezeRecord<T>(record: Record<string, T>): Readonly<Record<string, T>>
return Object.freeze({ ...record });
}
+function freezeNestedRecord<T extends string>(
+ record: Record<string, Record<string, T>>,
+): Readonly<Record<string, Readonly<Record<string, T>>>> {
+ const out: Record<string, Readonly<Record<string, T>>> = {};
+ for (const [key, inner] of Object.entries(record)) out[key] = Object.freeze({ ...inner });
+ return Object.freeze(out);
+}
+
function unique(values: ReadonlyArray<string>): string[] {
const seen = new Set<string>();
const out: string[] = [];
diff --git a/src/core/brain/schema-report.ts b/src/core/brain/schema-report.ts
index 90917a97..fcbfdb72 100644
--- a/src/core/brain/schema-report.ts
+++ b/src/core/brain/schema-report.ts
@@ -31,6 +31,19 @@ export type SchemaReportFinding =
readonly kind: "unused-declaration";
readonly category: SchemaVocabularyCategory;
readonly token: string;
+ }
+ | {
+ /**
+ * A typed edge whose endpoint page types violate the schema
+ * pack's `link_constraints`; the indexer's materialization
+ * post-pass blocked it (write-time-integrity-governance).
+ */
+ readonly kind: "link-constraint-violation";
+ readonly relation: string;
+ readonly source: string;
+ readonly target: string;
+ readonly source_type: string | null;
+ readonly target_type: string | null;
};
export interface BrainSchemaUsage {
@@ -229,8 +242,8 @@ function freezeUsage(counts: Map<string, number>): ReadonlyArray<SchemaTokenUsag
function compareFindings(a: SchemaReportFinding, b: SchemaReportFinding): number {
return (
a.kind.localeCompare(b.kind) ||
- a.category.localeCompare(b.category) ||
- a.token.localeCompare(b.token) ||
+ ("category" in a ? a.category : "").localeCompare("category" in b ? b.category : "") ||
+ ("token" in a ? a.token : "").localeCompare("token" in b ? b.token : "") ||
("path" in a ? a.path : "").localeCompare("path" in b ? b.path : "")
);
}
diff --git a/src/core/brain/secrets/crypto.ts b/src/core/brain/secrets/crypto.ts
new file mode 100644
index 00000000..712dd76d
--- /dev/null
+++ b/src/core/brain/secrets/crypto.ts
@@ -0,0 +1,83 @@
+/**
+ * Secret-custody crypto kernel (write-time-integrity-governance).
+ *
+ * Per-value AES-256-GCM from node:crypto - random 12-byte IV per
+ * encryption, authentication tag verified on every decrypt, so a
+ * tampered ciphertext fails closed instead of decoding garbage. The
+ * 32-byte key lives in a 0600 keyfile beside the ciphertext store;
+ * both stay under the vault-local state dir that never syncs as
+ * vault content.
+ *
+ * Honest threat model (documented, not implied): this protects
+ * against secret values entering an agent's context, against vault
+ * sync/export leakage, and against casual reads of vault markdown.
+ * It does NOT protect against root or same-user processes on the
+ * host - there is no daemon and no TPM in this design.
+ */
+
+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
+import { dirname } from "node:path";
+
+const ALGORITHM = "aes-256-gcm";
+const KEY_BYTES = 32;
+const IV_BYTES = 12;
+
+export interface EncryptedValue {
+ /** Base64 ciphertext. */
+ readonly ciphertext: string;
+ /** Base64 12-byte IV, unique per encryption. */
+ readonly iv: string;
+ /** Base64 GCM authentication tag. */
+ readonly tag: string;
+}
+
+/** Load the keyfile, creating it 0600 with 32 random bytes on first use. */
+export function loadOrCreateKey(keyPath: string): Buffer {
+ if (existsSync(keyPath)) {
+ const key = readFileSync(keyPath);
+ if (key.length !== KEY_BYTES) {
+ throw new Error(`secrets keyfile is corrupt (expected ${KEY_BYTES} bytes): ${keyPath}`);
+ }
+ return key;
+ }
+ mkdirSync(dirname(keyPath), { recursive: true, mode: 0o700 });
+ const key = randomBytes(KEY_BYTES);
+ // Exclusive create: two concurrent first-writers cannot truncate
+ // each other's key; the loser re-reads the winner's file.
+ let fd: number;
+ try {
+ fd = openSync(keyPath, "wx", 0o600);
+ } catch (exc) {
+ if ((exc as NodeJS.ErrnoException).code === "EEXIST") return loadOrCreateKey(keyPath);
+ throw exc;
+ }
+ try {
+ writeSync(fd, key);
+ } finally {
+ closeSync(fd);
+ }
+ return key;
+}
+
+export function encryptValue(key: Buffer, plaintext: string): EncryptedValue {
+ const iv = randomBytes(IV_BYTES);
+ const cipher = createCipheriv(ALGORITHM, key, iv);
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
+ return {
+ ciphertext: ciphertext.toString("base64"),
+ iv: iv.toString("base64"),
+ tag: cipher.getAuthTag().toString("base64"),
+ };
+}
+
+/** Decrypt one value; a wrong key or tampered payload throws. */
+export function decryptValue(key: Buffer, encrypted: EncryptedValue): string {
+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));
+ decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));
+ const plaintext = Buffer.concat([
+ decipher.update(Buffer.from(encrypted.ciphertext, "base64")),
+ decipher.final(),
+ ]);
+ return plaintext.toString("utf8");
+}
diff --git a/src/core/brain/secrets/exec.ts b/src/core/brain/secrets/exec.ts
new file mode 100644
index 00000000..56bc1d99
--- /dev/null
+++ b/src/core/brain/secrets/exec.ts
@@ -0,0 +1,139 @@
+/**
+ * Secret exec path (write-time-integrity-governance, t_0b134404):
+ * use a credential without it ever entering an agent's context. The
+ * command must match the secret's allowlist (glob patterns declared
+ * at set time by the operator - the capability gate), the value is
+ * injected into the subprocess env only, and captured stdout/stderr
+ * pass through the redactor with the resolved value as a known
+ * literal before reaching the caller. Denials are audited as
+ * `secret_exec_denied`.
+ */
+
+import { redactRawOutput } from "../../redactor.ts";
+import { appendAuditRecord } from "../../reliability/audit.ts";
+import { brainDirs } from "../paths.ts";
+import { join } from "node:path";
+import { resolveSecretForExec, type SecretAuditContext } from "./store.ts";
+
+export class SecretExecDeniedError extends Error {
+ readonly secret: string;
+ readonly command: string;
+ readonly allow: ReadonlyArray<string>;
+
+ constructor(secret: string, command: string, allow: ReadonlyArray<string>) {
+ super(
+ allow.length === 0
+ ? `secret "${secret}" has an empty allowlist - exec is denied entirely`
+ : `command does not match the allowlist of secret "${secret}": ${allow.join(", ")}`,
+ );
+ this.name = "SecretExecDeniedError";
+ this.secret = secret;
+ this.command = command;
+ this.allow = allow;
+ }
+}
+
+export interface RunWithSecretResult {
+ readonly exitCode: number;
+ /** Captured stdout, redacted (secret literal + standard patterns). */
+ readonly stdout: string;
+ /** Captured stderr, redacted the same way. */
+ readonly stderr: string;
+}
+
+/** Glob match: `*` is the only metacharacter, everything else literal. */
+export function matchesAllowlist(allow: ReadonlyArray<string>, command: string): boolean {
+ return allow.some((pattern) => {
+ const re = new RegExp(
+ "^" +
+ pattern
+ .split("*")
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
+ .join(".*") +
+ "$",
+ );
+ return re.test(command);
+ });
+}
+
+/**
+ * Baseline variables the subprocess receives. Deliberately minimal:
+ * inheriting the full parent env would hand an allowlisted command
+ * every credential the o2b process happens to carry (provider keys,
+ * CI tokens) and echo them back through captured output where the
+ * redactor only guarantees the requested secret literal. The child
+ * gets just enough to execute (binary resolution, temp dirs, locale)
+ * plus exactly one extra variable - the secret.
+ */
+const SAFE_BASE_ENV = [
+ "PATH",
+ "HOME",
+ "SHELL",
+ "USER",
+ "LANG",
+ "LC_ALL",
+ "TZ",
+ "TMPDIR",
+ "TEMP",
+ "TMP",
+] as const;
+
+/**
+ * Run `argv` with the secret injected as its declared env var.
+ * Allowlist-gated, audited both ways, output redacted. The subprocess
+ * env is built from a minimal safe baseline - never the full parent
+ * environment.
+ */
+export async function runWithSecret(
+ vault: string,
+ name: string,
+ argv: ReadonlyArray<string>,
+ ctx: SecretAuditContext,
+): Promise<RunWithSecretResult> {
+ if (argv.length === 0) throw new Error("secret run: a command is required after --");
+ const command = argv.join(" ");
+ const resolved = resolveSecretForExec(vault, name, ctx);
+ if (!matchesAllowlist(resolved.allow, command)) {
+ appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ timestamp: ctx.now.toISOString(),
+ actor: ctx.agent,
+ action: "secret_exec_denied",
+ target: resolved.name,
+ ok: false,
+ details: { command, allow: resolved.allow },
+ });
+ throw new SecretExecDeniedError(resolved.name, command, resolved.allow);
+ }
+
+ appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ timestamp: ctx.now.toISOString(),
+ actor: ctx.agent,
+ action: "secret_exec_started",
+ target: resolved.name,
+ ok: true,
+ details: { command, env_var: resolved.env_var },
+ });
+
+ const childEnv: Record<string, string> = {};
+ for (const key of SAFE_BASE_ENV) {
+ const value = process.env[key];
+ if (value !== undefined) childEnv[key] = value;
+ }
+ childEnv[resolved.env_var] = resolved.value;
+ const proc = Bun.spawn([...argv], {
+ env: childEnv,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ const literals = [resolved.value];
+ return {
+ exitCode,
+ stdout: redactRawOutput(stdout, { literals }),
+ stderr: redactRawOutput(stderr, { literals }),
+ };
+}
diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.ts
new file mode 100644
index 00000000..7f050f1a
--- /dev/null
+++ b/src/core/brain/secrets/store.ts
@@ -0,0 +1,290 @@
+/**
+ * Capability-gated secret custody store (write-time-integrity-
+ * governance, t_0b134404). Secrets live as per-value AES-256-GCM
+ * ciphertext in `<vault>/.open-second-brain/secrets/secrets.json`
+ * (0600) beside a 0600 keyfile - the vault-local state dir, never
+ * synced as vault content. The public surface never returns
+ * plaintext: `setSecret` ingests, `listSecrets` exposes metadata
+ * only, `resolveSecretForExec` exists for the exec path alone (env
+ * injection into an allowlisted subprocess - exec.ts), and every
+ * operation appends a no-values record to
+ * `Brain/log/secret-custody/` so custody is auditable from inside
+ * the vault.
+ */
+
+import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import lockfile from "proper-lockfile";
+
+import { appendAuditRecord } from "../../reliability/audit.ts";
+import { brainDirs } from "../paths.ts";
+import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";
+
+export const SECRETS_SCHEMA_VERSION = 1;
+
+const NAME_RE = /^[a-z0-9][a-z0-9_-]*$/;
+const ENV_VAR_RE = /^[A-Z_][A-Z0-9_]*$/;
+
+interface StoredSecret extends EncryptedValue {
+ readonly env_var: string;
+ /** Exec allowlist: glob patterns the joined command must match. */
+ readonly allow: ReadonlyArray<string>;
+ readonly created_at: string;
+ readonly last_used_at: string | null;
+}
+
+interface SecretsFile {
+ readonly version: number;
+ readonly secrets: Record<string, StoredSecret>;
+}
+
+/** Metadata view - everything except the ciphertext material. */
+export interface SecretMetadata {
+ readonly name: string;
+ readonly env_var: string;
+ readonly allow: ReadonlyArray<string>;
+ readonly created_at: string;
+ readonly last_used_at: string | null;
+}
+
+export interface SetSecretInput {
+ readonly name: string;
+ /** The secret material. Never logged, never returned. */
+ readonly value: string;
+ /** Env var the exec path injects; defaults to the name upcased. */
+ readonly envVar?: string;
+ /** Exec allowlist patterns; empty means exec is denied entirely. */
+ readonly allow?: ReadonlyArray<string>;
+ readonly agent: string;
+ readonly now: Date;
+}
+
+export interface SecretAuditContext {
+ readonly agent: string;
+ readonly now: Date;
+}
+
+export function secretsDir(vault: string): string {
+ return join(vault, ".open-second-brain", "secrets");
+}
+
+function storePath(vault: string): string {
+ return join(secretsDir(vault), "secrets.json");
+}
+
+function keyPath(vault: string): string {
+ return join(secretsDir(vault), "keyfile");
+}
+
+/**
+ * Serialise every read-modify-write of `secrets.json` across
+ * processes (CLI + MCP). proper-lockfile with retries, matching the
+ * search store's writer-lock discipline; the keyfile creation also
+ * creates the directory the lock anchors on.
+ */
+function withSecretsLock<T>(vault: string, fn: () => T): T {
+ loadOrCreateKey(keyPath(vault));
+ // The sync lockfile API has no retry option; spin briefly the same
+ // way the search store's writer lock does.
+ const maxAttempts = 20;
+ let release: (() => void) | null = null;
+ let lastError: unknown;
+ for (let attempt = 0; attempt < maxAttempts && release === null; attempt++) {
+ try {
+ release = lockfile.lockSync(secretsDir(vault), { stale: 10_000, realpath: false });
+ } catch (exc) {
+ if ((exc as NodeJS.ErrnoException).code !== "ELOCKED") throw exc;
+ lastError = exc;
+ if (attempt < maxAttempts - 1) Bun.sleepSync(25);
+ }
+ }
+ if (release === null) {
+ const msg = lastError instanceof Error ? lastError.message : String(lastError);
+ throw new Error(`another writer holds the secrets store lock: ${msg}`);
+ }
+ try {
+ return fn();
+ } finally {
+ void release();
+ }
+}
+
+export function setSecret(vault: string, input: SetSecretInput): SecretMetadata {
+ const name = input.name.trim().toLowerCase();
+ if (!NAME_RE.test(name)) {
+ throw new Error(
+ `secret name must be a lowercase slug ([a-z0-9_-], starting alphanumeric): ${JSON.stringify(input.name)}`,
+ );
+ }
+ if (input.value.trim().length === 0) {
+ throw new Error("secret value must not be empty");
+ }
+ const envVar = input.envVar ?? name.toUpperCase().replace(/-/g, "_");
+ if (!ENV_VAR_RE.test(envVar)) {
+ throw new Error(`secret env var must match ${ENV_VAR_RE}: ${JSON.stringify(envVar)}`);
+ }
+ const allow = (input.allow ?? []).map((pattern) => {
+ const trimmed = pattern.trim();
+ if (trimmed.length === 0) throw new Error("allow pattern must not be empty");
+ return trimmed;
+ });
+
+ const key = loadOrCreateKey(keyPath(vault));
+ const { next, existing } = withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ const current = file.secrets[name];
+ const updated: SecretsFile = {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: {
+ ...file.secrets,
+ [name]: {
+ ...encryptValue(key, input.value),
+ env_var: envVar,
+ allow,
+ created_at: current?.created_at ?? isoSecond(input.now),
+ last_used_at: current?.last_used_at ?? null,
+ },
+ },
+ };
+ writeStore(vault, updated);
+ return { next: updated, existing: current };
+ });
+ audit(vault, input, "secret_set", name, {
+ env_var: envVar,
+ allow,
+ replaced: existing !== undefined,
+ });
+ return toMetadata(name, next.secrets[name]!);
+}
+
+export function listSecrets(vault: string): SecretMetadata[] {
+ const file = readStore(vault);
+ return Object.entries(file.secrets)
+ .map(([name, stored]) => toMetadata(name, stored))
+ .toSorted((a, b) => a.name.localeCompare(b.name));
+}
+
+export function removeSecret(vault: string, name: string, ctx: SecretAuditContext): boolean {
+ const normalized = name.trim().toLowerCase();
+ const removed = withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ if (file.secrets[normalized] === undefined) return false;
+ const secrets = { ...file.secrets };
+ delete secrets[normalized];
+ writeStore(vault, { version: SECRETS_SCHEMA_VERSION, secrets });
+ return true;
+ });
+ if (removed) audit(vault, ctx, "secret_removed", normalized, {});
+ return removed;
+}
+
+export interface ResolvedSecret {
+ readonly name: string;
+ readonly env_var: string;
+ readonly allow: ReadonlyArray<string>;
+ /** The decrypted material - exec-path use only, never log it. */
+ readonly value: string;
+}
+
+/**
+ * Decrypt one secret for the exec path. THE ONLY reader of secret
+ * material; everything it returns must go straight into a subprocess
+ * env and nowhere else. Audited as `secret_resolved_for_exec`.
+ */
+export function resolveSecretForExec(
+ vault: string,
+ name: string,
+ ctx: SecretAuditContext = { agent: "cli", now: new Date() },
+): ResolvedSecret {
+ const file = readStore(vault);
+ const normalized = name.trim().toLowerCase();
+ const stored = file.secrets[normalized];
+ if (stored === undefined) {
+ const names = Object.keys(file.secrets).toSorted();
+ throw new Error(
+ `unknown secret "${normalized}" - stored: ${names.length === 0 ? "(none)" : names.join(", ")}`,
+ );
+ }
+ const key = loadOrCreateKey(keyPath(vault));
+ const value = decryptValue(key, stored);
+ touchLastUsed(vault, normalized, ctx.now);
+ audit(vault, ctx, "secret_resolved_for_exec", normalized, { env_var: stored.env_var });
+ return { name: normalized, env_var: stored.env_var, allow: stored.allow, value };
+}
+
+// ----- Internals -------------------------------------------------------------
+
+function toMetadata(name: string, stored: StoredSecret): SecretMetadata {
+ return {
+ name,
+ env_var: stored.env_var,
+ allow: stored.allow,
+ created_at: stored.created_at,
+ last_used_at: stored.last_used_at,
+ };
+}
+
+function readStore(vault: string): SecretsFile {
+ const path = storePath(vault);
+ if (!existsSync(path)) return { version: SECRETS_SCHEMA_VERSION, secrets: {} };
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (
+ parsed === null ||
+ typeof parsed !== "object" ||
+ (parsed as { version?: unknown }).version !== SECRETS_SCHEMA_VERSION
+ ) {
+ throw new Error(`secrets store is corrupt or from a newer version: ${path}`);
+ }
+ const secrets = (parsed as { secrets?: unknown }).secrets;
+ if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
+ throw new Error(`secrets store is corrupt: ${path}`);
+ }
+ return {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: { ...(secrets as Record<string, StoredSecret>) },
+ };
+}
+
+function writeStore(vault: string, file: SecretsFile): void {
+ // Key creation also creates the 0700 directory.
+ loadOrCreateKey(keyPath(vault));
+ const path = storePath(vault);
+ const tmp = `${path}.tmp`;
+ writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
+ renameSync(tmp, path);
+}
+
+function touchLastUsed(vault: string, name: string, now: Date): void {
+ // Re-read under the lock: the snapshot the resolver decrypted from
+ // may be stale by the time the usage stamp lands.
+ withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ const stored = file.secrets[name];
+ if (stored === undefined) return;
+ writeStore(vault, {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: { ...file.secrets, [name]: { ...stored, last_used_at: isoSecond(now) } },
+ });
+ });
+}
+
+function audit(
+ vault: string,
+ ctx: SecretAuditContext,
+ action: string,
+ name: string,
+ details: Record<string, unknown>,
+): void {
+ appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ timestamp: ctx.now.toISOString(),
+ actor: ctx.agent,
+ action,
+ target: name,
+ ok: true,
+ details,
+ });
+}
+
+function isoSecond(date: Date): string {
+ return date.toISOString().replace(/\.\d{3}Z$/, "Z");
+}
diff --git a/src/core/redactor.ts b/src/core/redactor.ts
index dfbc1d83..d9724655 100644
--- a/src/core/redactor.ts
+++ b/src/core/redactor.ts
@@ -145,13 +145,30 @@ export interface RedactRawOutputOptions {
* secrets.
*/
readonly maxInput?: number;
+ /**
+ * Known secret values to scrub verbatim (write-time-integrity-
+ * governance, secret custody): every literal occurrence is replaced
+ * before the pattern passes run, so a credential injected into a
+ * subprocess env can never travel back through captured output even
+ * when no key=value shape surrounds it.
+ */
+ readonly literals?: ReadonlyArray<string>;
}
export function redactRawOutput(text: string, opts: RedactRawOutputOptions = {}): string {
if (!text) return text;
+ // Scrub known literals BEFORE the truncation guard: a secret value
+ // straddling the cut boundary must not survive as a partial
+ // fragment in the kept prefix.
+ let out = text;
+ for (const literal of opts.literals ?? []) {
+ if (literal.length === 0) continue;
+ out = out.split(literal).join(PLACEHOLDER);
+ }
+
const maxInput = opts.maxInput ?? MAX_REDACTOR_INPUT;
- let out = text.length > maxInput ? text.slice(0, maxInput) + TRUNCATION_MARKER : text;
+ if (out.length > maxInput) out = out.slice(0, maxInput) + TRUNCATION_MARKER;
out = stripPrivateRegions(out);
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index cc65c22b..1405b67c 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -38,6 +38,9 @@ import {
} from "./embeddings/signature.ts";
import { extractLinks } from "./links.ts";
import { extractFrontmatterRelations } from "../graph/frontmatter-relations.ts";
+import { loadSchemaPack, type SchemaPack } from "../brain/schema-pack.ts";
+import { tieredFieldsForKind } from "../brain/frontmatter-tiers.ts";
+import { normalizeSchemaToken } from "../brain/schema-vocab.ts";
import { parseFrontmatterText } from "../vault.ts";
import { extractEntities } from "./entities.ts";
import { Store } from "./store.ts";
@@ -78,6 +81,8 @@ interface MutableStats {
embeddingsComputed: number;
embeddingsRetries: number;
errors: Array<{ readonly path: string; readonly message: string }>;
+ relationViolations: IndexStats["relationViolations"];
+ tierDrift: IndexStats["tierDrift"];
}
function newStats(): MutableStats {
@@ -90,6 +95,8 @@ function newStats(): MutableStats {
embeddingsComputed: 0,
embeddingsRetries: 0,
errors: [],
+ relationViolations: [],
+ tierDrift: [],
};
}
@@ -103,6 +110,8 @@ function freezeStats(s: MutableStats, durationMs: number): IndexStats {
embeddingsComputed: s.embeddingsComputed,
embeddingsRetries: s.embeddingsRetries,
errors: Object.freeze([...s.errors]),
+ relationViolations: Object.freeze([...s.relationViolations]),
+ tierDrift: Object.freeze([...s.tierDrift]),
durationMs,
});
}
@@ -111,6 +120,27 @@ function sha256(text: string): string {
return createHash("sha256").update(text).digest("hex");
}
+/** Deep-ish equality for frontmatter scalar/array values. */
+function tierValueEquals(left: unknown, right: unknown): boolean {
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return left.length === right.length && left.every((v, i) => tierValueEquals(v, right[i]));
+ }
+ return left === right;
+}
+
+/**
+ * The page's declared frontmatter `type` as a normalized token, or
+ * null when undeclared or not a usable scalar. Tolerant by design:
+ * a malformed `type` value never fails indexing, it just leaves the
+ * page untyped for constraint purposes.
+ */
+function pageTypeFromFrontmatter(frontmatter: Record<string, unknown>): string | null {
+ const raw = frontmatter["type"];
+ if (typeof raw !== "string") return null;
+ const normalized = normalizeSchemaToken(raw);
+ return normalized.length > 0 ? normalized : null;
+}
+
const UTF8_FATAL = new TextDecoder("utf-8", { fatal: true });
function readUtf8(absPath: string): string {
@@ -147,6 +177,13 @@ async function indexInto(
try {
const existing = store.listDocuments();
const seen = new Set<string>();
+ // Changed docs declaring a frontmatter `kind`, for the tier-guard
+ // post-pass (write-time-integrity-governance).
+ const tieredDocs: Array<{
+ docId: number;
+ relPath: string;
+ frontmatter: Record<string, unknown>;
+ }> = [];
for (const file of walkVault(config)) {
// Mark seen FIRST. If anything downstream throws (read fault,
@@ -194,13 +231,24 @@ async function indexInto(
stats.errors.push({ path: file.relPath, message: w });
}
+ // The document's declared frontmatter `type` is persisted so
+ // the link-constraint post-pass can join endpoint types
+ // without re-reading files (v6).
+ const [frontmatter] = parseFrontmatterText(content);
const docId = store.upsertDocument({
path: file.relPath,
title: chunkResult.title,
contentHash,
mtime: mtimeSec,
size: file.stat.size,
+ pageType: pageTypeFromFrontmatter(frontmatter),
});
+ // Framework-kind files feed the tier-guard post-pass: keep the
+ // parsed frontmatter of this run's changed docs that declare a
+ // `kind` (bounded - only Brain artifacts carry one).
+ if (typeof frontmatter["kind"] === "string" && frontmatter["kind"].length > 0) {
+ tieredDocs.push({ docId, relPath: file.relPath, frontmatter });
+ }
const chunkInputs: ChunkInput[] = chunkResult.chunks.map((c) => ({
chunkIndex: c.chunkIndex,
@@ -235,7 +283,6 @@ async function indexInto(
// (related / extends / contradicts / superseded_by) become typed
// edges. They belong to the document, not a chunk, so anchor them
// on the first chunk (or null when the doc produced no chunks).
- const [frontmatter] = parseFrontmatterText(content);
const relationChunkId = chunkIds[0] ?? null;
for (const edge of extractFrontmatterRelations(frontmatter)) {
links.push({
@@ -273,6 +320,69 @@ async function indexInto(
store.resolveLinkTargets();
+ // Link-constraint materialization post-pass
+ // (write-time-integrity-governance): recompute every typed edge's
+ // blocked flag from the current schema pack. Runs every pass - with
+ // no constraints declared it only resets stale flags, so removing a
+ // constraint restores edges without touching files. Fail-soft: an
+ // unparseable pack indexes as if no constraints were declared.
+ let pack: SchemaPack | null = null;
+ try {
+ pack = loadSchemaPack(config.vault);
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ stats.errors.push({ path: "Brain/_brain.yaml", message: `schema pack unreadable: ${msg}` });
+ }
+ stats.relationViolations = Object.freeze(
+ store.recomputeRelationConstraintFlags(pack?.link_constraints ?? {}),
+ );
+
+ // Tier-guard post-pass: for each changed framework-kind doc,
+ // compare the new identity-field values against the stored
+ // snapshot. A changed identity value stages a tier_drift finding
+ // (ask_user via `o2b brain tiers check|restore|accept`) and the
+ // snapshot keeps the expected value so repeated reindexes never
+ // absorb the hand-edit; system/business fields update silently -
+ // framework writers mutate them legitimately on every pass.
+ if (pack !== null) {
+ const detectedAt = new Date().toISOString();
+ for (const doc of tieredDocs) {
+ const kind = doc.frontmatter["kind"];
+ if (typeof kind !== "string") continue;
+ const fields = tieredFieldsForKind(pack, kind);
+ if (Object.keys(fields).length === 0) continue;
+ const prev = store.getTierSnapshot(doc.docId);
+ const next: Record<string, unknown> = {};
+ for (const [field, tier] of Object.entries(fields)) {
+ const current = doc.frontmatter[field];
+ if (prev === null || !(field in prev)) {
+ if (current !== undefined) next[field] = current;
+ continue;
+ }
+ const expected = prev[field];
+ // Deleting an identity field is as much a hand-edit as
+ // changing it: `current === undefined` stages drift with a
+ // null actual instead of silently dropping the snapshot.
+ if (tier === "identity" && !tierValueEquals(expected, current)) {
+ const actual = current === undefined ? null : current;
+ store.upsertTierDrift({
+ documentId: doc.docId,
+ field,
+ expected,
+ actual,
+ detectedAt,
+ });
+ stats.tierDrift = [...stats.tierDrift, { path: doc.relPath, field, expected, actual }];
+ next[field] = expected; // the snapshot keeps the truth
+ continue;
+ }
+ store.clearTierDrift(doc.docId, field);
+ if (current !== undefined) next[field] = current;
+ }
+ store.setTierSnapshot(doc.docId, next);
+ }
+ }
+
if (opts?.embeddings) {
await populateEmbeddings(store, config, stats, opts?.forceCost === true);
}
diff --git a/src/core/search/link-constraints.ts b/src/core/search/link-constraints.ts
new file mode 100644
index 00000000..3591e71f
--- /dev/null
+++ b/src/core/search/link-constraints.ts
@@ -0,0 +1,109 @@
+/**
+ * Link-type endpoint constraints (write-time-integrity-governance).
+ *
+ * The schema pack's `link_constraints` field declares, per link type,
+ * which `source_type->target_type` page-type pairs may carry that
+ * typed relation. Enforcement happens at materialization: the
+ * indexer's post-pass marks violating edges blocked so they fall back
+ * to plain untyped links instead of participating in typed-relation
+ * recall (polarity, traversal). Constraints constrain materialization,
+ * not authoring - the frontmatter stays untouched, the flags are
+ * recomputed from the current pack on every index run, and a relation
+ * with no declared constraints (or an endpoint whose page type is
+ * unknown) is always allowed, so an unconfigured vault is unaffected.
+ */
+
+import { Database } from "bun:sqlite";
+import { existsSync } from "node:fs";
+
+export type LinkConstraintMap = Readonly<Record<string, ReadonlyArray<string>>>;
+
+/** One typed edge whose endpoints violate the declared constraints. */
+export interface LinkConstraintViolation {
+ readonly relation: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ readonly sourceType: string;
+ readonly targetType: string;
+ /** The pairs the schema pack declares for this relation. */
+ readonly declared: ReadonlyArray<string>;
+}
+
+/**
+ * Decide whether one typed edge may materialize. Fail-open on missing
+ * information: a relation without declared constraints, or an endpoint
+ * whose page type is unknown (no `type:` frontmatter, or the document
+ * predates the `page_type` column), cannot be evaluated and passes.
+ */
+export function linkConstraintAllows(
+ constraints: LinkConstraintMap,
+ relation: string,
+ sourceType: string | null,
+ targetType: string | null,
+): boolean {
+ const declared = constraints[relation];
+ if (declared === undefined || declared.length === 0) return true;
+ if (sourceType === null || targetType === null) return true;
+ return declared.includes(`${sourceType}->${targetType}`);
+}
+
+/** One blocked edge as the lint surface reads it back from the index. */
+export interface BlockedRelationRow {
+ readonly relation: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ readonly sourceType: string | null;
+ readonly targetType: string | null;
+}
+
+/**
+ * Read the edges the last index pass blocked, straight from the index
+ * database. Lint-surface companion to the indexer post-pass: read-only,
+ * fail-soft - a missing index file, a pre-v6 schema, or any read error
+ * yields an empty list rather than failing the lint.
+ */
+export function readBlockedRelationRows(dbPath: string): ReadonlyArray<BlockedRelationRow> {
+ if (!existsSync(dbPath)) return [];
+ let db: Database | null = null;
+ try {
+ db = new Database(dbPath, { readonly: true });
+ return db
+ .query<
+ {
+ relation: string;
+ source_path: string;
+ target_path: string | null;
+ source_type: string | null;
+ target_type: string | null;
+ },
+ []
+ >(
+ "SELECT l.relation, sd.path AS source_path, l.target_path, " +
+ " sd.page_type AS source_type, td.page_type AS target_type " +
+ "FROM links l " +
+ "JOIN documents sd ON sd.id = l.source_document_id " +
+ "LEFT JOIN documents td ON td.id = COALESCE(" +
+ " l.target_document_id, " +
+ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
+ " (SELECT d.id FROM documents d " +
+ " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +
+ " AND 1 = (SELECT COUNT(*) FROM documents d2 " +
+ " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +
+ " ) " +
+ "WHERE l.relation IS NOT NULL AND l.relation_blocked = 1 " +
+ "ORDER BY sd.path, l.id",
+ )
+ .all()
+ .map((r) => ({
+ relation: r.relation,
+ sourcePath: r.source_path,
+ targetPath: r.target_path ?? "",
+ sourceType: r.source_type,
+ targetType: r.target_type,
+ }));
+ } catch {
+ return [];
+ } finally {
+ db?.close();
+ }
+}
diff --git a/src/core/search/schema.ts b/src/core/search/schema.ts
index 145c17db..8de8eea1 100644
--- a/src/core/search/schema.ts
+++ b/src/core/search/schema.ts
@@ -16,7 +16,7 @@ import { SearchError } from "./types.ts";
* this raises `SCHEMA_MISMATCH` on open — the operator must reindex
* with a newer binary.
*/
-export const LATEST_SCHEMA_VERSION = 5;
+export const LATEST_SCHEMA_VERSION = 6;
const DDL_V1 = `
CREATE TABLE IF NOT EXISTS documents (
@@ -265,6 +265,45 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([
`);
},
},
+ {
+ // v6 (write-time-integrity-governance) - link-constraint enforcement
+ // needs both endpoint page types at materialization time, so the
+ // document's declared frontmatter `type` is persisted alongside it,
+ // and a typed edge gains a `relation_blocked` flag the indexer's
+ // post-pass recomputes from the current schema pack on every run.
+ // The tier guard additionally snapshots a framework file's tiered
+ // frontmatter fields (`tier_snapshot`) and stages identity-field
+ // hand-edits in `tier_drift` for `o2b brain tiers check|restore`.
+ // All additive and reindex-safe: existing rows default to NULL
+ // page type (constraints cannot evaluate - allowed), unblocked
+ // edges, and no snapshot (first reindex seeds it).
+ version: 6,
+ up(db) {
+ const docCols = db.query<{ name: string }, []>("PRAGMA table_info(documents)").all();
+ if (!docCols.some((c) => c.name === "page_type")) {
+ db.exec("ALTER TABLE documents ADD COLUMN page_type TEXT");
+ }
+ if (!docCols.some((c) => c.name === "tier_snapshot")) {
+ db.exec("ALTER TABLE documents ADD COLUMN tier_snapshot TEXT");
+ }
+ const linkCols = db.query<{ name: string }, []>("PRAGMA table_info(links)").all();
+ if (!linkCols.some((c) => c.name === "relation_blocked")) {
+ db.exec("ALTER TABLE links ADD COLUMN relation_blocked INTEGER NOT NULL DEFAULT 0");
+ }
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS tier_drift (
+ id INTEGER PRIMARY KEY,
+ document_id INTEGER NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
+ field TEXT NOT NULL,
+ expected TEXT NOT NULL,
+ actual TEXT NOT NULL,
+ detected_at TEXT NOT NULL,
+ UNIQUE(document_id, field)
+ );
+ CREATE INDEX IF NOT EXISTS idx_tier_drift_document ON tier_drift(document_id);
+ `);
+ },
+ },
]);
/** Read the current schema version from `index_state`. Returns 0 if not yet recorded. */
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index 2a96b6aa..5b13b8fb 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -46,6 +46,12 @@ export interface DocumentInput {
readonly contentHash: string;
readonly mtime: number; // unix seconds
readonly size: number;
+ /**
+ * The page's declared frontmatter `type` (normalized token), or null
+ * when undeclared. Persisted so link-constraint enforcement can join
+ * endpoint types without re-reading files (v6).
+ */
+ readonly pageType?: string | null;
}
export interface DocumentSummary {
@@ -185,6 +191,15 @@ function tryLoadVecExtension(db: Database): boolean {
}
}
+/** Parse a JSON-encoded drift value; a corrupt cell surfaces as-is. */
+function parseJsonValue(raw: string): unknown {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+}
+
function nowIso(): string {
return new Date().toISOString();
}
@@ -507,20 +522,31 @@ export class Store {
const row = this.db
.query<
{ id: number },
- [string, string | null, string, number, number, string, string, string]
+ [string, string | null, string, number, number, string | null, string, string, string]
>(
- "INSERT INTO documents(path, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " +
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
+ "INSERT INTO documents(path, title, content_hash, mtime, size, page_type, created_at, updated_at, indexed_at) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT(path) DO UPDATE SET " +
" title = excluded.title, " +
" content_hash = excluded.content_hash, " +
" mtime = excluded.mtime, " +
" size = excluded.size, " +
+ " page_type = excluded.page_type, " +
" updated_at = excluded.updated_at, " +
" indexed_at = excluded.indexed_at " +
"RETURNING id",
)
- .get(doc.path, doc.title, doc.contentHash, doc.mtime, doc.size, now, now, now);
+ .get(
+ doc.path,
+ doc.title,
+ doc.contentHash,
+ doc.mtime,
+ doc.size,
+ doc.pageType ?? null,
+ now,
+ now,
+ now,
+ );
if (!row) {
throw new SearchError("INDEX_UNREADABLE", `upsertDocument returned no id for '${doc.path}'`);
}
@@ -912,6 +938,7 @@ export class Store {
>(
"SELECT source_document_id, relation, target_path FROM links " +
`WHERE source_document_id IN (${placeholders}) AND relation IS NOT NULL ` +
+ "AND relation_blocked = 0 " +
"ORDER BY id",
)
.all(...(documentIds as number[]));
@@ -958,12 +985,14 @@ export class Store {
" COALESCE(" +
" l.target_document_id, " +
" (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
- " (SELECT d.id FROM documents d WHERE d.path LIKE '%/' || l.target_path || '.md' " +
+ " (SELECT d.id FROM documents d " +
+ " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +
" AND 1 = (SELECT COUNT(*) FROM documents d2 " +
- " WHERE d2.path LIKE '%/' || l.target_path || '.md'))" +
+ " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +
" ) AS resolved_target_id " +
"FROM links l " +
`WHERE l.source_document_id IN (${placeholders}) AND l.relation IS NOT NULL ` +
+ "AND l.relation_blocked = 0 " +
"ORDER BY l.id",
)
.all(...(documentIds as number[]));
@@ -986,6 +1015,235 @@ export class Store {
return out;
}
+ /**
+ * Recompute every typed edge's `relation_blocked` flag from the
+ * current schema-pack constraints (write-time-integrity-governance).
+ * Runs after `resolveLinkTargets` on every index pass, so removing a
+ * constraint restores blocked edges on the next run without touching
+ * files. Endpoint resolution mirrors `typedRelationEdgesForDocuments`
+ * (exact id, `<target>.md`, unambiguous basename). Returns the rows
+ * that ended up blocked. With an empty constraint map the pass only
+ * resets stale flags.
+ */
+ recomputeRelationConstraintFlags(
+ constraints: Readonly<Record<string, ReadonlyArray<string>>>,
+ ): Array<{
+ readonly relation: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ readonly sourceType: string;
+ readonly targetType: string;
+ readonly declared: ReadonlyArray<string>;
+ }> {
+ const rows = this.db
+ .query<
+ {
+ id: number;
+ relation: string;
+ blocked: number;
+ source_path: string;
+ source_type: string | null;
+ target_path: string | null;
+ target_type: string | null;
+ },
+ []
+ >(
+ "SELECT l.id, l.relation, l.relation_blocked AS blocked, " +
+ " sd.path AS source_path, sd.page_type AS source_type, " +
+ " l.target_path, td.page_type AS target_type " +
+ "FROM links l " +
+ "JOIN documents sd ON sd.id = l.source_document_id " +
+ "LEFT JOIN documents td ON td.id = COALESCE(" +
+ " l.target_document_id, " +
+ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
+ " (SELECT d.id FROM documents d " +
+ " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +
+ " AND 1 = (SELECT COUNT(*) FROM documents d2 " +
+ " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +
+ " ) " +
+ "WHERE l.relation IS NOT NULL",
+ )
+ .all();
+ const block = this.db.query("UPDATE links SET relation_blocked = 1 WHERE id = ?");
+ const unblock = this.db.query("UPDATE links SET relation_blocked = 0 WHERE id = ?");
+ const violations: Array<{
+ relation: string;
+ sourcePath: string;
+ targetPath: string;
+ sourceType: string;
+ targetType: string;
+ declared: ReadonlyArray<string>;
+ }> = [];
+ for (const row of rows) {
+ const declared = constraints[row.relation];
+ const allowed =
+ declared === undefined ||
+ declared.length === 0 ||
+ row.source_type === null ||
+ row.target_type === null ||
+ declared.includes(`${row.source_type}->${row.target_type}`);
+ if (allowed) {
+ if (row.blocked !== 0) unblock.run(row.id);
+ continue;
+ }
+ if (row.blocked === 0) block.run(row.id);
+ violations.push({
+ relation: row.relation,
+ sourcePath: row.source_path,
+ targetPath: row.target_path ?? "",
+ sourceType: row.source_type!,
+ targetType: row.target_type!,
+ declared: declared!,
+ });
+ }
+ return violations;
+ }
+
+ /**
+ * The typed edges currently blocked by link constraints, for lint
+ * surfacing. Read-only over the flags the last index pass computed.
+ */
+ blockedRelationRows(): Array<{
+ readonly relation: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ readonly sourceType: string | null;
+ readonly targetType: string | null;
+ }> {
+ return this.db
+ .query<
+ {
+ relation: string;
+ source_path: string;
+ target_path: string | null;
+ source_type: string | null;
+ target_type: string | null;
+ },
+ []
+ >(
+ "SELECT l.relation, sd.path AS source_path, l.target_path, " +
+ " sd.page_type AS source_type, td.page_type AS target_type " +
+ "FROM links l " +
+ "JOIN documents sd ON sd.id = l.source_document_id " +
+ "LEFT JOIN documents td ON td.id = COALESCE(" +
+ " l.target_document_id, " +
+ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
+ " (SELECT d.id FROM documents d " +
+ " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +
+ " AND 1 = (SELECT COUNT(*) FROM documents d2 " +
+ " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +
+ " ) " +
+ "WHERE l.relation IS NOT NULL AND l.relation_blocked = 1 " +
+ "ORDER BY sd.path, l.id",
+ )
+ .all()
+ .map((r) => ({
+ relation: r.relation,
+ sourcePath: r.source_path,
+ targetPath: r.target_path ?? "",
+ sourceType: r.source_type,
+ targetType: r.target_type,
+ }));
+ }
+
+ /**
+ * The tiered-frontmatter snapshot the last index pass recorded for a
+ * document, or null when none exists (write-time-integrity-governance).
+ */
+ getTierSnapshot(documentId: number): Record<string, unknown> | null {
+ const row = this.db
+ .query<{ tier_snapshot: string | null }, [number]>(
+ "SELECT tier_snapshot FROM documents WHERE id = ?",
+ )
+ .get(documentId);
+ if (!row || row.tier_snapshot === null) return null;
+ try {
+ const parsed: unknown = JSON.parse(row.tier_snapshot);
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return parsed as Record<string, unknown>;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+ }
+
+ setTierSnapshot(documentId: number, snapshot: Readonly<Record<string, unknown>>): void {
+ this.db.run("UPDATE documents SET tier_snapshot = ? WHERE id = ?", [
+ JSON.stringify(snapshot),
+ documentId,
+ ]);
+ }
+
+ /** Stage one identity-field hand-edit; (document, field) upserts. */
+ upsertTierDrift(input: {
+ readonly documentId: number;
+ readonly field: string;
+ readonly expected: unknown;
+ readonly actual: unknown;
+ readonly detectedAt: string;
+ }): void {
+ this.db.run(
+ "INSERT INTO tier_drift(document_id, field, expected, actual, detected_at) " +
+ "VALUES (?, ?, ?, ?, ?) " +
+ "ON CONFLICT(document_id, field) DO UPDATE SET actual = excluded.actual",
+ [
+ input.documentId,
+ input.field,
+ JSON.stringify(input.expected),
+ JSON.stringify(input.actual),
+ input.detectedAt,
+ ],
+ );
+ }
+
+ clearTierDrift(documentId: number, field?: string): void {
+ if (field === undefined) {
+ this.db.run("DELETE FROM tier_drift WHERE document_id = ?", [documentId]);
+ } else {
+ this.db.run("DELETE FROM tier_drift WHERE document_id = ? AND field = ?", [
+ documentId,
+ field,
+ ]);
+ }
+ }
+
+ /** Open identity-drift findings, oldest first, with document paths. */
+ listTierDrift(): Array<{
+ readonly documentId: number;
+ readonly path: string;
+ readonly field: string;
+ readonly expected: unknown;
+ readonly actual: unknown;
+ readonly detectedAt: string;
+ }> {
+ return this.db
+ .query<
+ {
+ document_id: number;
+ path: string;
+ field: string;
+ expected: string;
+ actual: string;
+ detected_at: string;
+ },
+ []
+ >(
+ "SELECT t.document_id, d.path, t.field, t.expected, t.actual, t.detected_at " +
+ "FROM tier_drift t JOIN documents d ON d.id = t.document_id " +
+ "ORDER BY t.detected_at, t.id",
+ )
+ .all()
+ .map((r) => ({
+ documentId: r.document_id,
+ path: r.path,
+ field: r.field,
+ expected: parseJsonValue(r.expected),
+ actual: parseJsonValue(r.actual),
+ detectedAt: r.detected_at,
+ }));
+ }
+
/**
* Corpus document frequency per term (recall-trust-suite, coverage
* engine): how many distinct documents match each term in FTS. Each
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 7786d032..d4ea7c60 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -123,6 +123,32 @@ export interface IndexStats {
readonly path: string;
readonly message: string;
}>;
+ /**
+ * Typed edges blocked by the schema pack's `link_constraints` during
+ * this run's materialization post-pass
+ * (write-time-integrity-governance). Empty when no constraints are
+ * declared.
+ */
+ readonly relationViolations: ReadonlyArray<{
+ readonly relation: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ readonly sourceType: string;
+ readonly targetType: string;
+ readonly declared: ReadonlyArray<string>;
+ }>;
+ /**
+ * Identity-tier frontmatter fields whose value changed against the
+ * stored snapshot during this run - staged hand-edits awaiting
+ * `o2b brain tiers check|restore|accept`
+ * (write-time-integrity-governance).
+ */
+ readonly tierDrift: ReadonlyArray<{
+ readonly path: string;
+ readonly field: string;
+ readonly expected: unknown;
+ readonly actual: unknown;
+ }>;
readonly durationMs: number;
}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index b9ae1a2f..176088ff 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -46,7 +46,23 @@ import {
resolveSearchFocusContextPack,
resolveTriggerCooldownDays,
} from "../core/config.ts";
-import { resolveSearchConfig } from "../core/search/index.ts";
+import { indexVault, resolveSearchConfig } from "../core/search/index.ts";
+import { Store } from "../core/search/store.ts";
+import {
+ assignNoteLabel,
+ LabelVocabularyError,
+ readLabels,
+ removeNoteLabel,
+} from "../core/brain/labels.ts";
+import { loadSchemaPack } from "../core/brain/schema-pack.ts";
+import { listSecrets } from "../core/brain/secrets/store.ts";
+import { runWithSecret, SecretExecDeniedError } from "../core/brain/secrets/exec.ts";
+import { currentLease } from "../core/brain/maintenance/lease.ts";
+import { listJournal } from "../core/brain/maintenance/journal.ts";
+import { runMaintenance, type DailyWindow } from "../core/brain/maintenance/lane.ts";
+import { writeFrontmatterAtomic } from "../core/vault.ts";
+import { resolveNotePath } from "../core/brain/note-path.ts";
+import type { FrontmatterMap } from "../core/types.ts";
import { readActiveSessionFocus } from "../core/search/session-focus.ts";
import { brainActivePath, brainDirs } from "../core/brain/paths.ts";
import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";
@@ -1374,7 +1390,11 @@ async function toolBrainDoctor(
const strict = coerceBool(args, "strict");
const format = coerceFormat(args);
- const result = runDoctor(ctx.vault, { strict });
+ const result = runDoctor(ctx.vault, {
+ strict,
+ dbPath: resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined })
+ .dbPath,
+ });
// Decide a single ok flag — `strict` only changes the CLI exit code,
// so we mirror that semantic here: with `strict`, warnings demote ok
@@ -1790,6 +1810,271 @@ function toolBrainForesight(
return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };
}
+// ----- brain_labels (t_7a41f42d) ---------------------------------------------
+
+/** Controlled-vocabulary classification over the schema pack's labels. */
+function toolBrainLabels(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const op = args["operation"];
+ if (op !== "assign" && op !== "remove" && op !== "show") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels: operation must be assign|remove|show");
+ }
+ const path = args["path"];
+ if (typeof path !== "string" || path.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels: path must be a vault-relative string");
+ }
+ if (op === "show") {
+ const [metadata] = parseFrontmatter(vaultContainedPath(ctx.vault, path, "brain_labels show"));
+ return { path, labels: readLabels(metadata) };
+ }
+ const pack = loadSchemaPack(ctx.vault);
+ const dimension = args["dimension"];
+ if (typeof dimension !== "string" || dimension.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);
+ }
+ try {
+ if (op === "remove") {
+ return { ...removeNoteLabel(ctx.vault, path, { dimension, pack }) };
+ }
+ const value = args["value"];
+ if (typeof value !== "string" || value.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_labels assign: value must be non-empty");
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ return {
+ ...assignNoteLabel(ctx.vault, path, { dimension, value, pack, agent, now: new Date() }),
+ };
+ } catch (exc) {
+ if (exc instanceof LabelVocabularyError) {
+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
+// ----- brain_tiers (t_3f92d3f1) ----------------------------------------------
+
+/** Staged repair surface for identity-tier frontmatter hand-edits. */
+async function toolBrainTiers(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "check" && op !== "restore" && op !== "accept") {
+ throw new MCPError(INVALID_PARAMS, "brain_tiers: operation must be check|restore|accept");
+ }
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ if (op === "check") {
+ // Fail-soft: a vault that was never indexed has no snapshots and
+ // therefore no drift - not an error.
+ if (!existsSync(searchConfig.dbPath)) return { findings: [] };
+ const store = await Store.open(searchConfig, { mode: "read" });
+ try {
+ return { findings: store.listTierDrift() };
+ } finally {
+ await store.close();
+ }
+ }
+ const path = args["path"];
+ if (typeof path !== "string" || path.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: path must be a vault-relative string`);
+ }
+ if (op === "restore" && args["apply"] !== true) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_tiers restore: pass apply=true - restore writes the file",
+ );
+ }
+ const field = typeof args["field"] === "string" ? (args["field"] as string) : undefined;
+ if (!existsSync(searchConfig.dbPath)) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: the vault has no search index yet`);
+ }
+ const store = await Store.open(searchConfig, { mode: "write" });
+ try {
+ const docId = store.getDocumentIdByPath(path);
+ if (docId === null) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: not indexed: ${path}`);
+ }
+ const rows = store
+ .listTierDrift()
+ .filter((r) => r.documentId === docId && (field === undefined || r.field === field));
+ if (rows.length === 0) {
+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: no open drift for ${path}`);
+ }
+ if (op === "restore") {
+ const absolute = vaultContainedPath(ctx.vault, path, "brain_tiers restore");
+ const [metadata, body] = parseFrontmatter(absolute);
+ const next = { ...metadata };
+ for (const r of rows) {
+ next[r.field] = frontmatterValueFromSnapshot(r.expected, r.field);
+ }
+ writeFrontmatterAtomic(absolute, next, body, { overwrite: true });
+ for (const r of rows) store.clearTierDrift(docId, r.field);
+ return { restored: rows.map((r) => r.field), path };
+ }
+ const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };
+ for (const r of rows) {
+ snapshot[r.field] = r.actual;
+ store.clearTierDrift(docId, r.field);
+ }
+ store.setTierSnapshot(docId, snapshot);
+ return { accepted: rows.map((r) => r.field), path };
+ } finally {
+ await store.close();
+ }
+}
+
+/** Resolve a vault-relative path, refusing traversal and symlink escapes. */
+function vaultContainedPath(vault: string, relPath: string, label: string): string {
+ try {
+ return resolveNotePath(vault, relPath);
+ } catch (exc) {
+ throw new MCPError(INVALID_PARAMS, `${label}: ${(exc as Error).message}`);
+ }
+}
+
+/** Narrow a snapshot value to the shapes frontmatter can carry. */
+function frontmatterValueFromSnapshot(value: unknown, field: string): FrontmatterMap[string] {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ return value;
+ }
+ if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {
+ return value;
+ }
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_tiers restore: snapshot value for "${field}" is not a frontmatter scalar or string array`,
+ );
+}
+
+// ----- brain_secrets (t_0b134404) ---------------------------------------------
+
+/**
+ * Capability-gated custody, agent-facing subset: list metadata and
+ * run an allowlisted command. Deliberately NO set/get over MCP - the
+ * material enters via the operator's CLI and leaves only into a
+ * subprocess env.
+ */
+async function toolBrainSecrets(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "list" && op !== "run") {
+ throw new MCPError(INVALID_PARAMS, "brain_secrets: operation must be list|run");
+ }
+ if (op === "list") {
+ return { secrets: listSecrets(ctx.vault) };
+ }
+ const name = args["name"];
+ if (typeof name !== "string" || name.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "brain_secrets run: name must be non-empty");
+ }
+ const command = args["command"];
+ if (
+ !Array.isArray(command) ||
+ command.length === 0 ||
+ !command.every((part): part is string => typeof part === "string")
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_secrets run: command must be a non-empty array of strings",
+ );
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ try {
+ const result = await runWithSecret(ctx.vault, name, command, { agent, now: new Date() });
+ return { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr };
+ } catch (exc) {
+ if (exc instanceof SecretExecDeniedError) {
+ throw new MCPError(INVALID_PARAMS, `brain_secrets run: ${exc.message}`);
+ }
+ throw exc;
+ }
+}
+
+// ----- brain_maintenance (t_166d1226) ------------------------------------------
+
+/** Quiet-window, lease-guarded heavy maintenance lane. */
+async function toolBrainMaintenance(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const op = args["operation"];
+ if (op !== "run" && op !== "status") {
+ throw new MCPError(INVALID_PARAMS, "brain_maintenance: operation must be run|status");
+ }
+ const now = new Date();
+ if (op === "status") {
+ return {
+ lease: currentLease(ctx.vault, { now }),
+ journal: listJournal(ctx.vault, 10),
+ };
+ }
+ let window: DailyWindow | undefined;
+ const startHour = args["window_start_hour"];
+ const endHour = args["window_end_hour"];
+ if (startHour !== undefined || endHour !== undefined) {
+ if (
+ typeof startHour !== "number" ||
+ typeof endHour !== "number" ||
+ !Number.isInteger(startHour) ||
+ !Number.isInteger(endHour) ||
+ startHour < 0 ||
+ startHour > 23 ||
+ endHour < 0 ||
+ endHour > 23
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_maintenance run: window_start_hour/window_end_hour must be integers 0..23",
+ );
+ }
+ const tz = typeof args["tz"] === "string" ? (args["tz"] as string) : "UTC";
+ window = { startHour, endHour, tz };
+ }
+ const agentArg = args["agent"];
+ const agent =
+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const searchConfig = resolveSearchConfig({
+ vault: ctx.vault,
+ configPath: ctx.configPath ?? undefined,
+ });
+ const result = await runMaintenance(ctx.vault, {
+ now,
+ holder: `${agent}@${process.pid}`,
+ force: args["force"] === true,
+ ...(window !== undefined ? { window } : {}),
+ tasks: [
+ {
+ name: "dream",
+ run: async () => {
+ dream(ctx.vault, { now });
+ },
+ },
+ {
+ name: "reindex",
+ run: async () => {
+ await indexVault(searchConfig);
+ },
+ },
+ ],
+ });
+ return { verdict: result.verdict, tasks: result.tasks };
+}
+
// ----- brain_dead_ends (t_be62c62d) -----------------------------------------
/**
@@ -4373,6 +4658,103 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
handler: toolBrainForesight,
previewBudget: MCP_PREVIEW_BUDGET,
},
+ {
+ name: "brain_labels",
+ description:
+ "Controlled-vocabulary classification against the schema pack's labels field: assign (fail-closed - unknown dimensions/values rejected with the declared vocabulary), remove, or show a note's labels. Single-choice per dimension; persists as a labels frontmatter array plus a canonical label entity.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["assign", "remove", "show"],
+ description: "Tool operation.",
+ },
+ path: { type: "string", description: "Vault-relative note path." },
+ dimension: { type: "string", description: "Label dimension (assign/remove)." },
+ value: { type: "string", description: "Label value (assign)." },
+ agent: { type: "string", description: "Agent identity override (assign)." },
+ },
+ required: ["operation", "path"],
+ additionalProperties: false,
+ },
+ handler: toolBrainLabels,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_tiers",
+ description:
+ "Frontmatter tier guard: check lists staged identity-field hand-edits the index post-pass detected, restore (apply=true required) writes the expected value back into the file, accept adopts the hand-edit as the new snapshot baseline. Nothing auto-resolves.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["check", "restore", "accept"],
+ description: "Tool operation.",
+ },
+ path: { type: "string", description: "Vault-relative path (restore/accept)." },
+ field: { type: "string", description: "Restrict to one field (restore/accept)." },
+ apply: { type: "boolean", description: "Required true for restore - it writes the file." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainTiers,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_secrets",
+ description:
+ "Capability-gated secret custody, agent-facing subset: list stored secret metadata (never values) or run an allowlisted command with the secret injected as its declared env var - output comes back redacted. Storing and removing secrets stays on the operator's CLI (o2b brain secret).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["list", "run"], description: "Tool operation." },
+ name: { type: "string", description: "Secret name (run)." },
+ command: {
+ type: "array",
+ items: { type: "string" },
+ description: "Command argv to execute (run); must match the secret's allowlist.",
+ },
+ agent: { type: "string", description: "Agent identity override (run)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSecrets,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: "brain_maintenance",
+ description:
+ "Quiet-window, lease-guarded heavy maintenance lane: run executes dream + reindex stale-first behind the local-time window, recall-telemetry busy gate, and an expiring lease (force bypasses the soft gates, never the lease); status renders the lease holder and recent journal.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: { type: "string", enum: ["run", "status"], description: "Tool operation." },
+ force: { type: "boolean", description: "Bypass window and busy gates (run)." },
+ window_start_hour: {
+ type: "integer",
+ minimum: 0,
+ maximum: 23,
+ description: "Local hour the window opens, inclusive (run).",
+ },
+ window_end_hour: {
+ type: "integer",
+ minimum: 0,
+ maximum: 23,
+ description: "Local hour the window closes, exclusive (run).",
+ },
+ tz: { type: "string", description: "IANA timezone for the window (default UTC)." },
+ agent: { type: "string", description: "Agent identity override (run)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainMaintenance,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
{
name: "brain_procedural_graph",
description:
diff --git a/src/mcp/schema-tools.ts b/src/mcp/schema-tools.ts
index 6a93aee4..ccc28047 100644
--- a/src/mcp/schema-tools.ts
+++ b/src/mcp/schema-tools.ts
@@ -10,6 +10,7 @@ import {
reviewSchemaOrphans,
} from "../core/brain/schema-admin.ts";
import type { SchemaMutation } from "../core/brain/schema-mutate.ts";
+import { resolveSearchConfig } from "../core/search/index.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import { coerceStr } from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
@@ -21,7 +22,11 @@ const SCHEMA_INSPECT_VIEWS: Readonly<
Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>
> = Object.freeze({
graph: (ctx: ServerContext) => buildSchemaGraph(ctx.vault),
- lint: (ctx: ServerContext) => buildSchemaLint(ctx.vault),
+ lint: (ctx: ServerContext) =>
+ buildSchemaLint(ctx.vault, {
+ dbPath: resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined })
+ .dbPath,
+ }),
stats: (ctx: ServerContext) => buildSchemaStats(ctx.vault),
orphans: (ctx: ServerContext) => reviewSchemaOrphans(ctx.vault),
explain_type: (ctx: ServerContext, args: Record<string, unknown>) =>
diff --git a/tests/cli/brain-attr.test.ts b/tests/cli/brain-attr.test.ts
new file mode 100644
index 00000000..93d2e2bd
--- /dev/null
+++ b/tests/cli/brain-attr.test.ts
@@ -0,0 +1,120 @@
+/**
+ * `o2b brain attr` CLI surface (t_f5633190): per-type attribute
+ * fields - assign validates against the schema pack's declared
+ * descriptors (errors teach the vocabulary), remove drops one field,
+ * show renders the current map.
+ */
+
+import { afterEach, beforeEach, 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 { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-attr-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [paper]",
+ " attributes:",
+ " - paper.status=reading status, e.g. queued or finished",
+ ].join("\n") + "\n",
+ );
+ writeFileSync(
+ join(vault, "Brain", "notes", "paper.md"),
+ "---\ntype: paper\n---\n\n# Paper\n\nbody\n",
+ );
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("assign writes the attribute, show renders it, remove drops it", async () => {
+ const assign = await runCli([
+ "brain",
+ "attr",
+ "Brain/notes/paper.md",
+ "status=queued",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(assign.returncode).toBe(0);
+ const assigned = JSON.parse(assign.stdout) as { ok: boolean; attributes: string[] };
+ expect(assigned.ok).toBe(true);
+ expect(assigned.attributes).toEqual(["status=queued"]);
+ expect(readFileSync(join(vault, "Brain", "notes", "paper.md"), "utf8")).toContain(
+ "status=queued",
+ );
+
+ const show = await runCli([
+ "brain",
+ "attr",
+ "Brain/notes/paper.md",
+ "--show",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(show.returncode).toBe(0);
+ expect(JSON.parse(show.stdout)).toEqual({
+ ok: true,
+ path: "Brain/notes/paper.md",
+ attributes: { status: "queued" },
+ });
+
+ const remove = await runCli([
+ "brain",
+ "attr",
+ "Brain/notes/paper.md",
+ "--remove",
+ "status",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(remove.returncode).toBe(0);
+ const removed = JSON.parse(remove.stdout) as { removed: boolean; attributes: string[] };
+ expect(removed.removed).toBe(true);
+ expect(removed.attributes).toEqual([]);
+});
+
+test("an undeclared field is a usage error teaching the vocabulary", async () => {
+ const result = await runCli([
+ "brain",
+ "attr",
+ "Brain/notes/paper.md",
+ "rating=5",
+ "--vault",
+ vault,
+ ]);
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain(
+ "declared fields: status (reading status, e.g. queued or finished)",
+ );
+});
+
+test("missing mode or conflicting modes are usage errors", async () => {
+ const none = await runCli(["brain", "attr", "Brain/notes/paper.md", "--vault", vault]);
+ expect(none.returncode).toBe(2);
+ const both = await runCli([
+ "brain",
+ "attr",
+ "Brain/notes/paper.md",
+ "status=queued",
+ "--show",
+ "--vault",
+ vault,
+ ]);
+ expect(both.returncode).toBe(2);
+});
diff --git a/tests/cli/brain-label.test.ts b/tests/cli/brain-label.test.ts
new file mode 100644
index 00000000..912106e6
--- /dev/null
+++ b/tests/cli/brain-label.test.ts
@@ -0,0 +1,110 @@
+/**
+ * `o2b brain label` CLI surface (t_7a41f42d): controlled-vocabulary
+ * classification - assign validates fail-closed against the schema
+ * pack, remove drops one dimension, show renders the current set.
+ */
+
+import { afterEach, beforeEach, 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 { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-label-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ ["schema_version: 1", "schema:", " labels:", " - priority=low", " - priority=high"].join(
+ "\n",
+ ) + "\n",
+ );
+ writeFileSync(join(vault, "Brain", "notes", "rollout.md"), "# Rollout\n\nCanary first.\n");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("assign writes the label, show renders it, remove drops it", async () => {
+ const assign = await runCli([
+ "brain",
+ "label",
+ "Brain/notes/rollout.md",
+ "priority=high",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(assign.returncode).toBe(0);
+ const assigned = JSON.parse(assign.stdout) as { ok: boolean; labels: string[] };
+ expect(assigned.ok).toBe(true);
+ expect(assigned.labels).toEqual(["priority/high"]);
+ expect(readFileSync(join(vault, "Brain", "notes", "rollout.md"), "utf8")).toContain(
+ "priority/high",
+ );
+
+ const show = await runCli([
+ "brain",
+ "label",
+ "Brain/notes/rollout.md",
+ "--show",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(show.returncode).toBe(0);
+ expect(JSON.parse(show.stdout)).toEqual({
+ ok: true,
+ path: "Brain/notes/rollout.md",
+ labels: ["priority/high"],
+ });
+
+ const remove = await runCli([
+ "brain",
+ "label",
+ "Brain/notes/rollout.md",
+ "--remove",
+ "priority",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(remove.returncode).toBe(0);
+ const removed = JSON.parse(remove.stdout) as { removed: boolean; labels: string[] };
+ expect(removed.removed).toBe(true);
+ expect(removed.labels).toEqual([]);
+});
+
+test("an out-of-vocabulary value is a usage error carrying the allowed list", async () => {
+ const result = await runCli([
+ "brain",
+ "label",
+ "Brain/notes/rollout.md",
+ "priority=urgent",
+ "--vault",
+ vault,
+ ]);
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain("allowed values: low, high");
+});
+
+test("missing mode or conflicting modes are usage errors", async () => {
+ const none = await runCli(["brain", "label", "Brain/notes/rollout.md", "--vault", vault]);
+ expect(none.returncode).toBe(2);
+ const both = await runCli([
+ "brain",
+ "label",
+ "Brain/notes/rollout.md",
+ "priority=high",
+ "--show",
+ "--vault",
+ vault,
+ ]);
+ expect(both.returncode).toBe(2);
+});
diff --git a/tests/cli/brain-maintenance.test.ts b/tests/cli/brain-maintenance.test.ts
new file mode 100644
index 00000000..3cc41308
--- /dev/null
+++ b/tests/cli/brain-maintenance.test.ts
@@ -0,0 +1,84 @@
+/**
+ * `o2b brain maintenance` CLI surface (t_166d1226): run executes
+ * dream + reindex under the lease (exit 0 even on a gate skip - cron
+ * must not alarm on a quiet hour), status renders lease + journal.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-maint-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("run executes dream and reindex; status shows the journal", async () => {
+ const init = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(init.returncode).toBe(0);
+
+ const run = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(run.returncode).toBe(0);
+ const ran = JSON.parse(run.stdout) as {
+ verdict: string;
+ tasks: Array<{ name: string; ok: boolean }>;
+ };
+ expect(ran.verdict).toBe("run");
+ expect(ran.tasks.map((t) => t.name).toSorted()).toEqual(["dream", "reindex"]);
+ expect(ran.tasks.every((t) => t.ok)).toBe(true);
+ expect(existsSync(join(vault, ".open-second-brain", "maintenance-runs.jsonl"))).toBe(true);
+
+ const status = await runCli(["brain", "maintenance", "status", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(status.returncode).toBe(0);
+ const state = JSON.parse(status.stdout) as {
+ lease: unknown;
+ journal: Array<{ verdict: string }>;
+ };
+ expect(state.lease).toBeNull();
+ expect(state.journal.length).toBeGreaterThanOrEqual(2);
+});
+
+test("a window that excludes the current hour skips with exit 0", async () => {
+ const init = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(init.returncode).toBe(0);
+ // A degenerate 1-hour window that the current hour cannot match:
+ // pick the hour after next in UTC, exclusive end one hour later.
+ const hour = (new Date().getUTCHours() + 2) % 24;
+ const end = (hour + 1) % 24;
+ const run = await runCli(
+ ["brain", "maintenance", "run", "--window", `${hour}-${end}`, "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(run.returncode).toBe(0);
+ expect(JSON.parse(run.stdout).verdict).toBe("skipped:window");
+});
+
+test("a malformed window is a usage error", async () => {
+ const result = await runCli(
+ ["brain", "maintenance", "run", "--window", "25-3", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },
+ );
+ expect(result.returncode).toBe(2);
+});
diff --git a/tests/cli/brain-secret.test.ts b/tests/cli/brain-secret.test.ts
new file mode 100644
index 00000000..7ee38398
--- /dev/null
+++ b/tests/cli/brain-secret.test.ts
@@ -0,0 +1,115 @@
+/**
+ * `o2b brain secret` CLI surface (t_0b134404): set ingests the value
+ * from stdin (never argv), list shows metadata only, run injects the
+ * secret into an allowlisted subprocess and redacts the output, rm
+ * removes irrecoverably.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-secret-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("set from stdin, list metadata only, run with redaction, rm", async () => {
+ const set = await runCli(
+ [
+ "brain",
+ "secret",
+ "set",
+ "api-key",
+ "--env-var",
+ "MY_API_KEY",
+ "--allow",
+ "bun -e *",
+ "--vault",
+ vault,
+ "--json",
+ ],
+ { stdin: "sk-cli-secret-98765\n" },
+ );
+ expect(set.returncode).toBe(0);
+ expect(set.stdout).not.toContain("sk-cli-secret-98765");
+
+ const list = await runCli(["brain", "secret", "list", "--vault", vault, "--json"]);
+ expect(list.returncode).toBe(0);
+ const listed = JSON.parse(list.stdout) as {
+ secrets: Array<{ name: string; env_var: string; allow: string[] }>;
+ };
+ expect(listed.secrets).toHaveLength(1);
+ expect(listed.secrets[0]).toMatchObject({
+ name: "api-key",
+ env_var: "MY_API_KEY",
+ allow: ["bun -e *"],
+ });
+ expect(list.stdout).not.toContain("sk-cli-secret-98765");
+
+ const run = await runCli([
+ "brain",
+ "secret",
+ "run",
+ "api-key",
+ "--vault",
+ vault,
+ "--",
+ "bun",
+ "-e",
+ "console.log('got ' + process.env.MY_API_KEY)",
+ ]);
+ expect(run.returncode).toBe(0);
+ expect(run.stdout).not.toContain("sk-cli-secret-98765");
+ expect(run.stdout).toContain("***REDACTED***");
+
+ const denied = await runCli([
+ "brain",
+ "secret",
+ "run",
+ "api-key",
+ "--vault",
+ vault,
+ "--",
+ "bash",
+ "-c",
+ "env",
+ ]);
+ expect(denied.returncode).toBe(2);
+ expect(denied.stderr).toContain("allowlist");
+
+ const rm = await runCli(["brain", "secret", "rm", "api-key", "--vault", vault]);
+ expect(rm.returncode).toBe(0);
+ const after = await runCli(["brain", "secret", "list", "--vault", vault, "--json"]);
+ expect(JSON.parse(after.stdout).secrets).toHaveLength(0);
+});
+
+test("the value never lands in the store file or audit trail in plaintext", async () => {
+ await runCli(["brain", "secret", "set", "deploy-token", "--vault", vault], {
+ stdin: "ghp-deploy-token-555\n",
+ });
+ const storeRaw = readFileSync(
+ join(vault, ".open-second-brain", "secrets", "secrets.json"),
+ "utf8",
+ );
+ expect(storeRaw).not.toContain("ghp-deploy-token-555");
+});
+
+test("set without stdin value or --from-env is a usage error", async () => {
+ const result = await runCli(["brain", "secret", "set", "empty-one", "--vault", vault], {
+ stdin: "",
+ });
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain("stdin");
+});
diff --git a/tests/cli/brain-tiers.test.ts b/tests/cli/brain-tiers.test.ts
new file mode 100644
index 00000000..e786d87d
--- /dev/null
+++ b/tests/cli/brain-tiers.test.ts
@@ -0,0 +1,133 @@
+/**
+ * `o2b brain tiers` CLI surface (t_3f92d3f1): check lists staged
+ * identity-field hand-edits, restore --apply writes the expected
+ * value back into the file, accept adopts the hand-edit as the new
+ * snapshot baseline.
+ */
+
+import { afterEach, beforeEach, 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 { indexVault } from "../../src/core/search/indexer.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-tiers-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function writePref(id: string, body: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-spaces.md"),
+ `---\nkind: brain-preference\nid: ${id}\ncreated_at: 2026-05-01T00:00:00Z\ntopic: style\n---\n\n${body}`,
+ );
+}
+
+async function seedDrift(): Promise<void> {
+ const config = resolveSearchConfig({ vault });
+ writePref("pref-spaces", "Use spaces.\n");
+ await indexVault(config);
+ writePref("pref-tabs", "Use spaces everywhere.\n");
+ await indexVault(config);
+}
+
+test("check lists drift; restore --apply writes the expected value back", async () => {
+ await seedDrift();
+
+ const check = await runCli(["brain", "tiers", "check", "--vault", vault, "--json"]);
+ expect(check.returncode).toBe(0);
+ const checked = JSON.parse(check.stdout) as {
+ findings: Array<{ path: string; field: string; expected: string; actual: string }>;
+ };
+ expect(checked.findings).toHaveLength(1);
+ expect(checked.findings[0]).toMatchObject({
+ path: "Brain/preferences/pref-spaces.md",
+ field: "id",
+ expected: "pref-spaces",
+ actual: "pref-tabs",
+ });
+
+ const dry = await runCli([
+ "brain",
+ "tiers",
+ "restore",
+ "Brain/preferences/pref-spaces.md",
+ "--vault",
+ vault,
+ ]);
+ expect(dry.returncode).toBe(0);
+ expect(dry.stdout).toContain("would restore");
+ expect(readFileSync(join(vault, "Brain", "preferences", "pref-spaces.md"), "utf8")).toContain(
+ "pref-tabs",
+ );
+
+ const restore = await runCli([
+ "brain",
+ "tiers",
+ "restore",
+ "Brain/preferences/pref-spaces.md",
+ "--apply",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(restore.returncode).toBe(0);
+ const restored = readFileSync(join(vault, "Brain", "preferences", "pref-spaces.md"), "utf8");
+ expect(restored).toContain("id: pref-spaces");
+ expect(restored).toContain("Use spaces everywhere.");
+
+ const after = await runCli(["brain", "tiers", "check", "--vault", vault, "--json"]);
+ expect(JSON.parse(after.stdout).findings).toHaveLength(0);
+});
+
+test("accept adopts the hand-edit; later reindexes stay quiet", async () => {
+ await seedDrift();
+
+ const accept = await runCli([
+ "brain",
+ "tiers",
+ "accept",
+ "Brain/preferences/pref-spaces.md",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(accept.returncode).toBe(0);
+
+ const check = await runCli(["brain", "tiers", "check", "--vault", vault, "--json"]);
+ expect(JSON.parse(check.stdout).findings).toHaveLength(0);
+
+ // The accepted value is the new baseline: a reindex of a further
+ // body-only edit stages nothing.
+ writePref("pref-tabs", "Use spaces everywhere, with feeling.\n");
+ const stats = await indexVault(resolveSearchConfig({ vault }));
+ expect(stats.tierDrift).toHaveLength(0);
+});
+
+test("restore without drift is an operational failure", async () => {
+ writePref("pref-spaces", "Use spaces.\n");
+ await indexVault(resolveSearchConfig({ vault }));
+ const result = await runCli([
+ "brain",
+ "tiers",
+ "restore",
+ "Brain/preferences/pref-spaces.md",
+ "--apply",
+ "--vault",
+ vault,
+ ]);
+ expect(result.returncode).toBe(1);
+ expect(result.stderr).toContain("no open drift");
+});
diff --git a/tests/core/brain/attributes.test.ts b/tests/core/brain/attributes.test.ts
new file mode 100644
index 00000000..2332fd87
--- /dev/null
+++ b/tests/core/brain/attributes.test.ts
@@ -0,0 +1,174 @@
+/**
+ * Per-type attribute fields (t_f5633190): the schema pack's
+ * `attributes` field declares, per page type, a small set of fields
+ * with natural-language descriptions. The descriptions are agent
+ * guidance - they render in schema explain output - and validation is
+ * fail-closed: assigning an undeclared field lists the declared
+ * fields with their descriptions so the caller can self-correct.
+ * Values persist as a sorted `attributes: [field=value]` frontmatter
+ * array, filterable through the existing `--property` filter.
+ */
+
+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 {
+ assignNoteAttribute,
+ AttributeVocabularyError,
+ readAttributes,
+ removeNoteAttribute,
+ validateAttributeAssignment,
+} from "../../../src/core/brain/attributes.ts";
+import { explainSchemaToken } from "../../../src/core/brain/schema-admin.ts";
+import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+
+const PACK = parseSchemaPack(
+ [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [paper]",
+ " attributes:",
+ " - paper.status=reading status, e.g. queued or finished",
+ " - paper.year=publication year as a 4-digit number",
+ ].join("\n") + "\n",
+);
+
+describe("validateAttributeAssignment", () => {
+ test("accepts a declared field and trims the value", () => {
+ expect(validateAttributeAssignment(PACK, "paper", "status", " queued ")).toEqual({
+ type: "paper",
+ field: "status",
+ value: "queued",
+ });
+ });
+
+ test("a type without declared attributes fails listing the declared types", () => {
+ expect(() => validateAttributeAssignment(PACK, "person", "status", "x")).toThrow(
+ AttributeVocabularyError,
+ );
+ expect(() => validateAttributeAssignment(PACK, "person", "status", "x")).toThrow(
+ /person.*declared attribute types: paper/,
+ );
+ });
+
+ test("an undeclared field fails listing fields with their descriptions", () => {
+ expect(() => validateAttributeAssignment(PACK, "paper", "rating", "5")).toThrow(
+ /rating.*declared fields: status \(reading status, e\.g\. queued or finished\), year \(publication year as a 4-digit number\)/,
+ );
+ });
+
+ test("values must be single-line and comma-free", () => {
+ expect(() => validateAttributeAssignment(PACK, "paper", "status", "a\nb")).toThrow(
+ /single line/,
+ );
+ expect(() => validateAttributeAssignment(PACK, "paper", "status", "a,b")).toThrow(/comma/);
+ expect(() => validateAttributeAssignment(PACK, "paper", "status", " ")).toThrow(/empty/);
+ });
+});
+
+describe("assignNoteAttribute / removeNoteAttribute", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-attrs-"));
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "notes", "paper.md"),
+ "---\ntype: paper\ntitle: A Paper\n---\n\n# A Paper\n\nbody\n",
+ );
+ writeFileSync(join(vault, "notes", "untyped.md"), "# Untyped\n\nbody\n");
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("assignment reads the note's type, persists sorted field=value entries", () => {
+ assignNoteAttribute(vault, "notes/paper.md", { field: "year", value: "2026", pack: PACK });
+ const result = assignNoteAttribute(vault, "notes/paper.md", {
+ field: "status",
+ value: "queued",
+ pack: PACK,
+ });
+ expect(result.attributes).toEqual(["status=queued", "year=2026"]);
+ const [fm, body] = parseFrontmatter(join(vault, "notes", "paper.md"));
+ expect(fm["attributes"]).toEqual(["status=queued", "year=2026"]);
+ expect(fm["title"]).toBe("A Paper");
+ expect(body).toContain("body");
+ });
+
+ test("reassigning a field replaces its value", () => {
+ assignNoteAttribute(vault, "notes/paper.md", { field: "status", value: "queued", pack: PACK });
+ const result = assignNoteAttribute(vault, "notes/paper.md", {
+ field: "status",
+ value: "finished",
+ pack: PACK,
+ });
+ expect(result.attributes).toEqual(["status=finished"]);
+ });
+
+ test("a note without a type cannot take attributes", () => {
+ expect(() =>
+ assignNoteAttribute(vault, "notes/untyped.md", {
+ field: "status",
+ value: "queued",
+ pack: PACK,
+ }),
+ ).toThrow(/declares no type/);
+ });
+
+ test("removal drops one field and reports presence", () => {
+ assignNoteAttribute(vault, "notes/paper.md", { field: "status", value: "queued", pack: PACK });
+ const removed = removeNoteAttribute(vault, "notes/paper.md", { field: "status" });
+ expect(removed.removed).toBe(true);
+ expect(removed.attributes).toEqual([]);
+ const [fm] = parseFrontmatter(join(vault, "notes", "paper.md"));
+ expect(fm["attributes"]).toBeUndefined();
+ const again = removeNoteAttribute(vault, "notes/paper.md", { field: "status" });
+ expect(again.removed).toBe(false);
+ });
+
+ test("readAttributes parses field=value entries", () => {
+ assignNoteAttribute(vault, "notes/paper.md", { field: "year", value: "2026", pack: PACK });
+ const [fm] = parseFrontmatter(join(vault, "notes", "paper.md"));
+ expect(readAttributes(fm)).toEqual({ year: "2026" });
+ });
+});
+
+describe("schema explain surface", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-attrs-explain-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [paper]",
+ " attributes:",
+ " - paper.status=reading status, e.g. queued or finished",
+ ].join("\n") + "\n",
+ );
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("explainSchemaToken renders declared attribute descriptors", () => {
+ const explanation = explainSchemaToken(vault, "paper");
+ expect(explanation.attributes).toEqual({
+ status: "reading status, e.g. queued or finished",
+ });
+ });
+
+ test("a token without attributes explains with an empty descriptor map", () => {
+ const explanation = explainSchemaToken(vault, "note");
+ expect(explanation.attributes).toEqual({});
+ });
+});
diff --git a/tests/core/brain/frontmatter-tiers.test.ts b/tests/core/brain/frontmatter-tiers.test.ts
new file mode 100644
index 00000000..624c3ce2
--- /dev/null
+++ b/tests/core/brain/frontmatter-tiers.test.ts
@@ -0,0 +1,212 @@
+/**
+ * Tiered frontmatter field protection (t_3f92d3f1), part 1: the tier
+ * model and the tier-respecting merge. Four tiers - identity (join
+ * keys; hand-edit = corruption), system (framework bookkeeping),
+ * business (agent-written domain fields), user (freely editable).
+ * Resolution: schema-pack override > built-in framework defaults >
+ * user. The merge preserves user fields a framework write does not
+ * own and refuses to change an identity value unless explicitly told
+ * to. Unknown kinds resolve everything to user - a human's own vault
+ * is never constrained.
+ */
+
+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 {
+ FrontmatterTierConflictError,
+ mergeFrontmatterTiered,
+ resolveFieldTier,
+ tieredFieldsForKind,
+} from "../../../src/core/brain/frontmatter-tiers.ts";
+import { writePreference, type WritePreferenceInput } from "../../../src/core/brain/preference.ts";
+import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+
+const EMPTY_PACK = parseSchemaPack("schema_version: 1\n");
+
+const OVERRIDE_PACK = parseSchemaPack(
+ [
+ "schema_version: 1",
+ "schema:",
+ " frontmatter_tiers:",
+ " - brain-preference.topic=user",
+ " - recipe.id=identity",
+ ].join("\n") + "\n",
+);
+
+describe("resolveFieldTier", () => {
+ test("identity join keys of framework kinds are built-in", () => {
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "kind")).toBe("identity");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "id")).toBe("identity");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-entity", "entity_id")).toBe("identity");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-entity", "category")).toBe("identity");
+ });
+
+ test("underscore-prefixed fields of framework kinds are system", () => {
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "_status")).toBe("system");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "_confidence_value")).toBe("system");
+ });
+
+ test("known bookkeeping fields are system, domain fields business", () => {
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "created_at")).toBe("system");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-entity", "updated_at")).toBe("system");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "topic")).toBe("business");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "principle")).toBe("business");
+ });
+
+ test("undeclared fields and unknown kinds default to user", () => {
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "pinned")).toBe("user");
+ expect(resolveFieldTier(EMPTY_PACK, "brain-preference", "my-custom-note")).toBe("user");
+ expect(resolveFieldTier(EMPTY_PACK, "shopping-list", "id")).toBe("user");
+ });
+
+ test("schema-pack overrides win over built-ins and add new kinds", () => {
+ expect(resolveFieldTier(OVERRIDE_PACK, "brain-preference", "topic")).toBe("user");
+ expect(resolveFieldTier(OVERRIDE_PACK, "recipe", "id")).toBe("identity");
+ });
+
+ test("tieredFieldsForKind lists protected fields for the drift check", () => {
+ const fields = tieredFieldsForKind(EMPTY_PACK, "brain-preference");
+ expect(fields["kind"]).toBe("identity");
+ expect(fields["created_at"]).toBe("system");
+ expect(fields["topic"]).toBe("business");
+ expect(fields["pinned"]).toBeUndefined();
+ expect(tieredFieldsForKind(EMPTY_PACK, "shopping-list")).toEqual({});
+ });
+});
+
+describe("mergeFrontmatterTiered", () => {
+ const existing = {
+ kind: "brain-preference",
+ id: "pref-spaces",
+ created_at: "2026-05-01T00:00:00Z",
+ topic: "style",
+ principle: "Use spaces",
+ favorite_quote: "tabs are history",
+ };
+
+ test("a user field the framework write does not own survives", () => {
+ const merged = mergeFrontmatterTiered(
+ existing,
+ {
+ kind: "brain-preference",
+ id: "pref-spaces",
+ created_at: "2026-05-01T00:00:00Z",
+ topic: "style",
+ principle: "Use spaces, always",
+ },
+ { kind: "brain-preference", pack: EMPTY_PACK },
+ );
+ expect(merged["favorite_quote"]).toBe("tabs are history");
+ expect(merged["principle"]).toBe("Use spaces, always");
+ });
+
+ test("changing an identity value is refused with both values named", () => {
+ expect(() =>
+ mergeFrontmatterTiered(
+ existing,
+ { kind: "brain-preference", id: "pref-other", topic: "style" },
+ { kind: "brain-preference", pack: EMPTY_PACK },
+ ),
+ ).toThrow(FrontmatterTierConflictError);
+ expect(() =>
+ mergeFrontmatterTiered(
+ existing,
+ { kind: "brain-preference", id: "pref-other", topic: "style" },
+ { kind: "brain-preference", pack: EMPTY_PACK },
+ ),
+ ).toThrow(/id.*pref-spaces.*pref-other/);
+ });
+
+ test("acceptIdentity lets an explicit migration change the join key", () => {
+ const merged = mergeFrontmatterTiered(
+ existing,
+ { kind: "brain-preference", id: "pref-other" },
+ { kind: "brain-preference", pack: EMPTY_PACK, acceptIdentity: true },
+ );
+ expect(merged["id"]).toBe("pref-other");
+ });
+
+ test("unknown kinds merge exactly like a plain spread", () => {
+ const merged = mergeFrontmatterTiered(
+ { id: "anything", note: "mine" },
+ { id: "changed" },
+ { kind: "shopping-list", pack: EMPTY_PACK },
+ );
+ expect(merged).toEqual({ id: "changed", note: "mine" });
+ });
+
+ test("equal identity values pass without conflict", () => {
+ const merged = mergeFrontmatterTiered(
+ existing,
+ { kind: "brain-preference", id: "pref-spaces", topic: "style-v2" },
+ { kind: "brain-preference", pack: EMPTY_PACK },
+ );
+ expect(merged["topic"]).toBe("style-v2");
+ });
+
+ test("framework-owned legacy keys the writer no longer emits are dropped", () => {
+ const merged = mergeFrontmatterTiered(
+ { ...existing, status: "confirmed", applied_count: 3 },
+ { kind: "brain-preference", id: "pref-spaces", _status: "confirmed" },
+ { kind: "brain-preference", pack: EMPTY_PACK },
+ );
+ expect(merged["status"]).toBeUndefined();
+ expect(merged["applied_count"]).toBeUndefined();
+ expect(merged["_status"]).toBe("confirmed");
+ expect(merged["favorite_quote"]).toBe("tabs are history");
+ });
+});
+
+describe("writePreference integration", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-tier-writer-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ function pref(principle: string): WritePreferenceInput {
+ return {
+ slug: "spaces",
+ topic: "style",
+ principle,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: ["[[sig-2026-05-01-spaces]]"],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: BRAIN_CONFIDENCE.low,
+ confidence_value: null,
+ pinned: false,
+ };
+ }
+
+ test("a hand-added user field survives a framework rewrite", () => {
+ const { path } = writePreference(vault, pref("Use spaces"));
+ const withUserKey = readFileSync(path, "utf8").replace("---\n", "---\nmy_note: hands off\n");
+ writeFileSync(path, withUserKey);
+ writePreference(vault, pref("Use spaces, always"), { overwrite: true });
+ const rewritten = readFileSync(path, "utf8");
+ expect(rewritten).toContain("my_note: hands off");
+ expect(rewritten).toContain("Use spaces, always");
+ });
+
+ test("a hand-edited id makes the next framework rewrite throw", () => {
+ const { path } = writePreference(vault, pref("Use spaces"));
+ writeFileSync(path, readFileSync(path, "utf8").replace("id: pref-spaces", "id: pref-tabs"));
+ expect(() => writePreference(vault, pref("Use spaces, v2"), { overwrite: true })).toThrow(
+ FrontmatterTierConflictError,
+ );
+ });
+});
diff --git a/tests/core/brain/labels.test.ts b/tests/core/brain/labels.test.ts
new file mode 100644
index 00000000..481fe2a7
--- /dev/null
+++ b/tests/core/brain/labels.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Controlled-vocabulary labels (t_7a41f42d): the schema pack declares
+ * label dimensions with allowed values; assignment is fail-closed
+ * (unknown dimension or value rejected with the vocabulary in the
+ * error), one value per dimension per note, stored as a sorted
+ * `labels: [dim/value]` frontmatter array plus a canonical
+ * `label` entity in the registry for clustering.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { listEntities } from "../../../src/core/brain/entities/registry.ts";
+import {
+ assignNoteLabel,
+ LabelVocabularyError,
+ labelToken,
+ removeNoteLabel,
+ validateLabelAssignment,
+} from "../../../src/core/brain/labels.ts";
+import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+
+const PACK = parseSchemaPack(
+ [
+ "schema_version: 1",
+ "schema:",
+ " labels:",
+ " - priority=low",
+ " - priority=high",
+ " - sensitivity=public",
+ " - sensitivity=private",
+ ].join("\n") + "\n",
+);
+
+const EMPTY_PACK = parseSchemaPack("schema_version: 1\n");
+
+const NOW = new Date("2026-06-04T10:00:00Z");
+
+describe("validateLabelAssignment", () => {
+ test("normalizes and accepts declared dimension/value pairs", () => {
+ expect(validateLabelAssignment(PACK, " Priority ", "HIGH")).toEqual({
+ dimension: "priority",
+ value: "high",
+ token: "priority/high",
+ });
+ });
+
+ test("unknown dimension fails closed listing declared dimensions", () => {
+ expect(() => validateLabelAssignment(PACK, "mood", "high")).toThrow(LabelVocabularyError);
+ expect(() => validateLabelAssignment(PACK, "mood", "high")).toThrow(
+ /mood.*declared dimensions: priority, sensitivity/,
+ );
+ });
+
+ test("unknown value fails closed listing the allowed vocabulary", () => {
+ expect(() => validateLabelAssignment(PACK, "priority", "urgent")).toThrow(
+ /priority.*allowed values: low, high/,
+ );
+ });
+
+ test("a pack without labels rejects every assignment", () => {
+ expect(() => validateLabelAssignment(EMPTY_PACK, "priority", "high")).toThrow(
+ /no label dimensions are declared/,
+ );
+ });
+
+ test("labelToken renders the canonical dim/value form", () => {
+ expect(labelToken("priority", "high")).toBe("priority/high");
+ });
+});
+
+describe("assignNoteLabel / removeNoteLabel", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-labels-"));
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "rollout.md"),
+ "---\ntitle: Rollout\n---\n\n# Rollout\n\nCanary first.\n",
+ );
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("assignment writes a sorted labels array and preserves body and keys", () => {
+ const result = assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "sensitivity",
+ value: "private",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ expect(result.labels).toEqual(["sensitivity/private"]);
+ const [fm, body] = parseFrontmatter(join(vault, "Brain", "notes", "rollout.md"));
+ expect(fm["labels"]).toEqual(["priority/high", "sensitivity/private"]);
+ expect(fm["title"]).toBe("Rollout");
+ expect(body).toContain("Canary first.");
+ });
+
+ test("one value per dimension - reassignment replaces, idempotent repeat", () => {
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "low",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ const replaced = assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ expect(replaced.labels).toEqual(["priority/high"]);
+ const again = assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ expect(again.labels).toEqual(["priority/high"]);
+ expect(again.changed).toBe(false);
+ });
+
+ test("assignment registers a canonical label entity for clustering", () => {
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ const entities = listEntities(vault, { category: "label" });
+ expect(entities).toHaveLength(1);
+ expect(entities[0]!.name).toBe("priority/high");
+ });
+
+ test("invalid assignment never touches the file", () => {
+ expect(() =>
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "urgent",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ }),
+ ).toThrow(LabelVocabularyError);
+ const [fm] = parseFrontmatter(join(vault, "Brain", "notes", "rollout.md"));
+ expect(fm["labels"]).toBeUndefined();
+ });
+
+ test("a missing note fails with a clear error", () => {
+ expect(() =>
+ assignNoteLabel(vault, "Brain/notes/ghost.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ }),
+ ).toThrow(/does not exist/);
+ });
+
+ test("removal drops one dimension and reports whether it was present", () => {
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "sensitivity",
+ value: "public",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ const removed = removeNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ pack: PACK,
+ });
+ expect(removed.removed).toBe(true);
+ expect(removed.labels).toEqual(["sensitivity/public"]);
+ const again = removeNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ pack: PACK,
+ });
+ expect(again.removed).toBe(false);
+ const [fm] = parseFrontmatter(join(vault, "Brain", "notes", "rollout.md"));
+ expect(fm["labels"]).toEqual(["sensitivity/public"]);
+ });
+
+ test("removing the last label drops the labels key entirely", () => {
+ assignNoteLabel(vault, "Brain/notes/rollout.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ });
+ removeNoteLabel(vault, "Brain/notes/rollout.md", { dimension: "priority", pack: PACK });
+ const [fm] = parseFrontmatter(join(vault, "Brain", "notes", "rollout.md"));
+ expect(fm["labels"]).toBeUndefined();
+ });
+
+ test("path traversal outside the vault is refused", () => {
+ expect(() =>
+ assignNoteLabel(vault, "../outside.md", {
+ dimension: "priority",
+ value: "high",
+ pack: PACK,
+ agent: "tester",
+ now: NOW,
+ }),
+ ).toThrow(/outside the vault/);
+ });
+});
diff --git a/tests/core/brain/maintenance/maintenance.test.ts b/tests/core/brain/maintenance/maintenance.test.ts
new file mode 100644
index 00000000..716da75d
--- /dev/null
+++ b/tests/core/brain/maintenance/maintenance.test.ts
@@ -0,0 +1,174 @@
+/**
+ * Quiet-window, lease-guarded maintenance lane (t_166d1226): a heavy
+ * pass runs only inside the configured local-time window, only when
+ * recent interactive query-rate is low, and only under an expiring
+ * SQLite lease no second worker can grab; every attempt - including
+ * gate refusals - lands in a bounded journal.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ acquireLease,
+ currentLease,
+ releaseLease,
+} from "../../../../src/core/brain/maintenance/lease.ts";
+import {
+ dailyWindowContains,
+ evaluateGates,
+ runMaintenance,
+} from "../../../../src/core/brain/maintenance/lane.ts";
+import {
+ listJournal,
+ MAINTENANCE_JOURNAL_CAP,
+} from "../../../../src/core/brain/maintenance/journal.ts";
+import { emitRecallTelemetry } from "../../../../src/core/brain/recall-telemetry.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+
+const NOW = new Date("2026-06-05T03:30:00Z");
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-maint-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-maint-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("lease", () => {
+ test("a live lease blocks a second worker; expiry frees it", () => {
+ expect(acquireLease(vault, { holder: "worker-a", ttlMs: 60_000, now: NOW })).toBe(true);
+ expect(acquireLease(vault, { holder: "worker-b", ttlMs: 60_000, now: NOW })).toBe(false);
+ expect(currentLease(vault, { now: NOW })?.holder).toBe("worker-a");
+
+ const afterExpiry = new Date(NOW.getTime() + 61_000);
+ expect(acquireLease(vault, { holder: "worker-b", ttlMs: 60_000, now: afterExpiry })).toBe(true);
+ expect(currentLease(vault, { now: afterExpiry })?.holder).toBe("worker-b");
+ });
+
+ test("release only honors the holder", () => {
+ acquireLease(vault, { holder: "worker-a", ttlMs: 60_000, now: NOW });
+ expect(releaseLease(vault, { holder: "worker-b" })).toBe(false);
+ expect(releaseLease(vault, { holder: "worker-a" })).toBe(true);
+ expect(currentLease(vault, { now: NOW })).toBeNull();
+ });
+});
+
+describe("dailyWindowContains", () => {
+ test("plain window and midnight wrap, timezone-aware", () => {
+ // 03:30 UTC.
+ expect(dailyWindowContains(NOW, { startHour: 2, endHour: 6, tz: "UTC" })).toBe(true);
+ expect(dailyWindowContains(NOW, { startHour: 4, endHour: 6, tz: "UTC" })).toBe(false);
+ // Wrap: 22-04 contains 03:30.
+ expect(dailyWindowContains(NOW, { startHour: 22, endHour: 4, tz: "UTC" })).toBe(true);
+ // 03:30 UTC = 06:30 in UTC+3.
+ expect(dailyWindowContains(NOW, { startHour: 6, endHour: 8, tz: "Europe/Moscow" })).toBe(true);
+ });
+});
+
+describe("evaluateGates", () => {
+ test("no window configured and a quiet vault runs", () => {
+ expect(evaluateGates(vault, { now: NOW })).toBe("run");
+ });
+
+ test("outside the window skips", () => {
+ expect(
+ evaluateGates(vault, { now: NOW, window: { startHour: 10, endHour: 12, tz: "UTC" } }),
+ ).toBe("skipped:window");
+ });
+
+ test("recent interactive queries above the threshold skip as busy", () => {
+ for (let i = 0; i < 5; i++) {
+ emitRecallTelemetry(vault, {
+ host: "claude-code",
+ mode: "search",
+ status: "ok",
+ durationMs: 12,
+ resultCount: 3,
+ createdAt: new Date(NOW.getTime() - 60_000).toISOString(),
+ });
+ }
+ expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 5 } })).toBe(
+ "skipped:busy",
+ );
+ expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 6 } })).toBe("run");
+ });
+});
+
+describe("runMaintenance", () => {
+ test("runs registered tasks stale-first under the lease and journals everything", async () => {
+ const order: string[] = [];
+ const result = await runMaintenance(vault, {
+ now: NOW,
+ holder: "worker-a",
+ tasks: [
+ { name: "dream", run: async () => void order.push("dream") },
+ { name: "reindex", run: async () => void order.push("reindex") },
+ ],
+ });
+ expect(result.verdict).toBe("run");
+ expect(result.tasks.map((t) => t.name)).toEqual(["dream", "reindex"]);
+ expect(result.tasks.every((t) => t.ok)).toBe(true);
+ expect(order).toEqual(["dream", "reindex"]);
+ expect(currentLease(vault, { now: NOW })).toBeNull(); // released
+
+ const journal = listJournal(vault);
+ expect(journal.some((e) => e.verdict === "run" && e.task === "dream")).toBe(true);
+
+ // Second run: dream succeeded later than nothing - both ran, so
+ // stale-first keeps prior order; make reindex stale by failing it.
+ const failing = await runMaintenance(vault, {
+ now: new Date(NOW.getTime() + 120_000),
+ holder: "worker-a",
+ tasks: [
+ {
+ name: "reindex",
+ run: async () => {
+ throw new Error("disk full");
+ },
+ },
+ ],
+ });
+ expect(failing.tasks[0]!.ok).toBe(false);
+ expect(listJournal(vault).some((e) => e.task === "reindex" && e.ok === false)).toBe(true);
+ });
+
+ test("gate refusals are journaled; --force bypasses window but never the lease", async () => {
+ const window = { startHour: 10, endHour: 12, tz: "UTC" as const };
+ const skipped = await runMaintenance(vault, {
+ now: NOW,
+ holder: "worker-a",
+ window,
+ tasks: [{ name: "dream", run: async () => {} }],
+ });
+ expect(skipped.verdict).toBe("skipped:window");
+ expect(listJournal(vault).some((e) => e.verdict === "skipped:window")).toBe(true);
+
+ acquireLease(vault, { holder: "other-worker", ttlMs: 600_000, now: NOW });
+ const forced = await runMaintenance(vault, {
+ now: NOW,
+ holder: "worker-a",
+ window,
+ force: true,
+ tasks: [{ name: "dream", run: async () => {} }],
+ });
+ expect(forced.verdict).toBe("skipped:lease");
+ });
+
+ test("the journal is bounded", () => {
+ expect(MAINTENANCE_JOURNAL_CAP).toBeGreaterThanOrEqual(100);
+ });
+});
diff --git a/tests/core/brain/schema-pack-ontology.test.ts b/tests/core/brain/schema-pack-ontology.test.ts
new file mode 100644
index 00000000..e5280e70
--- /dev/null
+++ b/tests/core/brain/schema-pack-ontology.test.ts
@@ -0,0 +1,322 @@
+/**
+ * Schema-pack ontology fields (write-time-integrity-governance Task 1):
+ * `labels` (controlled-vocabulary dimensions), `link_constraints`
+ * (allowed source->target pairs per link type), `attributes`
+ * (per-type field descriptors), and `frontmatter_tiers` (per-kind
+ * field tier map). All additive: a config without them parses to
+ * empty frozen structures and renders nothing - the neutral default
+ * is pinned byte-for-byte.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { coerceSchemaMutations } from "../../../src/core/brain/schema-admin.ts";
+import {
+ applyMutationsToPack,
+ type SchemaMutation,
+} from "../../../src/core/brain/schema-mutate.ts";
+import {
+ FRONTMATTER_TIERS,
+ parseSchemaPack,
+ renderSchemaBlock,
+} from "../../../src/core/brain/schema-pack.ts";
+
+const BASE = [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [paper, person]",
+ " link_types:",
+ " - depends_on",
+].join("\n");
+
+describe("parseSchemaPack ontology fields", () => {
+ test("config without ontology fields parses to empty frozen structures", () => {
+ const pack = parseSchemaPack(BASE + "\n");
+ expect(pack.labels).toEqual({});
+ expect(pack.link_constraints).toEqual({});
+ expect(pack.attributes).toEqual({});
+ expect(pack.frontmatter_tiers).toEqual({});
+ expect(Object.isFrozen(pack.labels)).toBe(true);
+ expect(Object.isFrozen(pack.frontmatter_tiers)).toBe(true);
+ });
+
+ test("neutral default renders nothing - render is byte-identical to today", () => {
+ const pack = parseSchemaPack(BASE + "\n");
+ const block = renderSchemaBlock(pack);
+ expect(block).not.toContain("labels");
+ expect(block).not.toContain("link_constraints");
+ expect(block).not.toContain("attributes");
+ expect(block).not.toContain("frontmatter_tiers");
+ });
+
+ test("labels parse as dimension to enum values", () => {
+ const pack = parseSchemaPack(
+ [
+ BASE,
+ " labels:",
+ " - priority=low",
+ " - priority=high",
+ " - sensitivity=public",
+ ].join("\n") + "\n",
+ );
+ expect(pack.labels).toEqual({
+ priority: ["low", "high"],
+ sensitivity: ["public"],
+ });
+ });
+
+ test("label values are normalized and token-validated", () => {
+ const pack = parseSchemaPack([BASE, " labels:", " - Priority=HIGH"].join("\n") + "\n");
+ expect(pack.labels["priority"]).toEqual(["high"]);
+ expect(() =>
+ parseSchemaPack([BASE, " labels:", " - priority=not a token!"].join("\n") + "\n"),
+ ).toThrow(/schema\.labels\.priority/);
+ });
+
+ test("link_constraints parse as link_type to source->target pairs", () => {
+ const pack = parseSchemaPack(
+ [
+ BASE,
+ " link_constraints:",
+ " - depends_on=paper->paper",
+ " - depends_on=paper->person",
+ ].join("\n") + "\n",
+ );
+ expect(pack.link_constraints).toEqual({
+ depends_on: ["paper->paper", "paper->person"],
+ });
+ });
+
+ test("malformed endpoint pairs fail closed with a path-qualified error", () => {
+ expect(() =>
+ parseSchemaPack([BASE, " link_constraints:", " - depends_on=paper"].join("\n") + "\n"),
+ ).toThrow(/schema\.link_constraints\.depends_on.*source->target/);
+ expect(() =>
+ parseSchemaPack(
+ [BASE, " link_constraints:", " - depends_on=pa per->note"].join("\n") + "\n",
+ ),
+ ).toThrow(/schema\.link_constraints\.depends_on/);
+ });
+
+ test("attributes parse as type.field to description", () => {
+ const pack = parseSchemaPack(
+ [
+ BASE,
+ " attributes:",
+ " - paper.status=reading status, e.g. queued or finished",
+ " - paper.year=publication year as a 4-digit number",
+ ].join("\n") + "\n",
+ );
+ expect(pack.attributes).toEqual({
+ paper: {
+ status: "reading status, e.g. queued or finished",
+ year: "publication year as a 4-digit number",
+ },
+ });
+ });
+
+ test("attribute descriptions keep free text including = characters", () => {
+ const pack = parseSchemaPack(
+ [BASE, " attributes:", " - paper.rating=scale 1=worst to 5=best"].join("\n") + "\n",
+ );
+ expect(pack.attributes["paper"]!["rating"]).toBe("scale 1=worst to 5=best");
+ });
+
+ test("attribute keys without a type.field shape fail closed", () => {
+ expect(() =>
+ parseSchemaPack([BASE, " attributes:", " - status=loose description"].join("\n") + "\n"),
+ ).toThrow(/schema\.attributes.*type\.field/);
+ });
+
+ test("frontmatter_tiers parse as kind.field to tier", () => {
+ const pack = parseSchemaPack(
+ [
+ BASE,
+ " frontmatter_tiers:",
+ " - brain-preference.id=identity",
+ " - brain-preference.applied_count=system",
+ " - brain-preference.topic=business",
+ ].join("\n") + "\n",
+ );
+ expect(pack.frontmatter_tiers).toEqual({
+ "brain-preference": {
+ id: "identity",
+ applied_count: "system",
+ topic: "business",
+ },
+ });
+ });
+
+ test("unknown tier names fail closed listing the allowed tiers", () => {
+ expect(() =>
+ parseSchemaPack(
+ [BASE, " frontmatter_tiers:", " - brain-preference.id=readonly"].join("\n") + "\n",
+ ),
+ ).toThrow(/schema\.frontmatter_tiers.*identity/);
+ });
+
+ test("FRONTMATTER_TIERS exposes the four-level model", () => {
+ expect([...FRONTMATTER_TIERS]).toEqual(["identity", "system", "business", "user"]);
+ });
+});
+
+describe("renderSchemaBlock round-trip", () => {
+ test("parse(render(pack)) preserves all ontology fields", () => {
+ const text =
+ [
+ BASE,
+ " labels:",
+ " - priority=low",
+ " - priority=high",
+ " link_constraints:",
+ " - depends_on=paper->person",
+ " attributes:",
+ " - paper.status=reading status",
+ " frontmatter_tiers:",
+ " - brain-preference.id=identity",
+ ].join("\n") + "\n";
+ const pack = parseSchemaPack(text);
+ const reparsed = parseSchemaPack("schema_version: 1\n" + renderSchemaBlock(pack));
+ expect(reparsed.labels).toEqual(pack.labels);
+ expect(reparsed.link_constraints).toEqual(pack.link_constraints);
+ expect(reparsed.attributes).toEqual(pack.attributes);
+ expect(reparsed.frontmatter_tiers).toEqual(pack.frontmatter_tiers);
+ });
+});
+
+describe("ontology mutations", () => {
+ const base = parseSchemaPack(BASE + "\n");
+
+ test("add_label_dimension merges values; remove_label_dimension drops it", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "add_label_dimension", dimension: "priority", values: ["low", "high"] },
+ { op: "add_label_dimension", dimension: "priority", values: ["urgent"] },
+ ]);
+ expect(added.labels["priority"]).toEqual(["low", "high", "urgent"]);
+ const removed = applyMutationsToPack(added, [
+ { op: "remove_label_dimension", dimension: "priority" },
+ ]);
+ expect(removed.labels).toEqual({});
+ });
+
+ test("add_link_constraint requires a declared link type", () => {
+ const ok = applyMutationsToPack(base, [
+ { op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ ]);
+ expect(ok.link_constraints["depends_on"]).toEqual(["paper->person"]);
+ expect(() =>
+ applyMutationsToPack(base, [
+ { op: "add_link_constraint", link_type: "mystery", source: "paper", target: "person" },
+ ]),
+ ).toThrow(/link_constraints\.mystery.*not declared/);
+ });
+
+ test("remove_link_constraint drops one pair and prunes empty entries", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ ]);
+ const removed = applyMutationsToPack(added, [
+ { op: "remove_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ ]);
+ expect(removed.link_constraints).toEqual({});
+ });
+
+ test("set_attribute_field requires a declared type and single-line description", () => {
+ const ok = applyMutationsToPack(base, [
+ { op: "set_attribute_field", type: "paper", field: "status", description: "reading status" },
+ ]);
+ expect(ok.attributes["paper"]!["status"]).toBe("reading status");
+ expect(() =>
+ applyMutationsToPack(base, [
+ { op: "set_attribute_field", type: "ghost", field: "status", description: "x" },
+ ]),
+ ).toThrow(/attributes\.ghost.*not declared/);
+ expect(() =>
+ applyMutationsToPack(base, [
+ { op: "set_attribute_field", type: "paper", field: "status", description: "a\nb" },
+ ]),
+ ).toThrow(/single line/);
+ });
+
+ test("remove_attribute_field prunes empty type maps", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "set_attribute_field", type: "paper", field: "status", description: "reading status" },
+ ]);
+ const removed = applyMutationsToPack(added, [
+ { op: "remove_attribute_field", type: "paper", field: "status" },
+ ]);
+ expect(removed.attributes).toEqual({});
+ });
+
+ test("set_frontmatter_tier validates the tier; remove prunes empty kinds", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "set_frontmatter_tier", kind: "brain-preference", field: "id", tier: "identity" },
+ ]);
+ expect(added.frontmatter_tiers["brain-preference"]!["id"]).toBe("identity");
+ expect(() =>
+ applyMutationsToPack(base, [
+ {
+ op: "set_frontmatter_tier",
+ kind: "brain-preference",
+ field: "id",
+ tier: "readonly",
+ } as unknown as SchemaMutation,
+ ]),
+ ).toThrow(/frontmatter_tiers.*identity/);
+ const removed = applyMutationsToPack(added, [
+ { op: "remove_frontmatter_tier", kind: "brain-preference", field: "id" },
+ ]);
+ expect(removed.frontmatter_tiers).toEqual({});
+ });
+
+ test("remove_link_type also drops its constraints", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ ]);
+ const removed = applyMutationsToPack(added, [{ op: "remove_link_type", token: "depends_on" }]);
+ expect(removed.link_constraints).toEqual({});
+ });
+
+ test("remove_type drops the type's attributes alongside extractable/aliases", () => {
+ const added = applyMutationsToPack(base, [
+ { op: "add_type", category: "page_types", token: "book" },
+ { op: "set_attribute_field", type: "book", field: "author", description: "who wrote it" },
+ ]);
+ const removed = applyMutationsToPack(added, [
+ { op: "remove_type", category: "page_types", token: "book" },
+ ]);
+ expect(removed.attributes).toEqual({});
+ });
+});
+
+describe("coerceSchemaMutations (CLI/MCP boundary)", () => {
+ test("the ontology mutation ops coerce from raw JSON", () => {
+ const coerced = coerceSchemaMutations([
+ { op: "add_label_dimension", dimension: "priority", values: ["low", "high"] },
+ { op: "remove_label_dimension", dimension: "priority" },
+ { op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ { op: "remove_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
+ { op: "set_attribute_field", type: "paper", field: "status", description: "reading status" },
+ { op: "remove_attribute_field", type: "paper", field: "status" },
+ { op: "set_frontmatter_tier", kind: "brain-preference", field: "id", tier: "identity" },
+ { op: "remove_frontmatter_tier", kind: "brain-preference", field: "id" },
+ ]);
+ expect(coerced).toHaveLength(8);
+ expect(coerced[0]).toEqual({
+ op: "add_label_dimension",
+ dimension: "priority",
+ values: ["low", "high"],
+ });
+ });
+
+ test("malformed ontology mutations fail closed", () => {
+ expect(() =>
+ coerceSchemaMutations([{ op: "add_label_dimension", dimension: "priority", values: "low" }]),
+ ).toThrow(/values must be an array of strings/);
+ expect(() =>
+ coerceSchemaMutations([
+ { op: "set_frontmatter_tier", kind: "k", field: "f", tier: "readonly" },
+ ]),
+ ).toThrow(/tier must be one of identity, system, business, user/);
+ });
+});
diff --git a/tests/core/brain/secrets/exec.test.ts b/tests/core/brain/secrets/exec.test.ts
new file mode 100644
index 00000000..740dba74
--- /dev/null
+++ b/tests/core/brain/secrets/exec.test.ts
@@ -0,0 +1,135 @@
+/**
+ * Secret exec path (t_0b134404, part 2): allowlist-gated subprocess
+ * execution with env injection and redacted output. The capability
+ * gate is the operator-declared glob allowlist; a non-matching
+ * command is refused and audited, and a command that echoes the
+ * secret back gets the value scrubbed before the caller sees it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ matchesAllowlist,
+ runWithSecret,
+ SecretExecDeniedError,
+} from "../../../../src/core/brain/secrets/exec.ts";
+import { setSecret } from "../../../../src/core/brain/secrets/store.ts";
+
+const NOW = new Date("2026-06-05T10:00:00Z");
+const CTX = { agent: "tester", now: NOW };
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-secret-exec-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("matchesAllowlist (pure)", () => {
+ test("glob star spans arguments; everything else is literal", () => {
+ expect(matchesAllowlist(["curl *"], "curl https://api.example.com")).toBe(true);
+ expect(matchesAllowlist(["curl *"], "bash -c curl")).toBe(false);
+ expect(matchesAllowlist(["echo secret-test"], "echo secret-test")).toBe(true);
+ expect(matchesAllowlist([], "anything")).toBe(false);
+ });
+
+ test("regex metacharacters in patterns stay literal", () => {
+ expect(matchesAllowlist(["node script.js"], "node scriptxjs")).toBe(false);
+ });
+});
+
+describe("runWithSecret", () => {
+ test("an allowlisted command sees the env var; output is redacted", async () => {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-redact-me-12345",
+ envVar: "MY_API_KEY",
+ allow: ["bun -e *"],
+ agent: "tester",
+ now: NOW,
+ });
+ const result = await runWithSecret(
+ vault,
+ "api-key",
+ ["bun", "-e", "console.log('key=' + process.env.MY_API_KEY)"],
+ CTX,
+ );
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).not.toContain("sk-redact-me-12345");
+ expect(result.stdout).toContain("***REDACTED***");
+ });
+
+ test("a non-matching command is refused and audited", async () => {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-redact-me-12345",
+ allow: ["curl *"],
+ agent: "tester",
+ now: NOW,
+ });
+ await expect(runWithSecret(vault, "api-key", ["bash", "-c", "env"], CTX)).rejects.toThrow(
+ SecretExecDeniedError,
+ );
+ const auditDir = join(vault, "Brain", "log", "secret-custody");
+ const lines = readdirSync(auditDir)
+ .flatMap((f) => readFileSync(join(auditDir, f), "utf8").split("\n"))
+ .filter((l) => l.trim().length > 0)
+ .map((l) => JSON.parse(l) as { action: string; ok: boolean });
+ expect(lines.some((l) => l.action === "secret_exec_denied" && l.ok === false)).toBe(true);
+ });
+
+ test("an empty allowlist denies every exec", async () => {
+ setSecret(vault, {
+ name: "locked",
+ value: "sealed-value",
+ agent: "tester",
+ now: NOW,
+ });
+ await expect(runWithSecret(vault, "locked", ["echo", "hi"], CTX)).rejects.toThrow(
+ /empty allowlist/,
+ );
+ });
+
+ test("the subprocess env is minimal - unrelated parent vars do not leak", async () => {
+ process.env["UNRELATED_PARENT_TOKEN"] = "leak-me-not";
+ try {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-redact-me-12345",
+ envVar: "MY_API_KEY",
+ allow: ["bun -e *"],
+ agent: "tester",
+ now: NOW,
+ });
+ const result = await runWithSecret(
+ vault,
+ "api-key",
+ ["bun", "-e", "console.log('leak=' + process.env.UNRELATED_PARENT_TOKEN)"],
+ CTX,
+ );
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain("leak=undefined");
+ } finally {
+ delete process.env["UNRELATED_PARENT_TOKEN"];
+ }
+ });
+
+ test("the subprocess exit code propagates", async () => {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-redact-me-12345",
+ allow: ["bun -e *"],
+ agent: "tester",
+ now: NOW,
+ });
+ const result = await runWithSecret(vault, "api-key", ["bun", "-e", "process.exit(3)"], CTX);
+ expect(result.exitCode).toBe(3);
+ });
+});
diff --git a/tests/core/brain/secrets/store.test.ts b/tests/core/brain/secrets/store.test.ts
new file mode 100644
index 00000000..88c57406
--- /dev/null
+++ b/tests/core/brain/secrets/store.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Capability-gated secret custody store (t_0b134404, part 1):
+ * per-value AES-256-GCM ciphertext under the vault-local state dir
+ * with a 0600 keyfile, set/list/rm surface that never returns
+ * plaintext, fail-closed tamper detection, and a no-values audit
+ * trail in Brain/log/secret-custody/.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ listSecrets,
+ removeSecret,
+ resolveSecretForExec,
+ setSecret,
+ secretsDir,
+} from "../../../../src/core/brain/secrets/store.ts";
+
+const NOW = new Date("2026-06-05T10:00:00Z");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-secrets-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function set(name = "embed-key", value = "sk-super-secret-value"): void {
+ setSecret(vault, {
+ name,
+ value,
+ envVar: "EMBED_API_KEY",
+ allow: ["curl *"],
+ agent: "tester",
+ now: NOW,
+ });
+}
+
+describe("setSecret / listSecrets / removeSecret", () => {
+ test("set + list round-trips metadata and never the value", () => {
+ set();
+ const secrets = listSecrets(vault);
+ expect(secrets).toHaveLength(1);
+ expect(secrets[0]).toMatchObject({
+ name: "embed-key",
+ env_var: "EMBED_API_KEY",
+ allow: ["curl *"],
+ created_at: "2026-06-05T10:00:00Z",
+ });
+ expect(JSON.stringify(secrets)).not.toContain("sk-super-secret-value");
+ });
+
+ test("the value is encrypted at rest and the keyfile is 0600", () => {
+ set();
+ const dir = secretsDir(vault);
+ const storeRaw = readFileSync(join(dir, "secrets.json"), "utf8");
+ expect(storeRaw).not.toContain("sk-super-secret-value");
+ const keyMode = statSync(join(dir, "keyfile")).mode & 0o777;
+ expect(keyMode).toBe(0o600);
+ const storeMode = statSync(join(dir, "secrets.json")).mode & 0o777;
+ expect(storeMode).toBe(0o600);
+ });
+
+ test("resolveSecretForExec decrypts; tampered ciphertext fails closed", () => {
+ set();
+ expect(resolveSecretForExec(vault, "embed-key").value).toBe("sk-super-secret-value");
+
+ const storePath = join(secretsDir(vault), "secrets.json");
+ const parsed = JSON.parse(readFileSync(storePath, "utf8")) as {
+ secrets: Record<string, { ciphertext: string }>;
+ };
+ const ct = Buffer.from(parsed.secrets["embed-key"]!.ciphertext, "base64");
+ ct[0] = ct[0]! ^ 0xff;
+ parsed.secrets["embed-key"]!.ciphertext = ct.toString("base64");
+ const { writeFileSync } = require("node:fs") as typeof import("node:fs");
+ writeFileSync(storePath, JSON.stringify(parsed));
+ expect(() => resolveSecretForExec(vault, "embed-key")).toThrow();
+ });
+
+ test("an unknown name fails with the stored names listed", () => {
+ set();
+ expect(() => resolveSecretForExec(vault, "ghost")).toThrow(/ghost.*embed-key/);
+ });
+
+ test("removeSecret deletes the entry; the value is unrecoverable", () => {
+ set();
+ expect(removeSecret(vault, "embed-key", { agent: "tester", now: NOW })).toBe(true);
+ expect(listSecrets(vault)).toHaveLength(0);
+ expect(removeSecret(vault, "embed-key", { agent: "tester", now: NOW })).toBe(false);
+ });
+
+ test("set validates the name and refuses empty values", () => {
+ expect(() =>
+ setSecret(vault, { name: "bad name!", value: "x", agent: "tester", now: NOW }),
+ ).toThrow(/name/);
+ expect(() =>
+ setSecret(vault, { name: "ok-name", value: " ", agent: "tester", now: NOW }),
+ ).toThrow(/value/);
+ });
+
+ test("every operation lands a no-values audit record", () => {
+ set();
+ resolveSecretForExec(vault, "embed-key");
+ removeSecret(vault, "embed-key", { agent: "tester", now: NOW });
+ const auditDir = join(vault, "Brain", "log", "secret-custody");
+ const files = readdirSync(auditDir);
+ expect(files.length).toBeGreaterThanOrEqual(1);
+ const lines = files
+ .flatMap((f) => readFileSync(join(auditDir, f), "utf8").split("\n"))
+ .filter((l) => l.trim().length > 0)
+ .map((l) => JSON.parse(l) as { action: string });
+ const actions = lines.map((l) => l.action);
+ expect(actions).toContain("secret_set");
+ expect(actions).toContain("secret_resolved_for_exec");
+ expect(actions).toContain("secret_removed");
+ expect(JSON.stringify(lines)).not.toContain("sk-super-secret-value");
+ });
+});
diff --git a/tests/core/brain/tier-drift.test.ts b/tests/core/brain/tier-drift.test.ts
new file mode 100644
index 00000000..32e908de
--- /dev/null
+++ b/tests/core/brain/tier-drift.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Tier drift detection (t_3f92d3f1, part 2): the indexer seeds a
+ * tiered-frontmatter snapshot per framework-kind document and, on
+ * later runs, stages a tier_drift finding when an identity field's
+ * value changed against the snapshot. The snapshot keeps the expected
+ * value, so repeated reindexes never absorb a hand-edit; system-tier
+ * fields update silently because framework writers mutate them
+ * legitimately on every pass.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("tier-drift"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+function writePref(id: string, createdAt = "2026-05-01T00:00:00Z", body = "Use spaces.\n"): void {
+ writeMd(
+ vault,
+ "Brain/preferences/pref-spaces.md",
+ `---\nkind: brain-preference\nid: ${id}\ncreated_at: ${createdAt}\ntopic: style\n---\n\n${body}`,
+ );
+}
+
+async function drift(): Promise<ReturnType<Store["listTierDrift"]>> {
+ const store = await Store.open(makeConfig({ vault, dbPath }), { mode: "read" });
+ try {
+ return store.listTierDrift();
+ } finally {
+ await store.close();
+ }
+}
+
+test("a hand-edited identity field stages drift the reindex never absorbs", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writePref("pref-spaces");
+ const first = await indexVault(config);
+ expect(first.tierDrift).toHaveLength(0);
+ expect(await drift()).toHaveLength(0);
+
+ // Hand-edit the join key.
+ writePref("pref-tabs");
+ const second = await indexVault(config);
+ expect(second.tierDrift).toEqual([
+ {
+ path: "Brain/preferences/pref-spaces.md",
+ field: "id",
+ expected: "pref-spaces",
+ actual: "pref-tabs",
+ },
+ ]);
+ const rows = await drift();
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ field: "id", expected: "pref-spaces", actual: "pref-tabs" });
+
+ // A third run with the same hand-edit still reports against the
+ // ORIGINAL expected value - the snapshot did not absorb the edit.
+ // (The body must change SIZE: the indexer's mtime+size fastpath
+ // skips same-second same-size rewrites.)
+ writePref("pref-tabs", "2026-05-01T00:00:00Z", "Use considerably more spaces!\n");
+ const third = await indexVault(config);
+ expect(third.tierDrift).toEqual([
+ {
+ path: "Brain/preferences/pref-spaces.md",
+ field: "id",
+ expected: "pref-spaces",
+ actual: "pref-tabs",
+ },
+ ]);
+});
+
+test("restoring the original value clears the drift on the next run", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writePref("pref-spaces");
+ await indexVault(config);
+ writePref("pref-tabs");
+ await indexVault(config);
+ expect(await drift()).toHaveLength(1);
+
+ writePref("pref-spaces", "2026-05-01T00:00:00Z", "Use spaces - restored by hand.\n");
+ const healed = await indexVault(config);
+ expect(healed.tierDrift).toHaveLength(0);
+ expect(await drift()).toHaveLength(0);
+});
+
+test("deleting an identity field stages drift with a null actual", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writePref("pref-spaces");
+ await indexVault(config);
+ writeMd(
+ vault,
+ "Brain/preferences/pref-spaces.md",
+ "---\nkind: brain-preference\ncreated_at: 2026-05-01T00:00:00Z\ntopic: style\n---\n\nNo id anymore.\n",
+ );
+ const stats = await indexVault(config);
+ expect(stats.tierDrift).toEqual([
+ {
+ path: "Brain/preferences/pref-spaces.md",
+ field: "id",
+ expected: "pref-spaces",
+ actual: null,
+ },
+ ]);
+});
+
+test("system-tier changes update the snapshot without staging drift", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writePref("pref-spaces", "2026-05-01T00:00:00Z");
+ await indexVault(config);
+ writePref("pref-spaces", "2026-06-01T12:00:00Z", "Use spaces, refreshed by the framework.\n");
+ const stats = await indexVault(config);
+ expect(stats.tierDrift).toHaveLength(0);
+ expect(await drift()).toHaveLength(0);
+});
+
+test("unknown kinds never seed snapshots or drift", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writeMd(vault, "notes/list.md", "---\nkind: shopping-list\nid: original\n---\n\nMilk.\n");
+ await indexVault(config);
+ writeMd(vault, "notes/list.md", "---\nkind: shopping-list\nid: changed\n---\n\nMilk.\n");
+ const stats = await indexVault(config);
+ expect(stats.tierDrift).toHaveLength(0);
+ expect(await drift()).toHaveLength(0);
+});
+
+test("deleting the document drops its drift rows", async () => {
+ const config = makeConfig({ vault, dbPath });
+ writePref("pref-spaces");
+ await indexVault(config);
+ writePref("pref-tabs");
+ await indexVault(config);
+ expect(await drift()).toHaveLength(1);
+
+ const { rmSync } = await import("node:fs");
+ rmSync(join(vault, "Brain", "preferences", "pref-spaces.md"));
+ await indexVault(config);
+ expect(await drift()).toHaveLength(0);
+});
diff --git a/tests/core/search/link-constraints.test.ts b/tests/core/search/link-constraints.test.ts
new file mode 100644
index 00000000..754239c1
--- /dev/null
+++ b/tests/core/search/link-constraints.test.ts
@@ -0,0 +1,163 @@
+/**
+ * Link-type endpoint constraints (t_15453235): the schema pack's
+ * `link_constraints` field declares allowed (source_type, target_type)
+ * pairs per link type; the indexer's materialization post-pass marks
+ * violating typed edges blocked - they fall back to plain untyped
+ * links instead of participating in typed-relation recall - and the
+ * flags recompute from the current pack on every index run, so
+ * removing a constraint restores the edges without touching files.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { writeFileSync, mkdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { buildSchemaLint } from "../../../src/core/brain/schema-admin.ts";
+import { linkConstraintAllows } from "../../../src/core/search/link-constraints.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+const CONSTRAINTS = Object.freeze({
+ depends_on: Object.freeze(["preference->preference"]),
+});
+
+describe("linkConstraintAllows (pure)", () => {
+ test("a relation without declared constraints is always allowed", () => {
+ expect(linkConstraintAllows(CONSTRAINTS, "related", "preference", "receipt")).toBe(true);
+ });
+
+ test("a declared pair allows; an undeclared pair blocks", () => {
+ expect(linkConstraintAllows(CONSTRAINTS, "depends_on", "preference", "preference")).toBe(true);
+ expect(linkConstraintAllows(CONSTRAINTS, "depends_on", "preference", "receipt")).toBe(false);
+ });
+
+ test("a missing endpoint type cannot be evaluated - allowed", () => {
+ expect(linkConstraintAllows(CONSTRAINTS, "depends_on", null, "receipt")).toBe(true);
+ expect(linkConstraintAllows(CONSTRAINTS, "depends_on", "preference", null)).toBe(true);
+ });
+});
+
+describe("indexer materialization post-pass", () => {
+ let vault: string;
+ let dbPath: string;
+ let cleanup: () => void;
+
+ beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("link-constraints"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ function writeSchema(withConstraint: boolean): void {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ [
+ "schema_version: 1",
+ "schema:",
+ " page_types: [preference, receipt]",
+ " link_types:",
+ " - depends_on",
+ ...(withConstraint
+ ? [" link_constraints:", " - depends_on=preference->preference"]
+ : []),
+ ].join("\n") + "\n",
+ );
+ }
+
+ function writeNotes(): void {
+ writeMd(
+ vault,
+ "notes/pref-a.md",
+ '---\ntype: preference\ndepends_on: "[[notes/receipt-b]]"\nrelated: "[[notes/pref-c]]"\n---\n\n# A\n\nbody\n',
+ );
+ writeMd(vault, "notes/receipt-b.md", "---\ntype: receipt\n---\n\n# B\n\nbody\n");
+ writeMd(vault, "notes/pref-c.md", "---\ntype: preference\n---\n\n# C\n\nbody\n");
+ }
+
+ test("a violating edge is blocked, a conforming edge stays typed", async () => {
+ writeSchema(true);
+ writeNotes();
+ const config = makeConfig({ vault, dbPath });
+ const stats = await indexVault(config);
+ expect(stats.relationViolations).toHaveLength(1);
+ expect(stats.relationViolations[0]).toMatchObject({
+ relation: "depends_on",
+ sourcePath: "notes/pref-a.md",
+ sourceType: "preference",
+ targetType: "receipt",
+ });
+
+ const store = await Store.open(config, { mode: "read" });
+ try {
+ const docId = store.getDocumentIdByPath("notes/pref-a.md")!;
+ const typed = store.typedRelationsForDocuments([docId]).get(docId) ?? [];
+ const relations = typed.map((t) => t.relation);
+ expect(relations).not.toContain("depends_on");
+ expect(relations).toContain("related");
+ } finally {
+ store.close();
+ }
+ });
+
+ test("without constraints the typed edges are identical to today", async () => {
+ writeSchema(false);
+ writeNotes();
+ const config = makeConfig({ vault, dbPath });
+ const stats = await indexVault(config);
+ expect(stats.relationViolations).toHaveLength(0);
+ const store = await Store.open(config, { mode: "read" });
+ try {
+ const docId = store.getDocumentIdByPath("notes/pref-a.md")!;
+ const typed = store.typedRelationsForDocuments([docId]).get(docId) ?? [];
+ expect(typed.map((t) => t.relation).toSorted()).toEqual(["depends_on", "related"]);
+ } finally {
+ store.close();
+ }
+ });
+
+ test("removing the constraint restores the edge on the next index run", async () => {
+ writeSchema(true);
+ writeNotes();
+ const config = makeConfig({ vault, dbPath });
+ await indexVault(config);
+
+ writeSchema(false);
+ const stats = await indexVault(config);
+ expect(stats.relationViolations).toHaveLength(0);
+ const store = await Store.open(config, { mode: "read" });
+ try {
+ const docId = store.getDocumentIdByPath("notes/pref-a.md")!;
+ const typed = store.typedRelationsForDocuments([docId]).get(docId) ?? [];
+ expect(typed.map((t) => t.relation).toSorted()).toEqual(["depends_on", "related"]);
+ } finally {
+ store.close();
+ }
+ });
+
+ test("schema lint surfaces blocked edges with the declared pairs", async () => {
+ writeSchema(true);
+ writeNotes();
+ const config = makeConfig({ vault, dbPath });
+ await indexVault(config);
+
+ const lint = buildSchemaLint(vault, { dbPath });
+ const violation = lint.findings.find((f) => f.kind === "link-constraint-violation");
+ expect(violation).toBeDefined();
+ expect(violation).toMatchObject({
+ relation: "depends_on",
+ source: "notes/pref-a.md",
+ source_type: "preference",
+ target_type: "receipt",
+ });
+ });
+
+ test("lint without an index file stays silent on constraints", () => {
+ writeSchema(true);
+ const lint = buildSchemaLint(vault, { dbPath: join(vault, "missing.sqlite") });
+ expect(lint.findings.filter((f) => f.kind === "link-constraint-violation")).toHaveLength(0);
+ });
+});
diff --git a/tests/e2e/write-time-governance.integration.test.ts b/tests/e2e/write-time-governance.integration.test.ts
new file mode 100644
index 00000000..4d49405d
--- /dev/null
+++ b/tests/e2e/write-time-governance.integration.test.ts
@@ -0,0 +1,184 @@
+/**
+ * Write-Time Integrity & Governance Suite - end-to-end integration
+ * over one vault: ontology declaration through schema mutations
+ * (Task 1), label assignment + filterable recall (t_7a41f42d), a
+ * constraint-violating typed edge blocked at materialization
+ * (t_15453235), attribute validation teaching the vocabulary
+ * (t_f5633190), a hand-edited identity key detected and restored
+ * (t_3f92d3f1), secret custody with redacted exec (t_0b134404), and
+ * the lease-guarded maintenance lane (t_166d1226).
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { applySchemaMutations } from "../../src/core/brain/schema-mutate.ts";
+import { loadSchemaPack } from "../../src/core/brain/schema-pack.ts";
+import { assignNoteLabel } from "../../src/core/brain/labels.ts";
+import { assignNoteAttribute, AttributeVocabularyError } from "../../src/core/brain/attributes.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { runWithSecret } from "../../src/core/brain/secrets/exec.ts";
+import { setSecret } from "../../src/core/brain/secrets/store.ts";
+import { runMaintenance } from "../../src/core/brain/maintenance/lane.ts";
+import { listJournal } from "../../src/core/brain/maintenance/journal.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { search } from "../../src/core/search/search.ts";
+import { Store } from "../../src/core/search/store.ts";
+import { makeConfig } from "../helpers/search-fixtures.ts";
+
+const NOW = new Date("2026-06-05T03:00:00Z");
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-wtig-e2e-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-wtig-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+test("the suite composes end to end on one vault", async () => {
+ // -- 1. Declare the ontology through audited schema mutations --------
+ await applySchemaMutations(
+ vault,
+ [
+ { op: "add_type", category: "page_types", token: "paper" },
+ { op: "add_type", category: "page_types", token: "receipt" },
+ { op: "add_link_type", token: "depends_on" },
+ { op: "add_label_dimension", dimension: "priority", values: ["low", "high"] },
+ { op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "paper" },
+ {
+ op: "set_attribute_field",
+ type: "paper",
+ field: "status",
+ description: "reading status, e.g. queued or finished",
+ },
+ ],
+ { actor: "e2e", now: NOW },
+ );
+ const pack = loadSchemaPack(vault);
+ expect(pack.labels["priority"]).toEqual(["low", "high"]);
+
+ // -- 2. Notes: one conforming edge, one violating, one hand-edit bait --
+ writeFileSync(
+ join(vault, "notes-a.md"),
+ '---\ntype: paper\ndepends_on: "[[notes-b]]"\nrelated: "[[notes-c]]"\n---\n\n# A\n\nGovernance pilot note.\n',
+ );
+ writeFileSync(join(vault, "notes-b.md"), "---\ntype: receipt\n---\n\n# B\n\nA receipt.\n");
+ writeFileSync(join(vault, "notes-c.md"), "---\ntype: paper\n---\n\n# C\n\nCompanion paper.\n");
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-canary.md"),
+ "---\nkind: brain-preference\nid: pref-canary\ncreated_at: 2026-05-01T00:00:00Z\ntopic: deploys\n---\n\nCanary first.\n",
+ );
+
+ // -- 3. Labels: validated assignment, filterable recall ----------------
+ assignNoteLabel(vault, "notes-a.md", {
+ dimension: "priority",
+ value: "high",
+ pack,
+ agent: "e2e",
+ now: NOW,
+ });
+
+ const dbPath = join(vault, ".open-second-brain", "brain.sqlite");
+ const config = makeConfig({ vault, dbPath });
+ const first = await indexVault(config);
+
+ // -- 4. Link constraint: paper->receipt blocked, paper->paper typed ----
+ expect(first.relationViolations).toHaveLength(1);
+ expect(first.relationViolations[0]).toMatchObject({
+ relation: "depends_on",
+ sourceType: "paper",
+ targetType: "receipt",
+ });
+
+ const labeled = await search(config, {
+ query: "governance pilot",
+ properties: new Map([["labels", ["priority/high"]]]),
+ });
+ expect(labeled.results.some((r) => r.path === "notes-a.md")).toBe(true);
+
+ // -- 5. Attributes: the error teaches the vocabulary -------------------
+ expect(() =>
+ assignNoteAttribute(vault, "notes-a.md", { field: "rating", value: "5", pack }),
+ ).toThrow(AttributeVocabularyError);
+ const attr = assignNoteAttribute(vault, "notes-a.md", {
+ field: "status",
+ value: "queued",
+ pack,
+ });
+ expect(attr.attributes).toEqual(["status=queued"]);
+
+ // -- 6. Tier drift: hand-edit the join key, detect, restore ------------
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-canary.md"),
+ "---\nkind: brain-preference\nid: pref-mangled\ncreated_at: 2026-05-01T00:00:00Z\ntopic: deploys\n---\n\nCanary first, edited by hand.\n",
+ );
+ const second = await indexVault(config);
+ expect(second.tierDrift).toEqual([
+ {
+ path: "Brain/preferences/pref-canary.md",
+ field: "id",
+ expected: "pref-canary",
+ actual: "pref-mangled",
+ },
+ ]);
+ const store = await Store.open(config, { mode: "write" });
+ try {
+ const docId = store.getDocumentIdByPath("Brain/preferences/pref-canary.md")!;
+ const drift = store.listTierDrift().find((r) => r.documentId === docId)!;
+ expect(drift.expected).toBe("pref-canary");
+ store.clearTierDrift(docId, "id");
+ } finally {
+ await store.close();
+ }
+
+ // -- 7. Secret custody: redacted exec under the allowlist --------------
+ setSecret(vault, {
+ name: "deploy-token",
+ value: "tok-e2e-secret-31337",
+ allow: ["bun -e *"],
+ agent: "e2e",
+ now: NOW,
+ });
+ const exec = await runWithSecret(
+ vault,
+ "deploy-token",
+ ["bun", "-e", "console.log('t=' + process.env.DEPLOY_TOKEN)"],
+ { agent: "e2e", now: NOW },
+ );
+ expect(exec.exitCode).toBe(0);
+ expect(exec.stdout).not.toContain("tok-e2e-secret-31337");
+ const storeRaw = readFileSync(
+ join(vault, ".open-second-brain", "secrets", "secrets.json"),
+ "utf8",
+ );
+ expect(storeRaw).not.toContain("tok-e2e-secret-31337");
+
+ // -- 8. Maintenance lane: gated, leased, journaled ----------------------
+ const lane = await runMaintenance(vault, {
+ now: NOW,
+ holder: "e2e@1",
+ tasks: [
+ {
+ name: "reindex",
+ run: async () => {
+ await indexVault(config);
+ },
+ },
+ ],
+ });
+ expect(lane.verdict).toBe("run");
+ expect(lane.tasks[0]!.ok).toBe(true);
+ expect(listJournal(vault).some((e) => e.task === "reindex" && e.ok === true)).toBe(true);
+});
diff --git a/tests/mcp/brain-governance.test.ts b/tests/mcp/brain-governance.test.ts
new file mode 100644
index 00000000..e61ec60d
--- /dev/null
+++ b/tests/mcp/brain-governance.test.ts
@@ -0,0 +1,173 @@
+/**
+ * Write-Time Integrity & Governance Suite MCP tools: brain_labels
+ * (fail-closed vocabulary classification), brain_tiers (staged
+ * identity-drift repair), brain_secrets (list metadata / allowlisted
+ * run, never values), brain_maintenance (gated lane run/status).
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { setSecret } from "../../src/core/brain/secrets/store.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-gov-"));
+ vault = join(tmp, "vault");
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-gov-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const key of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ ]) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "gov-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function call(
+ server: MCPServer,
+ tool: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const res = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 99,
+ method: "tools/call",
+ params: { name: tool, arguments: args },
+ })) as { result?: { content?: Array<{ text?: string }> }; error?: { message: string } };
+ if (res.error !== undefined) throw new Error(res.error.message);
+ return JSON.parse(res.result!.content![0]!.text!) as Record<string, unknown>;
+}
+
+test("brain_labels assigns within the vocabulary and fails closed outside it", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ ["schema_version: 1", "schema:", " labels:", " - priority=low", " - priority=high"].join(
+ "\n",
+ ) + "\n",
+ );
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(join(vault, "notes", "rollout.md"), "# Rollout\n\nCanary first.\n");
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+
+ const assigned = await call(server, "brain_labels", {
+ operation: "assign",
+ path: "notes/rollout.md",
+ dimension: "priority",
+ value: "high",
+ });
+ expect(assigned["labels"]).toEqual(["priority/high"]);
+
+ const shown = await call(server, "brain_labels", {
+ operation: "show",
+ path: "notes/rollout.md",
+ });
+ expect(shown["labels"]).toEqual(["priority/high"]);
+
+ await expect(
+ call(server, "brain_labels", {
+ operation: "assign",
+ path: "notes/rollout.md",
+ dimension: "priority",
+ value: "urgent",
+ }),
+ ).rejects.toThrow(/allowed values: low, high/);
+});
+
+test("brain_tiers check is empty on a fresh vault; restore demands apply", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const checked = await call(server, "brain_tiers", { operation: "check" });
+ expect(checked["findings"]).toEqual([]);
+ await expect(
+ call(server, "brain_tiers", { operation: "restore", path: "Brain/x.md" }),
+ ).rejects.toThrow(/apply=true/);
+});
+
+test("brain_secrets lists metadata only and refuses a non-allowlisted run", async () => {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-mcp-secret-777",
+ allow: ["bun -e *"],
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+
+ const listed = await call(server, "brain_secrets", { operation: "list" });
+ expect(JSON.stringify(listed)).not.toContain("sk-mcp-secret-777");
+ expect((listed["secrets"] as Array<{ name: string }>)[0]!.name).toBe("api-key");
+
+ await expect(
+ call(server, "brain_secrets", {
+ operation: "run",
+ name: "api-key",
+ command: ["bash", "-c", "env"],
+ }),
+ ).rejects.toThrow(/allowlist/);
+
+ const ran = await call(server, "brain_secrets", {
+ operation: "run",
+ name: "api-key",
+ command: ["bun", "-e", "console.log('v=' + process.env.API_KEY)"],
+ });
+ expect(ran["exit_code"]).toBe(0);
+ expect(String(ran["stdout"])).not.toContain("sk-mcp-secret-777");
+});
+
+test("brain_maintenance run executes the lane; status reads the journal", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const ran = await call(server, "brain_maintenance", { operation: "run" });
+ expect(ran["verdict"]).toBe("run");
+ expect((ran["tasks"] as Array<{ ok: boolean }>).every((t) => t.ok)).toBe(true);
+
+ const status = await call(server, "brain_maintenance", { operation: "status" });
+ expect(status["lease"]).toBeNull();
+ expect((status["journal"] as unknown[]).length).toBeGreaterThanOrEqual(2);
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 475a5a86..81d07926 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -261,6 +261,11 @@ describe("tool listing", () => {
"brain_truth",
"brain_dead_ends",
"brain_foresight",
+ // Write-Time Integrity & Governance Suite.
+ "brain_labels",
+ "brain_tiers",
+ "brain_secrets",
+ "brain_maintenance",
// Agent Write Contract Suite: provider-agnostic write sessions.
"brain_write_session",
].toSorted(),
@@ -517,7 +522,9 @@ describe("stdio loop", () => {
// + brain_write_session (Agent Write Contract Suite) = 66.
// + brain_truth / brain_dead_ends / brain_foresight
// (Entity Truth & Self-Improving Dream Suite) = 69.
- expect(list.result.tools.length).toBe(69);
+ // + brain_labels / brain_tiers / brain_secrets / brain_maintenance
+ // (Write-Time Integrity & Governance Suite) = 73.
+ expect(list.result.tools.length).toBe(73);
});
test("returns parse error for invalid JSON", async () => {