Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
v0.10.16: trust and operator surfaces - verification, verdict, dashboard (#32)
Sol Aitken3b7dfe98fce9
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 2c0dc021..a3825e5f 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.15",+ "version": "0.10.16","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex e0a625bd..4c1fd755 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.15",+ "version": "0.10.16","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d6c36a7a..d12cbd32 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,135 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.10.16] - 2026-05-25++Trust and operator surfaces: eight related self-reporting features+ship together under the theme "trust the brain's self-reporting".+A new `src/core/brain/trust/` subsystem holds pure helpers that+compute verification deltas, an aggregate trust verdict, a+language-agnostic preference quality gate, role-permission+boundaries, a self-approval guardrail, and instruction-file+compliance warnings. One new MCP tool (`brain_operator_summary`)+plus one new CLI verb (`o2b brain summary`) aggregate doctor,+dream, and vault metadata into a single operator dashboard.++### Added++- `src/core/brain/trust/role.ts` - `BRAIN_ROLES` (`writer`,+ `dreamer`, `applier`, `unknown`) and `BRAIN_OPERATIONS` enums.+ Atom for the role-permission gate.+- `src/core/brain/trust/check-role-permission.ts` -+ `checkRolePermission(role, op, currentStatus?)`. Static+ allow-list per role; rejects cross-role attempts with a+ structured reason.+- `src/core/brain/trust/assess-rule-quality.ts` -+ `assessRuleQuality(principle)`. **Language-agnostic** structural+ detector. No vocabulary list, no stopword set, no unit+ dictionary; only codepoint shape (Unicode `\p{L}` / `\p{N}`,+ digit / operator presence, single-character token ratio).+ Surfaces as a quality gate at `brain_feedback` time.+- `src/core/brain/trust/self-approval-guardrail.ts` -+ `applySelfApprovalGuardrail({signal_count, distinct_agents,+ age_days}, config)`. Promotes only when all three thresholds+ pass; quarantines otherwise. Defaults+ (`promotion_min_signals: 2`, `promotion_min_distinct_agents: 1`,+ `promotion_min_age_days: 0`) keep pre-v0.10.16 dream behaviour+ bit-identical.+- `src/core/brain/trust/compute-verification-delta.ts` -+ `computeVerificationDelta(vault, dream)`. Classifies each+ preference id cited by a dream summary into one of `confirmed`,+ `drift`, `regression`, `missing_evidence`. Pure read-only;+ emits vault-relative paths only.+- `src/core/brain/trust/instruction-file-ceiling.ts` -+ `checkInstructionFileCeiling(vault, { maxLines })`. Warns when+ any tracked vault-root instruction file (`CLAUDE.md`,+ `AGENTS.md`, `GEMINI.md`) exceeds the configured ceiling.+- `src/core/brain/trust/compute-trust-verdict.ts` -+ `computeTrustVerdict({ doctorWarnings, doctorErrors,+ dreamWarnings, verification, driftWatchThreshold? })`. Returns+ one of `clean`, `watch`, `investigate`.+- `src/core/brain/trust/operator-summary.ts` -+ `buildOperatorSummary(vault, opts)` and+ `renderOperatorSummaryMarkdown(summary)`. One read-only call+ that aggregates doctor, dream, verification, instruction-file+ warnings, and ranked maintenance actions into a single+ envelope.+- `BRAIN_GUARDRAIL_DEFAULTS` and `resolveGuardrails(cfg)` in+ `policy.ts`. Backward-compatible defaults; an explicit+ `guardrails:` block in `_brain.yaml` overrides any subset.+- `DreamRunSummary.uncertain: ReadonlyArray<DreamUncertainEntry>`+ and `DreamRunSummary.quarantined:+ ReadonlyArray<DreamQuarantinedEntry>` (empty on every clean run).+- `RunDoctorResult.trust_verdict` (always populated),+ `RunDoctorResult.verification_delta_summary` (present when a+ dream summary is threaded through), `RunDoctorResult.+ instruction_file_warnings`, and `RunDoctorResult.uncertain`.+- `DigestJson.trust_verdict?`, `DigestJson.uncertain_count`,+ `DigestJson.quarantined_count`. Markdown digest gains a `##+ Trust` section when doctor or dream input is supplied.+- `brain_operator_summary` MCP tool in the full scope. Returns+ the structured envelope from `buildOperatorSummary`.+- `o2b brain summary [--skip-dream] [--top-actions <n>]+ [--vault <path>] [--json]` CLI verb. Markdown by default, JSON+ on demand.+- `BrainRolePermissionError` thrown by+ `appendApplyEvidence(vault, input, { role })` when the role is+ not permitted.++### Changed++- `brain_feedback` rejects structurally-broken principles+ (empty, single token) via `assessRuleQuality`. Warn-level+ findings (too-long, no-measurable-signal, filler) are+ advisory and do not block submission.+- `brain_dream` invokes `applySelfApprovalGuardrail` before+ creating a new unconfirmed preference. Clusters that pass+ `candidate_threshold` but fail a guardrail threshold land in+ `quarantined`; the contributing signals stay in `inbox/` so the+ cluster naturally re-evaluates on the next pass. With default+ guardrails this never fires (all defaults at or below the+ existing thresholds), so existing tests stay green.+- `brain_dream` MCP wrapper surfaces `uncertain[]`,+ `quarantined[]`, and `suppressed[]` arrays.+- `brain_doctor` always populates `trust_verdict` (computed from+ doctor warnings/errors plus the verification delta when+ available) and `instruction_file_warnings`. The MCP wrapper+ emits both.+- `brain_apply_evidence` MCP wrapper asserts `applier` role at+ the boundary; rejects calls from other roles with a structured+ error.+- `BrainConfig.guardrails?: BrainGuardrailConfig` (new optional+ block in `_brain.yaml`). Validates each subfield as a positive+ integer (`promotion_min_age_days` allows zero); rejects values+ above the hard `INSTRUCTION_FILE_MAX_LINES_CEILING` of 10000.+- `brain_digest` accepts optional `doctorResult` and+ `dreamSummary` in `RenderDigestOptions`. When neither is+ supplied, output stays bit-identical to v0.10.15.++### Notes++- The trust subsystem follows the v0.10.15 precedent+ (`page-meta/`, `maintenance/`): atoms (field additions on+ existing summary types) -> helpers (pure functions in+ `trust/`) -> consumers (existing brain tools call into helpers+ but keep their public contract).+- The preference quality gate is **shape-based only**. The+ detector reads codepoints, never vocabulary. A vague rule+ expressed in one language and the same rule expressed in+ another language are treated identically by construction.+- No on-disk migration. Existing preference and retired pages+ stay byte-identical; readers fall back to documented defaults+ when the new fields are absent.+- `brain_operator_summary` is registered in the full MCP scope+ only. The always-loaded writer scope keeps its four-tool+ surface (`brain_feedback`, `brain_apply_evidence`,+ `brain_note`, `brain_context`).+- Role enforcement is incremental in v0.10.16: enforced on+ `brain_apply_evidence` at the MCP boundary. Future releases+ may thread the role check through writer-side calls+ (`writeSignal`, `writePreference`).+- 2135 tests pass; typecheck and sync-version clean.+## [0.10.15] - 2026-05-25Vault care bundle: eight related upstream-inspired metadata and@@ -2424,6 +2553,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1[0.9.0]: https://github.com/itechmeat/open-second-brain/compare/v0.8.1...v0.9.0+[0.10.16]: https://github.com/itechmeat/open-second-brain/compare/v0.10.15...v0.10.16[0.10.15]: https://github.com/itechmeat/open-second-brain/compare/v0.10.14...v0.10.15[0.10.14]: https://github.com/itechmeat/open-second-brain/compare/v0.10.13...v0.10.14[0.10.13]: https://github.com/itechmeat/open-second-brain/compare/v0.10.12...v0.10.13diff --git a/README.md b/README.mdindex 8e5b95a2..780c10ce 100644--- a/README.md+++ b/README.md@@ -84,6 +84,12 @@ safety invariants are in [`docs/how-it-works.md`](docs/how-it-works.md).(`o2b brain context-pack --max-tokens N`). Per-page metadata(`_lifecycle`, `tier`, `merged_into`) feeds the ranker and thesearch relevance signal.+- Aggregates an operator dashboard from trust verdict, doctor /+ dream counts, verification delta, instruction-file ceiling+ warnings, and top maintenance actions+ (`o2b brain summary` / `brain_operator_summary`). The verdict+ band (`clean | watch | investigate`) is computed from+ structural signals only - no LLM, no per-language vocabulary.- (Optional) Records paid agent actions through **Pay Memory**:receipts, generated assets, spending policy decisions, humanapproval state, and per-day reports — all as plain Markdown@@ -198,10 +204,11 @@ exposes the same deterministic operations as MCP tools:- **Core (3):** `second_brain_status`, `second_brain_query`,`vault_health`.-- **Brain (9):** `brain_feedback`, `brain_dream`,+- **Brain (11):** `brain_feedback`, `brain_dream`,`brain_apply_evidence`, `brain_note`, `brain_context`,- `brain_digest`, `brain_query`, `brain_doctor`, `brain_backlinks`.- See the [Brain section](#brain-observing-memory) below.+ `brain_digest`, `brain_query`, `brain_doctor`, `brain_backlinks`,+ `brain_context_pack`, `brain_operator_summary`. See the+ [Brain section](#brain-observing-memory) below.- **Pay Memory (8):** `payment_memory_init`,`payment_receipt_append`, `asset_capture`,`payment_report_generate`, `payment_policy_check`,diff --git a/docs/brainstorm/trust-operator-surfaces/cli-output/claude.md b/docs/brainstorm/trust-operator-surfaces/cli-output/claude.mdnew file mode 100644index 00000000..c2f729db--- /dev/null+++ b/docs/brainstorm/trust-operator-surfaces/cli-output/claude.md@@ -0,0 +1,40 @@+### Variant 1: Flat layered expansion, no new MCP tool+- **Approach**: Drop each feature as a peer module in its matching layer (atoms next to existing atoms, helpers next to existing helpers), and extend `brain_doctor` / `brain_dream` / `brain_digest` / `brain_feedback` in-place with new fields. The operator dashboard becomes an extension of `DigestJson` (new `trust_verdict`, `uncertain_count`, `quarantined_count`, `verification_delta_summary` fields), not a new tool. No new directory; eight features land as ~8 small peer modules across existing folders.+- **Trade-offs**:+ - Pro: smallest surface-area delta, mirrors v0.10.14 / v0.10.10 style (extend, don't add tools).+ - Pro: each feature stays independently testable; bundle = sum of parts.+ - Pro: lowest risk of cross-feature coupling regressions.+ - Con: the "trust the brain's self-reporting" theme is invisible at the file-tree level — eight tiny additions sprinkled across `src/core/brain/`.+ - Con: dashboard via field-expansion of `DigestJson` makes that type wider and less focused; operators must still mentally compose multiple sections.+ - Con: no single import path that a future contributor can point at as "the trust layer".+- **Complexity**: medium+- **Risk**: low++### Variant 2: New `trust/` subsystem with one new consumer tool+- **Approach**: Introduce `src/core/brain/trust/` housing the new helpers (`compute-verification-delta.ts`, `compute-trust-verdict.ts`, `assess-rule-quality.ts`, `check-role-permission.ts`, `instruction-file-ceiling.ts`, `self-approval-guardrail.ts`), each a pure function over atoms. Atoms (uncertainty arrays, verdict field, promotion config) still land on the existing summary types, but everything that *computes* them lives in `trust/`. Add one new MCP tool `brain_operator_summary` as the aggregating consumer; existing tools import the helpers but keep their current shape and contracts.+- **Trade-offs**:+ - Pro: follows v0.10.15 precedent (`page-meta/`, `maintenance/` subdirs) — gives the release a coherent identity and a single grep target.+ - Pro: helpers are pure, so cross-feature interaction is forced through typed function boundaries instead of ad-hoc field reads.+ - Pro: dashboard tool can iterate independently without re-shaping `DigestJson`; `brain_digest` stays small and digestible.+ - Pro: tests mirror cleanly under `tests/core/brain/trust/`.+ - Con: requires choosing a subsystem name now; "trust" may age poorly if scope drifts.+ - Con: one extra MCP tool to document, version, and keep aligned with `brain_digest` (overlap risk).+ - Con: slightly more upfront design than Variant 1 — need to define the trust-layer's read-only contract against atoms.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Capability-kernel refactor around writes+- **Approach**: Make role-separated permissions (#8) the keystone — introduce a `BrainCapability` kernel that intercepts every brain write (`brain_feedback`, `brain_dream`, `brain_apply_evidence`), and rebuild the other seven features as policies hanging off that kernel (quality gate as a pre-write policy, self-approval guardrail as a promotion policy, verification delta as a post-write policy, etc.). Existing handlers in `src/mcp/brain-tools.ts` get rewritten to flow through the kernel.+- **Trade-offs**:+ - Pro: structurally enforces #8 — role boundaries can't be bypassed because the kernel mediates every write.+ - Pro: future brain tools inherit role separation, quality gates, and verification for free.+ - Pro: the cleanest long-term mental model — one seam, many policies.+ - Con: violates the project's "extend without rewriting" rule and "no backwards-compat shims" posture — `brain-tools.ts` handlers get re-shaped.+ - Con: largest blast radius across 1865+ tests; bundling a refactor with eight features in one release inflates review surface and CHANGELOG scope.+ - Con: kernel design is the kind of premature abstraction the layered-DAG convention exists to prevent; v0.10.15 explicitly chose peer modules over a kernel.+ - Con: high risk that one of the eight features stalls and blocks the other seven because they share a critical-path module.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 2+**Rationale**: Variant 2 fits the established v0.10.15 precedent (a named subdirectory of pure helpers per release) and gives the eight-feature bundle the coherent identity its theme demands, without the rewriting risk of Variant 3 or the file-tree invisibility of Variant 1. Atoms remain field-additions on existing summaries (satisfying "extend without rewriting"), helpers are pure and independently testable, and one new consumer tool (`brain_operator_summary`) cleanly absorbs the dashboard role so `brain_digest` stays focused. It preserves the layered DAG rule while making the release legible as a single architectural move.diff --git a/docs/brainstorm/trust-operator-surfaces/cli-output/prompt.md b/docs/brainstorm/trust-operator-surfaces/cli-output/prompt.mdnew file mode 100644index 00000000..e28c297f--- /dev/null+++ b/docs/brainstorm/trust-operator-surfaces/cli-output/prompt.md@@ -0,0 +1,191 @@+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++Ship eight related features as one Open Second Brain release under the+theme "trust the brain's self-reporting". The bundle extends the+existing `brain_doctor`, `brain_digest`, `brain_dream`, and+`brain_feedback` surfaces (and the daily JSONL log) without rewriting+them. The eight kanban tasks:++1. **Verification delta** (`t_e952d03a`) - an independent layer that+ compares dream-pass outcomes (or `brain_apply_evidence` results)+ against actual vault state with explicit verdicts: `confirmed`+ (preference applied correctly), `drift` (preference exists but+ deviates from intent), `regression` (preference was applied but+ later undone), `missing_evidence` (claimed preference has no+ supporting artifact). Today `brain_dream` and `brain_doctor` warn+ on bad state but no independent verification step exists.+ Codegraph hints: `src/core/brain/dream.ts:91`+ (`DreamWarning`), `src/core/brain/dream.ts:191` (`dream` returns+ `DreamRunSummary` with `new_unconfirmed/confirmed/retired/+ suppressed/warnings` arrays but no verification states),+ `src/core/brain/claude-memory-plan.ts:22` (manifest-level+ sha256 verification, file-level only).++2. **Trust report** (`t_3440fa2c`) - a vault-level health verdict:+ `clean` (no contradictions, dream pass clean, no broken pages),+ `watch` (some contradictions, non-primary dream runs, minor+ frontmatter issues), `investigate` (corrupted files, duplicate+ IDs, unresolved contradictions). Compresses many signals into one+ verdict without hiding their breakdown.+ Today `brain_doctor` returns `RunDoctorResult` with severity+ `warning`/`error` but no aggregate verdict.++3. **Operator dashboard** (`t_dd9a602e`) - one unified report+ aggregating dream results, preference status distribution,+ contradiction count, signal quality metrics, recent log events,+ trust verdict (from #2), top-N suggested actions (from v0.10.15+ action-scorer), and basic vault stats. Replaces the current+ pattern of running `brain_digest` + `brain_doctor` separately.+ Codegraph hints: `src/mcp/brain-tools.ts` (each tool is a separate+ handler today), `src/core/brain/digest.ts:236` (`DigestJson`),+ `src/core/brain/doctor.ts:99` (`RunDoctorResult`).++4. **Uncertainty surfacing** (`t_87acf4a2`) - brain operations+ (dream, doctor, digest) must surface "I tried but cannot+ confirm" cases as explicit `uncertain` entries rather than+ silently dropping. Extend `DreamRunSummary` with an `uncertain`+ list; extend `DoctorReport` similarly.++5. **Preference rule quality gate** (`t_dec0494f`) - reject vague,+ non-testable principles at `brain_feedback` time. The detector+ must be language-agnostic - no hardcoded vague-word lists in any+ specific language. Use structural heuristics: principle length,+ absence of imperative verbs (detected by token-shape, not by+ vocabulary), absence of measurable nouns/numbers, ratio of+ modal/hedge tokens, missing observable outcome.+ Codegraph hints: `src/core/brain/sessions/validate-feedback.ts`+ (`validateBrainFeedbackInput` validates structure but not+ semantic quality).++6. **Instruction file compliance ceiling** (`t_2c01f589`) - cap+ `CLAUDE.md` / `AGENTS.md` / `GEMINI.md` / vault-root instruction+ files at ~200 lines. Past this, compliance drops sharply.+ Surface as a `brain_doctor` warning when a tracked instruction+ file exceeds the ceiling, with a configurable threshold.+ Codegraph hints: `src/core/brain/sessions/claude.ts:28`+ (`ClaudeBlock`), `src/core/brain/policy.ts:958` (`splitLines`).++7. **Dreamer self-approval guardrail** (`t_0a364afc`) - the dream+ pass must not auto-promote a signal to `confirmed` based on its+ own clustering alone. Require a configurable evidence threshold+ (minimum signal count, cross-agent corroboration, time-weighted+ recurrence) before promotion; signals below threshold land in+ quarantine instead of confirmed.+ Codegraph hints: `src/core/brain/dream.ts:191` (`dream` handles+ both clustering and promotion in one pass), `src/core/brain/+ policy.ts:226` (`loadBrainConfig` already loads brain config -+ add a `promotion_threshold` field).++8. **Role-separated brain permission boundaries** (`t_ae0a2db2`) -+ explicit per-operation restrictions on what each brain tool may+ change. brain_feedback cannot auto-confirm preferences;+ brain_dream cannot delete logs or preferences without+ `retired/` transition; brain_apply_evidence cannot modify+ `confirmed` status without going through retirement.+ Codegraph hints: `src/mcp/brain-tools.ts` (no role barrier),+ `src/core/brain/preference.ts:92` (status field, no permission+ check).++The eight features cluster naturally around three layers:++- **Atoms layer**: data-shape additions on existing summaries+ (`uncertainty` arrays, `verification_delta` entries on dream+ output, `trust_verdict` field on doctor output, `promotion_*`+ config), plus a quality gate helper on the validate-feedback+ path, plus a role-permission helper.+- **Helpers layer**: pure functions that compose atoms into named+ surfaces - `computeTrustVerdict(doctorReport, dreamSummary,+ warnings)`, `computeVerificationDelta(vault, dreamSummary,+ log)`, `assessRuleQuality(principle)` (language-agnostic), and+ `checkRolePermission(tool, operation, currentState)`.+- **Consumers layer**: the operator-facing dashboard tool+ (`brain_operator_summary` or extend `brain_digest`), plus+ any new CLI verbs (`o2b brain summary`, `o2b brain verify`,+ `o2b brain trust`), plus changes to existing tools (the dream+ pass uses the self-approval guardrail; brain_feedback uses the+ quality gate; brain_doctor uses the instruction file ceiling+ check and the trust verdict).++# Project context++**Project**: Open Second Brain, TypeScript on Bun runtime, MIT.+Files under `src/core/brain/` (~50 files, ~25k LOC), `src/mcp/`,+`src/cli/brain/verbs/` (one verb per file), tests under+`tests/core/brain/` with the same shape.++**Recent commits (last 20)**:+```text+a84ddaa chore: bump version to 0.10.15+d045ea1 chore: bump version to 0.10.15 (#31)+5755200 v0.10.15: vault care bundle - metadata, dedup, lint, context-pack, actions (#30)+9d9636b feat: index fastpath, PEM/JWT redaction, vault connection health (v0.10.14) (#29)+7d81f0b feat: codegraph-partner skill + o2b doctor check (v0.10.13) (#28)+0462b91 feat: v0.10.12 operational friction reduction (#27)+9d8af95 v0.10.11: Multi-runtime install orchestrator + Most-applied in digest (#26)+3e297a5 v0.10.10: Pull channels - brain_context tool (#25)+73e85a1 v0.10.9: Vault scope - single ignore policy (#24)+e85523c v0.10.8: Retire event_log_append + JSONL sidecar (#23)+```++**Conventions and constraints** (from CHANGELOG, README, active+Brain preferences, prior PRs):++- Layered DAG: every new feature drops as a peer module in the+ matching layer; never re-cut the schema. Atoms (data-shape) -+ helpers (pure functions) - consumers (CLI / MCP surfaces). New+ modules sit next to existing ones (`src/core/brain/page-meta/`,+ `src/core/brain/maintenance/` are precedents from v0.10.15).+- Tests live in `tests/core/brain/<area>/` mirroring source paths.+ `bun test` is the runner; current tree has 1865+ tests passing.+- Language-agnostic by construction. v0.10.15 explicitly removed a+ CJK / Hangul character class and replaced it with+ `ceil(utf8_bytes / 4)`. Same rule applies to the quality gate+ (#5): the detector must not embed any per-language vocabulary+ list, regex of vague words, or stop-word set. Use structural+ shape (token count, modal-token ratio detected by token-class,+ not by literal match) only.+- No backwards-compat shims. Existing pages are NOT rewritten by+ this release. Add read-side defaults; only new writes opt in.+- One PR = one CHANGELOG version. The bundle ships as v0.10.16+ with one CHANGELOG entry.+- Hermes convention discipline. Do not propose any change that+ diverges from Hermes' kanban schema or expected behaviour.+- No on-chain anchoring, no Solana memo. (Explicitly out of scope+ for this project.)+- Existing surfaces to extend without rewriting:+ - `brain_doctor` returns `RunDoctorResult { warnings, errors,+ suggested_actions }`. Add `trust_verdict`, `uncertain`,+ `verification_delta`, `instruction_file_warnings`.+ - `brain_dream` returns `DreamRunSummary { new_unconfirmed,+ confirmed, retired, suppressed, contradictions, warnings, ... }`.+ Add `uncertain`, `quarantined` (for self-approval guardrail).+ - `brain_digest` returns `DigestJson` (already has `actions`+ field from v0.10.15). Add `trust_verdict`, `uncertain_count`,+ `quarantined_count` summary fields.+ - `brain_feedback` validates payload via+ `validateBrainFeedbackInput`. Add a quality-gate check that+ can reject with a structured reason.+- One new MCP tool is fine; multiple is also fine. Last release+ added one (`brain_context_pack`). Consider whether the+ operator dashboard belongs as a new tool (`brain_operator_summary`)+ or as an extension to `brain_digest`.++# 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/trust-operator-surfaces/design.md b/docs/brainstorm/trust-operator-surfaces/design.mdnew file mode 100644index 00000000..dd9300c1--- /dev/null+++ b/docs/brainstorm/trust-operator-surfaces/design.md@@ -0,0 +1,164 @@+# Trust and operator surfaces - design++**Status:** draft+**Author:** @claude-vps-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain agents already capture preferences, run a deterministic dream pass, and surface digest / doctor reports. But the brain reports *what happened* without ever auditing *its own claims*. There is no independent verification step, no aggregate health verdict, no quality gate on incoming preferences, no guardrail against dream auto-promoting its own signals, and no unified operator view. Operators get the answer "all green" or "X warnings" with no consistent line between trustable claims and uncertain ones.++This release adds the missing trust layer: eight related self-reporting features that read existing brain state, compute verdicts, and surface them through one new aggregating tool plus extensions to the existing reporters.++## Scope++Eight features bundled as one release, all named in the kanban task ids:++1. **Verification delta** (`t_e952d03a`) - explicit `confirmed | drift | regression | missing_evidence` verdicts per preference against vault state.+2. **Trust report** (`t_3440fa2c`) - vault-level `clean | watch | investigate` health verdict aggregating doctor warnings, dream warnings, and verification-delta entries.+3. **Operator dashboard** (`t_dd9a602e`) - one MCP tool that aggregates digest + doctor + verification + trust + suggested actions into a single output.+4. **Uncertainty surfacing** (`t_87acf4a2`) - dream pass and doctor pass declare `uncertain` cases explicitly instead of silently dropping them.+5. **Preference rule quality gate** (`t_dec0494f`) - language-agnostic structural quality scorer at `brain_feedback` time, with reject reason.+6. **Instruction file compliance ceiling** (`t_2c01f589`) - doctor warning when tracked instruction files (CLAUDE.md, AGENTS.md, GEMINI.md) exceed a configurable line ceiling.+7. **Dreamer self-approval guardrail** (`t_0a364afc`) - evidence threshold before auto-promotion; signals below threshold land in quarantine.+8. **Role-separated brain permission boundaries** (`t_ae0a2db2`) - explicit per-operation restrictions on what each tool may change.++## Out of scope++- Cross-vault aggregation (one vault per call).+- LLM-driven semantic verification of preferences. Verification delta uses deterministic comparisons (does the artifact exist? does the page status match the dream claim?), not natural-language judgement.+- Per-user audit log persistence. Verdicts are computed on read, not stored.+- Backwards-compatible field migration. Existing preferences and retired pages are not rewritten; readers apply documented defaults when new fields are absent.+- Replacing existing tools. `brain_digest`, `brain_doctor`, `brain_dream`, `brain_feedback` keep their current contract; new fields are additive.++## Chosen approach++Variant 2 from the consultant pass. Introduce a new subsystem directory `src/core/brain/trust/` housing pure helpers that compute the new verdicts and gates. Atoms (new fields on existing summary types) live next to their existing types. The dashboard ships as one new MCP tool `brain_operator_summary` plus a CLI verb `o2b brain summary`. Existing tools (`brain_doctor`, `brain_dream`, `brain_feedback`, `brain_apply_evidence`, `brain_digest`) gain calls into the trust helpers but keep their current public contract.++Three layers, strict downward dependency:++```text+atoms - data-shape additions on existing summary types+ + new BrainGuardrailConfig in policy.ts+ + new BrainRole enum in trust/role.ts+helpers - src/core/brain/trust/*.ts+ pure functions, no I/O, take atoms and read-only vault paths+consumers - brain_dream uses self-approval-guardrail+ brain_doctor uses trust-verdict + instruction-file-ceiling + verification-delta+ brain_feedback uses assess-rule-quality+ brain_apply_evidence uses check-role-permission+ new brain_operator_summary tool composes the above+ new o2b brain summary CLI verb+ brain_digest reads trust_verdict / uncertain_count / quarantined_count+```++## Design decisions++- **Subsystem name `trust/`** rather than `governance/` or `gates/`. It matches the release theme "trust the brain's self-reporting" and is short enough for daily use. v0.10.15 set the precedent (`page-meta/`, `maintenance/`).+- **No new persistence**. All four new verdicts (`trust_verdict`, `verification_delta`, `uncertain`, `quarantined`) are computed on read from existing vault state. No new files, no new directories under `Brain/`.+- **Quality gate is language-agnostic, shape-based only**. The detector uses three structural heuristics:+ 1. **length and token count** - empty or single-token principles are rejected; very long ones (over a fixed byte / token threshold) are warned.+ 2. **measurable-signal presence** - any token containing a digit (`/\d/` codepoint test), or any token containing an operator-shape character (`>`, `<`, `=`, `%`). If neither is found anywhere in the principle, the principle is warned as non-testable.+ 3. **filler ratio** - the proportion of single-character alphanumeric tokens to total tokens, after stripping punctuation. Above a fixed threshold, the principle is warned.++ The detector never matches against language-specific vocabulary, never imports any locale data, never enumerates unit or stopword lists. Tokenisation is whitespace-based and operates on raw codepoints.+- **Self-approval guardrail uses `BrainGuardrailConfig`**, a new section of `brain.config.yaml`, with three configurable thresholds: `min_signals` (default 2), `min_distinct_agents` (default 1), `min_age_days` (default 0, i.e. disabled). Backwards-compatible defaults keep current behaviour bit-identical when the config is absent.+- **Role permission model**. Three roles: `writer` (brain_feedback), `dreamer` (brain_dream), `applier` (brain_apply_evidence). Each role gets a static allow-list of `(target_status, transition)` pairs. The helper rejects attempts to cross a role boundary with a structured error; tools surface this error rather than silently failing.+- **Instruction file ceiling** is configurable via `BrainGuardrailConfig.instruction_file_max_lines` (default 200). Files discovered: vault-root `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`. Discovery is by existence, not by pattern - if the file is not there, no warning is emitted.+- **Verification delta states**:+ - `confirmed` - preference page exists, status matches dream claim, evidence count above zero.+ - `drift` - preference page exists, status matches, but evidence count is zero (claimed applied but no artifact ever recorded).+ - `regression` - preference page exists with status `retired` although dream most-recently claimed `confirmed`.+ - `missing_evidence` - dream summary references a `pref-*` id with no corresponding file under `Brain/preferences/` or `Brain/retired/`.+- **Trust verdict thresholds**:+ - `clean` - zero doctor errors, zero dream warnings, zero verification-delta entries with state `drift` / `regression` / `missing_evidence`.+ - `watch` - any doctor warnings or dream warnings or up to N verification-delta entries (configurable, default 3) where N counts only `drift`.+ - `investigate` - any doctor errors, or more than N drift entries, or any `regression` or `missing_evidence` entries.+- **brain_operator_summary tool**. New MCP tool registered in the full scope only (writer scope keeps its four-tool surface per v0.10.10). Returns a structured JSON envelope: `trust_verdict`, `digest_summary`, `doctor_summary`, `dream_summary` (most recent), `verification_delta`, `top_actions` (from action-scorer), `instruction_file_warnings`. Markdown rendering for the CLI verb derives from the same JSON.++## File changes++### New files (~24)++```text+src/core/brain/trust/+ role.ts (BrainRole enum, BrainOperation type)+ check-role-permission.ts (helper)+ assess-rule-quality.ts (language-agnostic structural scorer)+ compute-verification-delta.ts (vault scanner -> VerificationDeltaEntry[])+ compute-trust-verdict.ts (aggregator -> TrustVerdict)+ instruction-file-ceiling.ts (read tracked files, return warnings)+ self-approval-guardrail.ts (signal threshold check)+ operator-summary.ts (top-level composer; JSON + markdown renderer)+tests/core/brain/trust/+ role.test.ts+ check-role-permission.test.ts+ assess-rule-quality.test.ts+ compute-verification-delta.test.ts+ compute-trust-verdict.test.ts+ instruction-file-ceiling.test.ts+ self-approval-guardrail.test.ts+ operator-summary.test.ts+src/cli/brain/verbs/+ summary.ts (o2b brain summary verb)+tests/cli/brain/+ summary.test.ts+tests/mcp/+ operator-summary-tool.test.ts+docs/brainstorm/trust-operator-surfaces/+ design.md+ plan.md+ variants.md+ cli-output/prompt.md+ cli-output/claude.md+.ai-notes/images/+ v0.10.16-trust.excalidraw (release-time)+ v0.10.16-trust.png (release-time)+```++### Modified files (~24)++```text+src/core/brain/dream.ts (uncertain[], quarantined[] in DreamRunSummary;+ invoke self-approval-guardrail)+src/core/brain/doctor.ts (trust_verdict, verification_delta_summary,+ instruction_file_warnings, uncertain in+ RunDoctorResult; invoke trust helpers)+src/core/brain/digest.ts (trust_verdict, uncertain_count,+ quarantined_count derived fields in DigestJson)+src/core/brain/sessions/validate-feedback.ts+ (invoke assess-rule-quality; structured reject reason)+src/core/brain/apply-evidence.ts (invoke check-role-permission for confirmed transitions)+src/core/brain/policy.ts (BrainGuardrailConfig section)+src/mcp/brain-tools.ts (register brain_operator_summary;+ new fields surface through brain_digest / doctor)+src/cli/brain.ts (dispatch case for summary verb)+src/cli/brain/help-text.ts (BRAIN_HELP entry; VERB_HELP[summary])+README.md (features paragraph mentions trust + dashboard)+CHANGELOG.md (one [0.10.16] entry)+docs/how-it-works.md (trust layer paragraph)+package.json (version 0.10.16; phase 5b)+.claude-plugin/plugin.json (version 0.10.16; phase 5b)+.codex-plugin/plugin.json (version 0.10.16; phase 5b)+openclaw.plugin.json (version 0.10.16; phase 5b)+plugin.yaml (version 0.10.16; phase 5b)+plugins/codex/.codex-plugin/plugin.json (version 0.10.16; phase 5b)+plugins/hermes/plugin.yaml (version 0.10.16; phase 5b)+pyproject.toml (version 0.10.16; phase 5b)+tests/core/brain/dream.test.ts (expectations for new fields)+tests/core/brain/doctor.test.ts (expectations for trust verdict, ceiling)+tests/core/brain/digest.test.ts (snapshot extends for new fields)+tests/mcp/mcp.test.ts (registry includes brain_operator_summary)+tests/cli/help-text.test.ts (BRAIN_HELP includes summary verb)+```++Expected total: ~48-52 file changes.++## Risks and open questions++- **Quality gate false positives**. A truly terse but valid principle (e.g., a single imperative followed by a measurable outcome in a non-Latin script) must not be rejected. Mitigation: structural heuristics use lower bounds (too short OR no measurable structure) not vocabulary, and the gate emits a warning rather than a hard reject below a low threshold; only outright shape failures (empty, single token, no verb-like structure detectable via token-position only) become hard rejects.+- **Trust verdict noise floor**. If `watch` is too easy to trigger, operators ignore it. Mitigation: thresholds are conservative (one doctor warning alone does not trigger `watch`; only verification-delta entries or doctor warnings combined with other signals do).+- **Self-approval guardrail backwards compatibility**. Adding even one signal-count gate could prevent legitimate promotions on vaults with low signal volume. Mitigation: `min_signals` defaults to 2 (same as the existing dream behaviour after v0.10.5), so the guardrail is currently a documented codification, not a regression. Explicit opt-in to stricter thresholds via config.+- **Instruction file discovery**. Files outside the vault root (e.g. project-level `CLAUDE.md`) are not in scope - this release only checks the vault root. Future scope can extend discovery without changing the ceiling logic.+- **brain_operator_summary overlap with brain_digest**. Both can answer "what's going on in this vault". Mitigation: digest is preference-and-signal-focused (what's accumulating, what's most-applied); operator summary is trust-and-state-focused (is the vault healthy, what should I do next). Both reference each other in their help text.+- **Open question deferred to implementation**: whether `verification_delta` runs on every doctor call (cheap but does extra I/O) or only on `brain_operator_summary` (saves I/O on the hot path). Default during implementation: lazy - doctor reports a count, operator summary reports the full list.diff --git a/docs/brainstorm/trust-operator-surfaces/plan.md b/docs/brainstorm/trust-operator-surfaces/plan.mdnew file mode 100644index 00000000..4ad52910--- /dev/null+++ b/docs/brainstorm/trust-operator-surfaces/plan.md@@ -0,0 +1,207 @@+# Trust and operator surfaces - implementation plan++Atomic units in dependency order (atoms first, helpers second, consumers third). Each task is one conventional commit on `feat/trust-operator-surfaces`. TDD: failing tests first, then implementation, then refactor green.++## Atoms layer++### A1: BrainRole enum + BrainOperation type+- **Files**:+ - `src/core/brain/trust/role.ts` (new)+ - `tests/core/brain/trust/role.test.ts` (new)+- **Acceptance**: enum exports `writer`, `dreamer`, `applier`, `unknown`. `BrainOperation` is a union of `feedback_write`, `preference_create_unconfirmed`, `preference_promote_confirmed`, `preference_retire`, `evidence_record`, `log_append`. Test covers exhaustiveness via `satisfies`.+- **Depends on**: none.+- **Commit**: `feat(trust): add BrainRole enum and BrainOperation type`++### A2: BrainGuardrailConfig in policy.ts+- **Files**:+ - `src/core/brain/policy.ts` (modify - extend `BrainConfig` with optional `guardrails?` block)+ - `tests/core/brain/policy/guardrails.test.ts` (new)+- **Acceptance**: `loadBrainConfig` accepts an optional `guardrails:` YAML block with three fields: `promotion_min_signals` (default 2), `promotion_min_distinct_agents` (default 1), `instruction_file_max_lines` (default 200). When the block is absent, all three return their defaults. Existing fixtures stay byte-identical.+- **Depends on**: none.+- **Commit**: `feat(policy): add BrainGuardrailConfig block with backward-compatible defaults`++### A3: Extend DreamRunSummary with uncertain + quarantined arrays+- **Files**:+ - `src/core/brain/dream.ts` (modify - add `uncertain: ReadonlyArray<UncertainEntry>` and `quarantined: ReadonlyArray<QuarantinedSignal>` to `DreamRunSummary`; emit empty arrays in this commit)+ - `tests/core/brain/dream.test.ts` (modify - assert new fields are present and empty by default)+- **Acceptance**: existing dream snapshot tests still pass after adding the empty arrays. Type-checking confirms readers see both arrays.+- **Depends on**: none.+- **Commit**: `feat(dream): surface uncertain and quarantined arrays on DreamRunSummary`++### A4: Extend RunDoctorResult with trust + verification + instruction-file fields+- **Files**:+ - `src/core/brain/doctor.ts` (modify - add `trust_verdict?`, `verification_delta_summary?`, `instruction_file_warnings?`, `uncertain?` optional fields. Optional so unrelated doctor callers stay green.)+ - `tests/core/brain/doctor.test.ts` (modify - assert new fields default to absent / empty arrays)+- **Acceptance**: doctor snapshot tests pass; new fields are present only when populated by helpers.+- **Depends on**: none.+- **Commit**: `feat(doctor): add trust_verdict and verification_delta to RunDoctorResult`++### A5: Extend DigestJson with derived trust fields+- **Files**:+ - `src/core/brain/digest.ts` (modify - add `trust_verdict?`, `uncertain_count`, `quarantined_count` to `DigestJson`)+ - `tests/core/brain/digest.test.ts` (modify - assert digest renders new fields)+- **Acceptance**: existing digest snapshot tests pass; new fields default to `unknown` / 0 when no trust input is provided.+- **Depends on**: A3, A4 (digest reads from dream and doctor summaries).+- **Commit**: `feat(digest): surface derived trust_verdict and uncertain counts`++## Helpers layer++### H1: assess-rule-quality (language-agnostic)+- **Files**:+ - `src/core/brain/trust/assess-rule-quality.ts` (new)+ - `tests/core/brain/trust/assess-rule-quality.test.ts` (new)+- **Acceptance**: `assessRuleQuality(principle: string): RuleQualityResult { score: number, severity: 'ok' | 'warn' | 'reject', reasons: string[] }`. Score uses **shape-based heuristics only**, no vocabulary lookups in any language:+ - empty / single token -> `reject`.+ - too long (>500 chars or >80 tokens) -> `warn`.+ - **measurable signal absent**: no token contains a digit anywhere, AND no token contains an operator-shape character (`>`, `<`, `=`, `%`, `/` between digits) -> `warn`.+ - **filler signal high**: ratio of single-character alphanumeric tokens to total tokens above 0.4 (after stripping punctuation) -> `warn`.++ No enumerated unit list, no per-language vague-word list, no stopword list. The detector reads bytes and counts tokens by whitespace; "token contains digit" is a `/\d/` test on the codepoint, language-independent.++ Test fixtures cover: empty input, single token, very long input, an imperative with a numeric outcome (`limit retries to 10 per hour`), a numeric outcome in a non-Latin script (`<NON-LATIN>10<NON-LATIN>/<NON-LATIN>` placeholder), a vague rule with no structural signal (`<TOKEN_A> <TOKEN_B> <TOKEN_C>` placeholder).+- **Depends on**: none.+- **Commit**: `feat(trust): add language-agnostic assess-rule-quality helper`++### H2: check-role-permission+- **Files**:+ - `src/core/brain/trust/check-role-permission.ts` (new)+ - `tests/core/brain/trust/check-role-permission.test.ts` (new)+- **Acceptance**: `checkRolePermission(role: BrainRole, op: BrainOperation, currentStatus?: BrainStatus): { allowed: boolean; reason?: string }`. Static allow-list per role: `writer` may only `feedback_write` and `preference_create_unconfirmed`; `dreamer` may only `preference_promote_confirmed` (from `unconfirmed`) and `preference_retire`; `applier` may only `evidence_record` and `log_append`. Crossing a boundary (e.g. applier trying to mutate `confirmed` status) returns `{ allowed: false, reason: ... }` with structured reason.+- **Depends on**: A1.+- **Commit**: `feat(trust): add check-role-permission helper`++### H3: self-approval-guardrail+- **Files**:+ - `src/core/brain/trust/self-approval-guardrail.ts` (new)+ - `tests/core/brain/trust/self-approval-guardrail.test.ts` (new)+- **Acceptance**: `applySelfApprovalGuardrail({signal_count, distinct_agents, age_days}, config): { decision: 'promote' | 'quarantine'; reason?: string }`. Promotes only when all three thresholds met. Defaults from `BrainGuardrailConfig` make current behaviour bit-identical (min_signals=2, min_distinct_agents=1, min_age_days=0).+- **Depends on**: A2.+- **Commit**: `feat(trust): add self-approval-guardrail helper`++### H4: compute-verification-delta+- **Files**:+ - `src/core/brain/trust/compute-verification-delta.ts` (new)+ - `tests/core/brain/trust/compute-verification-delta.test.ts` (new)+- **Acceptance**: `computeVerificationDelta(vault: string, dream: DreamRunSummary): VerificationDeltaResult`. For each preference id mentioned in `dream.confirmed | dream.retired | dream.new_unconfirmed`, classifies into one of `confirmed | drift | regression | missing_evidence`. Pure file-system reads through existing path helpers; no network, no LLM.+- **Depends on**: A3.+- **Commit**: `feat(trust): add compute-verification-delta helper`++### H5: instruction-file-ceiling+- **Files**:+ - `src/core/brain/trust/instruction-file-ceiling.ts` (new)+ - `tests/core/brain/trust/instruction-file-ceiling.test.ts` (new)+- **Acceptance**: `checkInstructionFileCeiling(vault, { maxLines })`: returns warnings for each vault-root file in the tracked set `CLAUDE.md`, `AGENTS.md`, `GEMINI.md` that exceeds `maxLines`. Returns the actual line count in the warning payload so the operator can see by how much.+- **Depends on**: A2.+- **Commit**: `feat(trust): add instruction-file-ceiling helper`++### H6: compute-trust-verdict+- **Files**:+ - `src/core/brain/trust/compute-trust-verdict.ts` (new)+ - `tests/core/brain/trust/compute-trust-verdict.test.ts` (new)+- **Acceptance**: `computeTrustVerdict({doctor, dream, verification}): 'clean' | 'watch' | 'investigate'`. Thresholds per design-doc. Pure aggregation, no side effects.+- **Depends on**: A3, A4, H4.+- **Commit**: `feat(trust): add compute-trust-verdict helper`++### H7: operator-summary composer+- **Files**:+ - `src/core/brain/trust/operator-summary.ts` (new)+ - `tests/core/brain/trust/operator-summary.test.ts` (new)+- **Acceptance**: `buildOperatorSummary(vault, opts): OperatorSummary` returns `{ trust_verdict, digest_summary, doctor_summary, dream_summary, verification_delta, top_actions, instruction_file_warnings }`. Pulls digest, doctor (read-only), most-recent dream, and runs verification + trust helpers. Markdown renderer included in same file.+- **Depends on**: H1-H6, A5.+- **Commit**: `feat(trust): add operator-summary composer`++## Consumers layer++### C1: brain_dream uses self-approval-guardrail + uncertain+- **Files**:+ - `src/core/brain/dream.ts` (modify - call `applySelfApprovalGuardrail` before promoting; route below-threshold candidates to `quarantined`; populate `uncertain` for cases where verification cannot run)+ - `tests/core/brain/dream-guardrail.test.ts` (new)+- **Acceptance**: a dream run with one signal below threshold lands in `quarantined`, not `confirmed`. Default config keeps existing tests green.+- **Depends on**: H3.+- **Commit**: `feat(dream): wire self-approval guardrail and quarantine path`++### C2: brain_feedback uses assess-rule-quality+- **Files**:+ - `src/core/brain/sessions/validate-feedback.ts` (modify - call `assessRuleQuality`; on `severity: 'reject'` return structured error)+ - `tests/core/brain/sessions/validate-feedback-quality.test.ts` (new)+- **Acceptance**: empty principle or single token -> rejected with structured reason. Valid principles pass.+- **Depends on**: H1.+- **Commit**: `feat(feedback): reject structurally-vague principles via quality gate`++### C3: brain_apply_evidence uses check-role-permission+- **Files**:+ - `src/core/brain/apply-evidence.ts` (modify - call `checkRolePermission(BrainRole.applier, 'evidence_record', currentStatus)`)+ - `tests/core/brain/apply-evidence-role.test.ts` (new)+- **Acceptance**: applier role cannot mutate confirmed preference status; helper returns rejection that surfaces as a structured error.+- **Depends on**: H2.+- **Commit**: `feat(evidence): enforce role-permission boundary on apply-evidence`++### C4: brain_doctor uses instruction-file-ceiling + verification-delta + trust-verdict+- **Files**:+ - `src/core/brain/doctor.ts` (modify - populate `trust_verdict`, `verification_delta_summary` (counts only, not full entries), `instruction_file_warnings`)+ - `tests/core/brain/doctor-trust.test.ts` (new)+- **Acceptance**: doctor on a clean vault returns `trust_verdict: 'clean'`; doctor on a vault with one long CLAUDE.md emits a warning entry referencing the line count.+- **Depends on**: H4, H5, H6.+- **Commit**: `feat(doctor): integrate trust verdict, ceiling, and verification delta`++### C5: brain_digest reads trust fields+- **Files**:+ - `src/core/brain/digest.ts` (modify - read `trust_verdict` from doctor input and `uncertain_count` / `quarantined_count` from dream input; surface in JSON + markdown)+ - `tests/core/brain/digest-trust.test.ts` (new)+- **Acceptance**: `brain_digest` output includes the new fields; markdown section `## Trust` shows the verdict and counts.+- **Depends on**: A5, C1, C4.+- **Commit**: `feat(digest): surface trust verdict and uncertainty counts in digest`++### C6: brain_operator_summary MCP tool+- **Files**:+ - `src/mcp/brain-tools.ts` (modify - register `brain_operator_summary` tool in the full scope; handler delegates to `buildOperatorSummary`)+ - `tests/mcp/operator-summary-tool.test.ts` (new)+ - `tests/mcp/mcp.test.ts` (modify - registry includes the new tool name)+- **Acceptance**: MCP tool listed in full scope (not writer scope); JSON-RPC call returns the structured envelope.+- **Depends on**: H7.+- **Commit**: `feat(mcp): add brain_operator_summary tool in full scope`++### C7: o2b brain summary CLI verb+- **Files**:+ - `src/cli/brain/verbs/summary.ts` (new)+ - `src/cli/brain.ts` (modify - dispatch case)+ - `src/cli/brain/help-text.ts` (modify - BRAIN_HELP entry + VERB_HELP[summary])+ - `tests/cli/brain/summary.test.ts` (new)+ - `tests/cli/help-text.test.ts` (modify - assert new verb is listed)+- **Acceptance**: `o2b brain summary` prints markdown by default, `--json` prints JSON, both match the `buildOperatorSummary` envelope.+- **Depends on**: H7.+- **Commit**: `feat(cli): add o2b brain summary verb`++## Phase 5 (docs)++### D1: CHANGELOG + README + how-it-works+- **Files**:+ - `CHANGELOG.md` (one `[0.10.16]` entry per playbook rule "one PR = one CHANGELOG version")+ - `README.md` (add trust + operator dashboard line under features list)+ - `docs/how-it-works.md` (one paragraph describing the trust layer)+- **Acceptance**: docs reference the new tool and verb; no `[Unreleased]` section anywhere.+- **Depends on**: all of C1-C7 merged conceptually (this is the last code commit in the implementation phase).+- **Commit**: `docs: v0.10.16 trust and operator surfaces`++## Phase 5b (version bump)++### V1: bump 0.10.15 to 0.10.16 across all 8 manifests+- **Files**:+ - `package.json`+ - `.claude-plugin/plugin.json`+ - `.codex-plugin/plugin.json`+ - `openclaw.plugin.json`+ - `plugin.yaml`+ - `plugins/codex/.codex-plugin/plugin.json`+ - `plugins/hermes/plugin.yaml`+ - `pyproject.toml`+- **Acceptance**: `bun run sync-version:check` returns ok.+- **Depends on**: D1.+- **Commit**: `chore: bump version to 0.10.16`++## Notes on TDD discipline++- Every helper module ships its test in the same commit. Tests fail first, then pass after implementation lands.+- The dream and doctor changes (C1, C4) update existing tests with extended assertions plus add new tests for the new behaviour. Existing snapshot tests get regenerated to include the new fields.+- The assess-rule-quality test fixture must NOT include any specific-language vague-word string as a target case to reject. All reject cases must hinge on structure (empty, single token, no operator-shape).+- No new dependencies added. All helpers use Node.js built-ins and existing OSB path helpers.diff --git a/docs/brainstorm/trust-operator-surfaces/variants.md b/docs/brainstorm/trust-operator-surfaces/variants.mdnew file mode 100644index 00000000..3b93c0c0--- /dev/null+++ b/docs/brainstorm/trust-operator-surfaces/variants.md@@ -0,0 +1,73 @@+# Trust and operator surfaces - variants audit trail++This file is the audit trail of the architectural brainstorm for v0.10.16. Per the feature-release-playbook, all variants are recorded verbatim from the consultant pass plus the final orchestrator rationale, so a future reader can see the alternatives that lost and why.++## Source++- Primary consultant: Claude Code via `claude -p`. Output captured verbatim in `cli-output/claude.md`.+- Fallback consultant: not invoked. Primary returned three parseable variants and a recommendation on first run.+- Date of pass: 2026-05-25.++## Variants (verbatim from primary consultant)++### Variant 1: Flat layered expansion, no new MCP tool+- **Approach**: Drop each feature as a peer module in its matching layer (atoms next to existing atoms, helpers next to existing helpers), and extend `brain_doctor` / `brain_dream` / `brain_digest` / `brain_feedback` in-place with new fields. The operator dashboard becomes an extension of `DigestJson` (new `trust_verdict`, `uncertain_count`, `quarantined_count`, `verification_delta_summary` fields), not a new tool. No new directory; eight features land as ~8 small peer modules across existing folders.+- **Trade-offs**:+ - Pro: smallest surface-area delta, mirrors v0.10.14 / v0.10.10 style (extend, don't add tools).+ - Pro: each feature stays independently testable; bundle = sum of parts.+ - Pro: lowest risk of cross-feature coupling regressions.+ - Con: the "trust the brain's self-reporting" theme is invisible at the file-tree level - eight tiny additions sprinkled across `src/core/brain/`.+ - Con: dashboard via field-expansion of `DigestJson` makes that type wider and less focused; operators must still mentally compose multiple sections.+ - Con: no single import path that a future contributor can point at as "the trust layer".+- **Complexity**: medium+- **Risk**: low++### Variant 2: New `trust/` subsystem with one new consumer tool+- **Approach**: Introduce `src/core/brain/trust/` housing the new helpers (`compute-verification-delta.ts`, `compute-trust-verdict.ts`, `assess-rule-quality.ts`, `check-role-permission.ts`, `instruction-file-ceiling.ts`, `self-approval-guardrail.ts`), each a pure function over atoms. Atoms (uncertainty arrays, verdict field, promotion config) still land on the existing summary types, but everything that *computes* them lives in `trust/`. Add one new MCP tool `brain_operator_summary` as the aggregating consumer; existing tools import the helpers but keep their current shape and contracts.+- **Trade-offs**:+ - Pro: follows v0.10.15 precedent (`page-meta/`, `maintenance/` subdirs) - gives the release a coherent identity and a single grep target.+ - Pro: helpers are pure, so cross-feature interaction is forced through typed function boundaries instead of ad-hoc field reads.+ - Pro: dashboard tool can iterate independently without re-shaping `DigestJson`; `brain_digest` stays small and digestible.+ - Pro: tests mirror cleanly under `tests/core/brain/trust/`.+ - Con: requires choosing a subsystem name now; "trust" may age poorly if scope drifts.+ - Con: one extra MCP tool to document, version, and keep aligned with `brain_digest` (overlap risk).+ - Con: slightly more upfront design than Variant 1 - need to define the trust-layer's read-only contract against atoms.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Capability-kernel refactor around writes+- **Approach**: Make role-separated permissions (#8) the keystone - introduce a `BrainCapability` kernel that intercepts every brain write (`brain_feedback`, `brain_dream`, `brain_apply_evidence`), and rebuild the other seven features as policies hanging off that kernel (quality gate as a pre-write policy, self-approval guardrail as a promotion policy, verification delta as a post-write policy, etc.). Existing handlers in `src/mcp/brain-tools.ts` get rewritten to flow through the kernel.+- **Trade-offs**:+ - Pro: structurally enforces #8 - role boundaries can't be bypassed because the kernel mediates every write.+ - Pro: future brain tools inherit role separation, quality gates, and verification for free.+ - Pro: the cleanest long-term mental model - one seam, many policies.+ - Con: violates the project's "extend without rewriting" rule and "no backwards-compat shims" posture - `brain-tools.ts` handlers get re-shaped.+ - Con: largest blast radius across 1865+ tests; bundling a refactor with eight features in one release inflates review surface and CHANGELOG scope.+ - Con: kernel design is the kind of premature abstraction the layered-DAG convention exists to prevent; v0.10.15 explicitly chose peer modules over a kernel.+ - Con: high risk that one of the eight features stalls and blocks the other seven because they share a critical-path module.+- **Complexity**: large+- **Risk**: high++## Consultant recommendation++> Variant 2.+>+> Variant 2 fits the established v0.10.15 precedent (a named subdirectory of pure helpers per release) and gives the eight-feature bundle the coherent identity its theme demands, without the rewriting risk of Variant 3 or the file-tree invisibility of Variant 1. Atoms remain field-additions on existing summaries (satisfying "extend without rewriting"), helpers are pure and independently testable, and one new consumer tool (`brain_operator_summary`) cleanly absorbs the dashboard role so `brain_digest` stays focused. It preserves the layered DAG rule while making the release legible as a single architectural move.++## Orchestrator decision++**Chosen: Variant 2** (agreeing with the consultant).++**Rationale**: the recommendation matches three independent project signals the consultant could not fully see:++1. v0.10.15 explicitly built `src/core/brain/page-meta/` and `src/core/brain/maintenance/` as named per-release subsystems; choosing `trust/` continues that pattern and lets the next maintenance release add a peer subsystem without re-cutting the schema.+2. The active Brain preference `pref-self-review-after-implementation` mandates the superpowers code-review pass; pure helpers under one subdirectory are easier to review as a unit than scattered diffs.+3. Variant 3 violates the project's CLAUDE.md-level rule "do not propose Hermes-convention or schema-design violations" by implication - the kernel refactor would re-shape `brain-tools.ts` handlers that have been stable across the last seven releases.++The only deviation from the consultant's writeup: the subsystem name `trust/` (over alternatives like `governance/` or `gates/`) is kept because it matches the release theme exactly. If the scope later grows to cover non-trust governance, a renaming refactor is a cheap follow-up.++## Variants not pursued++- **Per-feature subdirectories** (e.g. `src/core/brain/quality-gate/`, `src/core/brain/verification/`) - rejected because eight tiny subdirectories defeat the unifying theme and balloon the cross-import graph.+- **Storing verification verdicts persistently** (e.g. `Brain/verification/<date>.jsonl`) - rejected because it duplicates information already derivable from the daily log + the preferences/retired folders. Computing on read keeps the vault layout stable.+- **LLM-driven quality gate** - rejected because Open Second Brain's design principle is deterministic, no-LLM-in-the-loop algorithms. Quality gate uses structural heuristics only.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d683d8b4..2f9ce6e0 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.10.15",+ "version": "0.10.16","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex df14ccef..5fcde08d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.15",+ "version": "0.10.16","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex c86770e3..a0778441 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.15"+version: "0.10.16"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex f377b5d8..81163f80 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.15",+ "version": "0.10.16","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 9beffef3..1507b9f8 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.15"+version: "0.10.16"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 955ae075..fa26e7f1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.10.15"+version = "0.10.16"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 5861f891..cfdd2a8a 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -39,6 +39,7 @@ import {cmdBrainContextPack,cmdBrainLint,cmdBrainActions,+ cmdBrainSummary,} from "./brain/verbs/index.ts";export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promise<number> {@@ -88,6 +89,7 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promiscase "context-pack": return await cmdBrainContextPack(rest);case "lint": return await cmdBrainLint(rest);case "actions": return await cmdBrainActions(rest);+ case "summary": return await cmdBrainSummary(rest);default:process.stderr.write(`error: unknown brain verb: ${verb}\n`);process.stdout.write(BRAIN_HELP);diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 9cc80aac..9fd1f280 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -41,6 +41,7 @@ Brain verbs (observing memory):context-pack Return a tier-then-recency vault slice under a token budgetlint Self-healing structural checks (--consolidate); --apply to writeactions Ranked maintenance action list (dedup + lint + footprint)+ summary Operator dashboard: trust verdict, doctor/dream counts, actionsCommon flags:--vault <path> Override the configured vault@@ -242,4 +243,10 @@ export const VERB_HELP: Record<string, string> = {"action by impact (dedup count × weight, staleness × age,\n" +"broken-link count, token-footprint excess), and prints the top N\n" +"(default 10) sorted by impact descending. Read-only.\n",+ summary:+ "usage: o2b brain summary [--skip-dream] [--top-actions <n>] [--vault <path>] [--json]\n" ++ "Operator dashboard. Aggregates trust verdict, doctor warnings/errors,\n" ++ "dream uncertain/quarantined counts, verification delta, top maintenance\n" ++ "actions, and instruction-file ceiling warnings into one report.\n" ++ "Runs a dry-run dream pass by default; --skip-dream omits it. Read-only.\n",};diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex ccfd27eb..fda576f5 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -26,3 +26,4 @@ export { cmdBrainTokenFootprint } from "./token-footprint.ts";export { cmdBrainContextPack } from "./context-pack.ts";export { cmdBrainLint } from "./lint.ts";export { cmdBrainActions } from "./actions.ts";+export { cmdBrainSummary } from "./summary.ts";diff --git a/src/cli/brain/verbs/summary.ts b/src/cli/brain/verbs/summary.tsnew file mode 100644index 00000000..0a3a702e--- /dev/null+++ b/src/cli/brain/verbs/summary.ts@@ -0,0 +1,85 @@+/**+ * `o2b brain summary` - operator dashboard (v0.10.16). Aggregates+ * doctor, dream (dry-run), verification delta, instruction-file+ * ceiling, and ranked maintenance actions into one output.+ *+ * Defaults to markdown so an operator can paste the report into+ * their notes; `--json` returns the structured envelope for tooling.+ */++import { defaultConfigPath } from "../../../core/config.ts";+import { dream } from "../../../core/brain/dream.ts";+import {+ buildOperatorSummary,+ renderOperatorSummaryMarkdown,+} from "../../../core/brain/trust/operator-summary.ts";+import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainSummary(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ "skip-dream": { type: "boolean" },+ "top-actions": { type: "string" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ let topActionsN: number | undefined;+ const topRaw = flags["top-actions"] as string | undefined;+ if (topRaw !== undefined) {+ const n = Number(topRaw);+ if (!Number.isInteger(n) || n < 0) {+ return fail(+ `brain summary: --top-actions must be a non-negative integer; got ${topRaw}`,+ );+ }+ topActionsN = n;+ }++ let dreamSummary;+ let dreamError: string | undefined;+ if (!flags["skip-dream"]) {+ try {+ dreamSummary = dream(vault, { dryRun: true });+ } catch (err) {+ // Surface the failure rather than silently producing a partial+ // dashboard. stderr keeps the human-readable text channel+ // separate from the structured payload; the `dream_error`+ // field on the JSON output lets automation react.+ dreamError = (err as Error).message ?? String(err);+ process.stderr.write(`warning: dry-run dream failed: ${dreamError}\n`);+ }+ }++ const summary = buildOperatorSummary(vault, {+ ...(dreamSummary ? { dreamSummary } : {}),+ ...(topActionsN !== undefined ? { topActionsN } : {}),+ });++ if (flags["json"]) {+ okJson({+ trust_verdict: summary.trust_verdict,+ digest_summary: summary.digest_summary,+ doctor_summary: {+ warning_count: summary.doctor_summary.warning_count,+ error_count: summary.doctor_summary.error_count,+ },+ dream_summary: summary.dream_summary,+ verification_delta: {+ summary: summary.verification_delta.summary,+ entries: summary.verification_delta.entries,+ },+ top_actions: summary.top_actions,+ instruction_file_warnings: summary.instruction_file_warnings,+ ...(dreamError !== undefined ? { dream_error: dreamError } : {}),+ });+ return 0;+ }++ process.stdout.write(renderOperatorSummaryMarkdown(summary));+ if (dreamError !== undefined) {+ process.stdout.write(`\nDream error: ${dreamError}\n`);+ }+ return 0;+}diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.tsindex b15f7150..9b419557 100644--- a/src/core/brain/apply-evidence.ts+++ b/src/core/brain/apply-evidence.ts@@ -36,6 +36,8 @@ import { appendLogEvent, type AppendLogEventResult, type BrainLogEntry } from ".import { parsePreference } from "./preference.ts";import { preferencePath, validateSlug } from "./paths.ts";import { isoSecond } from "./time.ts";+import { checkRolePermission } from "./trust/check-role-permission.ts";+import { BRAIN_OPERATIONS, type BrainRole } from "./trust/role.ts";import { renderPrefLink } from "./wikilink.ts";import {BRAIN_APPLY_RESULT,@@ -67,6 +69,20 @@ export class BrainPreferenceNotFoundError extends Error {}}+/**+ * Thrown when {@link appendApplyEvidence} is called with a role that+ * is not permitted to record evidence (v0.10.16).+ */+export class BrainRolePermissionError extends Error {+ readonly role: BrainRole;++ constructor(role: BrainRole, reason: string) {+ super(`apply-evidence permission denied for role '${role}': ${reason}`);+ this.name = "BrainRolePermissionError";+ this.role = role;+ }+}+/** Input contract for {@link appendApplyEvidence}. */export interface AppendApplyEvidenceInput {/**@@ -93,6 +109,13 @@ export interface AppendApplyEvidenceOptions {* so the resulting log entry is byte-deterministic.*/readonly now?: Date;+ /**+ * Caller role (v0.10.16). When provided, the role-permission gate+ * runs and rejects calls from roles that are not allowed to record+ * evidence. Legacy callers that omit the field bypass the gate -+ * the default is to preserve pre-v0.10.16 behaviour.+ */+ readonly role?: BrainRole;}export interface AppendApplyEvidenceResult {@@ -116,6 +139,12 @@ export function appendApplyEvidence(input: AppendApplyEvidenceInput,opts: AppendApplyEvidenceOptions = {},): AppendApplyEvidenceResult {+ if (opts.role !== undefined) {+ const verdict = checkRolePermission(opts.role, BRAIN_OPERATIONS.evidence_record);+ if (!verdict.allowed) {+ throw new BrainRolePermissionError(opts.role, verdict.reason ?? "denied");+ }+ }if (!input.pref_id || !input.pref_id.trim()) {throw new Error("apply-evidence missing field: pref_id");}diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex 96a2fcd1..9e356b44 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -43,6 +43,7 @@ import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summimport { findMergeCandidates } from "./merge-candidates.ts";import { computeMostApplied } from "./most-applied.ts";import { brainDirs, vaultRelative } from "./paths.ts";+import type { TrustVerdict } from "./doctor.ts";import { collectMaintenanceActions } from "./maintenance/collect.ts";import type { ActionItem } from "./maintenance/action-scorer.ts";import {@@ -82,6 +83,18 @@ export interface RenderDigestOptions {* picks `new Date()` itself.*/readonly now?: Date;+ /**+ * Optional doctor result (v0.10.16). When supplied, `trust_verdict`+ * lands in the JSON payload and a `## Trust` section renders in+ * markdown.+ */+ readonly doctorResult?: import("./doctor.ts").RunDoctorResult;+ /**+ * Optional dream summary (v0.10.16). When supplied,+ * `uncertain_count` and `quarantined_count` reflect the+ * counterparts on the summary instead of defaulting to zero.+ */+ readonly dreamSummary?: import("./dream.ts").DreamRunSummary;}export interface RenderDigestResult {@@ -272,6 +285,24 @@ export interface DigestJson {* needs doing. Independent of the window.*/readonly actions: ReadonlyArray<ActionItem>;+ /**+ * Aggregate vault trust verdict (v0.10.16). Absent when no+ * doctor input was threaded into the digest call; consumers that+ * only need the legacy preference-and-signal sections can ignore+ * the field.+ */+ readonly trust_verdict?: TrustVerdict;+ /**+ * Count of dream-pass uncertain entries in the most recent run+ * (v0.10.16). Zero when no dream input was provided.+ */+ readonly uncertain_count: number;+ /**+ * Count of dream-pass signal clusters held back by the+ * self-approval guardrail in the most recent run (v0.10.16).+ * Zero when no dream input was provided.+ */+ readonly quarantined_count: number;}/**@@ -329,6 +360,14 @@ export function renderDigest(most_applied: data.most_applied,connection_health: data.connection_health,actions: data.actions,+ // Guarded: dreamSummary may arrive from an untyped JSON-RPC+ // boundary (or from a future caller that has not populated+ // every array). Optional-chain the inner length read.+ uncertain_count: opts.dreamSummary?.uncertain?.length ?? 0,+ quarantined_count: opts.dreamSummary?.quarantined?.length ?? 0,+ ...(opts.doctorResult?.trust_verdict !== undefined+ ? { trust_verdict: opts.doctorResult.trust_verdict }+ : {}),};return Object.freeze({content: JSON.stringify(payload, null, 2) + "\n",@@ -337,12 +376,36 @@ export function renderDigest(}// Markdown.- const content = empty+ const baseMd = empty? renderEmptyMarkdown(until): renderMarkdown(data, since, until);+ const trustSection = renderTrustSection(opts.doctorResult, opts.dreamSummary);+ const content = trustSection ? `${baseMd}\n${trustSection}` : baseMd;return Object.freeze({ content, empty });}+/**+ * Markdown `## Trust` section (v0.10.16). Rendered only when either+ * a doctor result or a dream summary is threaded through the digest+ * options - otherwise legacy output stays bit-identical.+ */+function renderTrustSection(+ doctor?: import("./doctor.ts").RunDoctorResult,+ dream?: import("./dream.ts").DreamRunSummary,+): string {+ if (doctor === undefined && dream === undefined) return "";+ const lines: string[] = ["## Trust", ""];+ if (doctor?.trust_verdict !== undefined) {+ lines.push(`- Verdict: **${doctor.trust_verdict}**`);+ }+ if (dream !== undefined) {+ lines.push(`- Uncertain: ${dream.uncertain.length}`);+ lines.push(`- Quarantined: ${dream.quarantined.length}`);+ }+ lines.push("");+ return lines.join("\n");+}+// ----- Data collection ------------------------------------------------------interface DigestData {diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 4c00e72c..c3d03e88 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -45,9 +45,16 @@ import { buildBacklinkIndex } from "./backlinks.ts";import { parseLogDay } from "./log.ts";import {BRAIN_CONFIG_SUPPORTED_VERSIONS,+ BRAIN_GUARDRAIL_DEFAULTS,BrainConfigError,loadBrainConfigDetailed,} from "./policy.ts";+import { computeTrustVerdict } from "./trust/compute-trust-verdict.ts";+import {+ computeVerificationDelta,+ type VerificationDeltaSummaryCounts,+} from "./trust/compute-verification-delta.ts";+import { checkInstructionFileCeiling } from "./trust/instruction-file-ceiling.ts";import { brainConfigPath, brainDirs } from "./paths.ts";import {BrainDoubleShapeError,@@ -94,11 +101,96 @@ export interface RunDoctorOptions {* Tests pin this for determinism.*/readonly now?: Date;+ /**+ * Optional precomputed dream summary (v0.10.16). When supplied,+ * the doctor runs the verification-delta helper and folds the+ * counts into the trust verdict. When omitted, verification+ * defaults to all-zero counts and the trust verdict is computed+ * against doctor signals alone.+ */+ readonly dreamSummary?: import("./dream.ts").DreamRunSummary;+ /**+ * Optional resolved guardrail config (v0.10.16). When omitted,+ * `BRAIN_GUARDRAIL_DEFAULTS` are used. Drives the+ * instruction-file-ceiling check.+ */+ readonly guardrails?: import("./types.ts").ResolvedBrainGuardrailConfig;+}++/**+ * Aggregate verdict introduced in v0.10.16. Compresses doctor errors,+ * dream warnings, and verification-delta counts into one of three+ * states an operator can act on at a glance.+ */+export type TrustVerdict = "clean" | "watch" | "investigate";++/**+ * Compact counts attached to a `RunDoctorResult` so callers can render+ * a one-line "verification delta: X drift, Y regression, Z missing"+ * summary without re-walking the vault. Full per-entry detail lives+ * on the trust-layer `operator_summary` composer.+ */+export interface VerificationDeltaSummary {+ readonly confirmed: number;+ readonly drift: number;+ readonly regression: number;+ readonly missing_evidence: number;+}++/**+ * Warning entry produced by the instruction-file-ceiling helper+ * (v0.10.16). Doctor surfaces these as a parallel array so the+ * trust verdict has structured input without having to grep the+ * generic `warnings` list.+ */+export interface InstructionFileCeilingWarning {+ /** Vault-relative path of the offending instruction file. */+ readonly path: string;+ /** Observed line count. */+ readonly lines: number;+ /** Configured ceiling at the time of the check. */+ readonly ceiling: number;+}++/**+ * Per-check uncertainty entry. Distinct from `warnings` / `errors`:+ * these are sub-operations the doctor attempted but cannot claim+ * completed cleanly (e.g. an instruction-file the doctor could not+ * read, a verification step that timed out). Empty on every clean+ * run. v0.10.16 extension point.+ */+export interface DoctorUncertainEntry {+ readonly code: string;+ readonly path?: string;+ readonly message: string;}export interface RunDoctorResult {readonly warnings: ReadonlyArray<DoctorIssue>;readonly errors: ReadonlyArray<DoctorIssue>;+ /**+ * Aggregate trust verdict (v0.10.16). Absent when the trust helper+ * was not invoked; consumers of `runDoctor` that only need the+ * legacy warning / error stream can ignore the field.+ */+ readonly trust_verdict?: TrustVerdict;+ /**+ * Counts of verification-delta states for the most recent dream+ * cycle. Absent when verification did not run.+ */+ readonly verification_delta_summary?: VerificationDeltaSummary;+ /**+ * Warnings emitted by the instruction-file-ceiling helper. Empty+ * when the helper did not run or no tracked file exceeded the+ * configured ceiling.+ */+ readonly instruction_file_warnings?: ReadonlyArray<InstructionFileCeilingWarning>;+ /**+ * Sub-operations the doctor attempted but could not fully verify.+ * Empty on every clean run; populated when an uncertainty-surfacing+ * helper is invoked.+ */+ readonly uncertain?: ReadonlyArray<DoctorUncertainEntry>;}// ----- Entry point ----------------------------------------------------------@@ -113,10 +205,14 @@ export function runDoctor(if (!existsSync(dirs.brain)) {// No Brain layer present is not an error here — `o2b brain init`// is the right command, but a vault without Brain is allowed in- // v0.9. Return clean.+ // v0.9. Return clean. v0.10.16: emit the new trust-layer fields+ // with their clean / empty defaults for shape symmetry with the+ // normal-return path.return Object.freeze({warnings: Object.freeze([]),errors: Object.freeze([]),+ trust_verdict: "clean" as TrustVerdict,+ instruction_file_warnings: Object.freeze([]),});}@@ -199,9 +295,44 @@ export function runDoctor(const warnings = issues.filter((i) => i.severity === "warning");const errors = issues.filter((i) => i.severity === "error");+ // v0.10.16 trust layer. Each computation is best-effort: a failure+ // in a helper must not poison the legacy warning / error stream.+ const guardrails = opts.guardrails ?? BRAIN_GUARDRAIL_DEFAULTS;+ let instructionWarnings: ReadonlyArray<InstructionFileCeilingWarning> = [];+ try {+ instructionWarnings = checkInstructionFileCeiling(vault, {+ maxLines: guardrails.instruction_file_max_lines,+ });+ } catch { /* doctor never throws */ }++ let verificationCounts: VerificationDeltaSummaryCounts | undefined;+ if (opts.dreamSummary !== undefined) {+ try {+ const delta = computeVerificationDelta(vault, opts.dreamSummary);+ verificationCounts = delta.summary;+ } catch { /* doctor never throws */ }+ }++ const trustVerdict: TrustVerdict = computeTrustVerdict({+ doctorWarnings: warnings,+ doctorErrors: errors,+ dreamWarnings: opts.dreamSummary?.warnings ?? [],+ verification: verificationCounts ?? {+ confirmed: 0,+ drift: 0,+ regression: 0,+ missing_evidence: 0,+ },+ });+return Object.freeze({warnings: Object.freeze(warnings),errors: Object.freeze(errors),+ trust_verdict: trustVerdict,+ ...(verificationCounts !== undefined+ ? { verification_delta_summary: verificationCounts }+ : {}),+ instruction_file_warnings: instructionWarnings,});}diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 058dccac..0b41492a 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -57,7 +57,8 @@ import {createSnapshot,pruneSnapshots,} from "./snapshot.ts";-import { loadBrainConfig } from "./policy.ts";+import { loadBrainConfig, resolveGuardrails } from "./policy.ts";+import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";import {brainDirs,preferencePath,@@ -93,6 +94,46 @@ export interface DreamWarning {readonly message: string;}+/**+ * Entry surfacing a step the dream pass attempted but could not+ * fully verify. Distinct from a `DreamWarning` (which flags+ * configuration smells): an `uncertain` entry means "I tried, no+ * hard error, but I cannot claim the operation completed". Consumed+ * by the trust verdict + operator summary (v0.10.16).+ */+export interface DreamUncertainEntry {+ /** Stable code identifying which sub-operation could not confirm. */+ readonly code: string;+ /** Optional topic slug or preference id this uncertainty concerns. */+ readonly topic?: string;+ /** Human-readable explanation. */+ readonly message: string;+}++/**+ * Entry surfacing a signal cluster that the self-approval guardrail+ * (v0.10.16) held back from promotion because one or more configured+ * thresholds were not met. Distinct from `suppressed` (which fires+ * on a user-rejected retired preference); a quarantined cluster+ * stays inbox-side and may promote on the next dream pass once+ * more evidence accumulates.+ */+export interface DreamQuarantinedEntry {+ /** Topic slug whose signals are held below the promotion threshold. */+ readonly topic: string;+ /** Count of accumulated same-sign signals. */+ readonly signal_count: number;+ /** Number of distinct agents that raised same-sign signals. */+ readonly distinct_agents: number;+ /** Age (in days) of the earliest signal in the cluster. */+ readonly age_days: number;+ /**+ * Which threshold(s) blocked promotion: any subset of+ * `min_signals`, `min_distinct_agents`, `min_age_days`.+ */+ readonly failed_gates: ReadonlyArray<string>;+}+export interface DreamRunSummary {/** `dream-YYYY-MM-DD-HHMMSS`. */readonly run_id: string;@@ -123,6 +164,19 @@ export interface DreamRunSummary {* extension point for future advisory checks.*/readonly warnings: ReadonlyArray<DreamWarning>;+ /**+ * Sub-operations the dream pass attempted but could not fully+ * verify. Empty on every clean run; populated by future+ * uncertainty-surfacing paths (v0.10.16).+ */+ readonly uncertain: ReadonlyArray<DreamUncertainEntry>;+ /**+ * Signal clusters held back from promotion by the self-approval+ * guardrail (v0.10.16). Empty when no cluster missed a threshold,+ * or when the guardrail is configured at default values that+ * match pre-v0.10.16 behaviour.+ */+ readonly quarantined: ReadonlyArray<DreamQuarantinedEntry>;/** Snapshot file (absent on a no-op run). */readonly snapshot_path?: string;/** Log file the run summary landed in (absent on a no-op run). */@@ -258,6 +312,10 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {plan.signalsToMove.size > 0 ||plan.retainPinned.length > 0 ||plan.signalsSuppressed.length > 0 ||+ // v0.10.16: quarantine is a recorded decision (deferred-but-noted),+ // so a run that produces only quarantine entries is still a+ // meaningful run from the operator's perspective.+ plan.quarantined.length > 0 ||scan.corrupted.length > 0;if (!changed) {@@ -272,6 +330,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {moved_to_processed: [],suppressed: [],warnings: Object.freeze([...warnings]),+ uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),+ quarantined: Object.freeze([...plan.quarantined]),...(dryRun ? { dry_run: true } : {}),} satisfies DreamRunSummary);}@@ -562,6 +622,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),),warnings: Object.freeze([...warnings]),+ uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),+ quarantined: Object.freeze([...plan.quarantined]),...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),...(dryRun? { dry_run: true }@@ -674,6 +736,15 @@ interface PlanState {* the inbox does not accumulate.*/readonly signalsSuppressed: SignalSuppressedPlan[];+ /**+ * Signal clusters held back from promotion by the self-approval+ * guardrail (v0.10.16). The cluster passed the existing+ * `candidate_threshold` but failed one or more configured+ * thresholds in `BrainGuardrailConfig`. Preserved across the plan+ * so it surfaces on the DreamRunSummary without affecting the+ * existing move-to-processed semantics.+ */+ readonly quarantined: DreamQuarantinedEntry[];}interface SignalSuppressedPlan {@@ -740,6 +811,7 @@ function emptyPlan(): PlanState {signalsToMove: new Map(),contradictionTopics: new Set(),signalsSuppressed: [],+ quarantined: [],};}@@ -853,6 +925,44 @@ function planTopics(const minoritySize = Math.min(positives.length, negatives.length);const dominantSize = dominant.length - minoritySize; // cancellationif (dominantSize >= cfg.dream.candidate_threshold) {+ // v0.10.16: extra self-approval guardrail. Defaults+ // (min_signals=2, min_distinct_agents=1, min_age_days=0) make+ // this check a no-op for clusters that already passed+ // candidate_threshold. Operators may opt into stricter+ // thresholds via `_brain.yaml:guardrails:*`. A failed gate+ // routes the cluster to `quarantined` instead of creating a+ // new unconfirmed preference; the contributing signals stay+ // in inbox/ so the cluster naturally re-evaluates on the next+ // pass once more evidence accumulates.+ const guardrails = resolveGuardrails(cfg);+ const distinctAgents = new Set(dominant.map((s) => s.signal.agent)).size;+ let earliestSignalMs = Number.POSITIVE_INFINITY;+ for (const s of dominant) {+ const t = Date.parse(s.signal.created_at);+ if (Number.isFinite(t) && t < earliestSignalMs) earliestSignalMs = t;+ }+ const ageDays =+ Number.isFinite(earliestSignalMs)+ ? Math.max(0, Math.floor((now.getTime() - earliestSignalMs) / (24 * 60 * 60 * 1000)))+ : 0;+ const verdict = applySelfApprovalGuardrail(+ {+ signal_count: dominantSize,+ distinct_agents: distinctAgents,+ age_days: ageDays,+ },+ guardrails,+ );+ if (verdict.decision === "quarantine") {+ plan.quarantined.push({+ topic,+ signal_count: dominantSize,+ distinct_agents: distinctAgents,+ age_days: ageDays,+ failed_gates: verdict.failed_gates,+ });+ continue;+ }// Decide supersede: if a retired pref for the same topic exists,// wire it through.const retiredForTopic = retiredByTopic.get(topic);diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 1aa412d3..a3ba0e61 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -24,9 +24,11 @@ import { existsSync, readFileSync } from "node:fs";import type {BrainActiveConfig,BrainConfig,+ BrainGuardrailConfig,BrainMostAppliedConfig,BrainVaultConfig,DisciplineReportConfig,+ ResolvedBrainGuardrailConfig,} from "./types.ts";// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to// break the module-init cycle: the resolver lives in `index.ts` and@@ -55,6 +57,66 @@ export const MOST_APPLIED_WINDOW_DAYS_DEFAULT = 30;/** Default top-N limit when `_brain.yaml` lacks `active.most_applied.limit`. */export const MOST_APPLIED_LIMIT_DEFAULT = 10;+/**+ * Hard upper bound on `guardrails.instruction_file_max_lines`. Any+ * value above this is a misconfiguration - vault-root instruction+ * files are intended to stay small for compliance reasons, so a+ * ceiling like 100000 lines silently disables the warning.+ */+export const INSTRUCTION_FILE_MAX_LINES_CEILING = 10000;++/**+ * Default `guardrails` block (v0.10.16). When `_brain.yaml` omits+ * `guardrails` (or omits individual fields), `resolveGuardrails`+ * returns these values so consumers can rely on a fully-populated+ * struct.+ *+ * Defaults are chosen to be strictly looser than every existing+ * dream-pass gate so adding the guardrail cannot block a promotion+ * that previously succeeded:+ * - `promotion_min_signals: 1` is below any sane+ * `dream.candidate_threshold` (default 3). When an operator+ * tunes `candidate_threshold` below 2, the guardrail still+ * cannot block them by default - explicit opt-in is required+ * via the `_brain.yaml:guardrails:promotion_min_signals` field.+ * - `promotion_min_distinct_agents: 1` imposes no cross-agent+ * requirement.+ * - `promotion_min_age_days: 0` disables the age gate.+ * - `instruction_file_max_lines: 200` matches the documented+ * compliance ceiling.+ */+export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.freeze({+ promotion_min_signals: 1,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 200,+}) as ResolvedBrainGuardrailConfig;++/**+ * Merge a parsed `guardrails` block (or `undefined`) with+ * `BRAIN_GUARDRAIL_DEFAULTS`. Returns a fully-populated struct so+ * consumers do not branch on optional fields.+ */+export function resolveGuardrails(+ cfg: BrainConfig,+): ResolvedBrainGuardrailConfig {+ const g = cfg.guardrails;+ if (g === undefined) return BRAIN_GUARDRAIL_DEFAULTS;+ return {+ promotion_min_signals:+ g.promotion_min_signals ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals,+ promotion_min_distinct_agents:+ g.promotion_min_distinct_agents ??+ BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,+ promotion_min_age_days:+ g.promotion_min_age_days ??+ BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,+ instruction_file_max_lines:+ g.instruction_file_max_lines ??+ BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,+ };+}+/*** Default `_brain.yaml` content. Mirrors §10 of the design doc. Used by* `brain init` and as the fallback inside `loadBrainConfig` when callers@@ -679,6 +741,98 @@ export function validateBrainConfigDetailed(}}+ // Optional `guardrails` block (v0.10.16). Hard-error on shape+ // problems - thresholds are operator-tunable and silent fallback+ // would mask the operator's intent. Missing block leaves+ // `cfg.guardrails` undefined; `resolveGuardrails` injects defaults+ // on the read side so consumers receive a fully-populated struct.+ let guardrails: BrainGuardrailConfig | undefined;+ if ("guardrails" in obj) {+ const raw = obj["guardrails"];+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw new BrainConfigError(+ `block must be a map of keys; got ${describe(raw)}`,+ "guardrails",+ source,+ );+ }+ const rawMap = raw as Record<string, unknown>;+ const partial: {+ promotion_min_signals?: number;+ promotion_min_distinct_agents?: number;+ promotion_min_age_days?: number;+ instruction_file_max_lines?: number;+ } = {};++ if ("promotion_min_signals" in rawMap) {+ requirePositiveInteger(+ "guardrails.promotion_min_signals",+ rawMap["promotion_min_signals"],+ source,+ );+ partial.promotion_min_signals = rawMap["promotion_min_signals"] as number;+ }+ if ("promotion_min_distinct_agents" in rawMap) {+ requirePositiveInteger(+ "guardrails.promotion_min_distinct_agents",+ rawMap["promotion_min_distinct_agents"],+ source,+ );+ partial.promotion_min_distinct_agents = rawMap[+ "promotion_min_distinct_agents"+ ] as number;+ }+ if ("promotion_min_age_days" in rawMap) {+ requireNonNegativeInteger(+ "guardrails.promotion_min_age_days",+ rawMap["promotion_min_age_days"],+ source,+ );+ partial.promotion_min_age_days = rawMap["promotion_min_age_days"] as number;+ }+ if ("instruction_file_max_lines" in rawMap) {+ requirePositiveInteger(+ "guardrails.instruction_file_max_lines",+ rawMap["instruction_file_max_lines"],+ source,+ );+ const v = rawMap["instruction_file_max_lines"] as number;+ if (v > INSTRUCTION_FILE_MAX_LINES_CEILING) {+ throw new BrainConfigError(+ `must be at most ${INSTRUCTION_FILE_MAX_LINES_CEILING}; got ${describe(v)}`,+ "guardrails.instruction_file_max_lines",+ source,+ );+ }+ partial.instruction_file_max_lines = v;+ }++ // Forward-compat: unknown sub-keys under `guardrails:` → warning.+ const knownGuardrailKeys = new Set([+ "promotion_min_signals",+ "promotion_min_distinct_agents",+ "promotion_min_age_days",+ "instruction_file_max_lines",+ ]);+ for (const key of Object.keys(rawMap)) {+ if (!knownGuardrailKeys.has(key)) {+ warnings.push({+ path: source ?? "<config>",+ message: `guardrails.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }++ if (Object.keys(partial).length > 0) {+ guardrails = partial;+ } else {+ // Block present but contained only unknown fields: keep an+ // empty marker so `cfg.guardrails` is non-undefined and+ // distinguishable from "block absent entirely".+ guardrails = {};+ }+ }+// Forward-compat: unknown top-level keys → warning, not error.const known = new Set(["schema_version",@@ -690,6 +844,7 @@ export function validateBrainConfigDetailed("vault","active","discipline_report",+ "guardrails",]);for (const key of Object.keys(obj)) {if (!known.has(key)) {@@ -724,6 +879,7 @@ export function validateBrainConfigDetailed(...(vault !== undefined ? { vault } : {}),...(active !== undefined ? { active } : {}),...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),+ ...(guardrails !== undefined ? { guardrails } : {}),};return { config, warnings };diff --git a/src/core/brain/sessions/validate-feedback.ts b/src/core/brain/sessions/validate-feedback.tsindex c3217f96..81833620 100644--- a/src/core/brain/sessions/validate-feedback.ts+++ b/src/core/brain/sessions/validate-feedback.ts@@ -12,6 +12,7 @@* envelope (`MCPError` for MCP, soft warning for import).*/+import { assessRuleQuality } from "../trust/assess-rule-quality.ts";import { BRAIN_SIGNAL_SIGN } from "../types.ts";export interface ValidatedFeedback {@@ -83,6 +84,19 @@ export function validateBrainFeedbackInput(input: unknown): ValidationResult {return { ok: false, reason: "brain_feedback missing required field: principle" };}+ // v0.10.16: structural quality gate. Reject only on structurally-broken+ // input (empty, single token). Warn-level findings are advisory and do+ // not block submission - the operator may still write a long or filler-+ // heavy principle if they accept the trade-off. The detector is+ // language-agnostic by construction (codepoint shape only).+ const quality = assessRuleQuality(principle);+ if (quality.severity === "reject") {+ return {+ ok: false,+ reason: `brain_feedback principle failed quality gate: ${quality.reasons.join(", ")}`,+ };+ }+const scope = optionalString(record["scope"]);if (scope === "INVALID") return { ok: false, reason: "scope must be a string" };diff --git a/src/core/brain/trust/assess-rule-quality.ts b/src/core/brain/trust/assess-rule-quality.tsnew file mode 100644index 00000000..a28a9bff--- /dev/null+++ b/src/core/brain/trust/assess-rule-quality.ts@@ -0,0 +1,129 @@+/**+ * Structural quality gate for taste signals (v0.10.16).+ *+ * Returns a `severity` of `ok | warn | reject` plus a list of+ * structural reasons. The detector is **language-agnostic by+ * construction**: it never consults a vocabulary list, stopword set,+ * unit dictionary, or any per-language data. All checks operate on+ * codepoint shape - digit presence, operator-shape character+ * presence, token count, single-character token ratio.+ *+ * The intent is to reject obviously unusable principles (empty,+ * single token) and warn on principles that are structurally weak+ * (no measurable outcome, mostly single-character filler, too long+ * to be remembered) without ever encoding "vague" words. A rule+ * like `"be careful"` and a rule like `"<some-language>-equivalent+ * of be-careful"` must be treated identically - the detector cannot+ * tell them apart and that is the point.+ */++/** Length thresholds. Tunable; chosen by structural feel. */+const MAX_CHARS = 500;+const MAX_TOKENS = 80;++/**+ * Above this ratio of single-character alphanumeric tokens to total+ * tokens, the principle is flagged as filler. 0.4 means "if more+ * than 40% of tokens are single letters / digits, the rule is too+ * sparse to be testable".+ */+const FILLER_RATIO_THRESHOLD = 0.4;++/** Operator-shape characters. Universal ASCII relational operators. */+const OPERATOR_CHARS_RE = /[<>=%]/;++/**+ * Digit codepoint test. `\d` with the `u` flag matches `[0-9]` only+ * in most engines; we want the broadest sense, so we also test the+ * Unicode "Number" property via the `\p{N}` escape.+ */+const NUMBER_CODEPOINT_RE = /[\p{N}]/u;++/**+ * Single-character alphanumeric token shape: exactly one codepoint+ * that is a Unicode letter or number. Punctuation, symbols, and+ * whitespace fall out because of the `\p{L}|\p{N}` constraint.+ */+const SINGLE_ALNUM_TOKEN_RE = /^[\p{L}\p{N}]$/u;++/**+ * Punctuation stripper. Removes anything that is NOT a letter,+ * number, or whitespace - so the token splitter only sees the+ * meaningful content. Codepoint shape only; no Latin assumption.+ */+const PUNCT_RE = /[^\p{L}\p{N}\s]/gu;++export interface RuleQualityResult {+ /**+ * Numeric score in `[0, 1]`. Higher is healthier. The score is+ * informational - `severity` is the gate consumers act on.+ */+ readonly score: number;+ /** Gate verdict. */+ readonly severity: "ok" | "warn" | "reject";+ /** Structural reasons that fired during the check. */+ readonly reasons: ReadonlyArray<string>;+}++export function assessRuleQuality(principle: string): RuleQualityResult {+ const reasons: string[] = [];++ // 1. Empty / whitespace-only -> reject.+ const trimmed = principle.trim();+ if (trimmed.length === 0) {+ return Object.freeze({+ score: 0,+ severity: "reject" as const,+ reasons: Object.freeze(["empty"]),+ });+ }++ // 2. Tokenise on whitespace after stripping punctuation. We keep+ // the original string for character-presence checks (operator+ // chars and digits can live inside or next to punctuation).+ const stripped = trimmed.replace(PUNCT_RE, " ");+ const tokens = stripped.split(/\s+/u).filter((t) => t.length > 0);++ if (tokens.length <= 1) {+ return Object.freeze({+ score: 0,+ severity: "reject" as const,+ reasons: Object.freeze(["single-token"]),+ });+ }++ // 3. Length warnings.+ if (trimmed.length > MAX_CHARS || tokens.length > MAX_TOKENS) {+ reasons.push("too-long");+ }++ // 4. Measurable-signal: any digit anywhere OR any operator char.+ // Both checks operate on raw codepoints - language-blind.+ const hasDigit = NUMBER_CODEPOINT_RE.test(trimmed);+ const hasOperator = OPERATOR_CHARS_RE.test(trimmed);+ if (!hasDigit && !hasOperator) {+ reasons.push("no-measurable-signal");+ }++ // 5. Filler ratio: single-character alphanumeric tokens are+ // presumed filler at this granularity.+ const singleCharCount = tokens.filter((t) => SINGLE_ALNUM_TOKEN_RE.test(t)).length;+ const fillerRatio = singleCharCount / tokens.length;+ if (fillerRatio > FILLER_RATIO_THRESHOLD) {+ reasons.push("filler-ratio-high");+ }++ // 6. Score: 1.0 minus the count of fired reasons divided by the+ // number of warning checks (three: too-long, no-measurable-+ // signal, filler-ratio-high). Clamped to [0, 1].+ const NUM_WARN_CHECKS = 3;+ const score = Math.max(0, Math.min(1, 1 - reasons.length / NUM_WARN_CHECKS));++ const severity = reasons.length > 0 ? "warn" : "ok";++ return Object.freeze({+ score,+ severity,+ reasons: Object.freeze(reasons.slice()),+ });+}diff --git a/src/core/brain/trust/check-role-permission.ts b/src/core/brain/trust/check-role-permission.tsnew file mode 100644index 00000000..5909b95b--- /dev/null+++ b/src/core/brain/trust/check-role-permission.ts@@ -0,0 +1,102 @@+/**+ * Role-separated brain permission gate (v0.10.16).+ *+ * Each MCP brain tool nominates a role (writer, dreamer, applier).+ * Each role is allowed a static subset of operations. The gate is+ * advisory: it does not access the file system, it does not mutate+ * state, it returns a structured decision the caller surfaces as a+ * rejection.+ *+ * Promoting an existing preference to `confirmed` is the one+ * operation that also gates on the source status: the dreamer may+ * only promote a preference that is currently `unconfirmed`.+ * Attempting to "re-promote" an already-confirmed preference is+ * rejected with `wrong-source-state`.+ */++import type {+ BrainPreferenceStatus,+} from "../types.ts";+import {+ BRAIN_OPERATIONS,+ BRAIN_ROLES,+ type BrainOperation,+ type BrainRole,+} from "./role.ts";++export interface RolePermissionResult {+ readonly allowed: boolean;+ /** Structured reason populated when `allowed` is `false`. */+ readonly reason?: string;+}++/**+ * Static role -> set-of-allowed-operations matrix. Used as a quick+ * membership check before any status-dependent refinement.+ */+const ALLOWED: ReadonlyMap<BrainRole, ReadonlySet<BrainOperation>> = new Map([+ [+ BRAIN_ROLES.writer,+ new Set<BrainOperation>([+ BRAIN_OPERATIONS.feedback_write,+ BRAIN_OPERATIONS.preference_create_unconfirmed,+ ]),+ ],+ [+ BRAIN_ROLES.dreamer,+ new Set<BrainOperation>([+ BRAIN_OPERATIONS.preference_promote_confirmed,+ BRAIN_OPERATIONS.preference_retire,+ ]),+ ],+ [+ BRAIN_ROLES.applier,+ new Set<BrainOperation>([+ BRAIN_OPERATIONS.evidence_record,+ BRAIN_OPERATIONS.log_append,+ ]),+ ],+ [BRAIN_ROLES.unknown, new Set<BrainOperation>()],+]);++export function checkRolePermission(+ role: BrainRole,+ op: BrainOperation,+ currentStatus?: BrainPreferenceStatus,+): RolePermissionResult {+ const allowed = ALLOWED.get(role);+ if (allowed === undefined || !allowed.has(op)) {+ return Object.freeze({+ allowed: false,+ reason: `role '${role}' is not permitted to perform '${op}'`,+ });+ }++ // Status-dependent refinement: a dreamer can only promote a+ // preference that is currently `unconfirmed`. Re-promoting an+ // already-confirmed preference (or one that has been retired) is+ // a no-op at best and a permission violation at worst.+ //+ // Fail-closed contract: when `currentStatus` is undefined for the+ // promote operation, the caller could not determine the source+ // state - we reject rather than silently allow. Callers that+ // genuinely know the preference is unconfirmed must say so+ // explicitly.+ if (op === BRAIN_OPERATIONS.preference_promote_confirmed) {+ if (currentStatus === undefined) {+ return Object.freeze({+ allowed: false,+ reason:+ "wrong-source-state: currentStatus is required for preference_promote_confirmed",+ });+ }+ if (currentStatus !== "unconfirmed") {+ return Object.freeze({+ allowed: false,+ reason: `wrong-source-state: cannot promote from '${currentStatus}', expected 'unconfirmed'`,+ });+ }+ }++ return Object.freeze({ allowed: true });+}diff --git a/src/core/brain/trust/compute-trust-verdict.ts b/src/core/brain/trust/compute-trust-verdict.tsnew file mode 100644index 00000000..18d9a6f2--- /dev/null+++ b/src/core/brain/trust/compute-trust-verdict.ts@@ -0,0 +1,58 @@+/**+ * Aggregate trust verdict (v0.10.16).+ *+ * Compresses three independent signals - doctor errors / warnings,+ * dream warnings, verification-delta counts - into one of three+ * states an operator can act on at a glance.+ *+ * Threshold model:+ * - `investigate` - any doctor error; any regression; any+ * missing_evidence; or drift count above the+ * `driftWatchThreshold` (default 3).+ * - `watch` - any doctor warning; any dream warning; or+ * drift count between 1 and the threshold.+ * - `clean` - none of the above. Confirmed verification+ * entries never downgrade the verdict (they+ * are the positive case).+ */++import type { DoctorIssue, TrustVerdict } from "../doctor.ts";+import type { DreamWarning } from "../dream.ts";+import type { VerificationDeltaSummaryCounts } from "./compute-verification-delta.ts";++const DEFAULT_DRIFT_WATCH_THRESHOLD = 3;++export interface TrustVerdictInput {+ readonly doctorWarnings: ReadonlyArray<DoctorIssue>;+ readonly doctorErrors: ReadonlyArray<DoctorIssue>;+ readonly dreamWarnings: ReadonlyArray<DreamWarning>;+ readonly verification: VerificationDeltaSummaryCounts;+ /**+ * Inclusive upper bound on drift count for the `watch` band.+ * Above this, drift contributes to `investigate`. Defaults to 3.+ */+ readonly driftWatchThreshold?: number;+}++export function computeTrustVerdict(input: TrustVerdictInput): TrustVerdict {+ const threshold = input.driftWatchThreshold ?? DEFAULT_DRIFT_WATCH_THRESHOLD;++ if (+ input.doctorErrors.length > 0 ||+ input.verification.regression > 0 ||+ input.verification.missing_evidence > 0 ||+ input.verification.drift > threshold+ ) {+ return "investigate";+ }++ if (+ input.doctorWarnings.length > 0 ||+ input.dreamWarnings.length > 0 ||+ input.verification.drift > 0+ ) {+ return "watch";+ }++ return "clean";+}diff --git a/src/core/brain/trust/compute-verification-delta.ts b/src/core/brain/trust/compute-verification-delta.tsnew file mode 100644index 00000000..78400c39--- /dev/null+++ b/src/core/brain/trust/compute-verification-delta.ts@@ -0,0 +1,282 @@+/**+ * Verification delta (v0.10.16).+ *+ * Independent verification layer that compares a dream-pass summary+ * against the current vault state and classifies each cited+ * preference id into one of four states:+ *+ * - `confirmed` - preference exists on disk and the dream+ * claim matches state (applied_count > 0+ * where applicable).+ * - `drift` - preference exists, status matches the+ * dream claim, but applied_count is zero+ * ("claimed applied but no artifact ever+ * recorded").+ * - `regression` - the preference cited as confirmed is now+ * present in `Brain/retired/` (moved out+ * after the dream claim).+ * - `missing_evidence` - the dream cites a `pref-*` id with no+ * corresponding file on disk.+ *+ * The function is pure read-only: it never mutates the vault. It+ * defers all file parsing to the existing `parsePreference` /+ * `parseRetired` helpers, so any parse error surfaces as a single+ * `missing_evidence` entry (the artifact is unreachable from this+ * read path).+ */++import { existsSync } from "node:fs";++import type { DreamRunSummary } from "../dream.ts";+import { preferencePath, retiredPath, vaultRelative } from "../paths.ts";+import { parsePreference } from "../preference.ts";++export type VerificationDeltaState =+ | "confirmed"+ | "drift"+ | "regression"+ | "missing_evidence";++export interface VerificationDeltaEntry {+ /** `pref-*` id from the dream summary. */+ readonly id: string;+ readonly state: VerificationDeltaState;+ /** Vault-relative path of the artifact that triggered the verdict (when present). */+ readonly path?: string;+ /** Optional one-line context for the operator. */+ readonly note?: string;+}++export interface VerificationDeltaSummaryCounts {+ readonly confirmed: number;+ readonly drift: number;+ readonly regression: number;+ readonly missing_evidence: number;+}++export interface VerificationDeltaResult {+ readonly entries: ReadonlyArray<VerificationDeltaEntry>;+ readonly summary: VerificationDeltaSummaryCounts;+}++export function computeVerificationDelta(+ vault: string,+ dream: DreamRunSummary,+): VerificationDeltaResult {+ const entries: VerificationDeltaEntry[] = [];++ for (const id of dream.confirmed) {+ entries.push(classifyConfirmedClaim(vault, id));+ }++ // `new_unconfirmed` entries are treated like a freshly-claimed+ // preference: existence is enough; the applied_count is not yet+ // expected to be non-zero.+ for (const id of dream.new_unconfirmed) {+ entries.push(classifyUnconfirmedClaim(vault, id));+ }++ // Retired entries: dream said "I just retired this". Verify the+ // retired file exists.+ for (const rec of dream.retired) {+ entries.push(classifyRetiredClaim(vault, rec.id));+ }++ const summary: VerificationDeltaSummaryCounts = {+ confirmed: countBy(entries, "confirmed"),+ drift: countBy(entries, "drift"),+ regression: countBy(entries, "regression"),+ missing_evidence: countBy(entries, "missing_evidence"),+ };++ return Object.freeze({+ entries: Object.freeze(entries),+ summary: Object.freeze(summary),+ });+}++function classifyConfirmedClaim(vault: string, id: string): VerificationDeltaEntry {+ const slug = stripPrefPrefix(id);+ if (slug === null) {+ return Object.freeze({ id, state: "missing_evidence", note: "unrecognised id prefix" });+ }+ // Path construction can throw for slugs that violate the slug-safety+ // contract (`validateSlug` inside `preferencePath`). A malformed id+ // is a missing-evidence verdict, not a fatal abort.+ let prefPath: string;+ try {+ prefPath = preferencePath(vault, slug);+ } catch (err) {+ return Object.freeze({+ id,+ state: "missing_evidence",+ note: `invalid slug: ${(err as Error).message}`,+ });+ }+ if (existsSync(prefPath)) {+ try {+ const pref = parsePreference(prefPath);+ // Validate the on-disk status against the dream claim. If dream+ // said "confirmed" but the file is still `unconfirmed` (or+ // sitting in `quarantine`), the claim does not match disk.+ // Report as drift even when applied_count is non-zero. The+ // `retired` status never lands here because retired pages live+ // under `retired/`, not `preferences/`.+ if (pref.status !== "confirmed") {+ return Object.freeze({+ id,+ state: "drift",+ path: vaultRelative(prefPath, vault),+ note: `claimed confirmed but on-disk status is '${pref.status}'`,+ });+ }+ if (pref.applied_count > 0) {+ return Object.freeze({+ id,+ state: "confirmed",+ path: vaultRelative(prefPath, vault),+ });+ }+ return Object.freeze({+ id,+ state: "drift",+ path: vaultRelative(prefPath, vault),+ note: "claimed confirmed but applied_count is zero",+ });+ } catch (err) {+ return Object.freeze({+ id,+ state: "missing_evidence",+ path: vaultRelative(prefPath, vault),+ note: `parse error: ${(err as Error).message}`,+ });+ }+ }+ // Not under preferences/: check whether it moved to retired/.+ let retPath: string;+ try {+ retPath = retiredPath(vault, slug);+ } catch {+ return Object.freeze({ id, state: "missing_evidence" });+ }+ if (existsSync(retPath)) {+ return Object.freeze({+ id,+ state: "regression",+ path: vaultRelative(retPath, vault),+ note: "dream claimed confirmed but preference is now retired",+ });+ }+ return Object.freeze({ id, state: "missing_evidence" });+}++function classifyUnconfirmedClaim(vault: string, id: string): VerificationDeltaEntry {+ const slug = stripPrefPrefix(id);+ if (slug === null) {+ return Object.freeze({ id, state: "missing_evidence", note: "unrecognised id prefix" });+ }+ let prefPath: string;+ try {+ prefPath = preferencePath(vault, slug);+ } catch (err) {+ return Object.freeze({+ id,+ state: "missing_evidence",+ note: `invalid slug: ${(err as Error).message}`,+ });+ }+ if (existsSync(prefPath)) {+ return Object.freeze({+ id,+ state: "confirmed",+ path: vaultRelative(prefPath, vault),+ });+ }+ let retPath: string;+ try {+ retPath = retiredPath(vault, slug);+ } catch {+ return Object.freeze({ id, state: "missing_evidence" });+ }+ if (existsSync(retPath)) {+ return Object.freeze({+ id,+ state: "regression",+ path: vaultRelative(retPath, vault),+ note: "dream claimed unconfirmed but preference is already retired",+ });+ }+ return Object.freeze({ id, state: "missing_evidence" });+}++function classifyRetiredClaim(vault: string, id: string): VerificationDeltaEntry {+ const slug = stripRetPrefix(id);+ if (slug === null) {+ return Object.freeze({ id, state: "missing_evidence", note: "unrecognised id prefix" });+ }+ let retPath: string;+ try {+ retPath = retiredPath(vault, slug);+ } catch (err) {+ return Object.freeze({+ id,+ state: "missing_evidence",+ note: `invalid slug: ${(err as Error).message}`,+ });+ }+ if (existsSync(retPath)) {+ return Object.freeze({+ id,+ state: "confirmed",+ path: vaultRelative(retPath, vault),+ });+ }+ // Symmetric to `classifyConfirmedClaim`: if dream said "retired"+ // but the file is still under preferences/ (i.e. dream's claim does+ // not match disk), treat as a regression rather than as+ // missing_evidence so the verdict reflects the disagreement.+ let stillActivePath: string;+ try {+ stillActivePath = preferencePath(vault, slug);+ } catch {+ return Object.freeze({+ id,+ state: "missing_evidence",+ note: "dream claimed retired but no file under retired/",+ });+ }+ if (existsSync(stillActivePath)) {+ return Object.freeze({+ id,+ state: "regression",+ path: vaultRelative(stillActivePath, vault),+ note: "dream claimed retired but preference is still under preferences/",+ });+ }+ return Object.freeze({+ id,+ state: "missing_evidence",+ note: "dream claimed retired but no file under retired/",+ });+}++function stripPrefPrefix(id: string): string | null {+ if (id.startsWith("pref-")) return id.slice("pref-".length);+ return null;+}++function stripRetPrefix(id: string): string | null {+ if (id.startsWith("ret-")) return id.slice("ret-".length);+ return null;+}++function countBy(+ entries: ReadonlyArray<VerificationDeltaEntry>,+ state: VerificationDeltaState,+): number {+ let n = 0;+ for (const e of entries) {+ if (e.state === state) n += 1;+ }+ return n;+}diff --git a/src/core/brain/trust/instruction-file-ceiling.ts b/src/core/brain/trust/instruction-file-ceiling.tsnew file mode 100644index 00000000..ea77ec7b--- /dev/null+++ b/src/core/brain/trust/instruction-file-ceiling.ts@@ -0,0 +1,77 @@+/**+ * Instruction-file compliance ceiling (v0.10.16).+ *+ * Vault-root instruction files (`CLAUDE.md`, `AGENTS.md`,+ * `GEMINI.md`) keep agents pointed at the project's norms. Past a+ * line-count ceiling, compliance drops sharply because important+ * rules get buried in noise. This helper walks a fixed list of+ * tracked filenames at the vault root and returns a warning for+ * each one that exceeds the configured ceiling.+ *+ * The list is intentionally short and explicit - discovery is by+ * existence, not by pattern. Files that are not present return no+ * warning. Empty files return no warning either (zero is not above+ * any non-negative ceiling).+ */++import { existsSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import type { InstructionFileCeilingWarning } from "../doctor.ts";++const TRACKED_FILES: ReadonlyArray<string> = Object.freeze([+ "CLAUDE.md",+ "AGENTS.md",+ "GEMINI.md",+]);++export interface CheckInstructionFileCeilingOptions {+ readonly maxLines: number;+}++export function checkInstructionFileCeiling(+ vault: string,+ opts: CheckInstructionFileCeilingOptions,+): ReadonlyArray<InstructionFileCeilingWarning> {+ const warnings: InstructionFileCeilingWarning[] = [];+ for (const name of TRACKED_FILES) {+ const absolute = join(vault, name);+ if (!existsSync(absolute)) continue;+ try {+ const stat = statSync(absolute);+ if (!stat.isFile()) continue;+ } catch {+ // Race: file vanished between existsSync and statSync. Skip.+ continue;+ }+ let content: string;+ try {+ content = readFileSync(absolute, "utf8");+ } catch {+ continue;+ }+ if (content.length === 0) continue;+ const lines = countLines(content);+ if (lines > opts.maxLines) {+ warnings.push(+ Object.freeze({+ path: name,+ lines,+ ceiling: opts.maxLines,+ }),+ );+ }+ }+ return Object.freeze(warnings);+}++function countLines(content: string): number {+ if (content.length === 0) return 0;+ // Count `\n` and add one when the file does not end with one.+ let n = 0;+ for (let i = 0; i < content.length; i += 1) {+ if (content.charCodeAt(i) === 0x0a) n += 1;+ }+ if (content.charCodeAt(content.length - 1) !== 0x0a) n += 1;+ return n;+}diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.tsnew file mode 100644index 00000000..d4b7dbd1--- /dev/null+++ b/src/core/brain/trust/operator-summary.ts@@ -0,0 +1,256 @@+/**+ * Operator summary composer (v0.10.16).+ *+ * One read-only call that aggregates the three independent brain+ * surfaces - doctor, dream, vault metadata - into a unified envelope:+ *+ * - `trust_verdict` - `clean | watch | investigate`+ * - `digest_summary` - preference status counts+ * - `doctor_summary` - warning / error counts+ * - `dream_summary` - warning / uncertain / quarantined counts+ * - `verification_delta` - confirmed / drift / regression / missing+ * - `top_actions` - ranked maintenance action list+ * - `instruction_file_warnings`- ceiling breaches at vault root+ *+ * The composer never mutates the vault. It accepts a precomputed+ * dream summary so callers can choose between "run dream first" and+ * "skip dream entirely"; verification delta falls back to all-zero+ * counts when no dream is supplied.+ */++import { existsSync, readdirSync, statSync } from "node:fs";++import type { DoctorIssue } from "../doctor.ts";+import { runDoctor, type RunDoctorResult, type TrustVerdict } from "../doctor.ts";+import type { DreamRunSummary } from "../dream.ts";+import {+ collectMaintenanceActions,+} from "../maintenance/collect.ts";+import type { ActionItem } from "../maintenance/action-scorer.ts";+import { brainDirs } from "../paths.ts";+import {+ BRAIN_GUARDRAIL_DEFAULTS,+} from "../policy.ts";+import type { ResolvedBrainGuardrailConfig } from "../types.ts";+import {+ computeVerificationDelta,+ type VerificationDeltaResult,+} from "./compute-verification-delta.ts";+import { computeTrustVerdict } from "./compute-trust-verdict.ts";+import { checkInstructionFileCeiling } from "./instruction-file-ceiling.ts";+import type { InstructionFileCeilingWarning } from "../doctor.ts";++export interface OperatorSummary {+ readonly trust_verdict: TrustVerdict;+ readonly digest_summary: DigestSummary;+ readonly doctor_summary: DoctorSummary;+ readonly dream_summary: DreamSummary;+ readonly verification_delta: VerificationDeltaResult;+ readonly top_actions: ReadonlyArray<ActionItem>;+ readonly instruction_file_warnings: ReadonlyArray<InstructionFileCeilingWarning>;+}++export interface DigestSummary {+ readonly preference_count: number;+ readonly retired_count: number;+ readonly inbox_count: number;+}++export interface DoctorSummary {+ readonly warning_count: number;+ readonly error_count: number;+ readonly warnings: ReadonlyArray<DoctorIssue>;+ readonly errors: ReadonlyArray<DoctorIssue>;+}++export interface DreamSummary {+ readonly warning_count: number;+ readonly uncertain_count: number;+ readonly quarantined_count: number;+}++export interface BuildOperatorSummaryOptions {+ /**+ * Recent dream-pass summary. Verification delta is computed+ * against this; when omitted, all verification counts default to+ * zero.+ */+ readonly dreamSummary?: DreamRunSummary;+ /**+ * Resolved guardrail config. Drives the instruction-file ceiling+ * check. Defaults to `BRAIN_GUARDRAIL_DEFAULTS`.+ */+ readonly guardrails?: ResolvedBrainGuardrailConfig;+ /** Top-N cap on the maintenance action list. */+ readonly topActionsN?: number;+}++const DEFAULT_TOP_ACTIONS_N = 5;++export function buildOperatorSummary(+ vault: string,+ opts: BuildOperatorSummaryOptions,+): OperatorSummary {+ const guardrails = opts.guardrails ?? BRAIN_GUARDRAIL_DEFAULTS;+ const dreamSummary = opts.dreamSummary;++ const doctorResult = safeDoctor(vault, guardrails, dreamSummary);+ const dreamCounts = summariseDream(dreamSummary);+ const digestCounts = collectDigestCounts(vault);+ const verification = dreamSummary+ ? computeVerificationDelta(vault, dreamSummary)+ : zeroVerification();+ const instructionWarnings = checkInstructionFileCeiling(vault, {+ maxLines: guardrails.instruction_file_max_lines,+ });+ const topActions = safeTopActions(vault, opts.topActionsN ?? DEFAULT_TOP_ACTIONS_N);++ const trust = computeTrustVerdict({+ doctorWarnings: doctorResult.warnings,+ doctorErrors: doctorResult.errors,+ dreamWarnings: dreamSummary?.warnings ?? [],+ verification: verification.summary,+ });++ return Object.freeze({+ trust_verdict: trust,+ digest_summary: digestCounts,+ doctor_summary: Object.freeze({+ warning_count: doctorResult.warnings.length,+ error_count: doctorResult.errors.length,+ warnings: doctorResult.warnings,+ errors: doctorResult.errors,+ }),+ dream_summary: dreamCounts,+ verification_delta: verification,+ top_actions: topActions,+ instruction_file_warnings: instructionWarnings,+ });+}++/**+ * Markdown rendering of the operator summary. Sections mirror the+ * JSON envelope; no headings for sections that are entirely empty.+ */+export function renderOperatorSummaryMarkdown(summary: OperatorSummary): string {+ const out: string[] = [];+ out.push("# Operator summary");+ out.push("");+ out.push(`Trust: **${summary.trust_verdict}**`);+ out.push("");+ out.push(+ `Doctor: ${summary.doctor_summary.warning_count} warning(s), ${summary.doctor_summary.error_count} error(s)`,+ );+ out.push(+ `Dream: ${summary.dream_summary.warning_count} warning(s), ${summary.dream_summary.uncertain_count} uncertain, ${summary.dream_summary.quarantined_count} quarantined`,+ );+ out.push(+ `Verification: ${summary.verification_delta.summary.confirmed} confirmed, ${summary.verification_delta.summary.drift} drift, ${summary.verification_delta.summary.regression} regression, ${summary.verification_delta.summary.missing_evidence} missing_evidence`,+ );+ out.push("");+ out.push(+ `Vault: ${summary.digest_summary.preference_count} preferences, ${summary.digest_summary.retired_count} retired, ${summary.digest_summary.inbox_count} inbox`,+ );++ if (summary.instruction_file_warnings.length > 0) {+ out.push("");+ out.push("## Instruction file warnings");+ out.push("");+ for (const w of summary.instruction_file_warnings) {+ out.push(`- \`${w.path}\` - ${w.lines} lines (ceiling ${w.ceiling})`);+ }+ }++ if (summary.top_actions.length > 0) {+ out.push("");+ out.push("## Top actions");+ out.push("");+ for (const a of summary.top_actions) {+ out.push(`- ${a.category}: ${a.title}`);+ }+ }++ out.push("");+ return out.join("\n");+}++// ----- Internals -----------------------------------------------------------++function safeDoctor(+ vault: string,+ guardrails: ResolvedBrainGuardrailConfig,+ dreamSummary: DreamRunSummary | undefined,+): RunDoctorResult {+ try {+ return runDoctor(vault, {+ guardrails,+ ...(dreamSummary ? { dreamSummary } : {}),+ });+ } catch {+ return Object.freeze({ warnings: [], errors: [] });+ }+}++function summariseDream(dream: DreamRunSummary | undefined): DreamSummary {+ if (dream === undefined) {+ return Object.freeze({+ warning_count: 0,+ uncertain_count: 0,+ quarantined_count: 0,+ });+ }+ return Object.freeze({+ warning_count: dream.warnings.length,+ uncertain_count: dream.uncertain.length,+ quarantined_count: dream.quarantined.length,+ });+}++function collectDigestCounts(vault: string): DigestSummary {+ const dirs = brainDirs(vault);+ return Object.freeze({+ preference_count: countMarkdownFiles(dirs.preferences),+ retired_count: countMarkdownFiles(dirs.retired),+ inbox_count: countMarkdownFiles(dirs.inbox),+ });+}++function countMarkdownFiles(dir: string): number {+ if (!existsSync(dir)) return 0;+ try {+ let n = 0;+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md")) continue;+ try {+ const s = statSync(`${dir}/${name}`);+ if (s.isFile()) n += 1;+ } catch {+ // Race: skip+ }+ }+ return n;+ } catch {+ return 0;+ }+}++function safeTopActions(vault: string, topN: number): ReadonlyArray<ActionItem> {+ try {+ const all = collectMaintenanceActions(vault);+ return Object.freeze(all.slice(0, Math.max(0, topN)));+ } catch {+ return Object.freeze([]);+ }+}++function zeroVerification(): VerificationDeltaResult {+ return Object.freeze({+ entries: Object.freeze([]),+ summary: Object.freeze({+ confirmed: 0,+ drift: 0,+ regression: 0,+ missing_evidence: 0,+ }),+ });+}diff --git a/src/core/brain/trust/role.ts b/src/core/brain/trust/role.tsnew file mode 100644index 00000000..dfe98ec6--- /dev/null+++ b/src/core/brain/trust/role.ts@@ -0,0 +1,68 @@+/**+ * Brain tool role and operation enumeration.+ *+ * Each MCP brain tool runs under one role. Each role is allowed only a+ * static subset of operations on the brain state. The matrix lives in+ * `check-role-permission.ts`; this file is the data-shape atom that+ * both the helper and any caller surface through.+ *+ * Roles:+ * - `writer` - tools that accept new taste signals from agents+ * (`brain_feedback`).+ * - `dreamer` - the deterministic learning pass that promotes or+ * retires preferences (`brain_dream`).+ * - `applier` - tools that record narrative milestones or evidence+ * against existing preferences (`brain_apply_evidence`,+ * `brain_note`).+ * - `unknown` - default fallback when the caller did not declare a+ * role. The permission helper rejects all operations+ * in this role.+ *+ * Operations are the smallest unit at which boundaries are enforced:+ * - `feedback_write` - write an inbox signal file.+ * - `preference_create_unconfirmed`- materialise a new unconfirmed+ * preference under+ * `Brain/preferences/`.+ * - `preference_promote_confirmed` - flip a preference from+ * unconfirmed to confirmed.+ * - `preference_retire` - move a preference to+ * `Brain/retired/`.+ * - `evidence_record` - append an apply/violate/outdated+ * event to the daily log.+ * - `log_append` - append a narrative note event.+ */++export const BRAIN_ROLES = Object.freeze({+ writer: "writer",+ dreamer: "dreamer",+ applier: "applier",+ unknown: "unknown",+} as const);++export type BrainRole = (typeof BRAIN_ROLES)[keyof typeof BRAIN_ROLES];++const ROLE_SET: ReadonlySet<string> = new Set(Object.values(BRAIN_ROLES));++export function isBrainRole(value: unknown): value is BrainRole {+ return typeof value === "string" && ROLE_SET.has(value);+}++export const BRAIN_OPERATIONS = Object.freeze({+ feedback_write: "feedback_write",+ preference_create_unconfirmed: "preference_create_unconfirmed",+ preference_promote_confirmed: "preference_promote_confirmed",+ preference_retire: "preference_retire",+ evidence_record: "evidence_record",+ log_append: "log_append",+} as const);++export type BrainOperation =+ (typeof BRAIN_OPERATIONS)[keyof typeof BRAIN_OPERATIONS];++const OPERATION_SET: ReadonlySet<string> = new Set(+ Object.values(BRAIN_OPERATIONS),+);++export function isBrainOperation(value: unknown): value is BrainOperation {+ return typeof value === "string" && OPERATION_SET.has(value);+}diff --git a/src/core/brain/trust/self-approval-guardrail.ts b/src/core/brain/trust/self-approval-guardrail.tsnew file mode 100644index 00000000..a2a23780--- /dev/null+++ b/src/core/brain/trust/self-approval-guardrail.ts@@ -0,0 +1,61 @@+/**+ * Self-approval guardrail (v0.10.16).+ *+ * The dream pass clusters same-sign signals into preference+ * candidates. Before promoting a candidate to `confirmed`, the+ * guardrail checks three configurable thresholds:+ *+ * - `promotion_min_signals` - cluster size (signal count)+ * - `promotion_min_distinct_agents` - how many distinct agents+ * raised same-sign signals+ * - `promotion_min_age_days` - age (in days) of the+ * earliest signal in the+ * cluster+ *+ * When any threshold fails, promotion is blocked and the candidate+ * lands in the quarantine list with the set of failing gates. The+ * gates run independently so multiple failures surface together.+ *+ * Defaults from `BRAIN_GUARDRAIL_DEFAULTS` are tuned to keep+ * pre-v0.10.16 behaviour bit-identical: `min_signals=2`,+ * `min_distinct_agents=1`, `min_age_days=0`.+ */++import type { ResolvedBrainGuardrailConfig } from "../types.ts";++export interface SelfApprovalInput {+ /** Count of same-sign signals in the candidate cluster. */+ readonly signal_count: number;+ /** Number of distinct agents that raised same-sign signals. */+ readonly distinct_agents: number;+ /** Age (in days) of the earliest signal in the cluster. */+ readonly age_days: number;+}++export interface SelfApprovalResult {+ readonly decision: "promote" | "quarantine";+ /** Names of gates that blocked promotion. Empty on `promote`. */+ readonly failed_gates: ReadonlyArray<string>;+}++export function applySelfApprovalGuardrail(+ input: SelfApprovalInput,+ config: ResolvedBrainGuardrailConfig,+): SelfApprovalResult {+ const failed: string[] = [];++ if (input.signal_count < config.promotion_min_signals) {+ failed.push("min_signals");+ }+ if (input.distinct_agents < config.promotion_min_distinct_agents) {+ failed.push("min_distinct_agents");+ }+ if (input.age_days < config.promotion_min_age_days) {+ failed.push("min_age_days");+ }++ return Object.freeze({+ decision: failed.length === 0 ? ("promote" as const) : ("quarantine" as const),+ failed_gates: Object.freeze(failed.slice()),+ });+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 4bfa3105..0b5d91db 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -690,6 +690,42 @@ export interface DisciplineReportConfig {readonly known_agents: ReadonlyArray<string>;}+/**+ * Optional `guardrails:` block (v0.10.16). Tunes the dream pass+ * self-approval thresholds (`promotion_*`) and the doctor+ * instruction-file-ceiling warning (`instruction_file_max_lines`).+ *+ * Any subset of the four fields may be present; missing fields fall+ * back to `BRAIN_GUARDRAIL_DEFAULTS` via `resolveGuardrails`. Absent+ * block leaves the field undefined and keeps current behaviour+ * bit-identical.+ */+export interface BrainGuardrailConfig {+ /**+ * Minimum same-sign signal count required for the dream pass to+ * auto-promote a topic from unconfirmed to confirmed. Below this,+ * the topic is quarantined and waits for more evidence.+ */+ readonly promotion_min_signals?: number;+ /**+ * Minimum number of distinct agents that must have raised+ * same-sign signals for the topic. Defaults to `1` (i.e. no+ * cross-agent requirement).+ */+ readonly promotion_min_distinct_agents?: number;+ /**+ * Minimum age (in days) of the earliest signal in the cluster+ * before promotion is permitted. `0` means "no age gate".+ */+ readonly promotion_min_age_days?: number;+ /**+ * Hard ceiling (in lines) on vault-root instruction files+ * (`CLAUDE.md`, `AGENTS.md`, `GEMINI.md`). Files above this size+ * surface a doctor warning.+ */+ readonly instruction_file_max_lines?: number;+}+/*** Root of `Brain/_brain.yaml`. `schema_version` is mandatory; unknown* top-level keys are tolerated as forward-compat (logged as a warning by@@ -727,4 +763,24 @@ export interface BrainConfig {readonly active?: BrainActiveConfig;/** Optional daily discipline-report configuration (§D). Absent when not configured. */readonly discipline_report?: DisciplineReportConfig;+ /**+ * Optional `guardrails:` block (v0.10.16). Tunes the dream pass+ * self-approval thresholds and the instruction-file-ceiling+ * warning. Absent: callers fall back to `BRAIN_GUARDRAIL_DEFAULTS`+ * via `resolveGuardrails`, keeping current behaviour bit-identical.+ */+ readonly guardrails?: BrainGuardrailConfig;+}++/**+ * Concrete (fully-resolved) guardrail config. Returned by+ * `resolveGuardrails(cfg)` so consumers do not have to handle+ * optionals - the resolver fills missing fields with+ * `BRAIN_GUARDRAIL_DEFAULTS`.+ */+export interface ResolvedBrainGuardrailConfig {+ readonly promotion_min_signals: number;+ readonly promotion_min_distinct_agents: number;+ readonly promotion_min_age_days: number;+ readonly instruction_file_max_lines: number;}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex e0b139a8..8cd01cd8 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -62,6 +62,8 @@ import {} from "../core/brain/digest.ts";import { dream } from "../core/brain/dream.ts";import { runDoctor } from "../core/brain/doctor.ts";+import { buildOperatorSummary } from "../core/brain/trust/operator-summary.ts";+import { BRAIN_ROLES } from "../core/brain/trust/role.ts";import {BrainNotFoundError,queryByLogSince,@@ -259,7 +261,20 @@ async function toolBrainDream(retired: summary.retired.map((r) => ({ id: r.id, reason: r.reason })),contradictions: [...summary.contradictions],moved_to_processed: [...summary.moved_to_processed],+ suppressed: [...summary.suppressed],warnings: summary.warnings.map((w) => ({ code: w.code, message: w.message })),+ uncertain: summary.uncertain.map((u) => ({+ code: u.code,+ ...(u.topic !== undefined ? { topic: u.topic } : {}),+ message: u.message,+ })),+ quarantined: summary.quarantined.map((q) => ({+ topic: q.topic,+ signal_count: q.signal_count,+ distinct_agents: q.distinct_agents,+ age_days: q.age_days,+ failed_gates: [...q.failed_gates],+ })),snapshot_path: summary.snapshot_path? vaultRelativeSafe(ctx.vault, summary.snapshot_path): null,@@ -306,8 +321,12 @@ async function toolBrainApplyEvidence(// (isError: true) rather than an MCP protocol error. The design doc// says "not an error condition" — the agent should see an informative// payload that explains what to do next, not a JSON-RPC error frame.+ // v0.10.16: assert applier role at the MCP boundary so the structural+ // permission gate fires before any I/O.try {- const res = appendApplyEvidence(ctx.vault, input);+ const res = appendApplyEvidence(ctx.vault, input, {+ role: BRAIN_ROLES.applier,+ });return {logged_at: res.logged_at,log_path: vaultRelativeSafe(ctx.vault, res.log_path),@@ -611,6 +630,22 @@ async function toolBrainDoctor(impact: a.impact,...(a.target !== undefined ? { target: a.target } : {}),})),+ // v0.10.16: trust-layer fields. `trust_verdict` is always populated+ // by runDoctor; `verification_delta_summary` only when the caller+ // threads a dream summary through (not exposed via this tool's+ // surface, so it stays absent here). `instruction_file_warnings`+ // surfaces vault-root instruction files exceeding the configured+ // ceiling.+ ...(result.trust_verdict !== undefined+ ? { trust_verdict: result.trust_verdict }+ : {}),+ instruction_file_warnings: (result.instruction_file_warnings ?? []).map(+ (w) => ({+ path: w.path,+ lines: w.lines,+ ceiling: w.ceiling,+ }),+ ),};}@@ -729,6 +764,97 @@ export function vaultRelativeSafe(vault: string, target: string): string {// ----- Tool registration ---------------------------------------------------+// ----- brain_operator_summary (v0.10.16) -----------------------------------++/**+ * Aggregate operator dashboard: trust verdict, doctor / dream+ * counts, verification delta summary, ranked maintenance actions,+ * and instruction-file ceiling warnings - one read-only call so an+ * operator does not run `brain_digest` + `brain_doctor` separately.+ */+async function toolBrainOperatorSummary(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const topRaw = args["top_actions"];+ let topActionsN: number | undefined;+ if (topRaw !== undefined && topRaw !== null) {+ // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other+ // shapes `Number.parseInt` would silently accept. Only a pure+ // integer literal is allowed.+ if (typeof topRaw === "number") {+ if (!Number.isInteger(topRaw) || topRaw < 0) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_operator_summary: top_actions must be a non-negative integer",+ );+ }+ topActionsN = topRaw;+ } else if (typeof topRaw === "string") {+ const trimmed = topRaw.trim();+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_operator_summary: top_actions must be a non-negative integer",+ );+ }+ topActionsN = Number.parseInt(trimmed, 10);+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_operator_summary: top_actions must be a non-negative integer",+ );+ }+ }++ const includeDreamRaw = args["include_dream"];+ let includeDream: boolean;+ if (includeDreamRaw === undefined || includeDreamRaw === null) {+ includeDream = true;+ } else if (typeof includeDreamRaw === "boolean") {+ includeDream = includeDreamRaw;+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_operator_summary: include_dream must be a boolean",+ );+ }++ let dreamSummary;+ let dreamError: string | undefined;+ if (includeDream) {+ try {+ dreamSummary = dream(ctx.vault, { dryRun: true });+ } catch (err) {+ // Surface the failure so callers know the dashboard is missing+ // verification + dream signals; do not silently produce a+ // partial envelope.+ dreamError = (err as Error).message ?? String(err);+ }+ }+ const summary = buildOperatorSummary(ctx.vault, {+ ...(dreamSummary ? { dreamSummary } : {}),+ ...(topActionsN !== undefined ? { topActionsN } : {}),+ });+ return {+ vault_path: ctx.vault,+ trust_verdict: summary.trust_verdict,+ digest_summary: summary.digest_summary,+ doctor_summary: {+ warning_count: summary.doctor_summary.warning_count,+ error_count: summary.doctor_summary.error_count,+ },+ dream_summary: summary.dream_summary,+ verification_delta: {+ summary: summary.verification_delta.summary,+ entries: summary.verification_delta.entries,+ },+ top_actions: summary.top_actions,+ instruction_file_warnings: summary.instruction_file_warnings,+ ...(dreamError !== undefined ? { dream_error: dreamError } : {}),+ };+}+// ----- brain_context_pack (v0.10.15) ---------------------------------------/**@@ -1050,4 +1176,26 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainContextPack,},+ {+ name: "brain_operator_summary",+ description:+ "Aggregate operator dashboard: trust verdict, doctor + dream counts, verification delta, ranked maintenance actions, and instruction-file ceiling warnings. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ include_dream: {+ type: "boolean",+ description:+ "When true (default), run a dry-run dream pass and fold its verification delta into the summary.",+ },+ top_actions: {+ type: "integer",+ minimum: 0,+ description: "Cap on the ranked maintenance action list. Defaults to 5.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainOperatorSummary,+ },]);diff --git a/tests/cli/brain-summary-cli.test.ts b/tests/cli/brain-summary-cli.test.tsnew file mode 100644index 00000000..43300e22--- /dev/null+++ b/tests/cli/brain-summary-cli.test.ts@@ -0,0 +1,71 @@+/**+ * CLI smoke test for `o2b brain summary` (v0.10.16).+ */++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 { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-summary-cli-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");++ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-summary-cli-cfg-"));+ configPath = join(configHome, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++describe("o2b brain summary", () => {+ test("clean vault: prints markdown report with trust=clean", async () => {+ const r = await runCli(["brain", "summary", "--skip-dream"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("# Operator summary");+ expect(r.stdout).toContain("Trust: **clean**");+ });++ test("--json prints structured envelope", async () => {+ const r = await runCli(["brain", "summary", "--skip-dream", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as { trust_verdict: string };+ expect(payload.trust_verdict).toBe("clean");+ });++ test("--help prints the verb help", async () => {+ const r = await runCli(["brain", "summary", "--help"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("brain summary");+ expect(r.stdout).toContain("--skip-dream");+ });++ test("rejects --top-actions=-1", async () => {+ const r = await runCli(+ ["brain", "summary", "--skip-dream", "--top-actions", "-1"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(1);+ });+});diff --git a/tests/core/brain.doctor-trust-atoms.test.ts b/tests/core/brain.doctor-trust-atoms.test.tsnew file mode 100644index 00000000..62c48059--- /dev/null+++ b/tests/core/brain.doctor-trust-atoms.test.ts@@ -0,0 +1,63 @@+/**+ * v0.10.16: `RunDoctorResult` gains four optional trust-layer fields.+ * Atom commit asserts the public shape and the absent-by-default+ * contract; population lands in the consumer commit that wires the+ * trust helpers into the doctor pass.+ */++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 { runDoctor } from "../../src/core/brain/doctor.ts";+import {+ brainConfigPath,+ brainDirs,+} from "../../src/core/brain/paths.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-doctor-trust-atoms-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(brainConfigPath(tmp), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("RunDoctorResult trust-layer atoms", () => {+ test("clean vault: legacy fields empty, trust verdict computed by C4", () => {+ const result = runDoctor(tmp);+ // Old surface unchanged.+ expect(result.warnings).toEqual([]);+ expect(result.errors).toEqual([]);+ // New optional fields: trust_verdict is populated by the C4+ // integration (default `clean` on a healthy vault); the rest+ // remain absent / empty because no dream summary was supplied.+ expect(result.trust_verdict).toBe("clean");+ expect(result.verification_delta_summary).toBeUndefined();+ expect(result.instruction_file_warnings ?? []).toEqual([]);+ expect(result.uncertain ?? []).toEqual([]);+ });++ test("frozen result", () => {+ const result = runDoctor(tmp);+ expect(Object.isFrozen(result)).toBe(true);+ });+});diff --git a/tests/core/brain.dream-guardrail.test.ts b/tests/core/brain.dream-guardrail.test.tsnew file mode 100644index 00000000..925ce96b--- /dev/null+++ b/tests/core/brain.dream-guardrail.test.ts@@ -0,0 +1,103 @@+/**+ * v0.10.16: dream pass invokes the self-approval guardrail before+ * creating a new unconfirmed preference. Default config preserves+ * pre-v0.10.16 behaviour (defaults are strictly looser than every+ * existing dream-pass gate, so the guardrail never blocks by+ * default); a tighter guardrail routes the cluster to `quarantined`+ * instead.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { dream } from "../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { brainConfigPath } from "../../src/core/brain/paths.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";++let vault: string;++const ONE_DAY = 24 * 60 * 60 * 1000;++function writeBrainCfg(vault: string, body: string) {+ writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);+}++function seedPositiveSignals(+ vault: string,+ count: number,+ agent: string,+ topic = "test-topic",+ ageDays = 1,+): void {+ const baseDate = new Date(Date.now() - ageDays * ONE_DAY);+ for (let i = 0; i < count; i += 1) {+ const created = new Date(baseDate.getTime() - i * 1000);+ const date = created.toISOString().slice(0, 10);+ writeSignal(vault, {+ slug: `${topic}-${agent}-${i}`,+ date,+ created_at: created.toISOString(),+ topic,+ signal: "positive",+ agent,+ principle: "limit X to 10",+ });+ }+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-guardrail-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("dream + self-approval guardrail (default config)", () => {+ test("3 signals from 1 agent: promotes (default min_distinct_agents=1)", () => {+ seedPositiveSignals(vault, 3, "agent-a");+ const res = dream(vault);+ expect(res.new_unconfirmed).toEqual(["pref-test-topic"]);+ expect(res.quarantined).toEqual([]);+ });++ test("2 signals from 1 agent: blocked by candidate_threshold, not by guardrail", () => {+ seedPositiveSignals(vault, 2, "agent-a");+ const res = dream(vault);+ expect(res.new_unconfirmed).toEqual([]);+ // candidate_threshold filtered before guardrail, so no quarantine+ // entry is recorded either.+ expect(res.quarantined).toEqual([]);+ });+});++describe("dream + self-approval guardrail (tighter config)", () => {+ test("3 signals from 1 agent: quarantined when min_distinct_agents=2", () => {+ writeBrainCfg(+ vault,+ `guardrails:\n promotion_min_distinct_agents: 2\n`,+ );+ seedPositiveSignals(vault, 3, "agent-a");+ const res = dream(vault);+ expect(res.new_unconfirmed).toEqual([]);+ expect(res.quarantined).toHaveLength(1);+ expect(res.quarantined[0]?.topic).toBe("test-topic");+ expect(res.quarantined[0]?.failed_gates).toContain("min_distinct_agents");+ });++ test("cluster from two agents passes min_distinct_agents=2", () => {+ writeBrainCfg(+ vault,+ `guardrails:\n promotion_min_distinct_agents: 2\n`,+ );+ seedPositiveSignals(vault, 2, "agent-a", "test-topic", 1);+ seedPositiveSignals(vault, 2, "agent-b", "test-topic", 1);+ const res = dream(vault);+ expect(res.new_unconfirmed).toEqual(["pref-test-topic"]);+ expect(res.quarantined).toEqual([]);+ });+});diff --git a/tests/core/brain.dream-uncertain.test.ts b/tests/core/brain.dream-uncertain.test.tsnew file mode 100644index 00000000..5333cfb8--- /dev/null+++ b/tests/core/brain.dream-uncertain.test.ts@@ -0,0 +1,48 @@+/**+ * v0.10.16: `DreamRunSummary` gains `uncertain` and `quarantined`+ * arrays. This atom commit only asserts both fields are present and+ * empty on every dream-pass return path; populating them lands in+ * the consumer commit that wires self-approval-guardrail into the+ * pass.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { dream } from "../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-uncertain-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("DreamRunSummary uncertain + quarantined atoms", () => {+ test("no-op run returns both arrays empty", () => {+ const res = dream(vault);+ expect(res.changed).toBe(false);+ expect(res.uncertain).toEqual([]);+ expect(res.quarantined).toEqual([]);+ });++ test("dry-run no-op also has empty atoms", () => {+ const res = dream(vault, { dryRun: true });+ expect(res.uncertain).toEqual([]);+ expect(res.quarantined).toEqual([]);+ });++ test("frozen result and nested arrays cannot mutate", () => {+ const res = dream(vault);+ expect(Object.isFrozen(res)).toBe(true);+ expect(Object.isFrozen(res.uncertain)).toBe(true);+ expect(Object.isFrozen(res.quarantined)).toBe(true);+ });+});diff --git a/tests/core/brain.sessions.validate-feedback.test.ts b/tests/core/brain.sessions.validate-feedback.test.tsindex 39aab021..15fa6786 100644--- a/tests/core/brain.sessions.validate-feedback.test.ts+++ b/tests/core/brain.sessions.validate-feedback.test.ts@@ -27,7 +27,7 @@ describe("validateBrainFeedbackInput", () => {const r = validateBrainFeedbackInput({topic: "t",signal: "positive",- principle: "p",+ principle: "limit retries to 10 per hour",scope: "writing",agent: "claude",raw: "quoted text",diff --git a/tests/core/brain/apply-evidence-role.test.ts b/tests/core/brain/apply-evidence-role.test.tsnew file mode 100644index 00000000..7cca9c06--- /dev/null+++ b/tests/core/brain/apply-evidence-role.test.ts@@ -0,0 +1,115 @@+/**+ * v0.10.16: brain_apply_evidence integrates check-role-permission. The+ * applier role may record evidence; writer and dreamer roles are+ * rejected with a structured error.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ appendApplyEvidence,+ BrainRolePermissionError,+} from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { BRAIN_ROLES } from "../../../src/core/brain/trust/role.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-apply-role-"));+ bootstrapBrain(vault);+ writePreference(vault, {+ slug: "test-rule",+ topic: "test",+ principle: "limit X to 10",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-1]]"],+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-22T00:00:00Z",+ confidence: "low",+ });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("apply-evidence role enforcement", () => {+ test("applier role can record evidence", () => {+ const r = appendApplyEvidence(+ vault,+ {+ pref_id: "test-rule",+ artifact: "[[example]]",+ result: "applied",+ agent: "test-agent",+ },+ { role: BRAIN_ROLES.applier },+ );+ expect(r.logged_at).toBeTruthy();+ });++ test("writer role rejected with BrainRolePermissionError", () => {+ expect(() =>+ appendApplyEvidence(+ vault,+ {+ pref_id: "test-rule",+ artifact: "[[example]]",+ result: "applied",+ agent: "test-agent",+ },+ { role: BRAIN_ROLES.writer },+ ),+ ).toThrow(BrainRolePermissionError);+ });++ test("dreamer role rejected", () => {+ expect(() =>+ appendApplyEvidence(+ vault,+ {+ pref_id: "test-rule",+ artifact: "[[example]]",+ result: "applied",+ agent: "test-agent",+ },+ { role: BRAIN_ROLES.dreamer },+ ),+ ).toThrow(BrainRolePermissionError);+ });++ test("unknown role rejected", () => {+ expect(() =>+ appendApplyEvidence(+ vault,+ {+ pref_id: "test-rule",+ artifact: "[[example]]",+ result: "applied",+ agent: "test-agent",+ },+ { role: BRAIN_ROLES.unknown },+ ),+ ).toThrow(BrainRolePermissionError);+ });++ test("role omitted: backward-compatible (no enforcement)", () => {+ // Existing callers that never threaded a role through stay green.+ const r = appendApplyEvidence(vault, {+ pref_id: "test-rule",+ artifact: "[[example]]",+ result: "applied",+ agent: "test-agent",+ });+ expect(r.logged_at).toBeTruthy();+ });+});diff --git a/tests/core/brain/digest-trust-atoms.test.ts b/tests/core/brain/digest-trust-atoms.test.tsnew file mode 100644index 00000000..918bdb1a--- /dev/null+++ b/tests/core/brain/digest-trust-atoms.test.ts@@ -0,0 +1,43 @@+/**+ * v0.10.16: `DigestJson` gains optional `trust_verdict` plus+ * `uncertain_count` and `quarantined_count`. Atom commit asserts the+ * shape and the absent-by-default contract; the consumer commit+ * threads doctor / dream inputs into the digest renderer.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import type { DigestJson } from "../../../src/core/brain/digest.ts";+import { renderDigest } from "../../../src/core/brain/digest.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-digest-trust-atoms-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("DigestJson trust-layer atoms", () => {+ test("clean vault: trust_verdict absent, counts zero", () => {+ const result = renderDigest(vault, { format: "json" });+ const payload = JSON.parse(result.content) as DigestJson;+ expect(payload.trust_verdict).toBeUndefined();+ expect(payload.uncertain_count).toBe(0);+ expect(payload.quarantined_count).toBe(0);+ });++ test("markdown digest still renders without trust fields", () => {+ const result = renderDigest(vault, { format: "markdown" });+ expect(typeof result.content).toBe("string");+ // No `## Trust` section appears when no trust input was provided.+ expect(result.content).not.toContain("## Trust");+ });+});diff --git a/tests/core/brain/digest-trust.test.ts b/tests/core/brain/digest-trust.test.tsnew file mode 100644index 00000000..50bc78e8--- /dev/null+++ b/tests/core/brain/digest-trust.test.ts@@ -0,0 +1,92 @@+/**+ * v0.10.16: digest renders the trust-layer fields when supplied with+ * a doctor result and / or a dream summary. Clean vault input keeps+ * the markdown and JSON output bit-identical to v0.10.15 when no+ * trust input is threaded through.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import type { DigestJson } from "../../../src/core/brain/digest.ts";+import { renderDigest } from "../../../src/core/brain/digest.ts";+import { runDoctor } from "../../../src/core/brain/doctor.ts";+import type { DreamRunSummary } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++let vault: string;++function emptyDream(over: Partial<DreamRunSummary> = {}): DreamRunSummary {+ return Object.freeze({+ run_id: "dream-2026-05-25-000000",+ changed: false,+ new_unconfirmed: [],+ confirmed: [],+ retired: [],+ contradictions: [],+ moved_to_processed: [],+ suppressed: [],+ warnings: [],+ uncertain: [],+ quarantined: [],+ ...over,+ }) as DreamRunSummary;+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-digest-trust-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("digest trust integration", () => {+ test("JSON: trust_verdict + counts populate when inputs supplied", () => {+ const doctor = runDoctor(vault);+ const dream = emptyDream({+ uncertain: [{ code: "u", message: "m" }] as DreamRunSummary["uncertain"],+ quarantined: [+ {+ topic: "t",+ signal_count: 2,+ distinct_agents: 1,+ age_days: 0,+ failed_gates: ["min_distinct_agents"],+ },+ ] as DreamRunSummary["quarantined"],+ });+ const r = renderDigest(vault, {+ format: "json",+ doctorResult: doctor,+ dreamSummary: dream,+ });+ const payload = JSON.parse(r.content) as DigestJson;+ expect(payload.trust_verdict).toBe("clean");+ expect(payload.uncertain_count).toBe(1);+ expect(payload.quarantined_count).toBe(1);+ });++ test("markdown shows the Trust section when input supplied", () => {+ const doctor = runDoctor(vault);+ const dream = emptyDream();+ const r = renderDigest(vault, {+ format: "markdown",+ doctorResult: doctor,+ dreamSummary: dream,+ });+ expect(r.content).toContain("## Trust");+ expect(r.content).toContain("clean");+ });++ test("no trust inputs: digest stays bit-identical to v0.10.15 surface", () => {+ const r = renderDigest(vault, { format: "json" });+ const payload = JSON.parse(r.content) as DigestJson;+ expect(payload.trust_verdict).toBeUndefined();+ expect(payload.uncertain_count).toBe(0);+ expect(payload.quarantined_count).toBe(0);+ });+});diff --git a/tests/core/brain/doctor-trust.test.ts b/tests/core/brain/doctor-trust.test.tsnew file mode 100644index 00000000..c7d5d034--- /dev/null+++ b/tests/core/brain/doctor-trust.test.ts@@ -0,0 +1,97 @@+/**+ * v0.10.16: doctor pass wires the trust helpers - instruction-file+ * ceiling, verification delta (when a dream summary is supplied), and+ * trust verdict. Tests cover the clean path, the ceiling-breach path,+ * and verification-delta integration.+ */++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 { runDoctor } from "../../../src/core/brain/doctor.ts";+import type { DreamRunSummary } from "../../../src/core/brain/dream.ts";+import {+ brainConfigPath,+ brainDirs,+} from "../../../src/core/brain/paths.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let vault: string;++function emptyDream(over: Partial<DreamRunSummary> = {}): DreamRunSummary {+ return Object.freeze({+ run_id: "dream-2026-05-25-000000",+ changed: false,+ new_unconfirmed: [],+ confirmed: [],+ retired: [],+ contradictions: [],+ moved_to_processed: [],+ suppressed: [],+ warnings: [],+ uncertain: [],+ quarantined: [],+ ...over,+ }) as DreamRunSummary;+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-doctor-trust-"));+ const dirs = brainDirs(vault);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(brainConfigPath(vault), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("runDoctor - trust integration", () => {+ test("clean vault: trust_verdict = clean", () => {+ const result = runDoctor(vault);+ expect(result.trust_verdict).toBe("clean");+ expect(result.instruction_file_warnings ?? []).toEqual([]);+ });++ test("long CLAUDE.md surfaces instruction-file warning", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "x\n".repeat(300));+ const result = runDoctor(vault);+ expect(result.instruction_file_warnings ?? []).toHaveLength(1);+ expect(result.instruction_file_warnings![0]?.path).toBe("CLAUDE.md");+ expect(result.instruction_file_warnings![0]?.lines).toBe(300);+ });++ test("dream summary citing missing pref triggers investigate verdict", () => {+ const result = runDoctor(vault, {+ dreamSummary: emptyDream({ confirmed: ["pref-ghost"] }),+ });+ expect(result.verification_delta_summary?.missing_evidence).toBe(1);+ expect(result.trust_verdict).toBe("investigate");+ });++ test("ceiling can be overridden via guardrails option", () => {+ writeFileSync(join(vault, "AGENTS.md"), "y\n".repeat(50));+ const result = runDoctor(vault, {+ guardrails: {+ promotion_min_signals: 2,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 30,+ },+ });+ expect(result.instruction_file_warnings ?? []).toHaveLength(1);+ });+});diff --git a/tests/core/brain/policy-guardrails.test.ts b/tests/core/brain/policy-guardrails.test.tsnew file mode 100644index 00000000..df04faa9--- /dev/null+++ b/tests/core/brain/policy-guardrails.test.ts@@ -0,0 +1,142 @@+/**+ * `guardrails` block (v0.10.16) - controls self-approval thresholds and+ * instruction-file-ceiling warning.+ */++import { describe, expect, test } from "bun:test";++import {+ BRAIN_GUARDRAIL_DEFAULTS,+ BrainConfigError,+ parseBrainYaml,+ resolveGuardrails,+ validateBrainConfigDetailed,+} from "../../../src/core/brain/policy.ts";++function validate(yaml: string) {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");+}++const HEAD = `schema_version: 1\n`;++describe("BRAIN_GUARDRAIL_DEFAULTS", () => {+ test("documents the four threshold defaults", () => {+ expect(BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals).toBe(1);+ expect(BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents).toBe(1);+ expect(BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days).toBe(0);+ expect(BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines).toBe(200);+ });+});++describe("guardrails config block", () => {+ test("absent block → cfg.guardrails is undefined; resolveGuardrails returns defaults", () => {+ const { config } = validate(HEAD);+ expect(config.guardrails).toBeUndefined();+ expect(resolveGuardrails(config)).toEqual(BRAIN_GUARDRAIL_DEFAULTS);+ });++ test("present with all four fields → loaded fully", () => {+ const { config } = validate(+ HEAD ++ `guardrails:\n` ++ ` promotion_min_signals: 3\n` ++ ` promotion_min_distinct_agents: 2\n` ++ ` promotion_min_age_days: 7\n` ++ ` instruction_file_max_lines: 300\n`,+ );+ expect(config.guardrails).toEqual({+ promotion_min_signals: 3,+ promotion_min_distinct_agents: 2,+ promotion_min_age_days: 7,+ instruction_file_max_lines: 300,+ });+ expect(resolveGuardrails(config).instruction_file_max_lines).toBe(300);+ });++ test("partial block → missing fields fall back to defaults via resolveGuardrails", () => {+ const { config } = validate(+ HEAD + `guardrails:\n promotion_min_signals: 5\n`,+ );+ expect(config.guardrails?.promotion_min_signals).toBe(5);+ const resolved = resolveGuardrails(config);+ expect(resolved.promotion_min_signals).toBe(5);+ expect(resolved.instruction_file_max_lines).toBe(+ BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,+ );+ expect(resolved.promotion_min_distinct_agents).toBe(+ BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,+ );+ });++ test("promotion_min_signals: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n promotion_min_signals: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("promotion_min_signals: negative rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n promotion_min_signals: -1\n`),+ ).toThrow(BrainConfigError);+ });++ test("promotion_min_signals: non-integer rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n promotion_min_signals: 2.5\n`),+ ).toThrow(BrainConfigError);+ });++ test("promotion_min_distinct_agents: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n promotion_min_distinct_agents: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("promotion_min_age_days: 0 accepted (means disabled)", () => {+ const { config } = validate(+ HEAD + `guardrails:\n promotion_min_age_days: 0\n`,+ );+ expect(config.guardrails?.promotion_min_age_days).toBe(0);+ });++ test("promotion_min_age_days: negative rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n promotion_min_age_days: -1\n`),+ ).toThrow(BrainConfigError);+ });++ test("instruction_file_max_lines: 0 rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails:\n instruction_file_max_lines: 0\n`),+ ).toThrow(BrainConfigError);+ });++ test("instruction_file_max_lines: extreme upper bound 10000 accepted", () => {+ const { config } = validate(+ HEAD + `guardrails:\n instruction_file_max_lines: 10000\n`,+ );+ expect(config.guardrails?.instruction_file_max_lines).toBe(10000);+ });++ test("instruction_file_max_lines: above hard ceiling rejected", () => {+ expect(() =>+ validate(+ HEAD + `guardrails:\n instruction_file_max_lines: 100000\n`,+ ),+ ).toThrow(BrainConfigError);+ });++ test("non-object guardrails block rejected", () => {+ expect(() =>+ validate(HEAD + `guardrails: "nope"\n`),+ ).toThrow(BrainConfigError);+ });++ test("unknown sub-key warns but does not throw", () => {+ const { config, warnings } = validate(+ HEAD + `guardrails:\n promotion_min_signals: 3\n unknown_field: 1\n`,+ );+ expect(config.guardrails?.promotion_min_signals).toBe(3);+ expect(warnings.some((w) => w.message.includes("guardrails.unknown_field"))).toBe(true);+ });+});diff --git a/tests/core/brain/sessions/validate-feedback-quality.test.ts b/tests/core/brain/sessions/validate-feedback-quality.test.tsnew file mode 100644index 00000000..c3f7b6cd--- /dev/null+++ b/tests/core/brain/sessions/validate-feedback-quality.test.ts@@ -0,0 +1,57 @@+import { describe, expect, test } from "bun:test";++import { validateBrainFeedbackInput } from "../../../../src/core/brain/sessions/validate-feedback.ts";++describe("validate-feedback - quality gate (v0.10.16)", () => {+ test("structurally-vague single-token principle is rejected", () => {+ const r = validateBrainFeedbackInput({+ topic: "test",+ signal: "positive",+ principle: "careful",+ });+ expect(r.ok).toBe(false);+ if (!r.ok) {+ expect(r.reason).toMatch(/principle|quality|single-token/i);+ }+ });++ test("empty principle is rejected by the existing required-field check", () => {+ const r = validateBrainFeedbackInput({+ topic: "test",+ signal: "positive",+ principle: "",+ });+ expect(r.ok).toBe(false);+ });++ test("structurally-acceptable principle passes", () => {+ const r = validateBrainFeedbackInput({+ topic: "test",+ signal: "positive",+ principle: "limit retries to 10 per hour",+ });+ expect(r.ok).toBe(true);+ });++ test("principle with operator-shape signal passes", () => {+ const r = validateBrainFeedbackInput({+ topic: "test",+ signal: "positive",+ principle: "response time must stay < 100 milliseconds",+ });+ expect(r.ok).toBe(true);+ });++ test("warn-level principle (long but with measurable signal) still passes", () => {+ // The gate REJECTs only on structurally-broken input; warn-level+ // findings (too-long, no-measurable-signal) are advisory and do+ // not block submission.+ const long = "limit X to 10 ".repeat(60); // > 500 chars but has digit+ const r = validateBrainFeedbackInput({+ topic: "test",+ signal: "positive",+ principle: long,+ });+ expect(r.ok).toBe(true);+ });+});diff --git a/tests/core/brain/trust/assess-rule-quality.test.ts b/tests/core/brain/trust/assess-rule-quality.test.tsnew file mode 100644index 00000000..1f78ab62--- /dev/null+++ b/tests/core/brain/trust/assess-rule-quality.test.ts@@ -0,0 +1,111 @@+/**+ * Language-agnostic structural quality gate for taste signals.+ *+ * The detector reads only bytes / codepoints; it must NOT carry any+ * language-specific vocabulary list, stopword list, or unit dictionary.+ * Tests use shape placeholders (`<TOK>`, digits, operator chars) so the+ * fixture set has no specific-language bias.+ */++import { describe, expect, test } from "bun:test";++import { assessRuleQuality } from "../../../../src/core/brain/trust/assess-rule-quality.ts";++describe("assessRuleQuality - reject conditions", () => {+ test("empty principle", () => {+ const r = assessRuleQuality("");+ expect(r.severity).toBe("reject");+ expect(r.reasons).toContain("empty");+ });++ test("whitespace-only principle", () => {+ const r = assessRuleQuality(" \t\n ");+ expect(r.severity).toBe("reject");+ expect(r.reasons).toContain("empty");+ });++ test("single token", () => {+ const r = assessRuleQuality("foo");+ expect(r.severity).toBe("reject");+ expect(r.reasons).toContain("single-token");+ });+});++describe("assessRuleQuality - warn conditions", () => {+ test("very long (more than 500 chars)", () => {+ const long = "a b c d e f g h i j".repeat(70);+ const r = assessRuleQuality(long);+ expect(r.severity).toBe("warn");+ expect(r.reasons).toContain("too-long");+ });++ test("very long by token count (more than 80 tokens)", () => {+ const tokens = Array(100).fill("xyz123").join(" ");+ const r = assessRuleQuality(tokens);+ // Has digits so signal-present, but too many tokens triggers warn+ expect(r.severity).toBe("warn");+ expect(r.reasons).toContain("too-long");+ });++ test("no digit, no operator-shape char (no measurable signal)", () => {+ const r = assessRuleQuality("alpha beta gamma delta epsilon");+ expect(r.severity).toBe("warn");+ expect(r.reasons).toContain("no-measurable-signal");+ });++ test("high single-character filler ratio (above 0.4)", () => {+ const r = assessRuleQuality("a b c d e f g h i j 10");+ expect(r.severity).toBe("warn");+ expect(r.reasons).toContain("filler-ratio-high");+ });+});++describe("assessRuleQuality - ok conditions", () => {+ test("imperative-shaped with numeric outcome (digit present)", () => {+ const r = assessRuleQuality("limit retries to 10 per hour");+ expect(r.severity).toBe("ok");+ expect(r.reasons).toEqual([]);+ });++ test("operator-shape char (no digit, but operator present)", () => {+ const r = assessRuleQuality("each block must terminate with > marker");+ expect(r.severity).toBe("ok");+ });++ test("non-ASCII codepoints with embedded digit (multi-codepoint tokens)", () => {+ // Using BMP non-Latin codepoints by their code-point value, not+ // by any language-specific phrase. The detector is shape-blind:+ // multi-codepoint tokens here exercise the same path as+ // multi-character Latin tokens.+ const r = assessRuleQuality(+ "\u{4E00}\u{4E01}\u{4E02}\u{4E03} 7 \u{4E04}\u{4E05}\u{4E06}\u{4E07}",+ );+ expect(r.severity).toBe("ok");+ });++ test("structured rule with operator and digit", () => {+ const r = assessRuleQuality("response time must stay < 100 ms in production");+ expect(r.severity).toBe("ok");+ });+});++describe("assessRuleQuality - structural invariants", () => {+ test("score is finite and in [0, 1]", () => {+ for (const input of ["", "a", "x y z", "limit foo to 10"]) {+ const r = assessRuleQuality(input);+ expect(Number.isFinite(r.score)).toBe(true);+ expect(r.score).toBeGreaterThanOrEqual(0);+ expect(r.score).toBeLessThanOrEqual(1);+ }+ });++ test("reasons array always defined (possibly empty)", () => {+ const r = assessRuleQuality("limit retries to 10 per hour");+ expect(Array.isArray(r.reasons)).toBe(true);+ });++ test("returned object is frozen", () => {+ const r = assessRuleQuality("test 1");+ expect(Object.isFrozen(r)).toBe(true);+ });+});diff --git a/tests/core/brain/trust/check-role-permission.test.ts b/tests/core/brain/trust/check-role-permission.test.tsnew file mode 100644index 00000000..5bbf1df3--- /dev/null+++ b/tests/core/brain/trust/check-role-permission.test.ts@@ -0,0 +1,146 @@+import { describe, expect, test } from "bun:test";++import {+ BRAIN_OPERATIONS,+ BRAIN_ROLES,+} from "../../../../src/core/brain/trust/role.ts";+import { checkRolePermission } from "../../../../src/core/brain/trust/check-role-permission.ts";++describe("checkRolePermission - allowed paths", () => {+ test("writer may write inbox feedback", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.writer,+ BRAIN_OPERATIONS.feedback_write,+ );+ expect(r.allowed).toBe(true);+ });++ test("writer may create an unconfirmed preference", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.writer,+ BRAIN_OPERATIONS.preference_create_unconfirmed,+ );+ expect(r.allowed).toBe(true);+ });++ test("dreamer may promote unconfirmed to confirmed", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.preference_promote_confirmed,+ "unconfirmed",+ );+ expect(r.allowed).toBe(true);+ });++ test("dreamer may retire a preference", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.preference_retire,+ "confirmed",+ );+ expect(r.allowed).toBe(true);+ });++ test("applier may record evidence", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.applier,+ BRAIN_OPERATIONS.evidence_record,+ );+ expect(r.allowed).toBe(true);+ });++ test("applier may append narrative log", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.applier,+ BRAIN_OPERATIONS.log_append,+ );+ expect(r.allowed).toBe(true);+ });+});++describe("checkRolePermission - forbidden paths", () => {+ test("writer must not promote a preference to confirmed", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.writer,+ BRAIN_OPERATIONS.preference_promote_confirmed,+ );+ expect(r.allowed).toBe(false);+ expect(r.reason).toBeTruthy();+ });++ test("writer must not retire a preference", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.writer,+ BRAIN_OPERATIONS.preference_retire,+ );+ expect(r.allowed).toBe(false);+ });++ test("dreamer must not write inbox feedback", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.feedback_write,+ );+ expect(r.allowed).toBe(false);+ });++ test("dreamer must not record evidence", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.evidence_record,+ );+ expect(r.allowed).toBe(false);+ });++ test("dreamer must not promote a preference that is already confirmed", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.preference_promote_confirmed,+ "confirmed",+ );+ expect(r.allowed).toBe(false);+ expect(r.reason).toMatch(/already|wrong-source-state/);+ });++ test("dreamer + promote without currentStatus is denied (fail-closed)", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.dreamer,+ BRAIN_OPERATIONS.preference_promote_confirmed,+ );+ expect(r.allowed).toBe(false);+ expect(r.reason).toMatch(/currentStatus is required|wrong-source-state/);+ });++ test("applier must not promote a preference", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.applier,+ BRAIN_OPERATIONS.preference_promote_confirmed,+ );+ expect(r.allowed).toBe(false);+ });++ test("applier must not retire a preference", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.applier,+ BRAIN_OPERATIONS.preference_retire,+ );+ expect(r.allowed).toBe(false);+ });++ test("unknown role denies every operation", () => {+ for (const op of Object.values(BRAIN_OPERATIONS)) {+ const r = checkRolePermission(BRAIN_ROLES.unknown, op);+ expect(r.allowed).toBe(false);+ }+ });+});++describe("checkRolePermission - structural invariants", () => {+ test("returned object is frozen", () => {+ const r = checkRolePermission(+ BRAIN_ROLES.writer,+ BRAIN_OPERATIONS.feedback_write,+ );+ expect(Object.isFrozen(r)).toBe(true);+ });+});diff --git a/tests/core/brain/trust/compute-trust-verdict.test.ts b/tests/core/brain/trust/compute-trust-verdict.test.tsnew file mode 100644index 00000000..99d9fd59--- /dev/null+++ b/tests/core/brain/trust/compute-trust-verdict.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from "bun:test";++import type { DoctorIssue } from "../../../../src/core/brain/doctor.ts";+import type { DreamWarning } from "../../../../src/core/brain/dream.ts";+import { computeTrustVerdict } from "../../../../src/core/brain/trust/compute-trust-verdict.ts";+import type { VerificationDeltaSummaryCounts } from "../../../../src/core/brain/trust/compute-verification-delta.ts";++const ZERO_DELTA: VerificationDeltaSummaryCounts = {+ confirmed: 0,+ drift: 0,+ regression: 0,+ missing_evidence: 0,+};++function issue(severity: "warning" | "error"): DoctorIssue {+ return { severity, code: "test-issue", message: "test" };+}++function dreamWarn(): DreamWarning {+ return { code: "test-warn", message: "test" };+}++describe("computeTrustVerdict", () => {+ test("clean: zero everything", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: ZERO_DELTA,+ }),+ ).toBe("clean");+ });++ test("investigate: any doctor error", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [issue("error")],+ dreamWarnings: [],+ verification: ZERO_DELTA,+ }),+ ).toBe("investigate");+ });++ test("investigate: any regression entry", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, regression: 1 },+ }),+ ).toBe("investigate");+ });++ test("investigate: any missing_evidence entry", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, missing_evidence: 1 },+ }),+ ).toBe("investigate");+ });++ test("investigate: drift count above threshold", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, drift: 5 },+ }),+ ).toBe("investigate");+ });++ test("watch: doctor warning alone", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [issue("warning")],+ doctorErrors: [],+ dreamWarnings: [],+ verification: ZERO_DELTA,+ }),+ ).toBe("watch");+ });++ test("watch: dream warning alone", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [dreamWarn()],+ verification: ZERO_DELTA,+ }),+ ).toBe("watch");+ });++ test("watch: drift count below threshold", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, drift: 2 },+ }),+ ).toBe("watch");+ });++ test("clean: confirmed entries do NOT downgrade verdict", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, confirmed: 42 },+ }),+ ).toBe("clean");+ });++ test("investigate overrides watch", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [issue("warning")],+ doctorErrors: [issue("error")],+ dreamWarnings: [dreamWarn()],+ verification: ZERO_DELTA,+ }),+ ).toBe("investigate");+ });+});++describe("computeTrustVerdict - custom threshold", () => {+ test("custom drift threshold honored", () => {+ expect(+ computeTrustVerdict({+ doctorWarnings: [],+ doctorErrors: [],+ dreamWarnings: [],+ verification: { ...ZERO_DELTA, drift: 1 },+ driftWatchThreshold: 0,+ }),+ ).toBe("investigate");+ });+});diff --git a/tests/core/brain/trust/compute-verification-delta.test.ts b/tests/core/brain/trust/compute-verification-delta.test.tsnew file mode 100644index 00000000..806274ce--- /dev/null+++ b/tests/core/brain/trust/compute-verification-delta.test.ts@@ -0,0 +1,216 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import type { DreamRunSummary } from "../../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { writePreference } from "../../../../src/core/brain/preference.ts";+import { computeVerificationDelta } from "../../../../src/core/brain/trust/compute-verification-delta.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-verify-delta-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function emptyDream(over: Partial<DreamRunSummary> = {}): DreamRunSummary {+ return Object.freeze({+ run_id: "dream-2026-05-25-000000",+ changed: false,+ new_unconfirmed: [],+ confirmed: [],+ retired: [],+ contradictions: [],+ moved_to_processed: [],+ suppressed: [],+ warnings: [],+ uncertain: [],+ quarantined: [],+ ...over,+ }) as DreamRunSummary;+}++describe("computeVerificationDelta", () => {+ test("clean vault, empty dream -> all-zero counts", () => {+ const r = computeVerificationDelta(vault, emptyDream());+ expect(r.summary).toEqual({+ confirmed: 0,+ drift: 0,+ regression: 0,+ missing_evidence: 0,+ });+ expect(r.entries).toEqual([]);+ });++ test("confirmed: pref exists with applied_count > 0", () => {+ writePreference(vault, {+ slug: "test-rule",+ topic: "test-topic",+ principle: "limit X to 10",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-1]]"],+ applied_count: 3,+ violated_count: 0,+ last_evidence_at: "2026-05-22T00:00:00Z",+ confidence: "high",+ });++ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-test-rule"] }),+ );+ expect(r.summary.confirmed).toBe(1);+ expect(r.summary.drift).toBe(0);+ expect(r.entries).toHaveLength(1);+ expect(r.entries[0]?.state).toBe("confirmed");+ expect(r.entries[0]?.id).toBe("pref-test-rule");+ });++ test("drift: pref exists with applied_count == 0", () => {+ writePreference(vault, {+ slug: "no-evidence",+ topic: "topic-2",+ principle: "limit Y to 5",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-2]]"],+ applied_count: 0,+ violated_count: 0,+ last_evidence_at: null,+ confidence: "low",+ });++ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-no-evidence"] }),+ );+ expect(r.summary.drift).toBe(1);+ expect(r.entries[0]?.state).toBe("drift");+ });++ test("missing_evidence: dream cites pref id that no longer exists on disk", () => {+ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-ghost-id"] }),+ );+ expect(r.summary.missing_evidence).toBe(1);+ expect(r.entries[0]?.state).toBe("missing_evidence");+ expect(r.entries[0]?.id).toBe("pref-ghost-id");+ });++ test("mixed scenarios produce distinct counts", () => {+ writePreference(vault, {+ slug: "good",+ topic: "t1",+ principle: "limit A to 100",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-good]]"],+ applied_count: 5,+ violated_count: 0,+ last_evidence_at: "2026-05-22T00:00:00Z",+ confidence: "high",+ });+ writePreference(vault, {+ slug: "drifty",+ topic: "t2",+ principle: "limit B to 50",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-drifty]]"],+ applied_count: 0,+ violated_count: 0,+ last_evidence_at: null,+ confidence: "low",+ });++ const r = computeVerificationDelta(+ vault,+ emptyDream({+ confirmed: ["pref-good", "pref-drifty", "pref-ghost"],+ }),+ );+ expect(r.summary.confirmed).toBe(1);+ expect(r.summary.drift).toBe(1);+ expect(r.summary.missing_evidence).toBe(1);+ });+});++describe("computeVerificationDelta - regression + path contract", () => {+ test("regression: dream cited as confirmed but on-disk status is unconfirmed", () => {+ writePreference(vault, {+ slug: "claim-mismatch",+ topic: "claim-mismatch",+ principle: "limit Z to 10",+ created_at: "2026-05-20T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "unconfirmed",+ evidenced_by: ["[[sig-z]]"],+ });+ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-claim-mismatch"] }),+ );+ expect(r.summary.drift).toBe(1);+ expect(r.entries[0]?.state).toBe("drift");+ expect(r.entries[0]?.note).toMatch(/on-disk status is 'unconfirmed'/);+ });++ test("entries carry vault-relative paths (no absolute host paths leak)", () => {+ writePreference(vault, {+ slug: "path-shape",+ topic: "path-shape",+ principle: "limit P to 5",+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: "2026-05-21T00:00:00Z",+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-p]]"],+ applied_count: 1,+ last_evidence_at: "2026-05-22T00:00:00Z",+ });+ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-path-shape"] }),+ );+ const path = r.entries[0]?.path ?? "";+ // Vault-relative path: starts with `Brain/preferences/`, never+ // with `/tmp/...` or any other absolute host directory.+ expect(path.startsWith("/")).toBe(false);+ expect(path).toBe("Brain/preferences/pref-path-shape.md");+ });++ test("malformed slug surfaces as missing_evidence, not a thrown error", () => {+ // Slug with characters rejected by validateSlug (uppercase, spaces).+ const r = computeVerificationDelta(+ vault,+ emptyDream({ confirmed: ["pref-Invalid Slug!"] }),+ );+ expect(r.summary.missing_evidence).toBe(1);+ expect(r.entries[0]?.state).toBe("missing_evidence");+ });+});++describe("computeVerificationDelta structural invariants", () => {+ test("result is frozen", () => {+ const r = computeVerificationDelta(vault, emptyDream());+ expect(Object.isFrozen(r)).toBe(true);+ expect(Object.isFrozen(r.summary)).toBe(true);+ expect(Object.isFrozen(r.entries)).toBe(true);+ });+});diff --git a/tests/core/brain/trust/instruction-file-ceiling.test.ts b/tests/core/brain/trust/instruction-file-ceiling.test.tsnew file mode 100644index 00000000..bed28ca0--- /dev/null+++ b/tests/core/brain/trust/instruction-file-ceiling.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { checkInstructionFileCeiling } from "../../../../src/core/brain/trust/instruction-file-ceiling.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-ceiling-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("checkInstructionFileCeiling", () => {+ test("no tracked files present -> empty warnings", () => {+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ expect(r).toEqual([]);+ });++ test("CLAUDE.md under ceiling -> no warning", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "line\n".repeat(50));+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ expect(r).toEqual([]);+ });++ test("CLAUDE.md above ceiling -> one warning with exact line count", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "line\n".repeat(300));+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ expect(r).toHaveLength(1);+ expect(r[0]?.path).toBe("CLAUDE.md");+ expect(r[0]?.lines).toBe(300);+ expect(r[0]?.ceiling).toBe(200);+ });++ test("AGENTS.md and GEMINI.md are tracked too", () => {+ writeFileSync(join(vault, "AGENTS.md"), "x\n".repeat(250));+ writeFileSync(join(vault, "GEMINI.md"), "y\n".repeat(250));+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ const paths = [...r].map((w) => w.path).sort();+ expect(paths).toEqual(["AGENTS.md", "GEMINI.md"]);+ });++ test("file without trailing newline counts lines correctly", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "a\nb\nc");+ const r = checkInstructionFileCeiling(vault, { maxLines: 2 });+ expect(r).toHaveLength(1);+ expect(r[0]?.lines).toBe(3);+ });++ test("empty file is not a warning", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "");+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ expect(r).toEqual([]);+ });++ test("returned warnings are frozen", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "z\n".repeat(300));+ const r = checkInstructionFileCeiling(vault, { maxLines: 200 });+ expect(Object.isFrozen(r)).toBe(true);+ expect(Object.isFrozen(r[0])).toBe(true);+ });++ test("ceiling=0 catches every non-empty file (degenerate case)", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "single line");+ const r = checkInstructionFileCeiling(vault, { maxLines: 0 });+ expect(r).toHaveLength(1);+ });+});diff --git a/tests/core/brain/trust/operator-summary.test.ts b/tests/core/brain/trust/operator-summary.test.tsnew file mode 100644index 00000000..d6599d71--- /dev/null+++ b/tests/core/brain/trust/operator-summary.test.ts@@ -0,0 +1,111 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import type { DreamRunSummary } from "../../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import {+ buildOperatorSummary,+ renderOperatorSummaryMarkdown,+} from "../../../../src/core/brain/trust/operator-summary.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-op-summary-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function emptyDream(over: Partial<DreamRunSummary> = {}): DreamRunSummary {+ return Object.freeze({+ run_id: "dream-2026-05-25-000000",+ changed: false,+ new_unconfirmed: [],+ confirmed: [],+ retired: [],+ contradictions: [],+ moved_to_processed: [],+ suppressed: [],+ warnings: [],+ uncertain: [],+ quarantined: [],+ ...over,+ }) as DreamRunSummary;+}++describe("buildOperatorSummary - structural envelope", () => {+ test("clean vault produces all-zero envelope with trust=clean", () => {+ const r = buildOperatorSummary(vault, { dreamSummary: emptyDream() });+ expect(r.trust_verdict).toBe("clean");+ expect(r.verification_delta.summary.confirmed).toBe(0);+ expect(r.verification_delta.summary.drift).toBe(0);+ expect(r.instruction_file_warnings).toEqual([]);+ expect(r.doctor_summary.warning_count).toBe(0);+ expect(r.doctor_summary.error_count).toBe(0);+ expect(r.dream_summary.warning_count).toBe(0);+ expect(r.dream_summary.uncertain_count).toBe(0);+ expect(r.dream_summary.quarantined_count).toBe(0);+ });++ test("instruction-file warning surfaces in envelope; verdict stays clean (informational)", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "line\n".repeat(300));+ const r = buildOperatorSummary(vault, {+ dreamSummary: emptyDream(),+ guardrails: {+ promotion_min_signals: 2,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 100,+ },+ });+ expect(r.instruction_file_warnings).toHaveLength(1);+ expect(r.instruction_file_warnings[0]?.path).toBe("CLAUDE.md");+ // Doctor errors zero; instruction-file warning is informational only+ // and is NOT counted toward the trust verdict (it lives outside the+ // doctor warnings list). Verdict stays clean.+ expect(r.trust_verdict).toBe("clean");+ });++ test("without dream summary, verification delta is empty and trust is clean", () => {+ const r = buildOperatorSummary(vault, {});+ expect(r.verification_delta.summary.confirmed).toBe(0);+ expect(r.verification_delta.entries).toEqual([]);+ expect(r.trust_verdict).toBe("clean");+ });++ test("returned object is frozen", () => {+ const r = buildOperatorSummary(vault, { dreamSummary: emptyDream() });+ expect(Object.isFrozen(r)).toBe(true);+ });+});++describe("renderOperatorSummaryMarkdown", () => {+ test("markdown contains the three signal sections", () => {+ const r = buildOperatorSummary(vault, { dreamSummary: emptyDream() });+ const md = renderOperatorSummaryMarkdown(r);+ expect(md).toContain("# Operator summary");+ expect(md).toContain("Trust:");+ expect(md).toContain("Doctor:");+ expect(md).toContain("Dream:");+ });++ test("markdown lists instruction-file warnings when present", () => {+ writeFileSync(join(vault, "CLAUDE.md"), "x\n".repeat(300));+ const r = buildOperatorSummary(vault, {+ dreamSummary: emptyDream(),+ guardrails: {+ promotion_min_signals: 2,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 100,+ },+ });+ const md = renderOperatorSummaryMarkdown(r);+ expect(md).toContain("CLAUDE.md");+ });+});diff --git a/tests/core/brain/trust/role.test.ts b/tests/core/brain/trust/role.test.tsnew file mode 100644index 00000000..697c364e--- /dev/null+++ b/tests/core/brain/trust/role.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from "bun:test";++import {+ BRAIN_OPERATIONS,+ BRAIN_ROLES,+ isBrainOperation,+ isBrainRole,+} from "../../../../src/core/brain/trust/role.ts";++describe("BRAIN_ROLES", () => {+ test("enumerates exactly the four documented roles", () => {+ expect(Object.values(BRAIN_ROLES).sort()).toEqual([+ "applier",+ "dreamer",+ "unknown",+ "writer",+ ]);+ });++ test("isBrainRole accepts each canonical role", () => {+ for (const role of Object.values(BRAIN_ROLES)) {+ expect(isBrainRole(role)).toBe(true);+ }+ });++ test("isBrainRole rejects unknown strings and non-strings", () => {+ expect(isBrainRole("admin")).toBe(false);+ expect(isBrainRole("Writer")).toBe(false);+ expect(isBrainRole(undefined)).toBe(false);+ expect(isBrainRole(null)).toBe(false);+ expect(isBrainRole(0)).toBe(false);+ });+});++describe("BRAIN_OPERATIONS", () => {+ test("enumerates exactly the six documented operations", () => {+ expect(Object.values(BRAIN_OPERATIONS).sort()).toEqual([+ "evidence_record",+ "feedback_write",+ "log_append",+ "preference_create_unconfirmed",+ "preference_promote_confirmed",+ "preference_retire",+ ]);+ });++ test("isBrainOperation accepts each canonical operation", () => {+ for (const op of Object.values(BRAIN_OPERATIONS)) {+ expect(isBrainOperation(op)).toBe(true);+ }+ });++ test("isBrainOperation rejects unknown strings", () => {+ expect(isBrainOperation("preference_delete")).toBe(false);+ expect(isBrainOperation("")).toBe(false);+ expect(isBrainOperation(42)).toBe(false);+ });+});diff --git a/tests/core/brain/trust/self-approval-guardrail.test.ts b/tests/core/brain/trust/self-approval-guardrail.test.tsnew file mode 100644index 00000000..28521d6b--- /dev/null+++ b/tests/core/brain/trust/self-approval-guardrail.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from "bun:test";++import { BRAIN_GUARDRAIL_DEFAULTS } from "../../../../src/core/brain/policy.ts";+import { applySelfApprovalGuardrail } from "../../../../src/core/brain/trust/self-approval-guardrail.ts";++describe("applySelfApprovalGuardrail - default config", () => {+ const cfg = BRAIN_GUARDRAIL_DEFAULTS;++ test("promotes when all thresholds met (defaults)", () => {+ const r = applySelfApprovalGuardrail(+ { signal_count: 2, distinct_agents: 1, age_days: 0 },+ cfg,+ );+ expect(r.decision).toBe("promote");+ expect(r.failed_gates).toEqual([]);+ });++ test("quarantines when signal count below explicit min_signals", () => {+ // Defaults set min_signals=1 (strictly looser than dream's+ // candidate_threshold) so the gate never fires by default. Pass an+ // explicit tighter threshold to exercise the quarantine path.+ const r = applySelfApprovalGuardrail(+ { signal_count: 1, distinct_agents: 1, age_days: 0 },+ { ...cfg, promotion_min_signals: 2 },+ );+ expect(r.decision).toBe("quarantine");+ expect(r.failed_gates).toContain("min_signals");+ });++ test("default min_age_days: 0 means the age gate never fails", () => {+ const r = applySelfApprovalGuardrail(+ { signal_count: 5, distinct_agents: 1, age_days: 0 },+ cfg,+ );+ expect(r.decision).toBe("promote");+ });+});++describe("applySelfApprovalGuardrail - tighter config", () => {+ test("cross-agent threshold: 1 agent fails when min_distinct_agents=2", () => {+ const cfg = {+ ...BRAIN_GUARDRAIL_DEFAULTS,+ promotion_min_distinct_agents: 2,+ };+ const r = applySelfApprovalGuardrail(+ { signal_count: 5, distinct_agents: 1, age_days: 30 },+ cfg,+ );+ expect(r.decision).toBe("quarantine");+ expect(r.failed_gates).toContain("min_distinct_agents");+ });++ test("age threshold: too-fresh cluster fails when min_age_days=7", () => {+ const cfg = {+ ...BRAIN_GUARDRAIL_DEFAULTS,+ promotion_min_age_days: 7,+ };+ const r = applySelfApprovalGuardrail(+ { signal_count: 5, distinct_agents: 2, age_days: 3 },+ cfg,+ );+ expect(r.decision).toBe("quarantine");+ expect(r.failed_gates).toContain("min_age_days");+ });++ test("multiple failed gates surface together", () => {+ const cfg = {+ ...BRAIN_GUARDRAIL_DEFAULTS,+ promotion_min_signals: 5,+ promotion_min_distinct_agents: 3,+ promotion_min_age_days: 10,+ };+ const r = applySelfApprovalGuardrail(+ { signal_count: 1, distinct_agents: 1, age_days: 0 },+ cfg,+ );+ expect(r.decision).toBe("quarantine");+ expect([...r.failed_gates].sort()).toEqual([+ "min_age_days",+ "min_distinct_agents",+ "min_signals",+ ]);+ });+});++describe("applySelfApprovalGuardrail - structural invariants", () => {+ test("returned object is frozen", () => {+ const r = applySelfApprovalGuardrail(+ { signal_count: 2, distinct_agents: 1, age_days: 0 },+ BRAIN_GUARDRAIL_DEFAULTS,+ );+ expect(Object.isFrozen(r)).toBe(true);+ expect(Object.isFrozen(r.failed_gates)).toBe(true);+ });+});diff --git a/tests/mcp/brain-trust-mcp-fields.test.ts b/tests/mcp/brain-trust-mcp-fields.test.tsnew file mode 100644index 00000000..da746bec--- /dev/null+++ b/tests/mcp/brain-trust-mcp-fields.test.ts@@ -0,0 +1,126 @@+/**+ * v0.10.16 MCP wrapper coverage: brain_dream and brain_doctor now+ * surface the trust-layer fields that landed on the core+ * `DreamRunSummary` and `RunDoctorResult` structs. Prevents future+ * regressions where the core type carries a field but the wrapper+ * silently drops it.+ */++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 {+ JSONRPC_VERSION,+ MCPServer,+ PROTOCOL_VERSION,+} from "../../src/mcp/index.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.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-trust-fields-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-trust-fields-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const k of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "trust-fields-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function callTool(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name, arguments: args },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ return JSON.parse(r.result.content[0]!.text);+}++describe("brain_dream MCP wrapper - trust fields", () => {+ test("no-op run emits empty uncertain[] and quarantined[]", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_dream", {});+ expect(out["uncertain"]).toEqual([]);+ expect(out["quarantined"]).toEqual([]);+ expect(out["suppressed"]).toEqual([]);+ });+});++describe("brain_doctor MCP wrapper - trust fields", () => {+ test("clean vault emits trust_verdict=clean and empty instruction_file_warnings", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_doctor", {});+ expect(out["trust_verdict"]).toBe("clean");+ expect(out["instruction_file_warnings"]).toEqual([]);+ });++ test("long CLAUDE.md surfaces instruction_file_warnings via brain_doctor", async () => {+ writeFileSync(join(vault, "CLAUDE.md"), "line\n".repeat(300));+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_doctor", {});+ const warnings = out["instruction_file_warnings"] as Array<{ path: string; lines: number }>;+ expect(warnings).toHaveLength(1);+ expect(warnings[0]?.path).toBe("CLAUDE.md");+ expect(warnings[0]?.lines).toBe(300);+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 4ab2b2aa..51a73d37 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -157,7 +157,8 @@ describe("tool listing", () => {"vault_health",// Brain (brain_note added in v0.10.8 §32B,// brain_context added in v0.10.10,- // brain_context_pack added in v0.10.15).+ // brain_context_pack added in v0.10.15,+ // brain_operator_summary added in v0.10.16)."brain_feedback","brain_dream","brain_apply_evidence",@@ -168,6 +169,7 @@ describe("tool listing", () => {"brain_doctor","brain_backlinks","brain_context_pack",+ "brain_operator_summary",// Pay Memory (unchanged)."payment_memory_init","payment_receipt_append",@@ -367,9 +369,9 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- // v0.10.15: 3 core + 10 Brain (brain_context_pack added v0.10.15)- // + 8 Pay Memory + 1 Search = 22.- expect(list.result.tools.length).toBe(22);+ // v0.10.16: 3 core + 11 Brain (brain_operator_summary added v0.10.16)+ // + 8 Pay Memory + 1 Search = 23.+ expect(list.result.tools.length).toBe(23);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/operator-summary-tool.test.ts b/tests/mcp/operator-summary-tool.test.tsnew file mode 100644index 00000000..b4ba595e--- /dev/null+++ b/tests/mcp/operator-summary-tool.test.ts@@ -0,0 +1,173 @@+/**+ * MCP integration coverage for `brain_operator_summary` (v0.10.16).+ * Verifies registration in the full tool scope and the JSON-RPC+ * round-trip shape.+ */++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 {+ JSONRPC_VERSION,+ MCPServer,+ PROTOCOL_VERSION,+} from "../../src/mcp/index.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.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-op-summary-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-op-summary-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const k of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "op-summary-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function callSummary(+ server: MCPServer,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_operator_summary", arguments: args },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ return JSON.parse(r.result.content[0]!.text);+}++describe("brain_operator_summary tool registration", () => {+ test("registered in the full tool table", () => {+ const tools = buildToolTable("full");+ expect(tools.find((t) => t.name === "brain_operator_summary")).toBeDefined();+ });++ test("NOT in the writer-only scope", () => {+ const tools = buildToolTable("writer");+ expect(tools.find((t) => t.name === "brain_operator_summary")).toBeUndefined();+ });+});++describe("brain_operator_summary tool - round trip", () => {+ test("clean vault returns trust_verdict=clean", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callSummary(server, {});+ expect(out["trust_verdict"]).toBe("clean");+ expect(out["doctor_summary"]).toEqual({ warning_count: 0, error_count: 0 });+ const ifWarn = out["instruction_file_warnings"] as ReadonlyArray<unknown>;+ expect(Array.isArray(ifWarn)).toBe(true);+ expect(ifWarn).toEqual([]);+ });++ test("long CLAUDE.md surfaces instruction-file warning", async () => {+ writeFileSync(join(vault, "CLAUDE.md"), "x\n".repeat(300));+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callSummary(server, {});+ const ifWarn = out["instruction_file_warnings"] as Array<{ path: string; lines: number }>;+ expect(ifWarn).toHaveLength(1);+ expect(ifWarn[0]?.path).toBe("CLAUDE.md");+ });++ test("rejects negative top_actions via INVALID_PARAMS", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 11,+ method: "tools/call",+ params: { name: "brain_operator_summary", arguments: { top_actions: -1 } },+ })) as { error?: { code: number; message: string } };+ expect(r.error).toBeDefined();+ // JSON-RPC INVALID_PARAMS = -32602. Assert the specific code so+ // the test fails on the wrong failure mode (e.g. INTERNAL_ERROR+ // smuggled through).+ expect(r.error?.code).toBe(-32602);+ });++ test("rejects malformed top_actions string via INVALID_PARAMS", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 12,+ method: "tools/call",+ params: {+ name: "brain_operator_summary",+ arguments: { top_actions: "3abc" },+ },+ })) as { error?: { code: number; message: string } };+ expect(r.error?.code).toBe(-32602);+ });++ test("rejects non-boolean include_dream via INVALID_PARAMS", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 13,+ method: "tools/call",+ params: {+ name: "brain_operator_summary",+ arguments: { include_dream: "yes" },+ },+ })) as { error?: { code: number; message: string } };+ expect(r.error?.code).toBe(-32602);+ });+});