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.17.0 - Brain Lifecycle Review Suite: intent review, retention, monthly synthesis, complexity warning (#44)
Sol Aitken2bd3f485c74f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6a426b13..1bed927a 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.16.0",+ "version": "0.17.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex f1fbefa0..39fc89ba 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.16.0",+ "version": "0.17.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f272eab..10e923cb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,37 @@ 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.17.0] - 2026-05-28++Brain Lifecycle Review Suite. Open Second Brain now adds read-only review+surfaces around the existing deterministic learning loop: pre-dream signal+readiness, retention recommendations, monthly timeline synthesis, schema+contracts for lifecycle artifacts, and a discipline warning when vault+structure grows faster than recorded thinking.++### Added++- `o2b brain intent-review` and `brain_intent_review` for deterministic+ pre-dream review of active signal clusters. `dream` and+ `brain_review_candidates` now include the same `intent_reviews` audit data+ without changing existing mutation outcomes.+- `o2b brain retention` and `brain_retention` for recommendation-only+ keep/improve/park/prune review over retired preferences and processed+ signals. The review never deletes, moves, or edits Brain artifacts.+- `o2b brain monthly` and `brain_monthly_review` for monthly synthesis over+ timeline events, status transitions, retirements, contradictions, and+ neglected areas.+- Public lifecycle schema artifacts under `schemas/brain/` plus the local+ schema-contract registry used by tests and agent-facing envelopes.+- Discipline-report complexity-to-thinking metric, with an explicit+ productivity-trap sub-reason when structural churn outpaces recorded taste+ or evidence output.++### Changed++- Brain lifecycle CLI/MCP surfaces now reject malformed timestamps and month+ values with stable validation errors.+## [0.16.0] - 2026-05-28Agent boundary control surfaces. Open Second Brain now gives agents a@@ -1808,7 +1839,7 @@ with `source_type: inline`, the source-file wikilink in `source`,and a `dedup_hash`over the normalised payload. After capturethe source line is annotated`@osbβ [[sig-...]]`(inline form)or the info-string flips to`osb-checked`with a`<!-- @osbβ- [[sig-...]] -->`comment line (block form), making re-runs+ [[sig-...]] -->`comment line (block form), making re-runsidempotent. Default ignore set covers`Brain/`, `.git`,`node_modules`, `.obsidian`, `.trash`, `.stversions`,`.open-second-brain`; additional excludes via `--exclude`,@@ -3154,6 +3185,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.17.0]: https://github.com/itechmeat/open-second-brain/compare/v0.16.0...v0.17.0[0.16.0]: https://github.com/itechmeat/open-second-brain/compare/v0.15.0...v0.16.0[0.15.0]: https://github.com/itechmeat/open-second-brain/compare/v0.14.1...v0.15.0[0.14.1]: https://github.com/itechmeat/open-second-brain/compare/v0.14.0...v0.14.1diff --git a/README.md b/README.mdindex 4f94d9cb..f5a63db7 100644--- a/README.md+++ b/README.md@@ -105,14 +105,14 @@ The capabilities you actually feel day to day:| 2 | `dream` - the agent learns what you actually want | The nightly `dream` pass turns repeat corrections into rules: three signals on the same topic graduate to a confirmed preference. Its confidence rises every time the agent applies the rule and drops when it slips. No LLM inside the algorithm - counters and atomic file moves, nothing else. || 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows; `brain_agent_query` and `brain_agent_diff` let you inspect which agent contributed what. || 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osbβ` checkmark so re-runs skip it. |-| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` summarise what changed; `o2b brain stale` flags rules nothing has applied in months. |+| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` / `monthly` summarise what changed; `o2b brain intent-review` previews whether signal clusters are ready before the next `dream`; `o2b brain retention` recommends keep/improve/park/prune actions without deleting anything. || 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node β Obsidian opens the underlying note. || 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. || 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. || 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. || 10 | Pay Memory β audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), and the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), and the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.## CLI@@ -122,6 +122,9 @@ o2b init # Bootstrap the vault profileo2b doctor # Run vault + adapter checkso2b brain dream # Deterministic consolidation pass (idempotent)o2b brain digest # Recent transitions, markdown or JSON+o2b brain intent-review --json # Pre-dream signal readiness audit+o2b brain retention --json # Recommendation-only lifecycle review+o2b brain monthly --month 2026-05 --json # Month-level Brain synthesiso2b brain agent-query --agent claude --json # Source-agent provenance queryo2b brain agent-diff --mode diff --agent claude --agent codexo2b search "<query>" # FTS5 over the vault@@ -136,6 +139,7 @@ Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, P- The MCP server is a stdio subprocess that exits with the parent runtime.- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.+- Lifecycle review commands (`intent-review`, `retention`, `monthly`) are read-only. Retention emits recommendations only; it never deletes, moves, or edits Brain artifacts.- Hooks (Claude Code, Codex) only inject text into the agent's context; they never write to the vault directly.- Text written through Brain/Pay Memory redaction strips `<private>...</private>` regions before storage and masks secret-shaped assignments such as `api_key=...`.diff --git a/docs/brainstorm/brain-lifecycle-review-suite/cli-output/claude.md b/docs/brainstorm/brain-lifecycle-review-suite/cli-output/claude.mdnew file mode 100644index 00000000..18259c5d--- /dev/null+++ b/docs/brainstorm/brain-lifecycle-review-suite/cli-output/claude.md@@ -0,0 +1,45 @@+### Variant 1: Composable read-only review suite (dream untouched)++- **Approach**: Ship all five tasks as additive read-mostly surfaces layered around an unchanged dream. New `brain_retention` and `brain_monthly_review` tools, a `complexity_score` field added to discipline reports, JSON Schemas emitted (not enforced) into `Brain/schemas/` from existing TypeScript types, and a `brain_intent_review` advisory tool that scores signals likely to pass dream but does not actually filter them. Dream's single-pass behavior, signal flow, and outputs stay byte-for-byte identical.+- **Trade-offs**:+ - Pro: lowest blast radius; no risk of breaking deterministic dream or existing tests.+ - Pro: each task ships as an independent additive tool, easy to TDD and revert.+ - Pro: matches "recommendation-only" constraint trivially for retention.+ - Con: two-stage gate becomes advisory-only, which weakens the upstream pattern's actual filtering benefit (t_ef94345e).+ - Con: schemas-as-emission don't catch malformed input at the MCP boundary, so brain_doctor still carries that burden.+ - Con: surface area grows by 2-3 new tools/verbs without consolidating them under a unifying frame.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Staged lifecycle pipeline (port the buildroom)++- **Approach**: Restructure dream into an explicit pipeline of `intent_review β main_review β retention_review` stages with JSON Schema contracts between each, mirroring the upstream buildroom. Monthly review consumes the schema-validated stage artifacts as its primary input source, and the complexity-vs-thinking ratio is embedded into the intent_review stage as a filtering signal. Schemas live in `Brain/schemas/` and are enforced at every inter-stage boundary plus the MCP input layer.+- **Trade-offs**:+ - Pro: maximally coherent with the source articles' pipeline pattern; one design covers all five tasks.+ - Pro: schemas give brain_doctor much less to do; clear audit artifacts per stage.+ - Pro: two-stage gate becomes real filtering, not advisory.+ - Con: directly violates the constraint against rewriting dream into a multi-phase engine without strong justification.+ - Con: high risk to the deterministic core; planTopics, transition planning, and quarantine paths all need re-threading.+ - Con: schema enforcement either pulls in an Ajv-class dependency (constraint hesitation) or requires a non-trivial local validator.+ - Con: long migration path; intermediate states may break existing workruns and review-candidates dry-run.+- **Complexity**: large+- **Risk**: high++### Variant 3: Thin pre-filter + independent review pillars++- **Approach**: Add a real intent-review pre-pass that runs before dream and actually filters/marks signals (so dream's `planTopics` consumes a smaller, gated set), while leaving dream's internal main-review logic unchanged. Ship retention as a standalone recommendation-only `brain_retention` tool over `Brain/retired/` and `inbox/processed/`, ship `brain_monthly_review` as a new temporal aggregator built on `daily-brief`/`weekly-brief` and `vaultDelta`, extend `decideStatus`/`ActivitySummary` with a `complexity_score`, and emit JSON Schemas from existing TypeScript types into `Brain/schemas/` with optional lightweight enforcement only at the MCP input boundary (no Ajv dependency).+- **Trade-offs**:+ - Pro: hits all five task scopes without restructuring dream's main pass.+ - Pro: two-stage gate is genuinely two-stage (real filtering), not advisory like Variant 1.+ - Pro: retention is naturally recommendation-only because it's a separate read-only tool, satisfying t_6fa649b9's safety constraint exactly.+ - Pro: monthly review reuses the existing temporal index and brief helpers; complexity ratio is a small additive field in discipline.+ - Pro: schemas-as-emitted-contracts with optional boundary validation avoids heavy deps but still tightens MCP input safety.+ - Con: introduces a new pre-dream stage that must stay in sync with dream's signal expectations; needs careful contract testing.+ - Con: two read-only surfaces (retention, monthly) plus a discipline field plus an intent-review pre-pass plus schemas is still five distinct moving pieces β release coordination matters.+ - Con: complexity-vs-thinking metric is heuristic; tuning the threshold for discipline status may need iteration.+- **Complexity**: medium+- **Risk**: low-to-medium++### Recommended: Variant 3++**Rationale**: It delivers a coherent Brain lifecycle review release by sequencing the five tasks around their natural seams β pre-dream gating, dream untouched, post-dream retention, period-level monthly review, discipline-level complexity ratio, and schemas as additive contracts β which matches the project's deterministic, dependency-light, recommendation-only constraints far better than Variant 2's dream refactor. Versus Variant 1 it gives the two-stage gate real teeth and keeps retention safely isolated, without paying Variant 2's risk and dependency cost. The five pieces are independently TDD-able (pure core helpers first, CLI/MCP wrappers second) and can ship as additive verbs and tools with no breakage to existing public APIs.diff --git a/docs/brainstorm/brain-lifecycle-review-suite/cli-output/prompt.md b/docs/brainstorm/brain-lifecycle-review-suite/cli-output/prompt.mdnew file mode 100644index 00000000..9f9b5b65--- /dev/null+++ b/docs/brainstorm/brain-lifecycle-review-suite/cli-output/prompt.md@@ -0,0 +1,220 @@+You are brainstorming architectural variants for the following task set. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++This is a multi-task Open Second Brain release scope. The implementation should ship a coherent Brain lifecycle review suite from five Hermes kanban tasks.++## t_6fa649b9 | priority=3++TITLE: [article] Retention lifecycle for completed artifacts with keep/improve/park/prune review++**Source**: [[Articles/How to Build a Hermes Agent That Finds Important Work and Builds It Autonomously]]+**Article excerpt**: "A build being finished does not mean it should live forever. Retention asks whether an artifact should be: keep, improve, park, prune. Retention is recommendation-only in the public extraction. It can recommend what should happen, but it does not silently delete or move live artifacts."++### What++A systematic post-processing review cycle that evaluates completed brain artifacts (preferences, signals, log entries) and decides their fate: keep (active), improve (needs enhancement), park (preserve but inactive), or prune (remove). Currently OSB has status transitions (confirmed/quarantine/retired) but no structured lifecycle review after an artifact has been processed.++### Why useful for OSB++As the vault grows, retired preferences and processed signals accumulate without systematic review. A retention pass would prevent vault bloat, surface preferences that could be improved with new evidence, and ensure that pruned artifacts leave an audit trail. The recommendation-only approach ensures safety - no silent deletion of live state.++### Status in OSB++- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/brain/dream.ts:703 (RetirePlan interface with slug/principle/reason/supersededBy, but no keep/improve/park/prune states); src/core/brain/dream.ts:191 (dream function handles promotion and retirement in single pass); src/core/brain/paths.ts:105 (processedSignalPath moves signals to processed/ but no further lifecycle management). No retention review mechanism exists.++### Notes++The upstream pattern separates retention from the build loop - it recommends but doesn't mutate. OSB could implement as a brain_retention tool that runs after dream, scanning retired/ and inbox/processed/ for candidates.++### Latest comment++osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority 3; not_in_osb_useful, concrete; recommendation-only brain_retention tool, clear scope, unblocked.++## t_929a1333 | priority=3++TITLE: [article] Monthly comprehensive life review across all vault file types++**Source**: [[Articles/How to Build an Obsidian System That Runs Your Entire Life From One Folder]]+**Article excerpt**: "On the first day of every month N8N triggers a comprehensive life review workflow. It reads all activity from the previous month across every file type. It generates a monthly summary covering wins, patterns, decisions made, projects advanced, and goals progressed. It identifies any life areas that received no attention in the previous month. The monthly review compounds into your weekly reviews. Over 12 months you have a documented record of exactly how your life and work evolved."++### What++A scheduled monthly workflow that reads all vault activity from the previous month, generates a structured summary covering wins/patterns/decisions/projects/goals, identifies neglected areas, and produces a compounding record that enriches weekly reviews.++### Why useful for OSB++OSB has brain_dream (nightly signal consolidation) and brain_digest (preference summaries), but no periodic higher-order review that looks at the full vault holistically. A monthly review would surface long-term patterns and neglected areas that daily/weekly passes miss, and create a documented evolution record.++### Status in OSB++- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/discipline/decision.ts:15 (ActivitySummary interface); src/core/discipline/activity-git.ts:5 (ActivityWindow); src/core/discipline/activity-mtime.ts:17 (mtimeActivity); src/core/discipline/vault-delta.ts:39 (vaultDelta); src/core/brain/digest.ts (renders digests but scoped to preferences only, not full vault content). No monthly review mechanism exists.++### Notes++The upstream monthly review compounds into weekly reviews. OSB could implement as brain_monthly_review that reads vault content (not just Brain/ preferences) and generates a summary note. The ActivityWindow/ActivitySummary interfaces in src/core/discipline/ provide building blocks.++### Latest comment++osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority 3; not_in_osb_useful, read-only monthly review built on existing ActivityWindow/ActivitySummary and digest; clear output, unblocked.++## t_03752ca6 | priority=3++TITLE: [article] Vault complexity-to-thinking-activity ratio for productivity-trap detection++**Source**: [[Articles/Most Obsidian Beginners Accidentally Turn Their Vault Into a Productivity Trap]]+**Article excerpt**: "You spend more time redesigning your vault than actually using it. That single sentence explains why so many people quietly abandon Obsidian after a few weeks. The system became heavier than the thinking. And that's the opposite of what a second brain is supposed to do. A great vault should reduce friction. Not create more of it."++### What++A metric that compares vault structural complexity (folder depth, number of templates, tag proliferation, plugin count) against actual thinking output (preferences created, signals logged, connections formed) to detect when vault overhead exceeds productive use. When the ratio tips too far toward structure-over-substance, surface a warning in the discipline report.++### Why useful for OSB++OSB's discipline report already tracks vaultDelta (new signals, preferences, retired) and activity signals (commits, modified files). Adding a complexity-vs-activity ratio would extend the discipline report to catch the "productivity trap" early: a vault where the agent spends more cycles on vault organization than on generating or recording actual thinking. This maps directly to the existing decideStatus infrastructure in src/core/discipline/decision.ts.++### Status in OSB++- **Verdict**: present_weaker+- **Codegraph hints**: src/core/discipline/vault-delta.ts:5-47 (VaultDelta interface and vaultDelta function track new files by type); src/core/discipline/decision.ts:39-60 (decideStatus compares taste events vs activity signals); src/core/discipline/report.ts:33-87 (runDisciplineReport assembles the full report). No complexity metric or structure-vs-thinking ratio exists.++### Notes++The existing discipline report detects "activity present but zero brain events" (alert status). The extension would detect "high structure churn but low thinking output" - a different failure mode. Implementation could add a complexity_score to ActivitySummary (counting folder creates, template edits, config changes) and compare against vaultDelta thinking signals in decideStatus.++### Latest comment++osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority 3; present_weaker, extends discipline decideStatus with a complexity-vs-thinking metric; concrete and bounded.++## t_05cb41d7 | priority=2++TITLE: [article] Schema-gated artifact chain with JSON Schema validation for brain pipeline stages++**Source**: [[Articles/How to Build a Hermes Agent That Finds Important Work and Builds It Autonomously]]+**Article excerpt**: "The buildroom forces the system to separate research, ideas, reviews, plans, builds, verification, trust, retention, and operator reporting. In the buildroom, this exists as: schemas/research-input.schema.json, schemas/idea-contract.schema.json, schemas/intent-review.schema.json, schemas/main-review.schema.json, schemas/product-plan.schema.json, schemas/build-plan.schema.json, schemas/verification-report.schema.json, schemas/trust-report.schema.json, schemas/retention-review.schema.json, schemas/operator-summary.schema.json"++### What++JSON Schema validation files for each stage of the brain pipeline, ensuring that intermediate artifacts (brain_feedback input, dream output, preference transitions, log events) conform to explicit contracts. Currently OSB validates frontmatter structure but doesn't enforce JSON Schema contracts on the data flowing through brain operations.++### Why useful for OSB++Schema-gated artifacts would catch malformed brain_feedback submissions, invalid dream outputs, and inconsistent preference transitions before they land in the vault. This would make brain_doctor's job easier (fewer structural errors to detect) and provide clearer error messages when agents submit invalid data. The buildroom pattern of separate schemas per pipeline stage maps well to OSB's existing tool boundaries.++### Status in OSB++- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/brain/dream.ts:191 (dream function produces DreamRunSummary interface but no schema validation on output); src/core/brain/preference.ts (preference interface with status field but no JSON Schema enforcement); src/mcp/brain-tools.ts (MCP tool definitions accept parameters without schema validation). No JSON Schema registry or validation layer exists.++### Notes++The upstream buildroom ships schemas as separate .schema.json files in a schemas/ directory. OSB could implement similarly: a Brain/schemas/ directory with schema files for each brain operation, validated at the MCP tool boundary.++### Latest comment++osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority 2; not_in_osb_useful JSON-Schema registry across pipeline stages; design-heavy per-stage contracts, needs an ADR.++## t_ef94345e | priority=2++TITLE: [article] Two-stage signal review gate separating weak-signal filtering from approval decisions++**Source**: [[Articles/How to Build a Hermes Agent That Finds Important Work and Builds It Autonomously]]+**Article excerpt**: "The buildroom has both intent review and Main review. Intent review is the early filter. It checks whether the idea is ready to become a contract-backed candidate. The main review is the approval gate. A real Main review exists in the demo room: decision: approved_for_coder, risk_band: low, risk_score: 3, auto_approved: false, force_approved: false, block_reason: null"++### What++A two-stage promotion pipeline: stage one (intent review) filters weak or unsafe signals before they become candidates, stage two (main review) makes the actual approval decision with risk assessment. Currently OSB dream pass does both signal clustering and preference transitions in a single pass without separating the filtering stage from the approval stage.++### Why useful for OSB++A two-stage gate would improve signal quality: weak signals get filtered early without consuming the full dream pass budget, and approval decisions get explicit risk scoring. The upstream pattern shows structured review artifacts (intent-review.json, main-review.json with decision/risk_band/risk_score/auto_approved fields) that provide audit trails for why a signal was promoted or rejected.++### Status in OSB++- **Verdict**: not_in_osb_useful+- **Codegraph hints**: src/core/brain/dream.ts:746 (planTopics function handles both signal clustering and transition planning in one pass); src/core/brain/dream.ts:191 (dream function runs the entire pipeline without stage separation). src/core/brain/backlinks.ts:170 (collectSignals gathers signals but doesn't filter them before dream processing). No two-stage review gate exists.++### Notes++The upstream intent-review + main-review separation could map to OSB as: stage 1 filters signals by evidence quality and topic relevance before dream, stage 2 runs the actual preference promotion with risk scoring. This would make the dream pass more efficient and provide better audit trails.++### Latest comment++osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority 2; not_in_osb_useful two-stage review gate restructures the single-pass dream into intent + main review; architectural, needs design.++# Project context++Project: Open Second Brain, TypeScript/Bun CLI and MCP server, deterministic filesystem-first Brain memory layer over an Obsidian-compatible Markdown vault.++Recent commits:++- 9b87838 (HEAD -> main, tag: v0.16.0, origin/main, origin/HEAD) v0.16.0 - Agent boundary control surfaces: pinned context, Markdown links, MCP output contracts (#43)+- 66980b2 ci: drop bun version floor, track latest only (#42)+- feca6a7 (tag: v0.15.0) v0.15.0 - Cross-agent query foundation: source-agent provenance retrieval and comparison (#41)+- ffde4ac (tag: v0.14.1) chore(release): v0.14.1 (#40)+- bc97b38 refactor: add validation toolchain and normalize project formatting (#39)+- b76199a (tag: v0.14.0) v0.14.0 - Semantic Brain Health and Self-Maintenance: contradiction detection, concept gaps, stale claims, edit-history, remediation (#38)+- 2147640 (tag: v0.13.0) v0.13.0 - Hybrid Search and Recall Quality: explainable recall, MMR, link traversal, entity boost, header anchoring (#37)+- 84886d1 (tag: v0.12.0) v0.12.0 - Brain Integrity Suite: typed collision detection, content-hash drift, durable dream workruns (#36)+- c002268 (tag: v0.11.0) v0.11.0 - Brain-centric vault layout: one agent-owned root, opt-in user notes (#35)+- a8d4803 (tag: v0.10.18) v0.10.18 - temporal axis: timeline, belief evolution, stale watch, daily brief, weekly synthesis (#34)++Related files:++- src/core/brain/dream.ts - deterministic batch writer; DreamRunSummary already carries warnings/quarantined/gated_retires.+- src/core/brain/review-candidates.ts - read-only dry-run projection over dream; existing preview boundary for candidate review.+- src/core/brain/paths.ts - canonical Brain/ path helpers.+- src/core/brain/preference.ts - preference/retired parser and writer.+- src/core/brain/types.ts - Brain artifact, config, and event type contracts.+- src/core/brain/log.ts and src/core/brain/log-jsonl.ts - append-only audit trail and JSONL sidecar.+- src/core/brain/temporal/build-index.ts - timeline index over Brain log and retired frontmatter.+- src/core/brain/temporal/daily-brief.ts and weekly-brief.ts - read-only period summaries that monthly review can mirror/extend.+- src/core/discipline/decision.ts - discipline status decision over BrainEventCounts + ActivitySummary.+- src/core/discipline/report.ts - daily discipline report assembly.+- src/core/discipline/vault-delta.ts - counts new signals/preferences/retired in a window.+- src/mcp/brain-tools.ts - MCP tool definitions and handlers.+- src/cli/brain.ts, src/cli/brain/verbs/index.ts, src/cli/brain/help-text.ts - CLI brain verb wiring.+- tests/discipline/decision.test.ts, tests/discipline/report.test.ts - existing discipline report coverage.+- tests/mcp/brain-review-candidates.test.ts - existing review candidate MCP smoke test.+- tests/core/brain.doctor.test.ts, tests/cli/brain-health.test.ts - existing health/doctor patterns.++Conventions:++- The core must remain deterministic and dependency-light. No LLM calls inside core helpers.+- Brain writes are limited to Brain/; user-authored notes outside Brain/ are read-only and opt-in through config.+- Mutating CLI operations that touch Brain/ normally take snapshots or provide dry-run previews; read-only tools are preferred for autonomous agent surfaces.+- Public docs should use the full project name "Open Second Brain" rather than abbreviations.+- CLI read verbs should support --json where practical, mirroring MCP shapes.+- MCP tool outputs are structured JSON envelopes; recent releases add explicit output contracts for core agent-facing tools where useful.+- Tests are Bun tests under tests/; project verification commands are `bun run typecheck`, `bun run lint`, `bun run test`, and `bun run sync-version:check`.+- Versioning follows Semantic Versioning and Keep a Changelog; latest package version is 0.16.0.++Constraints:++- Prefer a coherent release of at most 5 features from the selected tasks.+- Do not silently delete, move, or auto-restore live artifacts for retention; recommendation-only is required.+- Avoid a full rewrite of dream into a large multi-phase engine unless strongly justified.+- Avoid adding heavy external dependencies for JSON Schema if a small local validator or schema emission contract is enough.+- Preserve existing public APIs unless an additive field/tool/verb is the smaller safer path.+- Keep new logic TDD-friendly: pure core helpers first, then CLI/MCP wrappers.++# 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/brain-lifecycle-review-suite/design.md b/docs/brainstorm/brain-lifecycle-review-suite/design.mdnew file mode 100644index 00000000..ec49459e--- /dev/null+++ b/docs/brainstorm/brain-lifecycle-review-suite/design.md@@ -0,0 +1,86 @@+# Brain Lifecycle Review Suite - reviewed, validated, retained, and summarized Brain state++**Status:** draft+**Author:** GitHub Copilot (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain already captures signals, promotes preferences through `dream`, renders daily/weekly summaries, and reports basic discipline status. The missing surface is the lifecycle layer around those operations: pre-dream signal review, explicit artifact contracts, post-dream retention recommendations, monthly synthesis, and a warning when vault structure grows faster than actual thinking output. The selected kanban scope should ship those five capabilities without turning the deterministic core into a broad multi-phase rewrite.++## Scope++- Add a deterministic intent-review stage for active signal clusters, surfaced through a CLI/MCP read-only report and threaded into dream/review-candidates as structured audit data.+- Add package-local JSON Schema contracts for the new lifecycle envelopes and selected existing Brain boundaries, with lightweight validation where it keeps MCP/CLI outputs honest.+- Add a recommendation-only retention review over retired preferences and processed signals with `keep`, `improve`, `park`, and `prune` outcomes. It must not delete, move, or auto-restore artifacts.+- Add a monthly review projection over the existing temporal index, daily/weekly period helpers, and vault activity counters.+- Extend discipline reporting with a complexity-to-thinking metric that can surface productivity-trap warnings without hiding existing `ok/info/alert` semantics.+- Add focused core, CLI, MCP, and docs coverage for each shipped surface.++## Out of scope++- Full multi-phase `dream` rewrite (`t_1e4f70f5`).+- LLM-driven enrichment, due-date inference, or frontmatter mutation for user-authored notes.+- Background watchdogs, automatic rollback, or self-healing restore.+- Generic external memory ingest adapters.+- Destructive retention actions. This release only recommends actions and explains why.+- Heavy JSON Schema dependencies or a complete validator implementation for every JSON Schema keyword.++## Chosen approach++Use the refined Variant 3 from the consultant: a thin deterministic pre-review boundary plus independent lifecycle review pillars. The implementation keeps `dream` as the single mutating batch operation and adds pure helpers around it. Intent review becomes the first stage of the promotion decision model, but it preserves current default promotion outcomes by making existing threshold/conflict/suppression decisions explicit rather than introducing surprising new mutation behavior.++Retention and monthly review are read-only projections. Schema contracts are package artifacts plus a small local validator for the exact envelope shapes this release owns. Discipline complexity is a bounded heuristic added to `ActivitySummary` and report rendering; it may elevate a structurally noisy, low-thinking day to `alert`, but it does not demote existing alerts or mask taste-event success.++## Design decisions++- Keep mutation centralized in `dream`. New CLI/MCP tools for retention, monthly review, and intent review are read-only; `dream` may include intent-review data in its summary, but no separate tool writes Brain state.+- Treat intent review as explicit stage separation, not a new product policy engine. The first implementation classifies clusters as `ready_for_main_review`, `needs_more_evidence`, `blocked_conflicted`, or `suppressed_by_rejected_retired`; `planTopics` consumes that stage so future policy can evolve behind a tested boundary.+- Model retention recommendations as deterministic heuristics over current files and log evidence: recently useful retired artifacts are `keep`, low-evidence or stale entries are `park`, contradictory/noisy entries are `improve`, and duplicate or orphaned processed signals can be `prune` candidates. All decisions include reasons and source paths.+- Build monthly review on `TimelineIndex` and existing period helpers so daily, weekly, and monthly summaries share event semantics. The monthly envelope should include wins, patterns, decisions, advanced projects/goals when visible from events, neglected areas from configured watched/read paths, and a generated-at timestamp.+- Put complexity scoring in `src/core/discipline/complexity.ts`. The score should be transparent: folder depth, template/config churn, tag proliferation, and structural-file changes, compared against thinking output from Brain feedback/evidence/transitions.+- Keep JSON Schema contracts additive and visible. Static schemas live in a repo-level `schemas/brain/` directory and are referenced by tests and docs; lightweight validation supports only the subset needed by the new envelopes (`type`, `required`, `properties`, `items`, `enum`, `additionalProperties`).+- Keep CLI/MCP naming explicit: `brain intent-review`, `brain retention`, `brain monthly`, and MCP mirrors `brain_intent_review`, `brain_retention`, `brain_monthly_review`. Schema contracts can be exposed through a read-only `brain_schema_contracts` MCP tool and CLI verb if implementation remains compact.+- Preserve public JSON style: snake_case over MCP, CLI `--json` mirroring core envelopes, deterministic ordering for stable tests.++## File changes++Expected new files:++- `src/core/brain/intent-review.ts`+- `src/core/brain/retention.ts`+- `src/core/brain/monthly-review.ts`+- `src/core/brain/schema-contracts.ts`+- `src/core/brain/schema-validator.ts`+- `src/core/discipline/complexity.ts`+- `src/cli/brain/verbs/intent-review.ts`+- `src/cli/brain/verbs/retention.ts`+- `src/cli/brain/verbs/monthly.ts`+- Optional: `src/cli/brain/verbs/schema-contracts.ts`+- `schemas/brain/*.schema.json`+- Core/CLI/MCP tests for each new surface++Expected modified files:++- `src/core/brain/dream.ts`+- `src/core/brain/review-candidates.ts`+- `src/core/brain/types.ts`+- `src/core/discipline/decision.ts`+- `src/core/discipline/report.ts`+- `src/core/discipline/render.ts`+- `src/mcp/brain-tools.ts`+- `src/cli/brain.ts`+- `src/cli/brain/verbs/index.ts`+- `src/cli/brain/help-text.ts`+- `docs/cli-reference.md`+- `docs/how-it-works.md`+- `README.md`+- `CHANGELOG.md` in docs phase++## Risks and open questions++- The biggest risk is accidental behavior drift in `dream`. The guardrail is to write intent-review tests before integration and preserve current outcomes in existing dream tests.+- Complexity scoring can be noisy. The first version should expose raw factors and use conservative thresholds.+- Monthly review can only summarize what deterministic events reveal; it must not invent project/goal progress from unparsed prose.+- JSON Schema validation scope must stay small. If schemas become broad enough to need full draft support, defer full enforcement behind a future ADR.+- The combined PR is intentionally larger than a single feature. Keep commits atomic by surface so review remains tractable.diff --git a/docs/brainstorm/brain-lifecycle-review-suite/plan.md b/docs/brainstorm/brain-lifecycle-review-suite/plan.mdnew file mode 100644index 00000000..6e86b186--- /dev/null+++ b/docs/brainstorm/brain-lifecycle-review-suite/plan.md@@ -0,0 +1,45 @@+# Brain Lifecycle Review Suite - implementation plan++## Tasks++### Task 1: Schema contracts foundation++- **Files**: `src/core/brain/schema-contracts.ts`, `src/core/brain/schema-validator.ts`, `schemas/brain/*.schema.json`, tests under `tests/core/`.+- **Acceptance**: failing tests first prove the expected schemas are registered, exported deterministically, and validate representative valid/invalid lifecycle envelopes without external dependencies.+- **Depends on**: none.++### Task 2: Intent review stage++- **Files**: `src/core/brain/intent-review.ts`, `src/core/brain/dream.ts`, `src/core/brain/review-candidates.ts`, `src/mcp/brain-tools.ts`, `src/cli/brain/verbs/intent-review.ts`, CLI/MCP/core tests.+- **Acceptance**: tests prove active signal clusters receive deterministic decisions and that `dream` / `brain_review_candidates` surface intent-review data while preserving existing promotion, suppression, quarantine, and contradiction outcomes.+- **Depends on**: Task 1.++### Task 3: Retention recommendations++- **Files**: `src/core/brain/retention.ts`, `src/mcp/brain-tools.ts`, `src/cli/brain/verbs/retention.ts`, core/CLI/MCP tests.+- **Acceptance**: tests prove retired preferences and processed signals are classified into `keep`, `improve`, `park`, or `prune` with reasons and no filesystem mutation.+- **Depends on**: Task 1.++### Task 4: Monthly review projection++- **Files**: `src/core/brain/monthly-review.ts`, `src/mcp/brain-tools.ts`, `src/cli/brain/verbs/monthly.ts`, temporal/core/CLI/MCP tests.+- **Acceptance**: tests prove a month window aggregates events, transitions, contradictions, source pointers, neglected areas, and generated metadata in stable order; CLI `--json` mirrors the MCP envelope.+- **Depends on**: Task 1.++### Task 5: Complexity-to-thinking discipline metric++- **Files**: `src/core/discipline/complexity.ts`, `src/core/discipline/decision.ts`, `src/core/discipline/report.ts`, `src/core/discipline/render.ts`, discipline tests.+- **Acceptance**: tests prove high structural complexity with low thinking output produces an explicit productivity-trap warning, while taste events and existing activity alerts retain their current behavior.+- **Depends on**: Task 1.++### Task 6: CLI/MCP registration polish++- **Files**: `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/help-text.ts`, `src/mcp/brain-tools.ts`, tests under `tests/cli/` and `tests/mcp/`.+- **Acceptance**: tests prove new verbs/tools are discoverable, reject malformed inputs, and return stable JSON shapes.+- **Depends on**: Tasks 2, 3, 4, 5.++### Task 7: Documentation and release notes++- **Files**: `README.md`, `docs/cli-reference.md`, `docs/how-it-works.md`, `CHANGELOG.md`, optional release draft artifacts.+- **Acceptance**: docs describe the new lifecycle review suite using the full project name and list the CLI/MCP surfaces accurately; changelog has one new version entry for the PR.+- **Depends on**: Tasks 2, 3, 4, 5, 6.diff --git a/docs/brainstorm/brain-lifecycle-review-suite/variants.md b/docs/brainstorm/brain-lifecycle-review-suite/variants.mdnew file mode 100644index 00000000..8bd27d79--- /dev/null+++ b/docs/brainstorm/brain-lifecycle-review-suite/variants.md@@ -0,0 +1,55 @@+# Brain Lifecycle Review Suite - variants++## Consultant output++### Variant 1: Composable read-only review suite (dream untouched)++- **Approach**: Ship all five tasks as additive read-mostly surfaces layered around an unchanged dream. New `brain_retention` and `brain_monthly_review` tools, a `complexity_score` field added to discipline reports, JSON Schemas emitted (not enforced) into `Brain/schemas/` from existing TypeScript types, and a `brain_intent_review` advisory tool that scores signals likely to pass dream but does not actually filter them. Dream's single-pass behavior, signal flow, and outputs stay byte-for-byte identical.+- **Trade-offs**:+ - Pro: lowest blast radius; no risk of breaking deterministic dream or existing tests.+ - Pro: each task ships as an independent additive tool, easy to TDD and revert.+ - Pro: matches "recommendation-only" constraint trivially for retention.+ - Con: two-stage gate becomes advisory-only, which weakens the upstream pattern's actual filtering benefit (t_ef94345e).+ - Con: schemas-as-emission don't catch malformed input at the MCP boundary, so brain_doctor still carries that burden.+ - Con: surface area grows by 2-3 new tools/verbs without consolidating them under a unifying frame.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Staged lifecycle pipeline (port the buildroom)++- **Approach**: Restructure dream into an explicit pipeline of `intent_review -> main_review -> retention_review` stages with JSON Schema contracts between each, mirroring the upstream buildroom. Monthly review consumes the schema-validated stage artifacts as its primary input source, and the complexity-vs-thinking ratio is embedded into the intent_review stage as a filtering signal. Schemas live in `Brain/schemas/` and are enforced at every inter-stage boundary plus the MCP input layer.+- **Trade-offs**:+ - Pro: maximally coherent with the source articles' pipeline pattern; one design covers all five tasks.+ - Pro: schemas give brain_doctor much less to do; clear audit artifacts per stage.+ - Pro: two-stage gate becomes real filtering, not advisory.+ - Con: directly violates the constraint against rewriting dream into a multi-phase engine without strong justification.+ - Con: high risk to the deterministic core; planTopics, transition planning, and quarantine paths all need re-threading.+ - Con: schema enforcement either pulls in an Ajv-class dependency (constraint hesitation) or requires a non-trivial local validator.+ - Con: long migration path; intermediate states may break existing workruns and review-candidates dry-run.+- **Complexity**: large+- **Risk**: high++### Variant 3: Thin pre-filter + independent review pillars++- **Approach**: Add a real intent-review pre-pass that runs before dream and actually filters/marks signals (so dream's `planTopics` consumes a smaller, gated set), while leaving dream's internal main-review logic unchanged. Ship retention as a standalone recommendation-only `brain_retention` tool over `Brain/retired/` and `inbox/processed/`, ship `brain_monthly_review` as a new temporal aggregator built on `daily-brief`/`weekly-brief` and `vaultDelta`, extend `decideStatus`/`ActivitySummary` with a `complexity_score`, and emit JSON Schemas from existing TypeScript types into `Brain/schemas/` with optional lightweight enforcement only at the MCP input boundary (no Ajv dependency).+- **Trade-offs**:+ - Pro: hits all five task scopes without restructuring dream's main pass.+ - Pro: two-stage gate is genuinely two-stage (real filtering), not advisory like Variant 1.+ - Pro: retention is naturally recommendation-only because it's a separate read-only tool, satisfying t_6fa649b9's safety constraint exactly.+ - Pro: monthly review reuses the existing temporal index and brief helpers; complexity ratio is a small additive field in discipline.+ - Pro: schemas-as-emitted-contracts with optional boundary validation avoids heavy deps but still tightens MCP input safety.+ - Con: introduces a new pre-dream stage that must stay in sync with dream's signal expectations; needs careful contract testing.+ - Con: two read-only recommendation surfaces (retention, monthly) plus a discipline field plus an intent-review pre-pass plus schemas is still five distinct moving pieces - release coordination matters.+ - Con: complexity-vs-thinking metric is heuristic; tuning the threshold for discipline status may need iteration.+- **Complexity**: medium+- **Risk**: low-to-medium++### Recommended: Variant 3++**Rationale**: It delivers a coherent Brain lifecycle review release by sequencing the five tasks around their natural seams - pre-dream gating, dream untouched, post-dream retention, period-level monthly review, discipline-level complexity ratio, and schemas as additive contracts - which matches the project's deterministic, dependency-light, recommendation-only constraints far better than Variant 2's dream refactor. Versus Variant 1 it gives the two-stage gate real teeth and keeps retention safely isolated, without paying Variant 2's risk and dependency cost. The five pieces are independently TDD-able (pure core helpers first, CLI/MCP wrappers second) and can ship as additive verbs and tools with no breakage to existing public APIs.++## Orchestrator decision++Agree with Variant 3, with one safety refinement: the intent-review stage must be a pure deterministic pre-stage whose default decisions preserve current dream outcomes unless a cluster is already below threshold, conflicted, or suppressed by an existing user-rejected retired preference. The goal is an explicit two-stage audit trail and structured gating boundary without turning this release into the larger multi-phase dream rewrite deferred by `t_1e4f70f5`.++Schema contracts should ship as local package artifacts and structured MCP/CLI envelopes first. Runtime validation should reuse a small local validator only for the new envelopes and selected MCP input boundaries; this avoids adding a heavy JSON Schema dependency while still making the contract visible and testable.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex fdbc20d1..ce25b0f4 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -29,6 +29,9 @@ o2b brain dream Run the deterministic consolidation pass (idempoteo2b brain apply-evidence Record applied / violated against a preference for a durable artifacto2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback; Markdown links follow link_output_format / OBSIDIAN_LINK_FORMAT+o2b brain intent-review Read-only pre-dream review of active signal clusters; --now ISO; --json mirrors brain_intent_review+o2b brain retention Recommendation-only lifecycle review over retired preferences and processed signals; --now ISO; --json mirrors brain_retention+o2b brain monthly Month-level Brain synthesis over timeline events, transitions, retirements, contradictions, and neglected areas; --month YYYY-MM; --json mirrors brain_monthly_reviewo2b brain query Read helper: by preference, by topic, or by log timestampo2b brain agent-query Read source-agent provenance; filters by --agent, --topic, --query, --kind, --limit; --json mirrors brain_agent_queryo2b brain agent-diff Compare source-agent coverage in browse/search/diff/map modes; --json mirrors brain_agent_diff@@ -60,6 +63,7 @@ o2b brain evolution Per-preference or per-topic belief evolution witho2b brain stale Structural staleness report (preferences / signals / log files) using configurable per-kind thresholdso2b brain daily Daily brief: counters, transitions, source pointerso2b brain weekly 7-day synthesis with contradictions list (signal-suppressed events + apply-evidence violated rows)+o2b brain monthly Monthly synthesis: event count, status transitions, retirements, contradictions, neglected areas```### Maintenance and operator surfaces@@ -88,7 +92,7 @@ o2b vault inspect <relpath> Point-check one vault-relative path; reports match## Discipline (daily logging cron)```text-o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime activity); status ok | info | alert+o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime/vault activity plus complexity-to-thinking ratio); status ok | info | alerto2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digesto2b discipline uninstall Remove the cron job; --weekly removes only the weekly digest, without flag removes both```diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 0b326536..ba751bc5 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -214,7 +214,8 @@ A single dream invocation is a deterministic pipeline:flowchart TDStart([o2b brain dream]) --> Load[Load _brain.yaml]Load --> Scan[Scan inbox/, preferences/, retired/, log/]- Scan --> Plan[Plan transitions:<br/>new unconfirmed, promotions,<br/>quarantine in/out, retires, signal moves]+ Scan --> Intent[Build read-only intent_reviews<br/>for active signal clusters]+ Intent --> Plan[Plan transitions:<br/>new unconfirmed, promotions,<br/>quarantine in/out, retires, signal moves]Plan --> Changed{Any changes planned?}Changed -- no --> NoOp([regenerate active.md<br/>return changed: false])Changed -- yes --> Snap["createSnapshot to<br/>.snapshots/dream-RUNID.tar.zst"]@@ -267,6 +268,11 @@ Key rules baked into the pipeline:created only when `candidate_threshold` (default 3) **same-sign**signals on one topic appear within `contradiction_window_days`.Mixed signals cancel and the rule does not form.+- **Intent review is audit data.** Each run computes `intent_reviews`+ before mutation so operators can see topics that are ready, weak, or+ conflicted. The review is exposed by `dream`, `brain_review_candidates`,+ `o2b brain intent-review`, and `brain_intent_review`; it preserves the+ existing transition outcomes by default.- **Pre-run snapshot before any mutation.** If snapshot fails, the runaborts without writing anything; safety net cannot be bypassed.- **Idempotency.** A second dream run on unchanged inputs is a no-op:@@ -360,7 +366,7 @@ flowchart LRcapability so clients know to enumerate them.- **`brain_context` MCP tool** (v0.10.10) lives in the always-loadedwriter-scope MCP server. Runtimes that lack a `SessionStart` hook- *and* do not auto-load MCP resources (Cursor, Aider, raw Claude+ _and_ do not auto-load MCP resources (Cursor, Aider, raw ClaudeAPI) can fetch the same `active.md` body, pinned current-task context,and active-preference counts with a single tool call.- **`Brain/pinned.md`** is a transient scratchpad for current-task facts.@@ -377,35 +383,38 @@ file is harmless: the next dream regenerates it.The same operations are reachable through two channels. Read columnsare mirrored in MCP; destructive operations are CLI-only by design.-| Operation | CLI verb | MCP tool | Side effect |-|--------------------------|----------------------------|-----------------------|------------------------|-| Bootstrap layer | `o2b brain init` | β | creates `Brain/` skeleton |-| Record taste signal | `o2b brain feedback` | `brain_feedback` | writes signal + log event (sanitised) |-| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |-| Record application | `o2b brain apply-evidence` | `brain_apply_evidence`| appends log event; `result β {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |-| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |-| Pin current-task context | β (use MCP) | `brain_pinned_context`| writes/appends/clears `Brain/pinned.md`; transient context, not a learned preference |-| Pull active context | β (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body, pinned context + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |-| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |-| Inspect state | `o2b brain query` | `brain_query` | read-only |-| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |-| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps |-| Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict |-| Preference edit-history | `o2b brain history <slug>` | β (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) |-| Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic |-| Manage search index | `o2b search index \| reindex \| status \| check` | β (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) |-| Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | β (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |-| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |-| Retire manually | `o2b brain reject` | β (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |-| Merge near-duplicate prefs | `o2b brain merge <keep> <drop>` | β (CLI-only) | folds `evidenced_by` and counters into `keep`; `drop` retires with reason `merged-into`; surfaced as candidates in `brain_digest` |-| Toggle pin | `o2b brain pin / unpin` | β (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |-| Protect Brain/ | `o2b brain protect / unprotect` | β (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |-| Restore snapshot | `o2b brain rollback` | β (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |-| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. |-| Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. |-| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |-| Import Claude memory | `o2b brain import-claude-memory` | β (CLI-only) | imports `metadata.type=feedback` entries from a Claude Code memory directory into `Brain/preferences/`. `--dry-run` prints a per-file plan; `--apply --yes` takes an `import-claude-memory-<ts>` snapshot before writing. Sidecar manifest `Brain/.imports/claude-memory.json` keys idempotency on body sha256. `UPDATE` preserves the eight evidence-related frontmatter fields. `CONFLICT` (existing pref outside the manifest) lands the safe writes and exits 2. |-| Daily discipline report | `o2b discipline {report\|install\|uninstall}` | β (CLI-only) | renders a deterministic Telegram MarkdownV2 block comparing per-agent brain-events vs runtime-agnostic activity (git/mtime/vault delta). `install` writes a Hermes cron entry (`--telegram-target` required; `--weekly` installs a Monday digest; `uninstall --weekly` removes only the weekly job). Status is binary: `alert` when taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero. |+| Operation | CLI verb | MCP tool | Side effect |+| -------------------------- | --------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Bootstrap layer | `o2b brain init` | β | creates `Brain/` skeleton |+| Record taste signal | `o2b brain feedback` | `brain_feedback` | writes signal + log event (sanitised) |+| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |+| Record application | `o2b brain apply-evidence` | `brain_apply_evidence` | appends log event; `result β {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |+| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |+| Pin current-task context | β (use MCP) | `brain_pinned_context` | writes/appends/clears `Brain/pinned.md`; transient context, not a learned preference |+| Pull active context | β (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body, pinned context + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |+| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |+| Pre-dream intent review | `o2b brain intent-review` | `brain_intent_review` | read-only; classifies active signal clusters as ready, needing evidence, or conflicted before the next `dream` |+| Lifecycle retention review | `o2b brain retention` | `brain_retention` | read-only; recommends keep / improve / park / prune for retired preferences and processed signals; no artifact is deleted or moved |+| Monthly synthesis | `o2b brain monthly` | `brain_monthly_review` | read-only; month-level counters for events, status transitions, retirements, contradictions, and neglected areas |+| Inspect state | `o2b brain query` | `brain_query` | read-only |+| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |+| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps |+| Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict |+| Preference edit-history | `o2b brain history <slug>` | β (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) |+| Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic |+| Manage search index | `o2b search index \| reindex \| status \| check` | β (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) |+| Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | β (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |+| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |+| Retire manually | `o2b brain reject` | β (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |+| Merge near-duplicate prefs | `o2b brain merge <keep> <drop>` | β (CLI-only) | folds `evidenced_by` and counters into `keep`; `drop` retires with reason `merged-into`; surfaced as candidates in `brain_digest` |+| Toggle pin | `o2b brain pin / unpin` | β (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |+| Protect Brain/ | `o2b brain protect / unprotect` | β (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |+| Restore snapshot | `o2b brain rollback` | β (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |+| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. |+| Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. |+| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |+| Import Claude memory | `o2b brain import-claude-memory` | β (CLI-only) | imports `metadata.type=feedback` entries from a Claude Code memory directory into `Brain/preferences/`. `--dry-run` prints a per-file plan; `--apply --yes` takes an `import-claude-memory-<ts>` snapshot before writing. Sidecar manifest `Brain/.imports/claude-memory.json` keys idempotency on body sha256. `UPDATE` preserves the eight evidence-related frontmatter fields. `CONFLICT` (existing pref outside the manifest) lands the safe writes and exits 2. |+| Daily discipline report | `o2b discipline {report\|install\|uninstall}` | β (CLI-only) | renders a deterministic Telegram MarkdownV2 block comparing per-agent brain-events vs runtime-agnostic activity (git/mtime/vault delta) plus a complexity-to-thinking ratio. `install` writes a Hermes cron entry (`--telegram-target` required; `--weekly` installs a Monday digest; `uninstall --weekly` removes only the weekly job). `alert` fires when taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero, or when structural churn grows much faster than recorded thinking. |Operations that change the **protected set** (`pin`, `unpin`,`reject`, `rollback`) and the **index lifecycle** (`search index`,@@ -417,15 +426,15 @@ business, never agent business.In addition to the tools above, MCP hosts can pull structured Braincontent as **resources** (added in v0.9.1):-| Resource URI | Body |-|-----------------------------------|---------------------------------------------------|-| `osb://preferences/active` | `Brain/active.md` (auto-regenerated on first read if missing) |-| `osb://digest/latest` | most recent `brain_digest` rendering |-| `osb://status` | Markdown form of the `second_brain_status.brain` block |-| `osb://preference/{id}` | one `pref-` / `ret-` file |-| `osb://topic/{slug}` | every signal + active/retired pref for a topic |-| `osb://log/{date}` | one day's `Brain/log/YYYY-MM-DD.md` (a parallel `YYYY-MM-DD.jsonl` sidecar carries the same events as one JSON row per line for machine consumers) |-| `osb://backlinks/{id}` | inverted reference map for `<id>` |+| Resource URI | Body |+| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |+| `osb://preferences/active` | `Brain/active.md` (auto-regenerated on first read if missing) |+| `osb://digest/latest` | most recent `brain_digest` rendering |+| `osb://status` | Markdown form of the `second_brain_status.brain` block |+| `osb://preference/{id}` | one `pref-` / `ret-` file |+| `osb://topic/{slug}` | every signal + active/retired pref for a topic |+| `osb://log/{date}` | one day's `Brain/log/YYYY-MM-DD.md` (a parallel `YYYY-MM-DD.jsonl` sidecar carries the same events as one JSON row per line for machine consumers) |+| `osb://backlinks/{id}` | inverted reference map for `<id>` |Resources are pure read; mutating verbs stay on `tools/call`.@@ -538,17 +547,17 @@ functions over the on-disk Brain state β no LLM, no network. The firstgroup are structural; the last three (v0.14.0) are semantic and alsopopulate the `semantic_health` report (see `brain_health` below):-| Code | Triggers when |-|---|---|-| `broken-backlinks` | a `[[pref-β¦]]` / `[[ret-β¦]]` / `[[sig-β¦]]` reference exists in `preferences/`, `retired/`, `inbox/`, or `log/`, but the target file does not |-| `duplicate-preferences` | pairwise Jaccard β₯ 0.7 on principle tokens within the same `(topic, scope)` bucket |-| `low-evidence-confirmed` | `status: confirmed` with `applied_count β€ low_max_applied` AND `confirmed_at` older than `unconfirmed_window_days` |-| `pinned-without-recent-evidence` | `pinned: true` with no evidence or evidence older than `stale_evidence_days` |-| `malformed-evidence-range` | `apply-evidence` `artifact` uses `[[file:β¦]]` range syntax but fails validation (`:abc-def`, `:120-100`, bare `:`) |-| `orphan-evidence` | `apply-evidence` `artifact` wikilink does not resolve to any file in the vault |-| `contradictory-preferences` | two confirmed preferences share a subject (principle Jaccard β₯ `health.contradiction_jaccard`) but carry an opposite sign of record |-| `concept-gap` | an entity recurs across β₯ `health.concept_gap_min_frequency` corpus entries with no covering preference topic |-| `stale-claim` | a confirmed preference's newest evidence is older than `health.stale_claim_max_age_days` |+| Code | Triggers when |+| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| `broken-backlinks` | a `[[pref-β¦]]` / `[[ret-β¦]]` / `[[sig-β¦]]` reference exists in `preferences/`, `retired/`, `inbox/`, or `log/`, but the target file does not |+| `duplicate-preferences` | pairwise Jaccard β₯ 0.7 on principle tokens within the same `(topic, scope)` bucket |+| `low-evidence-confirmed` | `status: confirmed` with `applied_count β€ low_max_applied` AND `confirmed_at` older than `unconfirmed_window_days` |+| `pinned-without-recent-evidence` | `pinned: true` with no evidence or evidence older than `stale_evidence_days` |+| `malformed-evidence-range` | `apply-evidence` `artifact` uses `[[file:β¦]]` range syntax but fails validation (`:abc-def`, `:120-100`, bare `:`) |+| `orphan-evidence` | `apply-evidence` `artifact` wikilink does not resolve to any file in the vault |+| `contradictory-preferences` | two confirmed preferences share a subject (principle Jaccard β₯ `health.contradiction_jaccard`) but carry an opposite sign of record |+| `concept-gap` | an entity recurs across β₯ `health.concept_gap_min_frequency` corpus entries with no covering preference topic |+| `stale-claim` | a confirmed preference's newest evidence is older than `health.stale_claim_max_age_days` |With `--strict`, warnings demote `ok` to `false` so CI can gate onhygiene. `brain_doctor` itself stays read-only β auto-modifying state on@@ -655,7 +664,7 @@ Key behaviours, all driven from `Brain/_brain.yaml`-free `search_*` /writer exclusivity (three attempts, 1 s backoff, then`INDEX_LOCKED`).- **Ranking.** `final_score = clamp01(keyword_weightΒ·norm_BM25 +- semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`.+semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`.BM25 is min-max-normalised within the candidate set; cosine is`1 - L2Β² / 2` on unit-normalised vectors; link boost rewardscandidates that other candidates reference via `[[wikilink]]` /diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 72e71e88..07fd195d 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.16.0",+ "version": "0.17.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex eb87b9cc..a893f114 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.16.0",+ "version": "0.17.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 487981a7..632ece03 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.16.0"+version: "0.17.0"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 376d4ea9..0c51c227 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.16.0",+ "version": "0.17.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex a1eaa9bf..e799d9e4 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.16.0"+version: "0.17.0"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex daceaeb4..f6e2a681 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.16.0"+version = "0.17.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/schemas/brain/complexity-report.schema.json b/schemas/brain/complexity-report.schema.jsonnew file mode 100644index 00000000..396f29db--- /dev/null+++ b/schemas/brain/complexity-report.schema.json@@ -0,0 +1,39 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "brain.complexity_report.v1",+ "title": "Brain Complexity Report v1",+ "type": "object",+ "required": [+ "schema_version",+ "generated_at",+ "score",+ "ratio",+ "thinking_activity",+ "structural_complexity",+ "warning",+ "factors"+ ],+ "additionalProperties": false,+ "properties": {+ "schema_version": { "type": "integer", "enum": [1] },+ "generated_at": { "type": "string", "format": "date-time" },+ "score": { "type": "integer", "minimum": 0 },+ "ratio": { "type": "number", "minimum": 0 },+ "thinking_activity": { "type": "integer", "minimum": 0 },+ "structural_complexity": { "type": "integer", "minimum": 0 },+ "warning": { "type": "boolean" },+ "factors": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["name", "value", "weight"],+ "additionalProperties": false,+ "properties": {+ "name": { "type": "string" },+ "value": { "type": "integer", "minimum": 0 },+ "weight": { "type": "integer", "minimum": 0 }+ }+ }+ }+ }+}diff --git a/schemas/brain/intent-review.schema.json b/schemas/brain/intent-review.schema.jsonnew file mode 100644index 00000000..e16fa783--- /dev/null+++ b/schemas/brain/intent-review.schema.json@@ -0,0 +1,43 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "brain.intent_review.v1",+ "title": "Brain Intent Review v1",+ "type": "object",+ "required": ["schema_version", "generated_at", "reviews"],+ "additionalProperties": false,+ "properties": {+ "schema_version": { "type": "integer", "enum": [1] },+ "generated_at": { "type": "string" },+ "reviews": {+ "type": "array",+ "items": {+ "type": "object",+ "required": [+ "topic",+ "decision",+ "signal_count",+ "risk_band",+ "risk_score",+ "reasons"+ ],+ "additionalProperties": false,+ "properties": {+ "topic": { "type": "string" },+ "decision": {+ "type": "string",+ "enum": [+ "ready_for_main_review",+ "needs_more_evidence",+ "blocked_conflicted",+ "suppressed_by_rejected_retired"+ ]+ },+ "signal_count": { "type": "integer" },+ "risk_band": { "type": "string", "enum": ["low", "medium", "high"] },+ "risk_score": { "type": "integer" },+ "reasons": { "type": "array", "items": { "type": "string" } }+ }+ }+ }+ }+}diff --git a/schemas/brain/monthly-review.schema.json b/schemas/brain/monthly-review.schema.jsonnew file mode 100644index 00000000..9e152f2e--- /dev/null+++ b/schemas/brain/monthly-review.schema.json@@ -0,0 +1,40 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "brain.monthly_review.v1",+ "title": "Brain Monthly Review v1",+ "type": "object",+ "required": ["schema_version", "generated_at", "month", "window", "summary"],+ "additionalProperties": false,+ "properties": {+ "schema_version": { "type": "integer", "enum": [1] },+ "generated_at": { "type": "string" },+ "month": { "type": "string" },+ "window": {+ "type": "object",+ "required": ["since", "until"],+ "additionalProperties": false,+ "properties": {+ "since": { "type": "string" },+ "until": { "type": "string" }+ }+ },+ "summary": {+ "type": "object",+ "required": [+ "events",+ "status_transitions",+ "retired",+ "contradictions",+ "neglected_areas"+ ],+ "additionalProperties": false,+ "properties": {+ "events": { "type": "integer" },+ "status_transitions": { "type": "integer" },+ "retired": { "type": "integer" },+ "contradictions": { "type": "integer" },+ "neglected_areas": { "type": "array", "items": { "type": "string" } }+ }+ }+ }+}diff --git a/schemas/brain/retention-review.schema.json b/schemas/brain/retention-review.schema.jsonnew file mode 100644index 00000000..a36c2aa4--- /dev/null+++ b/schemas/brain/retention-review.schema.json@@ -0,0 +1,44 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "brain.retention_review.v1",+ "title": "Brain Retention Review v1",+ "type": "object",+ "required": ["schema_version", "generated_at", "summary", "recommendations"],+ "additionalProperties": false,+ "properties": {+ "schema_version": { "type": "integer", "enum": [1] },+ "generated_at": { "type": "string", "format": "date-time" },+ "summary": {+ "type": "object",+ "required": ["keep", "improve", "park", "prune"],+ "additionalProperties": false,+ "properties": {+ "keep": { "type": "integer", "minimum": 0 },+ "improve": { "type": "integer", "minimum": 0 },+ "park": { "type": "integer", "minimum": 0 },+ "prune": { "type": "integer", "minimum": 0 }+ }+ },+ "recommendations": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["id", "artifact_type", "action", "reason", "path"],+ "additionalProperties": false,+ "properties": {+ "id": { "type": "string" },+ "artifact_type": {+ "type": "string",+ "enum": ["retired_preference", "processed_signal"]+ },+ "action": {+ "type": "string",+ "enum": ["keep", "improve", "park", "prune"]+ },+ "reason": { "type": "string" },+ "path": { "type": "string" }+ }+ }+ }+ }+}diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex be07261f..c3f3bd7c 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -15,6 +15,9 @@ import {cmdBrainDream,cmdBrainApplyEvidence,cmdBrainDigest,+ cmdBrainIntentReview,+ cmdBrainRetention,+ cmdBrainMonthly,cmdBrainQuery,cmdBrainAgentQuery,cmdBrainAgentDiff,@@ -87,6 +90,12 @@ export async function handleBrainSubcommand(return await cmdBrainApplyEvidence(rest);case "digest":return await cmdBrainDigest(rest);+ case "intent-review":+ return await cmdBrainIntentReview(rest);+ case "retention":+ return await cmdBrainRetention(rest);+ case "monthly":+ return await cmdBrainMonthly(rest);case "query":return await cmdBrainQuery(rest);case "agent-query":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 04dfa6b5..2472a06b 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -16,6 +16,9 @@ Brain verbs (observing memory):apply-evidence Log a real-work application of a preferencenote Append a one-line narrative milestone to Brain/log/todaydigest Render the recent-changes digest (markdown or --json)+ intent-review Read-only pre-dream review of active signal clusters+ retention Recommendation-only keep/improve/park/prune review+ monthly Monthly synthesis over Brain timeline activityquery Read by --preference, --topic, or --sinceagent-query Read Brain provenance by source agent (--agent; --json)agent-diff Compare source-agent coverage (browse/search/diff/map)@@ -86,6 +89,21 @@ export const VERB_HELP: Record<string, string> = {digest:"usage: o2b brain digest [--vault <path>] [--since <ISO>] [--until <ISO>] [--json] [--silent-if-empty]\n" +"Renders the 24-hour change digest. Empty + --silent-if-empty exits 2.\n",+ "intent-review":+ "usage: o2b brain intent-review [--vault <path>] [--now <ISO-8601>] [--json]\n" ++ "Read-only pre-dream review of active signal clusters. Surfaces whether\n" ++ "each topic is ready for main dream review, needs more evidence, or is\n" ++ "blocked by conflicting signals.\n",+ retention:+ "usage: o2b brain retention [--vault <path>] [--now <ISO-8601>] [--json]\n" ++ "Recommendation-only lifecycle review over retired preferences and\n" ++ "processed signals. Reports keep/improve/park/prune candidates and never\n" ++ "deletes or moves artifacts.\n",+ monthly:+ "usage: o2b brain monthly [--vault <path>] [--month YYYY-MM] [--json]\n" ++ "Read-only monthly synthesis over the Brain timeline: event count, status\n" ++ "transitions, retirements, contradictions, and neglected areas when\n" ++ "expected areas are supplied by future callers.\n",query:"usage: o2b brain query --preference <id> | --topic <slug> | --since <ISO> [--vault <path>] [--json]\n" +"Read-only lookup. One of --preference / --topic / --since is required.\n",diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 80a03e5e..a1631ee1 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -4,6 +4,9 @@ export { cmdBrainNote } from "./note.ts";export { cmdBrainDream } from "./dream.ts";export { cmdBrainApplyEvidence } from "./apply-evidence.ts";export { cmdBrainDigest } from "./digest.ts";+export { cmdBrainIntentReview } from "./intent-review.ts";+export { cmdBrainRetention } from "./retention.ts";+export { cmdBrainMonthly } from "./monthly.ts";export { cmdBrainQuery } from "./query.ts";export { cmdBrainAgentQuery } from "./agent-query.ts";export { cmdBrainAgentDiff } from "./agent-diff.ts";diff --git a/src/cli/brain/verbs/intent-review.ts b/src/cli/brain/verbs/intent-review.tsnew file mode 100644index 00000000..9cb910bc--- /dev/null+++ b/src/cli/brain/verbs/intent-review.ts@@ -0,0 +1,54 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildIntentReview } from "../../../core/brain/intent-review.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain intent-review [--vault PATH] [--now ISO] [--json]`+ *+ * Read-only pre-dream intent review over active signal clusters.+ */+export async function cmdBrainIntentReview(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ now: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const now = parseNow(flags["now"]);+ const report = buildIntentReview(vault, now ? { now } : {});++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Intent review generated ${report.generated_at}\n`);+ for (const review of report.reviews) {+ process.stdout.write(+ ` ${review.topic}: ${review.decision} (${review.signal_count} signals, ${review.risk_band} risk)\n`,+ );+ }+ if (report.reviews.length === 0) {+ process.stdout.write(" no active signal clusters\n");+ }+ return 0;+}++function parseNow(+ raw: string | boolean | string[] | undefined,+): Date | undefined {+ if (raw === undefined || raw === false) return undefined;+ if (typeof raw !== "string" || raw.trim().length === 0) {+ throw new CliError(+ "brain intent-review: --now must be an ISO-8601 timestamp",+ );+ }+ const date = new Date(raw);+ if (!Number.isFinite(date.getTime())) {+ throw new CliError(+ `brain intent-review: invalid --now ${JSON.stringify(raw)}`,+ );+ }+ return date;+}diff --git a/src/cli/brain/verbs/monthly.ts b/src/cli/brain/verbs/monthly.tsnew file mode 100644index 00000000..d94978ce--- /dev/null+++ b/src/cli/brain/verbs/monthly.ts@@ -0,0 +1,61 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ buildMonthlyReview,+ normalizeMonthlyReviewMonth,+} from "../../../core/brain/monthly-review.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++const MONTH_RE = /^\d{4}-\d{2}$/;++/**+ * `o2b brain monthly [--vault PATH] [--month YYYY-MM] [--json]`+ *+ * Read-only monthly synthesis over the Brain timeline.+ */+export async function cmdBrainMonthly(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ month: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const month = parseMonth(flags["month"]);+ const report = buildMonthlyReview(vault, month ? { month } : {});++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Monthly review ${report.month}\n`);+ process.stdout.write(+ ` window: ${report.window.since} .. ${report.window.until}\n`,+ );+ process.stdout.write(` events: ${report.summary.events}\n`);+ process.stdout.write(+ ` status transitions: ${report.summary.status_transitions}\n`,+ );+ process.stdout.write(` retired: ${report.summary.retired}\n`);+ process.stdout.write(` contradictions: ${report.summary.contradictions}\n`);+ if (report.summary.neglected_areas.length > 0) {+ process.stdout.write(+ ` neglected areas: ${report.summary.neglected_areas.join(", ")}\n`,+ );+ }+ return 0;+}++function parseMonth(+ raw: string | boolean | string[] | undefined,+): string | undefined {+ if (raw === undefined || raw === false) return undefined;+ if (typeof raw !== "string") {+ throw new CliError("brain monthly: --month must be YYYY-MM");+ }+ try {+ return normalizeMonthlyReviewMonth(raw);+ } catch {+ throw new CliError("brain monthly: --month must be YYYY-MM");+ }+}diff --git a/src/cli/brain/verbs/retention.ts b/src/cli/brain/verbs/retention.tsnew file mode 100644index 00000000..28c863d9--- /dev/null+++ b/src/cli/brain/verbs/retention.ts@@ -0,0 +1,50 @@+import { defaultConfigPath } from "../../../core/config.ts";+import { buildRetentionReview } from "../../../core/brain/retention.ts";+import { CliError, parse, resolveBrainVault } from "../helpers.ts";++/**+ * `o2b brain retention [--vault PATH] [--now ISO] [--json]`+ *+ * Recommendation-only lifecycle review over retired preferences and processed signals.+ */+export async function cmdBrainRetention(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ now: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const now = parseNow(flags["now"]);+ const report = buildRetentionReview(vault, now ? { now } : {});++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`Retention review generated ${report.generated_at}\n`);+ process.stdout.write(+ ` keep=${report.summary.keep} improve=${report.summary.improve} park=${report.summary.park} prune=${report.summary.prune}\n`,+ );+ for (const recommendation of report.recommendations) {+ process.stdout.write(+ ` ${recommendation.action} ${recommendation.id} (${recommendation.artifact_type}) - ${recommendation.reason}\n`,+ );+ }+ return 0;+}++function parseNow(+ raw: string | boolean | string[] | undefined,+): Date | undefined {+ if (raw === undefined || raw === false) return undefined;+ if (typeof raw !== "string" || raw.trim().length === 0) {+ throw new CliError("brain retention: --now must be an ISO-8601 timestamp");+ }+ const date = new Date(raw);+ if (!Number.isFinite(date.getTime())) {+ throw new CliError(`brain retention: invalid --now ${JSON.stringify(raw)}`);+ }+ return date;+}diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 1c519371..53a69efe 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -39,11 +39,23 @@ import { basename, join } from "node:path";import { parseFrontmatter } from "../vault.ts";import { regenerateActiveQuiet } from "./active.ts";-import { openWorkrun, WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";+import {+ openWorkrun,+ WORKRUN_PHASE,+ type WorkrunHandle,+} from "./dream-workrun.ts";import { collectEvidenceForSlug } from "./evidence.ts";+import {+ buildIntentReview,+ type BrainIntentReviewEntry,+} from "./intent-review.ts";import { writePreferenceTxn } from "./preference-txn.ts";import { appendLogEvent, parseLogDay, type BrainLogEntry } from "./log.ts";-import { moveToRetired, parsePreference, wouldRewritePreference } from "./preference.ts";+import {+ moveToRetired,+ parsePreference,+ wouldRewritePreference,+} from "./preference.ts";import { parseSignal } from "./signal.ts";import { isPinned } from "./pin.ts";import { createSnapshot, pruneSnapshots } from "./snapshot.ts";@@ -189,6 +201,13 @@ export interface DreamRunSummary {* match pre-v0.10.16 behaviour.*/readonly quarantined: ReadonlyArray<DreamQuarantinedEntry>;+ /**+ * Deterministic pre-dream intent review over active signal clusters.+ * This is audit data for the two-stage gate: intent review explains+ * whether a cluster is ready for the existing main dream review,+ * needs more evidence, or is blocked by conflicting signals.+ */+ readonly intent_reviews: ReadonlyArray<BrainIntentReviewEntry>;/*** Brain Integrity Suite (v0.12.0). Retires the dream pass planned* but declined to execute because the source preference's evidence@@ -276,7 +295,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {const warnings: DreamWarning[] = [];const callerAgent = opts.agentName?.trim() ?? "";const isNonPrimary =- cfg.primary_agent !== null && callerAgent.length > 0 && callerAgent !== cfg.primary_agent;+ cfg.primary_agent !== null &&+ callerAgent.length > 0 &&+ callerAgent !== cfg.primary_agent;if (isNonPrimary) {warnings.push({code: "non-primary-dream-run",@@ -291,6 +312,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// can emit `skip-corrupted-frontmatter` log entries without// aborting.const scan = scanBrain(vault);+ const intentReview = buildIntentReview(vault, { now });// 1-2. Plan per-topic transitions: new unconfirmed preferences,// same-sign noted-redundant moves, rebuttal accumulation.@@ -349,6 +371,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {warnings: Object.freeze([...warnings]),uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),quarantined: Object.freeze([...plan.quarantined]),+ intent_reviews: Object.freeze([...intentReview.reviews]),gated_retires: Object.freeze([] as ReadonlyArray<DreamGatedRetireEntry>),...(dryRun ? { dry_run: true } : {}),} satisfies DreamRunSummary);@@ -413,7 +436,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {topic: np.topic,principle: np.principle,created_at: isoSecond(now),- unconfirmed_until: isoSecond(addDays(now, cfg.dream.unconfirmed_window_days)),+ unconfirmed_until: isoSecond(+ addDays(now, cfg.dream.unconfirmed_window_days),+ ),status: BRAIN_PREFERENCE_STATUS.unconfirmed,evidenced_by: np.evidencedBy,// No evidence yet β Wilson lower bound on (0, 0) is 0. Pre-@@ -481,7 +506,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {if (gateThreshold !== undefined && gateThreshold > 0) {try {const existing = parsePreference(fromPath);- if (shouldGateRetireFromConfirmed(existing, r.reason, gateThreshold)) {+ if (+ shouldGateRetireFromConfirmed(existing, r.reason, gateThreshold)+ ) {gatedRetires.push({pref_id: existing.id,topic: existing.topic,@@ -548,7 +575,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// exclude retires the destructive-from-confirmed gate skipped, or// the next dream pass would parse a `pref-foo` log claiming the// pref was retired while the file is still in `preferences/`.- const gatedSlugs = new Set(gatedRetires.map((g) => g.pref_id.replace(/^pref-/, "")));+ const gatedSlugs = new Set(+ gatedRetires.map((g) => g.pref_id.replace(/^pref-/, "")),+ );// Emit log entries: skip-corrupted-frontmatter first (chronological// sense: corruption was detected during planning), then per-topic@@ -628,18 +657,23 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {const confirmedIds = Array.from(refresh.confirmed.values()).map((slug) =>renderPrefLink({id: `pref-${slug}`,- principle: refresh.updated.get(slug)?.principle ?? slugToPrefPrinciple.get(slug) ?? "",+ principle:+ refresh.updated.get(slug)?.principle ??+ slugToPrefPrinciple.get(slug) ??+ "",}),);const retiredEntries = plan.retires.filter((r) => !gatedSlugs.has(r.slug)).map(- (r) => `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,+ (r) =>+ `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,);const summaryBody: Record<string, string | ReadonlyArray<string>> = {run_id: runId,};- if (newUnconfirmedIds.length > 0) summaryBody["new_unconfirmed"] = newUnconfirmedIds;+ if (newUnconfirmedIds.length > 0)+ summaryBody["new_unconfirmed"] = newUnconfirmedIds;if (confirmedIds.length > 0) summaryBody["confirmed"] = confirmedIds;if (retiredEntries.length > 0) summaryBody["retired"] = retiredEntries;if (moved.length > 0) summaryBody["moved_to_processed"] = moved;@@ -647,7 +681,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {summaryBody["contradictions"] = Array.from(plan.contradictionTopics);}if (plan.signalsSuppressed.length > 0) {- summaryBody["suppressed"] = plan.signalsSuppressed.map((s) => `${s.signal} β ${s.retired}`);+ summaryBody["suppressed"] = plan.signalsSuppressed.map(+ (s) => `${s.signal} β ${s.retired}`,+ );}if (refresh.bandDrops.length > 0) {// Format matches the digest's tolerant `parseShiftLine` parser:@@ -686,7 +722,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// successful dream run into an error. The next run will retry.// Surface so an operator can spot a recurring disk/permission// issue instead of wondering why retention stopped.- process.stderr.write(`warning: prune snapshots failed: ${(err as Error).message}\n`);+ process.stderr.write(+ `warning: prune snapshots failed: ${(err as Error).message}\n`,+ );}regenerateActiveQuiet(vault, { now });}@@ -713,6 +751,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {warnings: Object.freeze([...warnings]),uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),quarantined: Object.freeze([...plan.quarantined]),+ intent_reviews: Object.freeze([...intentReview.reviews]),gated_retires: Object.freeze([...gatedRetires]),...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),...(dryRun@@ -740,7 +779,8 @@ export function shouldGateRetireFromConfirmed(if (reason === BRAIN_RETIRED_REASON.mergedInto) return false;if (existing.status !== BRAIN_PREFERENCE_STATUS.confirmed) return false;if (existing.pinned) return false;- const evidenceCount = (existing.applied_count ?? 0) + (existing.violated_count ?? 0);+ const evidenceCount =+ (existing.applied_count ?? 0) + (existing.violated_count ?? 0);return evidenceCount < threshold;}@@ -802,8 +842,10 @@ function scanBrain(vault: string): ScanResult {const [meta] = parseFrontmatter(full);const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";const id = typeof meta["id"] === "string" ? meta["id"] : "";- const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";- const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;+ const principle =+ typeof meta["principle"] === "string" ? meta["principle"] : "";+ const scope =+ typeof meta["scope"] === "string" ? meta["scope"] : undefined;const userReason =typeof meta["user_rejected_reason"] === "string"? (meta["user_rejected_reason"] as string).trim()@@ -969,7 +1011,15 @@ function planTopics(for (const [topic, sigs] of byTopic) {const active = prefByTopic.get(topic);if (active) {- handleSignalsOnActivePref(active, sigs, plan, cfg, now, scan.signals, reservedSlugs);+ handleSignalsOnActivePref(+ active,+ sigs,+ plan,+ cfg,+ now,+ scan.signals,+ reservedSlugs,+ );continue;}// v0.10.1 _summary Β§6: when a retired pref for this topic carries@@ -986,7 +1036,9 @@ function planTopics(// prefs on the same topic are tried in order β the first matching// suppressor wins. Non-matching signals fall through and remain// eligible for candidate-pref planning below.- const suppressors = (retiredByTopic.get(topic) ?? []).filter((r) => !!r.user_rejected_reason);+ const suppressors = (retiredByTopic.get(topic) ?? []).filter(+ (r) => !!r.user_rejected_reason,+ );let candidateSigs: SignalRecord[] = sigs;if (suppressors.length > 0) {const remaining: SignalRecord[] = [];@@ -1021,9 +1073,14 @@ function planTopics(cfg.dream.contradiction_window_days,now,);- const positives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive);- const negatives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative);- const dominant = positives.length >= negatives.length ? positives : negatives;+ const positives = windowedSigs.filter(+ (s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive,+ );+ const negatives = windowedSigs.filter(+ (s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative,+ );+ const dominant =+ positives.length >= negatives.length ? positives : negatives;const minoritySize = Math.min(positives.length, negatives.length);const dominantSize = dominant.length - minoritySize; // cancellationif (dominantSize >= cfg.dream.candidate_threshold) {@@ -1044,7 +1101,12 @@ function planTopics(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)))+ ? Math.max(+ 0,+ Math.floor(+ (now.getTime() - earliestSignalMs) / (24 * 60 * 60 * 1000),+ ),+ ): 0;const verdict = applySelfApprovalGuardrail({@@ -1068,7 +1130,9 @@ function planTopics(// wire it through.const retiredForTopic = retiredByTopic.get(topic);const supersedes =- retiredForTopic && retiredForTopic.length > 0 ? retiredForTopic[0]!.id : undefined;+ retiredForTopic && retiredForTopic.length > 0+ ? retiredForTopic[0]!.id+ : undefined;const sign = dominant[0]!.signal.signal;// Slug from topic for the canonical filename, but reserve slugs// already present in retired/. Otherwise a superseding preference@@ -1139,7 +1203,9 @@ function handleSignalsOnActivePref(// conservative, fail-loud choice: the operator gets a clear// rebut/retire signal and can manually intervene if the system// misread their intent.- const signCounts = (records: ReadonlyArray<SignalRecord>): { pos: number; neg: number } =>+ const signCounts = (+ records: ReadonlyArray<SignalRecord>,+ ): { pos: number; neg: number } =>countSigns(records.map((r) => r.signal.signal));// Tier-1 derivation now lives in the shared `sign.ts` helper so the@@ -1148,8 +1214,12 @@ function handleSignalsOnActivePref(// the old `evidenceRecords.length > 0` branch (every signal carries a// polarity, so a resolved evidence link always counts); `"unknown"`// is the old "no evidenced signal resolved" fall-through.- const signSignById = new Map(allSignals.map((r) => [r.signal.id, r.signal.signal]));- const topicRecords = allSignals.filter((r) => r.signal.topic === active.pref.topic);+ const signSignById = new Map(+ allSignals.map((r) => [r.signal.id, r.signal.signal]),+ );+ const topicRecords = allSignals.filter(+ (r) => r.signal.topic === active.pref.topic,+ );const evidenceSign = dominantSignOf(active.pref.evidenced_by, signSignById);let activeSign: BrainSignalSign;@@ -1160,12 +1230,14 @@ function handleSignalsOnActivePref(// the active inbox set β use them.const historical = topicRecords.filter((r) => !sigs.includes(r));const c = signCounts(historical);- activeSign = c.pos >= c.neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;+ activeSign =+ c.pos >= c.neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;} else {// Fallback: assume the active pref is OPPOSITE to the incoming// dominant sign. A unanimous flood thus reads as rebuttal.const c = signCounts(sigs);- activeSign = c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;+ activeSign =+ c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;}const oppositeSign: BrainSignalSign =@@ -1173,7 +1245,11 @@ function handleSignalsOnActivePref(? BRAIN_SIGNAL_SIGN.negative: BRAIN_SIGNAL_SIGN.positive;- const windowed = filterWithinWindow(sigs, cfg.dream.contradiction_window_days, now);+ const windowed = filterWithinWindow(+ sigs,+ cfg.dream.contradiction_window_days,+ now,+ );const sameSign = windowed.filter((s) => s.signal.signal === activeSign);const opposing = windowed.filter((s) => s.signal.signal === oppositeSign);@@ -1220,7 +1296,10 @@ function handleSignalsOnActivePref(// same slug, since `moveToRetired` unlinks the source first.// For safety against a half-completed move, we suffix with// `-rebut`.- const newSlug = allocatePreferencePlanSlug(`${slug}-rebut`, reservedSlugs);+ const newSlug = allocatePreferencePlanSlug(+ `${slug}-rebut`,+ reservedSlugs,+ );const principle = opposing[0]!.signal.principle;const scope = opposing[0]!.signal.scope;const evidencedBy = opposing.map((s) => `[[${s.signal.id}]]`);@@ -1255,11 +1334,19 @@ function collectReservedPreferenceSlugs(scan: ScanResult): Set<string> {return out;}-function preferenceSlugFromId(id: string, prefix: "pref-" | "ret-"): string | null {- return id.startsWith(prefix) && id.length > prefix.length ? id.slice(prefix.length) : null;+function preferenceSlugFromId(+ id: string,+ prefix: "pref-" | "ret-",+): string | null {+ return id.startsWith(prefix) && id.length > prefix.length+ ? id.slice(prefix.length)+ : null;}-function allocatePreferencePlanSlug(base: string, reserved: Set<string>): string {+function allocatePreferencePlanSlug(+ base: string,+ reserved: Set<string>,+): string {let candidate = base;let suffix = 2;while (reserved.has(candidate)) {@@ -1285,7 +1372,11 @@ function recordSignalMove(plan: PlanState, rec: SignalRecord): void {});}-function filterWithinWindow(sigs: SignalRecord[], windowDays: number, now: Date): SignalRecord[] {+function filterWithinWindow(+ sigs: SignalRecord[],+ windowDays: number,+ now: Date,+): SignalRecord[] {const minTime = now.getTime() - windowDays * 24 * 3600 * 1000;return sigs.filter((s) => {const t = Date.parse(s.signal.created_at);@@ -1404,7 +1495,10 @@ function parseWikilinkFromBodyValue(value: unknown): string | null {return typeof value === "string" ? parseWikilink(value) : null;}-function resolveMergeAlias(slug: string, aliases: ReadonlyMap<string, string>): string {+function resolveMergeAlias(+ slug: string,+ aliases: ReadonlyMap<string, string>,+): string {let current = slug;const seen = new Set<string>();while (!seen.has(current)) {@@ -1442,15 +1536,25 @@ function planRefresh(const retiringSlugs = new Set(plan.retires.map((r) => r.slug));for (const rec of scan.preferences) {- const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;+ const slug = rec.pref.id.startsWith("pref-")+ ? rec.pref.id.slice("pref-".length)+ : rec.pref.id;if (retiringSlugs.has(slug)) continue;const ev = bySlug.get(slug) ?? [];- const applied = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.applied).length;- const violated = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.violated).length;- const outdatedCount = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.outdated).length;+ const applied = ev.filter(+ (e) => e.result === BRAIN_APPLY_RESULT.applied,+ ).length;+ const violated = ev.filter(+ (e) => e.result === BRAIN_APPLY_RESULT.violated,+ ).length;+ const outdatedCount = ev.filter(+ (e) => e.result === BRAIN_APPLY_RESULT.outdated,+ ).length;const lastEvidence = ev.length > 0 ? ev[ev.length - 1]!.timestamp : null;- const firstApplied = ev.find((e) => e.result === BRAIN_APPLY_RESULT.applied);+ const firstApplied = ev.find(+ (e) => e.result === BRAIN_APPLY_RESULT.applied,+ );// `outdated` is a context-driven retire signal: a single event// means the rule's scope still matches but the artifact shows@@ -1516,7 +1620,13 @@ function planRefresh(}}- const confidence = computeConfidence(applied, violated, lastEvidence, cfg, now);+ const confidence = computeConfidence(+ applied,+ violated,+ lastEvidence,+ cfg,+ now,+ );// Idempotency on a no-op rerun: skip refresh for prefs where// counters AND status are unchanged AND the on-disk body already@@ -1531,7 +1641,8 @@ function planRefresh(// body-bytes check in `wouldRewritePreference` is what triggers// the write that populates the field.const valueDifferent =- previousValue !== null && Math.abs(previousValue - confidence.value) > 1e-6;+ previousValue !== null &&+ Math.abs(previousValue - confidence.value) > 1e-6;const countersChanged =applied !== rec.pref.applied_count ||violated !== rec.pref.violated_count ||@@ -1583,7 +1694,9 @@ function planRefresh(...(rec.pref.revision !== undefined && rec.pref.revision > 0? { revision: rec.pref.revision }: {}),- ...(rec.pref.content_hash !== undefined ? { content_hash: rec.pref.content_hash } : {}),+ ...(rec.pref.content_hash !== undefined+ ? { content_hash: rec.pref.content_hash }+ : {}),})) {// Counters and body both unchanged β true no-op for this pref.@@ -1659,7 +1772,8 @@ export function computeConfidence(const pHat = applied / n;const denom = 1 + z2 / n;const centre = (pHat + z2 / (2 * n)) / denom;- const margin = (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;+ const margin =+ (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;wilsonLow = Math.max(0, centre - margin);}let freshness = 0;@@ -1696,7 +1810,9 @@ function planAutoRetires(refresh: RefreshResult,): void {for (const rec of scan.preferences) {- const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;+ const slug = rec.pref.id.startsWith("pref-")+ ? rec.pref.id.slice("pref-".length)+ : rec.pref.id;// Already planned to retire (rebutted)? Skip.if (plan.retires.some((r) => r.slug === slug)) continue;@@ -1749,7 +1865,9 @@ function planAutoRetires(// gate on the same staleness rule using `confirmed_at`. We// measure from confirmation in that case (cheaper than a// hand-crafted invariant check).- const confirmedAt = refreshed ? refreshed.confirmed_at : rec.pref.confirmed_at;+ const confirmedAt = refreshed+ ? refreshed.confirmed_at+ : rec.pref.confirmed_at;if (!confirmedAt) continue;const days = daysBetween(Date.parse(confirmedAt), now.getTime());if (days > cfg.retire.stale_evidence_days) {@@ -1772,7 +1890,10 @@ function planAutoRetires(}continue;}- const days = daysBetween(Date.parse(effectiveLastEvidence), now.getTime());+ const days = daysBetween(+ Date.parse(effectiveLastEvidence),+ now.getTime(),+ );if (days > cfg.retire.stale_evidence_days) {if (isPinned(rec.pref)) {plan.retainPinned.push({@@ -1840,7 +1961,8 @@ function nextAvailableDreamRunId(vault: string, baseRunId: string): string {let candidate = baseRunId;for (let n = 2;- existsSync(snapshotPath(vault, candidate)) || existsSync(dreamWorkrunPath(vault, candidate));+ existsSync(snapshotPath(vault, candidate)) ||+ existsSync(dreamWorkrunPath(vault, candidate));n++) {candidate = `${baseRunId}-${n}`;diff --git a/src/core/brain/intent-review.ts b/src/core/brain/intent-review.tsnew file mode 100644index 00000000..f519678b--- /dev/null+++ b/src/core/brain/intent-review.ts@@ -0,0 +1,219 @@+import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { brainDirs, vaultRelative } from "./paths.ts";+import { loadBrainConfig } from "./policy.ts";+import { parseRetired } from "./preference.ts";+import { parseSignal } from "./signal.ts";+import { BRAIN_SIGNAL_SIGN, type BrainSignal, type BrainSignalSign } from "./types.ts";++export type BrainIntentDecision =+ | "ready_for_main_review"+ | "needs_more_evidence"+ | "blocked_conflicted"+ | "suppressed_by_rejected_retired";++export type BrainIntentRiskBand = "low" | "medium" | "high";++export interface BrainIntentReviewEntry {+ readonly topic: string;+ readonly decision: BrainIntentDecision;+ readonly signal_count: number;+ readonly risk_band: BrainIntentRiskBand;+ readonly risk_score: number;+ readonly reasons: ReadonlyArray<string>;+}++export interface BrainIntentReviewReport {+ readonly schema_version: 1;+ readonly generated_at: string;+ readonly reviews: ReadonlyArray<BrainIntentReviewEntry>;+}++export interface BuildIntentReviewOptions {+ readonly now?: Date;+}++interface SignalRecord {+ readonly path: string;+ readonly signal: BrainSignal;+}++interface RejectedRetiredSuppressor {+ readonly topic: string;+ readonly scope?: string;+}++export function buildIntentReview(+ vault: string,+ options: BuildIntentReviewOptions = {},+): BrainIntentReviewReport {+ const now = options.now ?? new Date();+ const config = loadBrainConfig(vault);+ const records = collectActiveSignals(vault).filter((record) =>+ isWithinWindow(record.signal.created_at, config.dream.contradiction_window_days, now),+ );+ const byTopic = new Map<string, SignalRecord[]>();+ for (const record of records) {+ const topicRecords = byTopic.get(record.signal.topic);+ if (topicRecords === undefined) {+ byTopic.set(record.signal.topic, [record]);+ } else {+ topicRecords.push(record);+ }+ }+ const rejectedRetiredByTopic = collectRejectedRetiredSuppressors(vault);++ const reviews = [...byTopic.entries()]+ .toSorted(([leftTopic], [rightTopic]) => leftTopic.localeCompare(rightTopic))+ .map(([topic, topicRecords]) =>+ reviewTopic(+ topic,+ topicRecords,+ config.dream.candidate_threshold,+ rejectedRetiredByTopic.get(topic) ?? [],+ ),+ );++ return Object.freeze({+ schema_version: 1 as const,+ generated_at: now.toISOString(),+ reviews: Object.freeze(reviews),+ });+}++function collectActiveSignals(vault: string): SignalRecord[] {+ const inbox = brainDirs(vault).inbox;+ if (!existsSync(inbox)) return [];+ const records: SignalRecord[] = [];+ for (const name of readdirSync(inbox).toSorted()) {+ if (!name.endsWith(".md")) continue;+ const path = join(inbox, name);+ try {+ records.push({+ path: vaultRelative(vault, path),+ signal: parseSignal(path),+ });+ } catch {+ continue;+ }+ }+ return records;+}++function collectRejectedRetiredSuppressors(+ vault: string,+): Map<string, RejectedRetiredSuppressor[]> {+ const retiredDir = brainDirs(vault).retired;+ const byTopic = new Map<string, RejectedRetiredSuppressor[]>();+ if (!existsSync(retiredDir)) return byTopic;+ for (const name of readdirSync(retiredDir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ try {+ const retired = parseRetired(join(retiredDir, name));+ if (!retired.user_rejected_reason?.trim()) continue;+ const suppressor: RejectedRetiredSuppressor = {+ topic: retired.topic,+ ...(retired.scope ? { scope: retired.scope } : {}),+ };+ const existing = byTopic.get(retired.topic);+ if (existing === undefined) {+ byTopic.set(retired.topic, [suppressor]);+ } else {+ existing.push(suppressor);+ }+ } catch {+ continue;+ }+ }+ return byTopic;+}++function reviewTopic(+ topic: string,+ records: ReadonlyArray<SignalRecord>,+ candidateThreshold: number,+ rejectedRetiredSuppressors: ReadonlyArray<RejectedRetiredSuppressor>,+): BrainIntentReviewEntry {+ const candidateRecords = records.filter(+ (record) => !isSuppressedByRejectedRetired(record, rejectedRetiredSuppressors),+ );+ const suppressedCount = records.length - candidateRecords.length;+ const positiveCount = countSign(candidateRecords, BRAIN_SIGNAL_SIGN.positive);+ const negativeCount = countSign(candidateRecords, BRAIN_SIGNAL_SIGN.negative);+ const minorityCount = Math.min(positiveCount, negativeCount);+ const dominantCount = Math.max(positiveCount, negativeCount);+ const effectiveSignalCount = dominantCount - minorityCount;+ const signalCount = records.length;++ let decision: BrainIntentDecision;+ const reasons: string[] = [];+ if (suppressedCount > 0 && candidateRecords.length === 0) {+ decision = "suppressed_by_rejected_retired";+ reasons.push("signals match a user-rejected retired preference");+ } else if (positiveCount > 0 && negativeCount > 0 && effectiveSignalCount < candidateThreshold) {+ decision = "blocked_conflicted";+ reasons.push("opposing signals cancel below the promotion threshold");+ } else if (effectiveSignalCount >= candidateThreshold) {+ decision = "ready_for_main_review";+ reasons.push("dominant signal count meets the promotion threshold");+ } else {+ decision = "needs_more_evidence";+ reasons.push("dominant signal count is below the promotion threshold");+ }+ if (suppressedCount > 0 && candidateRecords.length > 0) {+ reasons.push("some signals match a user-rejected retired preference");+ }++ const riskScore = scoreRisk(decision, minorityCount, signalCount, candidateThreshold);+ return Object.freeze({+ topic,+ decision,+ signal_count: signalCount,+ risk_band: riskBand(riskScore),+ risk_score: riskScore,+ reasons: Object.freeze(reasons),+ });+}++function isSuppressedByRejectedRetired(+ record: SignalRecord,+ suppressors: ReadonlyArray<RejectedRetiredSuppressor>,+): boolean {+ return suppressors.some((suppressor) => {+ if (!suppressor.scope) return true;+ return record.signal.scope === suppressor.scope;+ });+}++function countSign(records: ReadonlyArray<SignalRecord>, sign: BrainSignalSign): number {+ return records.filter((record) => record.signal.signal === sign).length;+}++function scoreRisk(+ decision: BrainIntentDecision,+ minorityCount: number,+ signalCount: number,+ candidateThreshold: number,+): number {+ if (decision === "suppressed_by_rejected_retired") return 6;+ if (decision === "blocked_conflicted") return 8;+ if (decision === "needs_more_evidence") return 5;+ if (minorityCount > 0) return 4;+ if (signalCount === candidateThreshold) return 2;+ return 1;+}++function riskBand(score: number): BrainIntentRiskBand {+ if (score >= 7) return "high";+ if (score >= 4) return "medium";+ return "low";+}++function isWithinWindow(createdAt: string, windowDays: number, now: Date): boolean {+ const createdMs = Date.parse(createdAt);+ if (!Number.isFinite(createdMs)) return false;+ const nowMs = now.getTime();+ const minTime = nowMs - windowDays * 24 * 60 * 60 * 1000;+ return createdMs >= minTime && createdMs <= nowMs;+}diff --git a/src/core/brain/monthly-review.ts b/src/core/brain/monthly-review.tsnew file mode 100644index 00000000..224e42b0--- /dev/null+++ b/src/core/brain/monthly-review.ts@@ -0,0 +1,128 @@+import { buildTimelineIndex } from "./temporal/build-index.ts";+import { collectTransitions } from "./temporal/period-common.ts";+import type { TemporalEvent } from "./temporal/types.ts";+import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND } from "./types.ts";++export interface MonthlyReviewWindow {+ readonly since: string;+ readonly until: string;+}++export interface MonthlyReviewSummary {+ readonly events: number;+ readonly status_transitions: number;+ readonly retired: number;+ readonly contradictions: number;+ readonly neglected_areas: ReadonlyArray<string>;+}++export interface MonthlyReviewReport {+ readonly schema_version: 1;+ readonly generated_at: string;+ readonly month: string;+ readonly window: MonthlyReviewWindow;+ readonly summary: MonthlyReviewSummary;+}++export interface BuildMonthlyReviewOptions {+ /** Target month in `YYYY-MM` form. Defaults to current UTC month. */+ readonly month?: string;+ readonly now?: Date;+ /** Optional area labels expected to show activity in the month. */+ readonly expectedAreas?: ReadonlyArray<string>;+}++const MONTH_RE = /^\d{4}-\d{2}$/;++export function buildMonthlyReview(+ vault: string,+ options: BuildMonthlyReviewOptions = {},+): MonthlyReviewReport {+ const now = options.now ?? new Date();+ const month = normalizeMonthlyReviewMonth(+ options.month ?? now.toISOString().slice(0, 7),+ );+ const window = monthWindow(month);+ const index = buildTimelineIndex(vault, window);+ const transitions = collectTransitions(index.events);+ const retired = transitions.filter(+ (transition) => transition.kind === "retirement",+ ).length;+ const contradictions = countContradictions(index.events);++ return Object.freeze({+ schema_version: 1 as const,+ generated_at: now.toISOString(),+ month,+ window,+ summary: Object.freeze({+ events: index.events.length,+ status_transitions: transitions.length,+ retired,+ contradictions,+ neglected_areas: Object.freeze(+ neglectedAreas(index.events, options.expectedAreas ?? []),+ ),+ }),+ });+}++export function normalizeMonthlyReviewMonth(month: string): string {+ const normalized = month.trim();+ if (!MONTH_RE.test(normalized)) {+ throw new Error(+ `buildMonthlyReview: month must be YYYY-MM; got ${JSON.stringify(month)}`,+ );+ }+ const monthNumber = Number(normalized.slice(5, 7));+ if (monthNumber < 1 || monthNumber > 12) {+ throw new Error(+ `buildMonthlyReview: invalid month ${JSON.stringify(month)}`,+ );+ }+ return normalized;+}++function monthWindow(month: string): MonthlyReviewWindow {+ const start = Date.parse(`${month}-01T00:00:00Z`);+ if (!Number.isFinite(start)) {+ throw new Error(+ `buildMonthlyReview: invalid month ${JSON.stringify(month)}`,+ );+ }+ const startDate = new Date(start);+ const endDate = new Date(+ Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth() + 1, 1),+ );+ return Object.freeze({+ since: `${month}-01T00:00:00Z`,+ until: endDate.toISOString().replace(".000Z", "Z"),+ });+}++function countContradictions(events: ReadonlyArray<TemporalEvent>): number {+ let count = 0;+ for (const event of events) {+ if (event.kind === BRAIN_LOG_EVENT_KIND.signalSuppressed) count += 1;+ if (+ event.kind === BRAIN_LOG_EVENT_KIND.applyEvidence &&+ event.result === BRAIN_APPLY_RESULT.violated+ ) {+ count += 1;+ }+ }+ return count;+}++function neglectedAreas(+ events: ReadonlyArray<TemporalEvent>,+ expectedAreas: ReadonlyArray<string>,+): string[] {+ if (expectedAreas.length === 0) return [];+ const lowerText = events+ .map((event) => JSON.stringify(event).toLowerCase())+ .join("\n");+ return expectedAreas+ .filter((area) => !lowerText.includes(area.toLowerCase()))+ .toSorted();+}diff --git a/src/core/brain/retention.ts b/src/core/brain/retention.tsnew file mode 100644index 00000000..0b40dc12--- /dev/null+++ b/src/core/brain/retention.ts@@ -0,0 +1,188 @@+import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { brainDirs, vaultRelative } from "./paths.ts";+import { parseRetired } from "./preference.ts";+import { parseSignal } from "./signal.ts";+import type { BrainRetired, BrainSignal } from "./types.ts";++export type RetentionAction = "keep" | "improve" | "park" | "prune";+export type RetentionArtifactType = "retired_preference" | "processed_signal";++export interface RetentionRecommendation {+ readonly id: string;+ readonly artifact_type: RetentionArtifactType;+ readonly action: RetentionAction;+ readonly reason: string;+ readonly path: string;+}++export interface RetentionSummary {+ readonly keep: number;+ readonly improve: number;+ readonly park: number;+ readonly prune: number;+}++export interface RetentionReviewReport {+ readonly schema_version: 1;+ readonly generated_at: string;+ readonly summary: RetentionSummary;+ readonly recommendations: ReadonlyArray<RetentionRecommendation>;+}++export interface BuildRetentionReviewOptions {+ readonly now?: Date;+}++const OLD_PROCESSED_SIGNAL_DAYS = 30;+const PARK_RETIRED_AFTER_DAYS = 90;++export function buildRetentionReview(+ vault: string,+ options: BuildRetentionReviewOptions = {},+): RetentionReviewReport {+ const now = options.now ?? new Date();+ const recommendations = [+ ...collectRetiredPreferences(vault, now),+ ...collectProcessedSignals(vault, now),+ ].toSorted((left, right) => left.id.localeCompare(right.id));++ return Object.freeze({+ schema_version: 1 as const,+ generated_at: now.toISOString(),+ summary: Object.freeze(summarize(recommendations)),+ recommendations: Object.freeze(recommendations),+ });+}++function collectRetiredPreferences(+ vault: string,+ now: Date,+): RetentionRecommendation[] {+ const retiredDir = brainDirs(vault).retired;+ if (!existsSync(retiredDir)) return [];+ const recommendations: RetentionRecommendation[] = [];+ for (const name of readdirSync(retiredDir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ const path = join(retiredDir, name);+ try {+ const retired = parseRetired(path);+ recommendations.push(recommendRetired(vault, path, retired, now));+ } catch {+ continue;+ }+ }+ return recommendations;+}++function collectProcessedSignals(+ vault: string,+ now: Date,+): RetentionRecommendation[] {+ const processedDir = brainDirs(vault).processed;+ if (!existsSync(processedDir)) return [];+ const recommendations: RetentionRecommendation[] = [];+ for (const name of readdirSync(processedDir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ const path = join(processedDir, name);+ try {+ const signal = parseSignal(path);+ recommendations.push(recommendProcessedSignal(vault, path, signal, now));+ } catch {+ continue;+ }+ }+ return recommendations;+}++function recommendRetired(+ vault: string,+ path: string,+ retired: BrainRetired,+ now: Date,+): RetentionRecommendation {+ const applied = retired.applied_count ?? 0;+ const violated = retired.violated_count ?? 0;+ const ageDays = daysSince(retired.retired_at, now);+ let action: RetentionAction;+ let reason: string;++ if (violated > applied && violated > 0) {+ action = "improve";+ reason =+ "retired rule has more violations than applications; review wording before reuse";+ } else if (applied > 0 || retired.last_evidence_at !== null) {+ action = "keep";+ reason = "retired rule has an evidence trail worth preserving for audit";+ } else if (ageDays >= PARK_RETIRED_AFTER_DAYS) {+ action = "park";+ reason =+ "old retired rule has no evidence trail; preserve inactive unless needed";+ } else {+ action = "improve";+ reason =+ "recent retired rule has no evidence trail; review whether it needs clarification";+ }++ return Object.freeze({+ id: retired.id,+ artifact_type: "retired_preference" as const,+ action,+ reason,+ path: vaultRelative(vault, path),+ });+}++function recommendProcessedSignal(+ vault: string,+ path: string,+ signal: BrainSignal,+ now: Date,+): RetentionRecommendation {+ const ageDays = daysSince(signal.created_at, now);+ const hasSource = (signal.source?.length ?? 0) > 0;+ let action: RetentionAction;+ let reason: string;++ if (!hasSource && ageDays >= OLD_PROCESSED_SIGNAL_DAYS) {+ action = "prune";+ reason =+ "old processed one-off signal has no source pointers; safe candidate for manual pruning";+ } else if (hasSource) {+ action = "keep";+ reason =+ "processed signal carries source pointers that preserve audit context";+ } else {+ action = "park";+ reason =+ "processed signal is recent; leave it inactive until the next retention pass";+ }++ return Object.freeze({+ id: signal.id,+ artifact_type: "processed_signal" as const,+ action,+ reason,+ path: vaultRelative(vault, path),+ });+}++function summarize(+ recommendations: ReadonlyArray<RetentionRecommendation>,+): RetentionSummary {+ const summary = { keep: 0, improve: 0, park: 0, prune: 0 };+ for (const recommendation of recommendations) {+ summary[recommendation.action] += 1;+ }+ return summary;+}++function daysSince(iso: string, now: Date): number {+ const timestamp = Date.parse(iso);+ if (!Number.isFinite(timestamp)) return 0;+ return Math.max(+ 0,+ Math.floor((now.getTime() - timestamp) / (24 * 60 * 60 * 1000)),+ );+}diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.tsindex 535a15f4..f792c5c1 100644--- a/src/core/brain/review-candidates.ts+++ b/src/core/brain/review-candidates.ts@@ -14,6 +14,7 @@*/import { dream } from "./dream.ts";+import type { BrainIntentReviewEntry } from "./intent-review.ts";import { BRAIN_RETIRED_REASON, type BrainRetiredReason } from "./types.ts";export interface ReviewCandidatesReport {@@ -55,6 +56,8 @@ export interface ReviewCandidatesReport {readonly threshold: number;readonly attempted_reason: BrainRetiredReason;}>;+ /** Intent-review decisions for active signal clusters before main dream planning. */+ readonly intent_reviews: ReadonlyArray<BrainIntentReviewEntry>;}export interface BuildReviewCandidatesOptions {@@ -105,5 +108,8 @@ export function buildReviewCandidates(}),),),+ intent_reviews: Object.freeze(+ summary.intent_reviews.map((review) => Object.freeze({ ...review })),+ ),} satisfies ReviewCandidatesReport);}diff --git a/src/core/brain/schema-contracts.ts b/src/core/brain/schema-contracts.tsnew file mode 100644index 00000000..90ce4991--- /dev/null+++ b/src/core/brain/schema-contracts.ts@@ -0,0 +1,311 @@+export type SchemaType = "object" | "array" | "string" | "integer" | "number" | "boolean";++export interface SchemaNode {+ readonly type?: SchemaType;+ readonly title?: string;+ readonly description?: string;+ readonly format?: "date-time";+ readonly minimum?: number;+ readonly maximum?: number;+ readonly enum?: ReadonlyArray<unknown>;+ readonly required?: ReadonlyArray<string>;+ readonly properties?: Readonly<Record<string, SchemaNode>>;+ readonly items?: SchemaNode;+ readonly additionalProperties?: boolean;+}++export interface BrainSchemaContract extends SchemaNode {+ readonly id: string;+ readonly title: string;+ readonly schema_version: 1;+}++export interface SchemaValidationResult {+ readonly ok: boolean;+ readonly errors: ReadonlyArray<string>;+}++const INTENT_REVIEW_SCHEMA: BrainSchemaContract = {+ id: "brain.intent_review.v1",+ title: "Brain Intent Review v1",+ schema_version: 1,+ type: "object",+ required: ["schema_version", "generated_at", "reviews"],+ additionalProperties: false,+ properties: {+ schema_version: { type: "integer", enum: [1] },+ generated_at: { type: "string", format: "date-time" },+ reviews: {+ type: "array",+ items: {+ type: "object",+ required: ["topic", "decision", "signal_count", "risk_band", "risk_score", "reasons"],+ additionalProperties: false,+ properties: {+ topic: { type: "string" },+ decision: {+ type: "string",+ enum: [+ "ready_for_main_review",+ "needs_more_evidence",+ "blocked_conflicted",+ "suppressed_by_rejected_retired",+ ],+ },+ signal_count: { type: "integer" },+ risk_band: { type: "string", enum: ["low", "medium", "high"] },+ risk_score: { type: "integer" },+ reasons: { type: "array", items: { type: "string" } },+ },+ },+ },+ },+};++const RETENTION_REVIEW_SCHEMA: BrainSchemaContract = {+ id: "brain.retention_review.v1",+ title: "Brain Retention Review v1",+ schema_version: 1,+ type: "object",+ required: ["schema_version", "generated_at", "summary", "recommendations"],+ additionalProperties: false,+ properties: {+ schema_version: { type: "integer", enum: [1] },+ generated_at: { type: "string", format: "date-time" },+ summary: {+ type: "object",+ required: ["keep", "improve", "park", "prune"],+ additionalProperties: false,+ properties: {+ keep: { type: "integer", minimum: 0 },+ improve: { type: "integer", minimum: 0 },+ park: { type: "integer", minimum: 0 },+ prune: { type: "integer", minimum: 0 },+ },+ },+ recommendations: {+ type: "array",+ items: {+ type: "object",+ required: ["id", "artifact_type", "action", "reason", "path"],+ additionalProperties: false,+ properties: {+ id: { type: "string" },+ artifact_type: {+ type: "string",+ enum: ["retired_preference", "processed_signal"],+ },+ action: {+ type: "string",+ enum: ["keep", "improve", "park", "prune"],+ },+ reason: { type: "string" },+ path: { type: "string" },+ },+ },+ },+ },+};++const MONTHLY_REVIEW_SCHEMA: BrainSchemaContract = {+ id: "brain.monthly_review.v1",+ title: "Brain Monthly Review v1",+ schema_version: 1,+ type: "object",+ required: ["schema_version", "generated_at", "month", "window", "summary"],+ additionalProperties: false,+ properties: {+ schema_version: { type: "integer", enum: [1] },+ generated_at: { type: "string", format: "date-time" },+ month: { type: "string" },+ window: {+ type: "object",+ required: ["since", "until"],+ additionalProperties: false,+ properties: {+ since: { type: "string" },+ until: { type: "string" },+ },+ },+ summary: {+ type: "object",+ required: ["events", "status_transitions", "retired", "contradictions", "neglected_areas"],+ additionalProperties: false,+ properties: {+ events: { type: "integer" },+ status_transitions: { type: "integer" },+ retired: { type: "integer" },+ contradictions: { type: "integer" },+ neglected_areas: { type: "array", items: { type: "string" } },+ },+ },+ },+};++const COMPLEXITY_REPORT_SCHEMA: BrainSchemaContract = {+ id: "brain.complexity_report.v1",+ title: "Brain Complexity Report v1",+ schema_version: 1,+ type: "object",+ required: [+ "schema_version",+ "generated_at",+ "score",+ "ratio",+ "thinking_activity",+ "structural_complexity",+ "warning",+ "factors",+ ],+ additionalProperties: false,+ properties: {+ schema_version: { type: "integer", enum: [1] },+ generated_at: { type: "string", format: "date-time" },+ score: { type: "integer", minimum: 0 },+ ratio: { type: "number", minimum: 0 },+ thinking_activity: { type: "integer", minimum: 0 },+ structural_complexity: { type: "integer", minimum: 0 },+ warning: { type: "boolean" },+ factors: {+ type: "array",+ items: {+ type: "object",+ required: ["name", "value", "weight"],+ additionalProperties: false,+ properties: {+ name: { type: "string" },+ value: { type: "integer", minimum: 0 },+ weight: { type: "integer", minimum: 0 },+ },+ },+ },+ },+};++export const BRAIN_SCHEMA_CONTRACTS: ReadonlyArray<BrainSchemaContract> = Object.freeze([+ INTENT_REVIEW_SCHEMA,+ RETENTION_REVIEW_SCHEMA,+ MONTHLY_REVIEW_SCHEMA,+ COMPLEXITY_REPORT_SCHEMA,+]);++export function getBrainSchemaContract(id: string): BrainSchemaContract | undefined {+ return BRAIN_SCHEMA_CONTRACTS.find((schema) => schema.id === id);+}++export function validateSchemaContract(schema: SchemaNode, value: unknown): SchemaValidationResult {+ const errors: string[] = [];+ validateNode(schema, value, "", errors);+ return Object.freeze({+ ok: errors.length === 0,+ errors: Object.freeze(errors),+ });+}++function validateNode(schema: SchemaNode, value: unknown, path: string, errors: string[]): void {+ if (schema.type !== undefined && !matchesType(schema.type, value)) {+ errors.push(`${formatPath(path)} must be ${schema.type}`);+ return;+ }++ if (schema.enum !== undefined && !schema.enum.some((allowed) => Object.is(allowed, value))) {+ errors.push(+ `${formatPath(path)} must be one of ${schema.enum.map(formatEnumValue).join(", ")}`,+ );+ return;+ }++ validateScalarConstraints(schema, value, path, errors);++ if (schema.type === "object") {+ validateObject(schema, value, path, errors);+ return;+ }++ if (schema.type === "array") {+ validateArray(schema, value, path, errors);+ }+}++function validateScalarConstraints(+ schema: SchemaNode,+ value: unknown,+ path: string,+ errors: string[],+): void {+ if (schema.format === "date-time" && typeof value === "string") {+ const parsed = Date.parse(value);+ if (!Number.isFinite(parsed)) {+ errors.push(`${formatPath(path)} must be date-time`);+ }+ }+ if (typeof value !== "number") return;+ if (schema.minimum !== undefined && value < schema.minimum) {+ errors.push(`${formatPath(path)} must be >= ${schema.minimum}`);+ }+ if (schema.maximum !== undefined && value > schema.maximum) {+ errors.push(`${formatPath(path)} must be <= ${schema.maximum}`);+ }+}++function validateObject(schema: SchemaNode, value: unknown, path: string, errors: string[]): void {+ if (!isRecord(value)) return;+ const properties = schema.properties ?? {};+ for (const requiredKey of schema.required ?? []) {+ if (!(requiredKey in value)) {+ errors.push(`${formatPath(appendPath(path, requiredKey))} is required`);+ }+ }+ for (const [key, childValue] of Object.entries(value)) {+ const childSchema = properties[key];+ if (childSchema === undefined) {+ if (schema.additionalProperties === false) {+ errors.push(`${formatPath(appendPath(path, key))} is not allowed`);+ }+ continue;+ }+ validateNode(childSchema, childValue, appendPath(path, key), errors);+ }+}++function validateArray(schema: SchemaNode, value: unknown, path: string, errors: string[]): void {+ if (!Array.isArray(value)) return;+ const itemSchema = schema.items;+ if (itemSchema === undefined) return;+ for (let index = 0; index < value.length; index++) {+ validateNode(itemSchema, value[index], `${path}[${index}]`, errors);+ }+}++function matchesType(type: SchemaType, value: unknown): boolean {+ switch (type) {+ case "object":+ return isRecord(value);+ case "array":+ return Array.isArray(value);+ case "string":+ return typeof value === "string";+ case "integer":+ return typeof value === "number" && Number.isInteger(value);+ case "number":+ return typeof value === "number" && Number.isFinite(value);+ case "boolean":+ return typeof value === "boolean";+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function appendPath(path: string, key: string): string {+ return path.length === 0 ? key : `${path}.${key}`;+}++function formatPath(path: string): string {+ return path.length === 0 ? "<root>" : path;+}++function formatEnumValue(value: unknown): string {+ return JSON.stringify(value);+}diff --git a/src/core/discipline/activity-git.ts b/src/core/discipline/activity-git.tsindex 706d3546..ba6c3b50 100644--- a/src/core/discipline/activity-git.ts+++ b/src/core/discipline/activity-git.ts@@ -10,11 +10,15 @@ export interface ActivityWindow {export interface GitActivity {readonly commits: number;readonly filesChanged: number;+ readonly pathsChanged?: ReadonlyArray<string>;readonly insertions: number;readonly deletions: number;}-export function gitActivity(path: string, win: ActivityWindow): GitActivity | null {+export function gitActivity(+ path: string,+ win: ActivityWindow,+): GitActivity | null {if (!existsSync(join(path, ".git"))) return null;const since = win.startUtc.toISOString();const until = win.endUtc.toISOString();@@ -60,5 +64,11 @@ export function gitActivity(path: string, win: ActivityWindow): GitActivity | nuseenFiles.add(m[3]!);}- return { commits, filesChanged: seenFiles.size, insertions, deletions };+ return {+ commits,+ filesChanged: seenFiles.size,+ pathsChanged: [...seenFiles].toSorted(),+ insertions,+ deletions,+ };}diff --git a/src/core/discipline/activity-mtime.ts b/src/core/discipline/activity-mtime.tsindex e854ee47..1eb34dbe 100644--- a/src/core/discipline/activity-mtime.ts+++ b/src/core/discipline/activity-mtime.ts@@ -1,5 +1,5 @@import { lstatSync, readdirSync, statSync } from "node:fs";-import { join } from "node:path";+import { join, relative } from "node:path";import type { ActivityWindow } from "./activity-git.ts";const EXCLUDE_DIRS: ReadonlySet<string> = new Set([@@ -19,12 +19,17 @@ const EXCLUDE_DIRS: ReadonlySet<string> = new Set([export interface MtimeActivity {readonly modifiedFiles: number;+ readonly modifiedPaths: ReadonlyArray<string>;}-export function mtimeActivity(root: string, win: ActivityWindow): MtimeActivity {+export function mtimeActivity(+ root: string,+ win: ActivityWindow,+): MtimeActivity {const startMs = win.startUtc.getTime();const endMs = win.endUtc.getTime();let count = 0;+ const modifiedPaths: string[] = [];function walk(dir: string): void {let entries: string[];@@ -62,10 +67,13 @@ export function mtimeActivity(root: string, win: ActivityWindow): MtimeActivitycontinue;}const m = st.mtimeMs;- if (m >= startMs && m < endMs) count += 1;+ if (m >= startMs && m < endMs) {+ count += 1;+ modifiedPaths.push(relative(root, p).replaceAll("\\", "/"));+ }}}walk(root);- return { modifiedFiles: count };+ return { modifiedFiles: count, modifiedPaths: modifiedPaths.toSorted() };}diff --git a/src/core/discipline/complexity.ts b/src/core/discipline/complexity.tsnew file mode 100644index 00000000..86d81c07--- /dev/null+++ b/src/core/discipline/complexity.ts@@ -0,0 +1,211 @@+import { existsSync, readFileSync, statSync } from "node:fs";+import { basename, join } from "node:path";++export interface ComplexityFactor {+ readonly name: string;+ readonly value: number;+ readonly weight: number;+}++export interface ComplexityReport {+ readonly schema_version: 1;+ readonly generated_at: string;+ readonly score: number;+ readonly ratio: number;+ readonly thinking_activity: number;+ readonly structural_complexity: number;+ readonly warning: boolean;+ readonly factors: ReadonlyArray<ComplexityFactor>;+}++export interface BuildComplexityReportInput {+ readonly thinkingActivity: number;+ readonly structuralFilesChanged: number;+ readonly maxFolderDepth?: number;+ readonly templateChanges?: number;+ readonly configChanges?: number;+ readonly tagProliferation?: number;+}++export interface BuildComplexityReportOptions {+ readonly now?: Date;+}++export interface ComplexityChangedPath {+ readonly root: string;+ readonly relativePath: string;+}++export interface ComplexityPathFactors {+ readonly maxFolderDepth: number;+ readonly templateChanges: number;+ readonly configChanges: number;+ readonly tagProliferation: number;+}++const WARNING_RATIO = 4;+const WARNING_SCORE = 8;++export function buildComplexityReport(+ input: BuildComplexityReportInput,+ options: BuildComplexityReportOptions = {},+): ComplexityReport {+ const now = options.now ?? new Date();+ const factors: ComplexityFactor[] = [+ {+ name: "structural_files_changed",+ value: input.structuralFilesChanged,+ weight: 1,+ },+ { name: "max_folder_depth", value: input.maxFolderDepth ?? 0, weight: 1 },+ { name: "template_changes", value: input.templateChanges ?? 0, weight: 2 },+ { name: "config_changes", value: input.configChanges ?? 0, weight: 2 },+ {+ name: "tag_proliferation",+ value: input.tagProliferation ?? 0,+ weight: 1,+ },+ ].filter((factor) => factor.value > 0);+ const structuralComplexity = factors.reduce(+ (total, factor) => total + factor.value * factor.weight,+ 0,+ );+ const thinkingActivity = Math.max(0, input.thinkingActivity);+ const ratio = structuralComplexity / Math.max(1, thinkingActivity);+ const warning =+ structuralComplexity >= WARNING_SCORE && ratio >= WARNING_RATIO;++ return Object.freeze({+ schema_version: 1 as const,+ generated_at: now.toISOString(),+ score: structuralComplexity,+ ratio,+ thinking_activity: thinkingActivity,+ structural_complexity: structuralComplexity,+ warning,+ factors: Object.freeze(factors),+ });+}++export function complexityPathFactors(+ changedPaths: ReadonlyArray<ComplexityChangedPath>,+): ComplexityPathFactors {+ let maxFolderDepth = 0;+ let templateChanges = 0;+ let configChanges = 0;+ const tags = new Set<string>();++ for (const changedPath of changedPaths) {+ const relativePath = normaliseRelativePath(changedPath.relativePath);+ maxFolderDepth = Math.max(maxFolderDepth, folderDepth(relativePath));+ if (isTemplatePath(relativePath)) templateChanges += 1;+ if (isConfigPath(relativePath)) configChanges += 1;+ for (const tag of tagsInChangedMarkdown(changedPath.root, relativePath)) {+ tags.add(tag);+ }+ }++ return {+ maxFolderDepth,+ templateChanges,+ configChanges,+ tagProliferation: tags.size,+ };+}++function normaliseRelativePath(relativePath: string): string {+ return relativePath.replaceAll("\\", "/");+}++function folderDepth(relativePath: string): number {+ const parts = relativePath.split("/").filter(Boolean);+ return Math.max(0, parts.length - 1);+}++function isTemplatePath(relativePath: string): boolean {+ return relativePath+ .split("/")+ .some((segment) => segment.toLowerCase().includes("template"));+}++function isConfigPath(relativePath: string): boolean {+ const lowerPath = relativePath.toLowerCase();+ const fileName = basename(lowerPath);+ return (+ lowerPath.startsWith(".") ||+ lowerPath.includes("/.") ||+ lowerPath.includes(".obsidian/") ||+ fileName === "_brain.yaml" ||+ fileName === "package.json" ||+ fileName === "pyproject.toml" ||+ fileName.endsWith(".config.js") ||+ fileName.endsWith(".config.ts") ||+ fileName.endsWith(".config.json") ||+ fileName.endsWith(".toml") ||+ fileName.endsWith(".yaml") ||+ fileName.endsWith(".yml")+ );+}++function tagsInChangedMarkdown(root: string, relativePath: string): string[] {+ if (!relativePath.toLowerCase().endsWith(".md")) return [];+ const absolutePath = join(root, relativePath);+ if (!existsSync(absolutePath)) return [];+ try {+ if (!statSync(absolutePath).isFile()) return [];+ return extractTags(readFileSync(absolutePath, "utf8"));+ } catch {+ return [];+ }+}++function extractTags(text: string): string[] {+ const tags = new Set<string>();+ const lines = text.split(/\r?\n/);+ collectFrontmatterTags(lines, tags);+ const inlineTag = /(^|\s)#([A-Za-z0-9][A-Za-z0-9_/-]*)/g;+ for (const match of text.matchAll(inlineTag)) {+ tags.add(match[2]!.toLowerCase());+ }+ return [...tags].toSorted();+}++function collectFrontmatterTags(lines: string[], tags: Set<string>): void {+ if (lines[0] !== "---") return;+ for (let index = 1; index < lines.length; index += 1) {+ const line = lines[index]!;+ if (line === "---") return;+ const inline = line.match(/^tags:\s*\[(.*)]\s*$/i);+ if (inline) {+ for (const tag of inline[1]!.split(",")) addTag(tags, tag);+ continue;+ }+ if (/^tags:\s*$/i.test(line)) {+ collectFrontmatterTagList(lines, index + 1, tags);+ return;+ }+ const scalar = line.match(/^tags:\s*(\S.*)$/i);+ if (scalar) addTag(tags, scalar[1]!);+ }+}++function collectFrontmatterTagList(+ lines: string[],+ startIndex: number,+ tags: Set<string>,+): void {+ for (let index = startIndex; index < lines.length; index += 1) {+ const line = lines[index]!;+ if (line === "---" || /^\S/.test(line)) return;+ const item = line.match(/^\s*-\s*(\S.*)$/);+ if (item) addTag(tags, item[1]!);+ }+}++function addTag(tags: Set<string>, raw: string): void {+ const tag = raw+ .trim()+ .replace(/^#/, "")+ .replace(/^['"]|['"]$/g, "");+ if (tag.length > 0) tags.add(tag.toLowerCase());+}diff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.tsindex c956a664..f35be231 100644--- a/src/core/discipline/decision.ts+++ b/src/core/discipline/decision.ts@@ -2,6 +2,7 @@ import type { BrainEventCounts } from "./log-counts.ts";import type { GitActivity } from "./activity-git.ts";import type { VaultDelta } from "./vault-delta.ts";import type { TranscriptActivity } from "./transcripts/types.ts";+import type { ComplexityReport } from "./complexity.ts";export interface RepoActivityRow {readonly path: string;@@ -16,6 +17,8 @@ export interface ActivitySummary {readonly repo: ReadonlyArray<RepoActivityRow>;readonly nonRepo: ReadonlyArray<NonRepoActivityRow>;readonly vaultDelta: VaultDelta;+ /** Productivity-trap detector: structure churn compared to thinking output. */+ readonly complexity?: ComplexityReport;/*** Per-runtime session-transcript activity (v0.10.11). Optional so* the type is back-compat with callers / tests that have not been@@ -51,10 +54,11 @@ export function decideStatus(for (const u of events.unknownAgents) {tasteEvents += u.counts.feedback + u.counts.apply_evidence;}- if (tasteEvents > 0) return "ok";+ const complexityWarning = activity.complexity?.warning === true;+ if (tasteEvents > 0 && !complexityWarning) return "ok";const repoCommits = activity.repo.reduce((a, r) => a + r.git.commits, 0);const mtimeFiles = activity.nonRepo.reduce((a, r) => a + r.modifiedFiles, 0);const vaultActive = activity.vaultDelta.total > 0;- const activitySignal = repoCommits > 0 || mtimeFiles >= 3 || vaultActive;+ const activitySignal = repoCommits > 0 || mtimeFiles >= 3 || vaultActive || complexityWarning;return activitySignal ? "alert" : "info";}diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.tsindex a24fe938..abf90e24 100644--- a/src/core/discipline/render.ts+++ b/src/core/discipline/render.ts@@ -48,6 +48,12 @@ export function renderReport(r: RenderInput): string {lines.push(`\\- vault β ${vd.newSignals} new signals, ${vd.newPreferences} new preferences, ${vd.newRetired} new retired`,);+ const complexity = r.activity.complexity;+ if (complexity !== undefined) {+ lines.push(+ `\\- complexity β score ${complexity.score}, thinking ${complexity.thinking_activity}, ratio ${formatRatio(complexity.ratio)}`,+ );+ }const transcripts = r.activity.transcripts;if (transcripts && transcripts.byRuntime.length > 0) {const parts = transcripts.byRuntime@@ -78,6 +84,16 @@ export function renderReport(r: RenderInput): string {"_Sub\\-reason: transcript\\-confirmed β runtime session files dated to this window\\._",);}+ if (complexity?.warning === true) {+ lines.push(+ "_Sub\\-reason: productivity\\-trap β vault structure grew faster than recorded thinking\\._",+ );+ }}return lines.join("\n");}++function formatRatio(value: number): string {+ if (Number.isInteger(value)) return String(value);+ return value.toFixed(2);+}diff --git a/src/core/discipline/report.ts b/src/core/discipline/report.tsindex cf2e0835..5d908b29 100644--- a/src/core/discipline/report.ts+++ b/src/core/discipline/report.ts@@ -6,6 +6,11 @@ import { countBrainEvents, type BrainEventCounts } from "./log-counts.ts";import { gitActivity } from "./activity-git.ts";import { mtimeActivity } from "./activity-mtime.ts";import { vaultDelta } from "./vault-delta.ts";+import {+ buildComplexityReport,+ complexityPathFactors,+ type ComplexityChangedPath,+} from "./complexity.ts";import {decideStatus,type ActivitySummary,@@ -37,12 +42,24 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRe// false` β so the Hermes cron stays silent instead of posting empty// messages on every tick.if (!existsSync(brainConfigPath(opts.vault))) {- return { status: "disabled", text: "", localDate: null, events: null, activity: null };+ return {+ status: "disabled",+ text: "",+ localDate: null,+ events: null,+ activity: null,+ };}const cfg = loadBrainConfig(opts.vault);const d = cfg.discipline_report;if (!d || !d.enabled) {- return { status: "disabled", text: "", localDate: null, events: null, activity: null };+ return {+ status: "disabled",+ text: "",+ localDate: null,+ events: null,+ activity: null,+ };}const now = opts.now ?? new Date();const win = yesterdayWindow(now, d.timezone);@@ -50,13 +67,20 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineReconst repo: RepoActivityRow[] = [];const nonRepo: NonRepoActivityRow[] = [];+ const changedPaths: ComplexityChangedPath[] = [];for (const p of d.watched_paths) {const g = gitActivity(p, win);if (g !== null) {repo.push({ path: p, git: g });+ for (const relativePath of g.pathsChanged ?? []) {+ changedPaths.push({ root: p, relativePath });+ }} else if (existsSync(p)) {const m = mtimeActivity(p, win);nonRepo.push({ path: p, modifiedFiles: m.modifiedFiles });+ for (const relativePath of m.modifiedPaths) {+ changedPaths.push({ root: p, relativePath });+ }}}const vd = vaultDelta(opts.vault, win);@@ -74,7 +98,26 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRetranscripts = { byRuntime: [], totalFiles: 0 };}- const activity: ActivitySummary = { repo, nonRepo, vaultDelta: vd, transcripts };+ const structuralFilesChanged =+ repo.reduce((total, row) => total + row.git.filesChanged, 0) ++ nonRepo.reduce((total, row) => total + row.modifiedFiles, 0);+ const pathFactors = complexityPathFactors(changedPaths);+ const complexity = buildComplexityReport(+ {+ thinkingActivity: countTasteEvents(events),+ structuralFilesChanged,+ ...pathFactors,+ },+ { now },+ );++ const activity: ActivitySummary = {+ repo,+ nonRepo,+ vaultDelta: vd,+ transcripts,+ complexity,+ };const status = decideStatus(events, activity);const text = renderReport({localDate: win.localDate,@@ -85,3 +128,14 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRe});return { status, text, localDate: win.localDate, events, activity };}++function countTasteEvents(events: BrainEventCounts): number {+ let total = 0;+ for (const counts of Object.values(events.byAgent)) {+ total += counts.feedback + counts.apply_evidence;+ }+ for (const unknown of events.unknownAgents) {+ total += unknown.counts.feedback + unknown.counts.apply_evidence;+ }+ return total;+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex a30748d6..fb74a05d 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -67,6 +67,9 @@ import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts"import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";import { dream } from "../core/brain/dream.ts";+import { buildIntentReview } from "../core/brain/intent-review.ts";+import { buildRetentionReview } from "../core/brain/retention.ts";+import { buildMonthlyReview, normalizeMonthlyReviewMonth } from "../core/brain/monthly-review.ts";import { buildReviewCandidates } from "../core/brain/review-candidates.ts";import { runDoctor } from "../core/brain/doctor.ts";import { buildOperatorSummary } from "../core/brain/trust/operator-summary.ts";@@ -314,6 +317,72 @@ async function toolBrainDream(// ----- brain_review_candidates --------------------------------------------+async function toolBrainIntentReview(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const nowDate = coerceIsoDate(args, "now");+ const report = buildIntentReview(ctx.vault, nowDate ? { now: nowDate } : {});+ return {+ schema_version: report.schema_version,+ generated_at: report.generated_at,+ reviews: report.reviews.map((review) => ({+ topic: review.topic,+ decision: review.decision,+ signal_count: review.signal_count,+ risk_band: review.risk_band,+ risk_score: review.risk_score,+ reasons: [...review.reasons],+ })),+ };+}++async function toolBrainRetention(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const nowDate = coerceIsoDate(args, "now");+ const report = buildRetentionReview(ctx.vault, nowDate ? { now: nowDate } : {});+ return {+ schema_version: report.schema_version,+ generated_at: report.generated_at,+ summary: report.summary,+ recommendations: report.recommendations.map((recommendation) => ({+ id: recommendation.id,+ artifact_type: recommendation.artifact_type,+ action: recommendation.action,+ reason: recommendation.reason,+ path: recommendation.path,+ })),+ };+}++async function toolBrainMonthlyReview(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const monthRaw = args["month"];+ let month: string | undefined;+ if (monthRaw !== undefined && monthRaw !== null) {+ if (typeof monthRaw !== "string") {+ throw new MCPError(INVALID_PARAMS, "brain_monthly_review: month must be YYYY-MM");+ }+ try {+ month = normalizeMonthlyReviewMonth(monthRaw);+ } catch {+ throw new MCPError(INVALID_PARAMS, "brain_monthly_review: month must be YYYY-MM");+ }+ }+ const report = buildMonthlyReview(ctx.vault, month ? { month } : {});+ return {+ schema_version: report.schema_version,+ generated_at: report.generated_at,+ month: report.month,+ window: report.window,+ summary: report.summary,+ };+}+async function toolBrainReviewCandidates(ctx: ServerContext,args: Record<string, unknown>,@@ -346,6 +415,14 @@ async function toolBrainReviewCandidates(threshold: g.threshold,attempted_reason: g.attempted_reason,})),+ intent_reviews: report.intent_reviews.map((review) => ({+ topic: review.topic,+ decision: review.decision,+ signal_count: review.signal_count,+ risk_band: review.risk_band,+ risk_score: review.risk_score,+ reasons: [...review.reasons],+ })),};}@@ -1517,8 +1594,13 @@ async function toolBrainContextPack(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const maxRaw = args["max_tokens"];- const maxTokens = typeof maxRaw === "number" ? maxRaw : Number.parseInt(String(maxRaw ?? ""), 10);- if (!Number.isFinite(maxTokens) || maxTokens <= 0) {+ const maxTokens =+ typeof maxRaw === "number"+ ? maxRaw+ : typeof maxRaw === "string" && /^[0-9]+$/.test(maxRaw.trim())+ ? Number.parseInt(maxRaw.trim(), 10)+ : Number.NaN;+ if (!Number.isInteger(maxTokens) || maxTokens <= 0) {throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");}const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;@@ -1622,10 +1704,60 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainDream,},+ {+ name: "brain_intent_review",+ description:+ "Read-only pre-dream intent review over active signal clusters. Returns each topic's decision, signal count, risk band, risk score, and reasons without mutating files.",+ inputSchema: {+ type: "object",+ properties: {+ now: {+ type: "string",+ description:+ "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainIntentReview,+ },+ {+ name: "brain_retention",+ description:+ "Recommendation-only lifecycle review over retired preferences and processed signals. Returns keep/improve/park/prune candidates and never deletes or moves artifacts.",+ inputSchema: {+ type: "object",+ properties: {+ now: {+ type: "string",+ description:+ "Optional ISO-8601 timestamp used as the wall clock for the review (testing / replay).",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainRetention,+ },+ {+ name: "brain_monthly_review",+ description:+ "Read-only monthly synthesis over Brain timeline activity: event count, status transitions, retirements, contradictions, and neglected areas.",+ inputSchema: {+ type: "object",+ properties: {+ month: {+ type: "string",+ description: "Optional target month in YYYY-MM form. Defaults to the current UTC month.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainMonthlyReview,+ },{name: "brain_review_candidates",description:- "Read-only preview of what the next `brain_dream` invocation would do. Returns `would_create`, `would_promote`, `would_retire`, `would_supersede`, `clusters_below_threshold`, and `gated_retires` without mutating any files. Useful for agents that want to be deliberate before triggering the learning pass, or for operators inspecting the dream pass intent.",+ "Read-only preview of what the next `brain_dream` invocation would do. Returns `would_create`, `would_promote`, `would_retire`, `would_supersede`, `clusters_below_threshold`, `gated_retires`, and `intent_reviews` without mutating any files. Useful for agents that want to be deliberate before triggering the learning pass, or for operators inspecting the dream pass intent.",inputSchema: {type: "object",properties: {diff --git a/tests/cli/brain-intent-review.test.ts b/tests/cli/brain-intent-review.test.tsnew file mode 100644index 00000000..0b0174d0--- /dev/null+++ b/tests/cli/brain-intent-review.test.ts@@ -0,0 +1,65 @@+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 { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { runCli } from "../helpers/run-cli.ts";++let root: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-intent-review-cli-"));+ vault = join(root, "vault");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+ configPath = join(root, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+ for (let index = 0; index < 3; index++) {+ writeSignal(vault, {+ topic: "ready-topic",+ signal: "positive",+ agent: "test",+ principle: "ready topic principle",+ created_at: `2026-05-2${index + 1}T10:00:00Z`,+ date: `2026-05-2${index + 1}`,+ slug: `ready-topic-${index}`,+ });+ }+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe("o2b brain intent-review", () => {+ test("prints JSON intent review report", async () => {+ const result = await runCli(["brain", "intent-review", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(result.returncode).toBe(0);+ const payload = JSON.parse(result.stdout) as {+ reviews: Array<{ topic: string; decision: string }>;+ };+ expect(payload.reviews).toEqual([+ expect.objectContaining({+ topic: "ready-topic",+ decision: "ready_for_main_review",+ }),+ ]);+ });++ test("rejects malformed --now", async () => {+ const result = await runCli(+ ["brain", "intent-review", "--now", "not-a-date"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ },+ );+ expect(result.returncode).toBe(1);+ expect(result.stderr).toContain("invalid --now");+ });+});diff --git a/tests/cli/brain-monthly.test.ts b/tests/cli/brain-monthly.test.tsnew file mode 100644index 00000000..b4af8299--- /dev/null+++ b/tests/cli/brain-monthly.test.ts@@ -0,0 +1,56 @@+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 { appendLogEvent } from "../../src/core/brain/log.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";+import { runCli } from "../helpers/run-cli.ts";++let root: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-monthly-cli-"));+ vault = join(root, "vault");+ mkdirSync(brainDirs(vault).log, { recursive: true });+ configPath = join(root, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+ appendLogEvent(vault, {+ timestamp: "2026-05-10T10:00:00Z",+ eventType: BRAIN_LOG_EVENT_KIND.feedback,+ body: { topic: "monthly", sign: "positive", agent: "test" },+ });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe("o2b brain monthly", () => {+ test("prints JSON monthly review", async () => {+ const result = await runCli(+ ["brain", "monthly", "--json", "--month", "2026-05"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ },+ );+ expect(result.returncode).toBe(0);+ const payload = JSON.parse(result.stdout) as {+ month: string;+ summary: { events: number };+ };+ expect(payload.month).toBe("2026-05");+ expect(payload.summary.events).toBe(1);+ });++ test("rejects malformed --month", async () => {+ const result = await runCli(["brain", "monthly", "--month", "2026-13"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(result.returncode).toBe(1);+ expect(result.stderr).toContain("YYYY-MM");+ });+});diff --git a/tests/cli/brain-retention.test.ts b/tests/cli/brain-retention.test.tsnew file mode 100644index 00000000..6b7dd968--- /dev/null+++ b/tests/cli/brain-retention.test.ts@@ -0,0 +1,67 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ mkdirSync,+ mkdtempSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { processedSignalPath, signalPath } from "../../src/core/brain/paths.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { runCli } from "../helpers/run-cli.ts";++let root: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-retention-cli-"));+ vault = join(root, "vault");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+ configPath = join(root, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+ writeSignal(vault, {+ topic: "discarded-signal",+ signal: "negative",+ agent: "test",+ principle: "old one-off signal",+ created_at: "2026-04-01T00:00:00Z",+ date: "2026-04-01",+ slug: "discarded-signal",+ });+ renameSync(+ signalPath(vault, "2026-04-01", "discarded-signal"),+ processedSignalPath(vault, "2026-04-01", "discarded-signal"),+ );+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe("o2b brain retention", () => {+ test("prints JSON retention recommendations", async () => {+ const result = await runCli(+ ["brain", "retention", "--json", "--now", "2026-05-28T00:00:00Z"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ },+ );+ expect(result.returncode).toBe(0);+ const payload = JSON.parse(result.stdout) as { summary: { prune: number } };+ expect(payload.summary.prune).toBe(1);+ });++ test("rejects malformed --now", async () => {+ const result = await runCli(["brain", "retention", "--now", "not-a-date"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(result.returncode).toBe(1);+ expect(result.stderr).toContain("invalid --now");+ });+});diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.tsindex 5864d854..1992dd6f 100644--- a/tests/cli/brain.test.ts+++ b/tests/cli/brain.test.ts@@ -68,6 +68,9 @@ describe("brain --help", () => {expect(r.stdout).toContain("dream");expect(r.stdout).toContain("apply-evidence");expect(r.stdout).toContain("digest");+ expect(r.stdout).toContain("intent-review");+ expect(r.stdout).toContain("retention");+ expect(r.stdout).toContain("monthly");expect(r.stdout).toContain("query");expect(r.stdout).toContain("reject");expect(r.stdout).toContain("pin");@@ -147,9 +150,12 @@ describe("brain init", () => {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(init.returncode).toBe(0);- const r = await runCli(["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);@@ -160,9 +166,12 @@ describe("brain init", () => {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(init.returncode).toBe(0);- const r = await runCli(["brain", "init", "--vault", vault, "--primary-agent", " "], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "init", "--vault", vault, "--primary-agent", " "],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr.toLowerCase()).toContain("primary-agent");});@@ -171,9 +180,12 @@ describe("brain init", () => {describe("brain set-primary", () => {test("writes the agent name into _brain.yaml", async () => {await bootstrap();- const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "set-primary", "hermes-vps", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("primary_agent: null β hermes-vps");const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");@@ -185,9 +197,12 @@ describe("brain set-primary", () => {await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "set-primary", "hermes-vps", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("already set to hermes-vps");});@@ -197,9 +212,12 @@ describe("brain set-primary", () => {await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(["brain", "set-primary", "--clear", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "set-primary", "--clear", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("hermes-vps β null");});@@ -214,9 +232,12 @@ describe("brain set-primary", () => {test("--json emits structured output", async () => {await bootstrap();- const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault, "--json"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "set-primary", "hermes-vps", "--vault", vault, "--json"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.previous).toBeNull();@@ -248,7 +269,9 @@ describe("brain feedback", () => {expect(r.returncode).toBe(0);expect(r.stdout).toContain("signal: ");expect(r.stdout).toContain("id: sig-");- const inbox = readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md"));+ const inbox = readdirSync(join(vault, "Brain", "inbox")).filter((n) =>+ n.endsWith(".md"),+ );expect(inbox.length).toBe(1);const body = readFileSync(join(vault, "Brain", "inbox", inbox[0]!), "utf8");expect(body).toContain("no-abbrev");@@ -258,7 +281,16 @@ describe("brain feedback", () => {test("missing --topic exits 1 naming the flag", async () => {await bootstrap();const r = await runCli(- ["brain", "feedback", "--vault", vault, "--signal", "positive", "--principle", "x"],+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--signal",+ "positive",+ "--principle",+ "x",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(1);@@ -328,18 +360,24 @@ describe("brain dream", () => {test("--now must be ISO-8601", async () => {await bootstrap();- const r = await runCli(["brain", "dream", "--vault", vault, "--now", "not-a-date"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "dream", "--vault", vault, "--now", "not-a-date"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("--now");});test("blank --agent exits 1 instead of falling back to the resolved default", async () => {await bootstrap();- const r = await runCli(["brain", "dream", "--vault", vault, "--agent", " "], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "dream", "--vault", vault, "--agent", " "],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("--agent");});@@ -348,9 +386,12 @@ describe("brain dream", () => {describe("brain apply-evidence", () => {test("missing required flag exits 1 naming the flag", async () => {await bootstrap();- const r = await runCli(["brain", "apply-evidence", "--vault", vault, "--artifact", "[[foo]]"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "apply-evidence", "--vault", vault, "--artifact", "[[foo]]"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("--pref");});@@ -421,7 +462,9 @@ describe("brain apply-evidence", () => {);expect(r.returncode).toBe(0);expect(r.stdout).toContain("logged:");- const logs = readdirSync(join(vault, "Brain", "log")).filter((n) => n.endsWith(".md"));+ const logs = readdirSync(join(vault, "Brain", "log")).filter((n) =>+ n.endsWith(".md"),+ );expect(logs.length).toBe(1);const body = readFileSync(join(vault, "Brain", "log", logs[0]!), "utf8");expect(body).toContain("apply-evidence");@@ -441,9 +484,12 @@ describe("brain digest", () => {test("--silent-if-empty exits 2 with no body", async () => {await bootstrap();- const r = await runCli(["brain", "digest", "--vault", vault, "--silent-if-empty"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "digest", "--vault", vault, "--silent-if-empty"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(2);expect(r.stdout.trim()).toBe("");});@@ -473,7 +519,15 @@ describe("brain query", () => {test("--topic on empty vault returns empty result", async () => {await bootstrap();const r = await runCli(- ["brain", "query", "--vault", vault, "--topic", "no-such-topic", "--json"],+ [+ "brain",+ "query",+ "--vault",+ vault,+ "--topic",+ "no-such-topic",+ "--json",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -484,18 +538,24 @@ describe("brain query", () => {test("--preference on missing pref exits 2", async () => {await bootstrap();- const r = await runCli(["brain", "query", "--vault", vault, "--preference", "pref-nope"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "query", "--vault", vault, "--preference", "pref-nope"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(2);expect(r.stderr).toContain("brain query");});test("--since requires ISO timestamp", async () => {await bootstrap();- const r = await runCli(["brain", "query", "--vault", vault, "--since", "garbage"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "query", "--vault", vault, "--since", "garbage"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("--since");});@@ -538,8 +598,12 @@ describe("brain reject", () => {);expect(r.returncode).toBe(0);expect(r.stdout).toContain("retired: ret-obsolete");- expect(existsSync(join(vault, "Brain", "preferences", "pref-obsolete.md"))).toBe(false);- expect(existsSync(join(vault, "Brain", "retired", "ret-obsolete.md"))).toBe(true);+ expect(+ existsSync(join(vault, "Brain", "preferences", "pref-obsolete.md")),+ ).toBe(false);+ expect(existsSync(join(vault, "Brain", "retired", "ret-obsolete.md"))).toBe(+ true,+ );});test("missing --id exits 1", async () => {@@ -553,9 +617,12 @@ describe("brain reject", () => {test("missing --reason exits 1 (mandatory from v0.10.1)", async () => {await bootstrap();- const r = await runCli(["brain", "reject", "--vault", vault, "--id", "pref-ghost"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "reject", "--vault", vault, "--id", "pref-ghost"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("--reason");});@@ -563,7 +630,16 @@ describe("brain reject", () => {test("unknown pref exits 2", async () => {await bootstrap();const r = await runCli(- ["brain", "reject", "--vault", vault, "--id", "pref-ghost", "--reason", "ghost"],+ [+ "brain",+ "reject",+ "--vault",+ vault,+ "--id",+ "pref-ghost",+ "--reason",+ "ghost",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(2);@@ -590,9 +666,12 @@ describe("brain reject", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const pin = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-important"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const pin = await runCli(+ ["brain", "pin", "--vault", vault, "--id", "pref-important"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(pin.returncode).toBe(0);const r = await runCli(@@ -612,7 +691,9 @@ describe("brain reject", () => {expect(r.stderr.toLowerCase()).toContain("pinned");expect(r.stderr).toContain("--yes");// Pref must still exist (rejection refused).- expect(existsSync(join(vault, "Brain", "preferences", "pref-important.md"))).toBe(true);+ expect(+ existsSync(join(vault, "Brain", "preferences", "pref-important.md")),+ ).toBe(true);});test("pinned pref retires with --yes", async () => {@@ -653,9 +734,14 @@ describe("brain reject", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);- expect(existsSync(join(vault, "Brain", "retired", "ret-important.md"))).toBe(true);+ expect(+ existsSync(join(vault, "Brain", "retired", "ret-important.md")),+ ).toBe(true);// Β§6: the user reason must land on the retired file's frontmatter.- const ret = readFileSync(join(vault, "Brain", "retired", "ret-important.md"), "utf8");+ const ret = readFileSync(+ join(vault, "Brain", "retired", "ret-important.md"),+ "utf8",+ );expect(ret).toContain("user_rejected_reason: no longer the right call");});});@@ -685,14 +771,20 @@ describe("brain pin / unpin", () => {test("pin then idempotent rerun", async () => {await seedPref();- const r1 = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r1 = await runCli(+ ["brain", "pin", "--vault", vault, "--id", "pref-rule"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r1.returncode).toBe(0);expect(r1.stdout).toContain("pinned: pref-rule");- const r2 = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r2 = await runCli(+ ["brain", "pin", "--vault", vault, "--id", "pref-rule"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r2.returncode).toBe(0);expect(r2.stdout).toContain("already pinned");});@@ -702,9 +794,12 @@ describe("brain pin / unpin", () => {await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(["brain", "unpin", "--vault", vault, "--id", "pref-rule"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "unpin", "--vault", vault, "--id", "pref-rule"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("unpinned: pref-rule");});@@ -744,9 +839,12 @@ describe("brain rollback", () => {await runCli(["brain", "dream", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(["brain", "rollback", "--vault", vault, "--list", "--json"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "rollback", "--vault", vault, "--list", "--json"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);const list = JSON.parse(r.stdout) as Array<{ run_id: string }>;// Snapshot may or may not have been written depending on whether@@ -766,9 +864,12 @@ describe("brain rollback", () => {test("unknown run_id exits 2", async () => {await bootstrap();- const r = await runCli(["brain", "rollback", "--vault", vault, "no-such-run", "--yes"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "rollback", "--vault", vault, "no-such-run", "--yes"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(2);expect(r.stderr.toLowerCase()).toContain("snapshot not found");});@@ -779,9 +880,12 @@ describe("brain rollback", () => {// --json β otherwise scripted callers deadlock waiting for stdin.// The new non-interactive guard short-circuits before the snapshot// existence probe; we treat that as the contract under test.- const r = await runCli(["brain", "rollback", "--vault", vault, "any-run", "--json"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "rollback", "--vault", vault, "any-run", "--json"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );// Either 1 (non-interactive guard) or 2 (snapshot-not-found) is// acceptable as long as the call returns without hanging. The// crucial bit is no timeout.@@ -842,13 +946,23 @@ describe("brain rollback", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(- readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md")).length,+ readdirSync(join(vault, "Brain", "inbox")).filter((n) =>+ n.endsWith(".md"),+ ).length,).toBeGreaterThanOrEqual(1);// 4. Rollback to the snapshot. State B drifted (a new signal// landed after the snapshot), so v0.10.6 rollback requires// --force-rollback to overwrite the live tree.const r = await runCli(- ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes", "--force-rollback"],+ [+ "brain",+ "rollback",+ "--vault",+ vault,+ dpayload.run_id,+ "--yes",+ "--force-rollback",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -902,9 +1016,12 @@ describe("brain rollback", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const r = await runCli(["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(2);expect(r.stderr).toContain("Drift detected");expect(r.stderr).toContain("--force-rollback");@@ -956,7 +1073,15 @@ describe("brain rollback", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);const r = await runCli(- ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes", "--json"],+ [+ "brain",+ "rollback",+ "--vault",+ vault,+ dpayload.run_id,+ "--yes",+ "--json",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(2);@@ -1000,12 +1125,20 @@ describe("brain rollback", () => {if (!dpayload.changed) return;// Simulate a pre-v0.10.6 snapshot: archive with no manifest.- const sidecar = join(vault, "Brain", ".snapshots", `${dpayload.run_id}.manifest.json`);+ const sidecar = join(+ vault,+ "Brain",+ ".snapshots",+ `${dpayload.run_id}.manifest.json`,+ );rmSync(sidecar, { force: true });- const r = await runCli(["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stderr).toContain("no manifest sidecar");expect(r.stderr).toContain("predates v0.10.6");@@ -1086,11 +1219,18 @@ describe("brain scan-inline", () => {await bootstrap();const notePath = join(vault, "Daily", "2026-05-16.md");mkdirSync(join(vault, "Daily"), { recursive: true });- writeFileSync(notePath, "@osb feedback negative topic=cli-test principle=p\n", "utf8");+ writeFileSync(+ notePath,+ "@osb feedback negative topic=cli-test principle=p\n",+ "utf8",+ );- const r = await runCli(["brain", "scan-inline", "--vault", vault, "--path", "Daily"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "scan-inline", "--vault", vault, "--path", "Daily"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/created: 1/);@@ -1106,17 +1246,31 @@ describe("brain scan-inline", () => {await bootstrap();const notePath = join(vault, "Daily", "2026-05-16.md");mkdirSync(join(vault, "Daily"), { recursive: true });- writeFileSync(notePath, "@osb feedback negative topic=dry principle=p\n", "utf8");+ writeFileSync(+ notePath,+ "@osb feedback negative topic=dry principle=p\n",+ "utf8",+ );const before = readFileSync(notePath, "utf8");const r = await runCli(- ["brain", "scan-inline", "--vault", vault, "--dry-run", "--path", "Daily"],+ [+ "brain",+ "scan-inline",+ "--vault",+ vault,+ "--dry-run",+ "--path",+ "Daily",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);expect(readFileSync(notePath, "utf8")).toBe(before);const inbox = join(vault, "Brain", "inbox");- expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(0);+ expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(+ 0,+ );});test("--json emits machine-readable summary", async () => {@@ -1160,10 +1314,16 @@ describe("brain scan-inline", () => {describe("brain import-session", () => {test("imports a single .jsonl file and creates signals", async () => {await bootstrap();- const fixture = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");- const r = await runCli(["brain", "import-session", fixture, "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/claude-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/signals_created: [1-9]/);@@ -1174,21 +1334,35 @@ describe("brain import-session", () => {test("--dry-run does not create signals", async () => {await bootstrap();- const fixture = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");- const r = await runCli(["brain", "import-session", fixture, "--vault", vault, "--dry-run"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/claude-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault, "--dry-run"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);const inbox = join(vault, "Brain", "inbox");- expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(0);+ expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(+ 0,+ );});test("--json structured output", async () => {await bootstrap();- const fixture = join(process.cwd(), "tests/fixtures/sessions/codex-minimal.jsonl");- const r = await runCli(["brain", "import-session", fixture, "--vault", vault, "--json"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const fixture = join(+ process.cwd(),+ "tests/fixtures/sessions/codex-minimal.jsonl",+ );+ const r = await runCli(+ ["brain", "import-session", fixture, "--vault", vault, "--json"],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.ok).toBe(true);@@ -1200,9 +1374,12 @@ describe("brain import-session", () => {await bootstrap();const junk = join(tmp, "junk.jsonl");writeFileSync(junk, '{"foo":"bar"}\n', "utf8");- const r = await runCli(["brain", "import-session", junk, "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "import-session", junk, "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(2);expect(r.stderr.toLowerCase()).toMatch(/autodetect|format/);});@@ -1222,9 +1399,12 @@ describe("brain vault resolution", () => {describe("brain protect", () => {test("--target claudecode --print returns the JSON shape, exit 0", async () => {await bootstrap();- const r = await runCli(["brain", "protect", "--target", "claudecode", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "protect", "--target", "claudecode", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("Write(");expect(r.stdout).toContain("preview only");@@ -1233,18 +1413,24 @@ describe("brain protect", () => {test("--target codex --print includes the managed fence", async () => {await bootstrap();- const r = await runCli(["brain", "protect", "--target", "codex", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "protect", "--target", "codex", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("# >>> open-second-brain managed >>>");});test("unknown --target exits 1 with a clear message", async () => {await bootstrap();- const r = await runCli(["brain", "protect", "--target", "vim", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ const r = await runCli(+ ["brain", "protect", "--target", "vim", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(1);expect(r.stderr).toContain("unknown");expect(r.stderr).toContain("claudecode");@@ -1253,7 +1439,15 @@ describe("brain protect", () => {test("--apply writes settings.json and is idempotent", async () => {await bootstrap();const first = await runCli(- ["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"],+ [+ "brain",+ "protect",+ "--target",+ "claudecode",+ "--vault",+ vault,+ "--apply",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(first.returncode).toBe(0);@@ -1263,7 +1457,15 @@ describe("brain protect", () => {expect(bytesAfterFirst).toContain("Write(");const second = await runCli(- ["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"],+ [+ "brain",+ "protect",+ "--target",+ "claudecode",+ "--vault",+ vault,+ "--apply",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(second.returncode).toBe(0);@@ -1273,15 +1475,31 @@ describe("brain protect", () => {test("apply + unprotect round-trip leaves no managed entries", async () => {await bootstrap();- await runCli(["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });- const r = await runCli(["brain", "unprotect", "--target", "claudecode", "--vault", vault], {- env: { OPEN_SECOND_BRAIN_CONFIG: config },- });+ await runCli(+ [+ "brain",+ "protect",+ "--target",+ "claudecode",+ "--vault",+ vault,+ "--apply",+ ],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );+ const r = await runCli(+ ["brain", "unprotect", "--target", "claudecode", "--vault", vault],+ {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ },+ );expect(r.returncode).toBe(0);expect(r.stdout).toContain("removed");- const parsed = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));+ const parsed = JSON.parse(+ readFileSync(join(vault, ".claude", "settings.json"), "utf8"),+ );// After unprotect, OSB-owned deny entries are gone. The keys may// remain empty (user could have other rules) β assert via filter.const ownedLeft = (parsed.permissions?.deny ?? []).filter((e: string) =>diff --git a/tests/core/brain.dream-guardrail.test.ts b/tests/core/brain.dream-guardrail.test.tsindex eefa73ab..7b8608b8 100644--- a/tests/core/brain.dream-guardrail.test.ts+++ b/tests/core/brain.dream-guardrail.test.ts@@ -63,6 +63,13 @@ describe("dream + self-approval guardrail (default config)", () => {const res = dream(vault);expect(res.new_unconfirmed).toEqual(["pref-test-topic"]);expect(res.quarantined).toEqual([]);+ expect(res.intent_reviews).toEqual([+ expect.objectContaining({+ topic: "test-topic",+ decision: "ready_for_main_review",+ signal_count: 3,+ }),+ ]);});test("2 signals from 1 agent: blocked by candidate_threshold, not by guardrail", () => {diff --git a/tests/core/brain.intent-review.test.ts b/tests/core/brain.intent-review.test.tsnew file mode 100644index 00000000..fc89513d--- /dev/null+++ b/tests/core/brain.intent-review.test.ts@@ -0,0 +1,109 @@+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 { bootstrapBrain } from "../../src/core/brain/init.ts";+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";+import { preferencePath } from "../../src/core/brain/paths.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { buildIntentReview } from "../../src/core/brain/intent-review.ts";+import { BRAIN_RETIRED_REASON } from "../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-intent-review-"));+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function signal(topic: string, sign: "positive" | "negative", index: number): void {+ writeSignal(vault, {+ topic,+ signal: sign,+ agent: index % 2 === 0 ? "claude" : "codex",+ principle: `${topic} ${sign} principle`,+ created_at: `2026-05-2${index}T10:00:00Z`,+ date: `2026-05-2${index}`,+ slug: `${topic}-${index}`,+ });+}++describe("buildIntentReview", () => {+ test("classifies ready, weak, and conflicted signal clusters", () => {+ signal("ready-topic", "positive", 1);+ signal("ready-topic", "positive", 2);+ signal("ready-topic", "positive", 3);+ signal("weak-topic", "negative", 1);+ signal("conflicted-topic", "positive", 1);+ signal("conflicted-topic", "positive", 2);+ signal("conflicted-topic", "negative", 3);+ signal("conflicted-topic", "negative", 4);++ const report = buildIntentReview(vault, {+ now: new Date("2026-05-28T00:00:00Z"),+ });++ expect(report.schema_version).toBe(1);+ expect(report.reviews.map((review) => review.topic)).toEqual([+ "conflicted-topic",+ "ready-topic",+ "weak-topic",+ ]);+ expect(report.reviews.find((review) => review.topic === "ready-topic")?.decision).toBe(+ "ready_for_main_review",+ );+ expect(report.reviews.find((review) => review.topic === "weak-topic")?.decision).toBe(+ "needs_more_evidence",+ );+ expect(report.reviews.find((review) => review.topic === "conflicted-topic")?.decision).toBe(+ "blocked_conflicted",+ );+ });++ test("excludes future signals and surfaces user-rejected retired suppressors", () => {+ writePreference(vault, {+ slug: "rejected-topic",+ topic: "rejected-topic",+ principle: "do not regrow rejected rules",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: [],+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-08T00:00:00Z",+ });+ moveToRetired(+ vault,+ preferencePath(vault, "rejected-topic"),+ BRAIN_RETIRED_REASON.userRejected,+ {+ now: new Date("2026-05-20T00:00:00Z"),+ retired_by: "test",+ evidenceApplied: [],+ evidenceViolated: [],+ user_rejected_reason: "operator rejected the rule",+ },+ );+ signal("future-topic", "positive", 9);+ signal("rejected-topic", "positive", 1);++ const report = buildIntentReview(vault, {+ now: new Date("2026-05-28T00:00:00Z"),+ });++ expect(report.reviews.map((review) => review.topic)).toEqual(["rejected-topic"]);+ expect(report.reviews[0]).toMatchObject({+ decision: "suppressed_by_rejected_retired",+ signal_count: 1,+ risk_band: "medium",+ });+ });+});diff --git a/tests/core/brain.monthly-review.test.ts b/tests/core/brain.monthly-review.test.tsnew file mode 100644index 00000000..8001effa--- /dev/null+++ b/tests/core/brain.monthly-review.test.ts@@ -0,0 +1,60 @@+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 { appendLogEvent } from "../../src/core/brain/log.ts";+import { buildMonthlyReview } from "../../src/core/brain/monthly-review.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import {+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+} from "../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-monthly-review-"));+ mkdirSync(brainDirs(vault).log, { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("buildMonthlyReview", () => {+ test("aggregates month events, transitions, and contradictions", () => {+ appendLogEvent(vault, {+ timestamp: "2026-05-10T10:00:00Z",+ eventType: BRAIN_LOG_EVENT_KIND.dream,+ body: {+ confirmed: ["[[pref-use-tests|Use tests]]"],+ retired: ["[[ret-old-rule|Old rule]] (stale-no-evidence)"],+ },+ });+ appendLogEvent(vault, {+ timestamp: "2026-05-11T10:00:00Z",+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,+ body: {+ preference: "[[pref-use-tests]]",+ artifact: "[[src/core/example.ts]]",+ result: BRAIN_APPLY_RESULT.violated,+ },+ });++ const report = buildMonthlyReview(vault, {+ month: "2026-05",+ now: new Date("2026-06-01T00:00:00Z"),+ });++ expect(report.month).toBe("2026-05");+ expect(report.window).toEqual({+ since: "2026-05-01T00:00:00Z",+ until: "2026-06-01T00:00:00Z",+ });+ expect(report.summary.events).toBe(2);+ expect(report.summary.status_transitions).toBe(2);+ expect(report.summary.retired).toBe(1);+ expect(report.summary.contradictions).toBe(1);+ });+});diff --git a/tests/core/brain.retention.test.ts b/tests/core/brain.retention.test.tsnew file mode 100644index 00000000..31e71ef3--- /dev/null+++ b/tests/core/brain.retention.test.ts@@ -0,0 +1,85 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { preferencePath, processedSignalPath, signalPath } from "../../src/core/brain/paths.ts";+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { buildRetentionReview } from "../../src/core/brain/retention.ts";+import { BRAIN_RETIRED_REASON } from "../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-retention-"));+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("buildRetentionReview", () => {+ test("recommends keep/prune without mutating artifacts", () => {+ writePreference(vault, {+ slug: "useful-rule",+ topic: "useful-rule",+ principle: "keep useful retired rules visible",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: [],+ applied_count: 3,+ violated_count: 0,+ last_evidence_at: "2026-05-20T00:00:00Z",+ });+ const retired = moveToRetired(+ vault,+ preferencePath(vault, "useful-rule"),+ BRAIN_RETIRED_REASON.staleNoEvidence,+ {+ now: new Date("2026-05-21T00:00:00Z"),+ retired_by: "test",+ evidenceApplied: [],+ evidenceViolated: [],+ },+ );++ writeSignal(vault, {+ topic: "discarded-signal",+ signal: "negative",+ agent: "test",+ principle: "old one-off signal",+ created_at: "2026-04-01T00:00:00Z",+ date: "2026-04-01",+ slug: "discarded-signal",+ });+ const activeSignal = signalPath(vault, "2026-04-01", "discarded-signal");+ const processedSignal = processedSignalPath(vault, "2026-04-01", "discarded-signal");+ renameSync(activeSignal, processedSignal);+ const retiredMtimeBefore = statSync(retired.path).mtimeMs;+ const processedMtimeBefore = statSync(processedSignal).mtimeMs;++ const report = buildRetentionReview(vault, {+ now: new Date("2026-05-28T00:00:00Z"),+ });++ expect(report.summary.keep).toBe(1);+ expect(report.summary.prune).toBe(1);+ expect(report.recommendations).toEqual([+ expect.objectContaining({ id: "ret-useful-rule", action: "keep" }),+ expect.objectContaining({+ id: "sig-2026-04-01-discarded-signal",+ action: "prune",+ }),+ ]);+ expect(existsSync(retired.path)).toBe(true);+ expect(existsSync(processedSignal)).toBe(true);+ expect(statSync(retired.path).mtimeMs).toBe(retiredMtimeBefore);+ expect(statSync(processedSignal).mtimeMs).toBe(processedMtimeBefore);+ });+});diff --git a/tests/core/brain.schema-contracts.test.ts b/tests/core/brain.schema-contracts.test.tsnew file mode 100644index 00000000..b08996da--- /dev/null+++ b/tests/core/brain.schema-contracts.test.ts@@ -0,0 +1,104 @@+import { describe, expect, test } from "bun:test";++import {+ BRAIN_SCHEMA_CONTRACTS,+ getBrainSchemaContract,+ validateSchemaContract,+} from "../../src/core/brain/schema-contracts.ts";++describe("Brain schema contracts", () => {+ test("registers lifecycle review schemas in stable order", () => {+ expect(BRAIN_SCHEMA_CONTRACTS.map((schema) => schema.id)).toEqual([+ "brain.intent_review.v1",+ "brain.retention_review.v1",+ "brain.monthly_review.v1",+ "brain.complexity_report.v1",+ ]);+ expect(getBrainSchemaContract("brain.retention_review.v1")?.title).toBe(+ "Brain Retention Review v1",+ );+ });++ test("validates a retention review envelope", () => {+ const schema = getBrainSchemaContract("brain.retention_review.v1");+ expect(schema).toBeDefined();+ const valid = validateSchemaContract(schema!, {+ schema_version: 1,+ generated_at: "2026-05-28T12:00:00.000Z",+ summary: {+ keep: 1,+ improve: 0,+ park: 0,+ prune: 0,+ },+ recommendations: [+ {+ id: "ret-old-rule",+ artifact_type: "retired_preference",+ action: "keep",+ reason: "recently retired with evidence trail",+ path: "Brain/retired/ret-old-rule.md",+ },+ ],+ });+ expect(valid.ok).toBe(true);++ const invalid = validateSchemaContract(schema!, {+ schema_version: 1,+ generated_at: "2026-05-28T12:00:00.000Z",+ summary: {+ keep: 1,+ improve: 0,+ park: 0,+ prune: 0,+ },+ recommendations: [+ {+ id: "ret-old-rule",+ artifact_type: "retired_preference",+ action: "delete",+ reason: "unsupported action",+ path: "Brain/retired/ret-old-rule.md",+ },+ ],+ });+ expect(invalid.ok).toBe(false);+ expect(invalid.errors[0]).toContain("recommendations[0].action");+ });++ test("enforces lifecycle scalar invariants", () => {+ const retention = getBrainSchemaContract("brain.retention_review.v1");+ expect(retention).toBeDefined();+ const invalidRetention = validateSchemaContract(retention!, {+ schema_version: 1,+ generated_at: "not-a-date",+ summary: {+ keep: -1,+ improve: 0,+ park: 0,+ prune: 0,+ },+ recommendations: [],+ });+ expect(invalidRetention.ok).toBe(false);+ expect(invalidRetention.errors).toContain("generated_at must be date-time");+ expect(invalidRetention.errors).toContain("summary.keep must be >= 0");++ const complexity = getBrainSchemaContract("brain.complexity_report.v1");+ expect(complexity).toBeDefined();+ const invalidComplexity = validateSchemaContract(complexity!, {+ schema_version: 1,+ generated_at: "2026-05-28T12:00:00.000Z",+ score: -1,+ ratio: -0.1,+ thinking_activity: 0,+ structural_complexity: 1,+ warning: false,+ factors: [{ name: "depth", value: -1, weight: 1 }],+ });+ expect(invalidComplexity.ok).toBe(false);+ expect(invalidComplexity.errors).toContain("score must be >= 0");+ expect(invalidComplexity.errors).toContain("ratio must be >= 0");+ expect(invalidComplexity.errors).toContain("factors[0].value must be >= 0");+ });+});diff --git a/tests/discipline/activity-git.test.ts b/tests/discipline/activity-git.test.tsindex d4fc1b00..c23be398 100644--- a/tests/discipline/activity-git.test.ts+++ b/tests/discipline/activity-git.test.ts@@ -11,7 +11,9 @@ let repo: string;beforeAll(() => {repo = mkdtempSync(join(tmpdir(), "o2b-disc-git-"));execSync("git init -q -b main", { cwd: repo });- execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", {+ cwd: repo,+ });writeFileSync(join(repo, "a.txt"), "hello\n");execSync("git add a.txt && git commit -q -m c1 --date=2026-05-17T10:00:00Z", {cwd: repo,@@ -38,6 +40,7 @@ describe("gitActivity", () => {});expect(out?.commits).toBe(2);expect(out?.filesChanged).toBe(1);+ expect(out?.pathsChanged).toEqual(["a.txt"]);expect(out?.insertions).toBe(2); // 1 + 1expect(out?.deletions).toBe(0);});diff --git a/tests/discipline/activity-mtime.test.ts b/tests/discipline/activity-mtime.test.tsindex 2dbd8cb5..559acd18 100644--- a/tests/discipline/activity-mtime.test.ts+++ b/tests/discipline/activity-mtime.test.ts@@ -31,6 +31,7 @@ describe("mtimeActivity", () => {endUtc: new Date("2026-05-18T00:00:00Z"),});expect(out.modifiedFiles).toBe(3);+ expect(out.modifiedPaths).toEqual(["in1.txt", "in2.md", "subdir/in3.md"]);rmSync(root, { recursive: true });});});diff --git a/tests/discipline/complexity.test.ts b/tests/discipline/complexity.test.tsnew file mode 100644index 00000000..b76188b2--- /dev/null+++ b/tests/discipline/complexity.test.ts@@ -0,0 +1,57 @@+import { 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 {+ buildComplexityReport,+ complexityPathFactors,+} from "../../src/core/discipline/complexity.ts";++describe("complexity report", () => {+ test("weights path-derived structure factors", () => {+ const root = mkdtempSync(join(tmpdir(), "o2b-disc-complexity-"));+ try {+ mkdirSync(join(root, "notes", "deep", "templates"), { recursive: true });+ writeFileSync(+ join(root, "notes", "deep", "templates", "daily.md"),+ "---\ntags: [workflow, review]\n---\n#brain/review\n",+ );+ writeFileSync(join(root, ".obsidian.json"), "{}\n");++ const pathFactors = complexityPathFactors([+ { root, relativePath: "notes/deep/templates/daily.md" },+ { root, relativePath: ".obsidian.json" },+ ]);+ const report = buildComplexityReport({+ thinkingActivity: 1,+ structuralFilesChanged: 2,+ ...pathFactors,+ });++ expect(report.factors).toContainEqual({+ name: "max_folder_depth",+ value: 3,+ weight: 1,+ });+ expect(report.factors).toContainEqual({+ name: "template_changes",+ value: 1,+ weight: 2,+ });+ expect(report.factors).toContainEqual({+ name: "config_changes",+ value: 1,+ weight: 2,+ });+ expect(report.factors).toContainEqual({+ name: "tag_proliferation",+ value: 3,+ weight: 1,+ });+ expect(report.warning).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/tests/discipline/decision.test.ts b/tests/discipline/decision.test.tsindex 9ef77c0a..882861ce 100644--- a/tests/discipline/decision.test.ts+++ b/tests/discipline/decision.test.ts@@ -24,7 +24,12 @@ describe("decideStatus", () => {} as any;const someRepoActivity = {...noActivity,- repo: [{ path: "/a", git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 } }],+ repo: [+ {+ path: "/a",+ git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 },+ },+ ],};const someMtimeActivity = {...noActivity,@@ -34,6 +39,19 @@ describe("decideStatus", () => {...noActivity,vaultDelta: { newSignals: 0, newPreferences: 1, newRetired: 0, total: 1 },};+ const highComplexity = {+ ...noActivity,+ complexity: {+ schema_version: 1,+ generated_at: "2026-05-28T00:00:00.000Z",+ score: 12,+ ratio: 12,+ thinking_activity: 0,+ structural_complexity: 12,+ warning: true,+ factors: [{ name: "structure_churn", value: 12, weight: 1 }],+ },+ } as any;test("0 events + 0 activity β info", () => {expect(decideStatus(noEvents, noActivity)).toBe("info");@@ -51,9 +69,13 @@ describe("decideStatus", () => {test("0 events + vault delta β alert", () => {expect(decideStatus(noEvents, someVaultDelta)).toBe("alert");});- test("taste events present (feedback or apply_evidence) β ok regardless of activity", () => {+ test("0 events + high complexity-to-thinking ratio β alert", () => {+ expect(decideStatus(noEvents, highComplexity)).toBe("alert");+ });+ test("taste events present β ok unless complexity warning fires", () => {expect(decideStatus(someTasteEvents, noActivity)).toBe("ok");expect(decideStatus(someTasteEvents, someRepoActivity)).toBe("ok");+ expect(decideStatus(someTasteEvents, highComplexity)).toBe("alert");});test("only `other` events (snapshot/dream/import) do NOT count as taste β alert if activity", () => {diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.tsindex 904a105c..830b3443 100644--- a/tests/discipline/render.test.ts+++ b/tests/discipline/render.test.ts@@ -9,8 +9,20 @@ describe("renderReport", () => {status: "ok",events: {byAgent: {- "@claude-vps-agent": { feedback: 2, apply_evidence: 3, note: 1, other: 0, total: 6 },- "@codex-vps-agent": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ "@claude-vps-agent": {+ feedback: 2,+ apply_evidence: 3,+ note: 1,+ other: 0,+ total: 6,+ },+ "@codex-vps-agent": {+ feedback: 0,+ apply_evidence: 0,+ note: 0,+ other: 0,+ total: 0,+ },},unknownAgents: [],total: 6,@@ -19,11 +31,21 @@ describe("renderReport", () => {repo: [{path: "/srv/projects/foo",- git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 },+ git: {+ commits: 4,+ filesChanged: 27,+ insertions: 312,+ deletions: 148,+ },},],nonRepo: [],- vaultDelta: { newSignals: 1, newPreferences: 0, newRetired: 0, total: 1 },+ vaultDelta: {+ newSignals: 1,+ newPreferences: 0,+ newRetired: 0,+ total: 1,+ },},});expect(text).toContain("OSB discipline");@@ -44,14 +66,26 @@ describe("renderReport", () => {timezone: "UTC",status: "alert",events: {- byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ },unknownAgents: [],total: 0,},activity: {- repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],+ repo: [+ {+ path: "/x",+ git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 },+ },+ ],nonRepo: [],- vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ vaultDelta: {+ newSignals: 0,+ newPreferences: 0,+ newRetired: 0,+ total: 0,+ },},});expect(text).toContain("Status: alert");@@ -65,17 +99,33 @@ describe("renderReport", () => {timezone: "UTC",status: "alert",events: {- byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ },unknownAgents: [],total: 0,},activity: {- repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],+ repo: [+ {+ path: "/x",+ git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 },+ },+ ],nonRepo: [],- vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ vaultDelta: {+ newSignals: 0,+ newPreferences: 0,+ newRetired: 0,+ total: 0,+ },transcripts: {byRuntime: [- { runtime: "claudecode", fileCount: 2, agentHint: "claude-vps-agent" },+ {+ runtime: "claudecode",+ fileCount: 2,+ agentHint: "claude-vps-agent",+ },{ runtime: "codex", fileCount: 0, agentHint: "codex-vps-agent" },],totalFiles: 2,@@ -87,22 +137,78 @@ describe("renderReport", () => {expect(text).toContain("transcript\\-confirmed");});+ test("status: alert + complexity warning adds productivity-trap sub-reason", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: {+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ },+ unknownAgents: [],+ total: 0,+ },+ activity: {+ repo: [],+ nonRepo: [],+ vaultDelta: {+ newSignals: 0,+ newPreferences: 0,+ newRetired: 0,+ total: 0,+ },+ complexity: {+ schema_version: 1,+ generated_at: "2026-05-28T00:00:00.000Z",+ score: 12,+ ratio: 12,+ thinking_activity: 0,+ structural_complexity: 12,+ warning: true,+ factors: [{ name: "structure_churn", value: 12, weight: 1 }],+ },+ },+ });+ expect(text).toContain("\\- complexity β score 12, thinking 0, ratio 12");+ expect(text).toContain("complexity β score 12, thinking 0, ratio 12");+ expect(text).toContain("productivity\\-trap");+ });+test("transcripts with zero files omit the line and skip the sub-reason", () => {const text = renderReport({localDate: "2026-05-17",timezone: "UTC",status: "alert",events: {- byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ },unknownAgents: [],total: 0,},activity: {- repo: [{ path: "/x", git: { commits: 1, filesChanged: 1, insertions: 1, deletions: 0 } }],+ repo: [+ {+ path: "/x",+ git: { commits: 1, filesChanged: 1, insertions: 1, deletions: 0 },+ },+ ],nonRepo: [],- vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ vaultDelta: {+ newSignals: 0,+ newPreferences: 0,+ newRetired: 0,+ total: 0,+ },transcripts: {- byRuntime: [{ runtime: "claudecode", fileCount: 0, agentHint: "claude-vps-agent" }],+ byRuntime: [+ {+ runtime: "claudecode",+ fileCount: 0,+ agentHint: "claude-vps-agent",+ },+ ],totalFiles: 0,},},diff --git a/tests/discipline/report.test.ts b/tests/discipline/report.test.tsindex 1ab2fa6f..030e6a5d 100644--- a/tests/discipline/report.test.ts+++ b/tests/discipline/report.test.ts@@ -24,7 +24,9 @@ describe("runDisciplineReport", () => {const repo = join(vault, "repo");mkdirSync(repo);execSync("git init -q -b main", { cwd: repo });- execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", {+ cwd: repo,+ });writeFileSync(join(repo, "a.txt"), "hi\n");execSync("git add . && git commit -q -m c1", {cwd: repo,@@ -45,6 +47,49 @@ describe("runDisciplineReport", () => {rmSync(vault, { recursive: true });});+ test("end-to-end: high structure churn emits complexity warning", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-complexity-vault-"));+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n" ++ " enabled: true\n timezone: UTC\n" ++ " watched_paths:\n - " ++ vault ++ "/repo\n" ++ " known_agents:\n - '@claude-vps-agent'\n",+ "utf8",+ );++ const repo = join(vault, "repo");+ mkdirSync(repo);+ execSync("git init -q -b main", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", {+ cwd: repo,+ });+ for (let index = 0; index < 12; index++) {+ writeFileSync(join(repo, `structure-${index}.md`), "metadata only\n");+ }+ execSync("git add . && git commit -q -m structure", {+ cwd: repo,+ env: {+ ...process.env,+ GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z",+ GIT_AUTHOR_DATE: "2026-05-17T10:00:00Z",+ },+ });++ const res = runDisciplineReport({+ vault,+ now: new Date("2026-05-18T01:00:00Z"),+ });+ expect(res.status).toBe("alert");+ expect(res.activity?.complexity?.warning).toBe(true);+ expect(res.text).toContain("complexity");+ expect(res.text).toContain("productivity\\-trap");+ rmSync(vault, { recursive: true });+ });+test("disabled config β result.status='disabled', empty text", () => {const vault = mkdtempSync(join(tmpdir(), "o2b-disc-dis-"));mkdirSync(join(vault, "Brain"), { recursive: true });@@ -70,7 +115,11 @@ describe("runDisciplineReport", () => {test("malformed Brain config is not silently disabled", () => {const vault = mkdtempSync(join(tmpdir(), "o2b-disc-bad-"));mkdirSync(join(vault, "Brain"), { recursive: true });- writeFileSync(join(vault, "Brain", "_brain.yaml"), "not: valid: yaml\n", "utf8");+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "not: valid: yaml\n",+ "utf8",+ );expect(() => runDisciplineReport({ vault, now: new Date() })).toThrow();rmSync(vault, { recursive: true });});diff --git a/tests/mcp/brain-intent-review.test.ts b/tests/mcp/brain-intent-review.test.tsnew file mode 100644index 00000000..da4f0239--- /dev/null+++ b/tests/mcp/brain-intent-review.test.ts@@ -0,0 +1,63 @@+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 { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";++let vault: string;+let ctx: { vault: string; configPath: string };++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-intent-review-mcp-"));+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+ ctx = { vault, configPath: join(vault, "config.yaml") };+ for (let index = 0; index < 3; index++) {+ writeSignal(vault, {+ topic: "ready-topic",+ signal: "positive",+ agent: "test",+ principle: "ready topic principle",+ created_at: `2026-05-2${index + 1}T10:00:00Z`,+ date: `2026-05-2${index + 1}`,+ slug: `ready-topic-${index}`,+ });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("brain_intent_review MCP tool", () => {+ test("is registered and returns review entries", async () => {+ const tool = BRAIN_TOOLS.find(+ (entry) => entry.name === "brain_intent_review",+ );+ expect(tool).toBeDefined();+ const out = (await tool!.handler(ctx as any, {+ now: "2026-05-28T00:00:00Z",+ })) as Record<string, unknown>;+ expect(out["schema_version"]).toBe(1);+ expect(out["reviews"]).toEqual([+ expect.objectContaining({+ topic: "ready-topic",+ decision: "ready_for_main_review",+ }),+ ]);+ });++ test("rejects malformed now", async () => {+ const tool = BRAIN_TOOLS.find(+ (entry) => entry.name === "brain_intent_review",+ );+ await expect(+ tool!.handler(ctx as any, { now: "not-a-date" }),+ ).rejects.toMatchObject({+ code: -32602,+ });+ });+});diff --git a/tests/mcp/brain-monthly.test.ts b/tests/mcp/brain-monthly.test.tsnew file mode 100644index 00000000..d4d19b04--- /dev/null+++ b/tests/mcp/brain-monthly.test.ts@@ -0,0 +1,52 @@+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 { appendLogEvent } from "../../src/core/brain/log.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";++let vault: string;+let ctx: { vault: string; configPath: string };++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-monthly-mcp-"));+ mkdirSync(brainDirs(vault).log, { recursive: true });+ ctx = { vault, configPath: join(vault, "config.yaml") };+ appendLogEvent(vault, {+ timestamp: "2026-05-10T10:00:00Z",+ eventType: BRAIN_LOG_EVENT_KIND.feedback,+ body: { topic: "monthly", sign: "positive", agent: "test" },+ });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("brain_monthly_review MCP tool", () => {+ test("is registered and returns monthly summary", async () => {+ const tool = BRAIN_TOOLS.find(+ (entry) => entry.name === "brain_monthly_review",+ );+ expect(tool).toBeDefined();+ const out = (await tool!.handler(ctx as any, {+ month: "2026-05",+ })) as Record<string, unknown>;+ expect(out["month"]).toBe("2026-05");+ expect((out["summary"] as Record<string, unknown>)["events"]).toBe(1);+ });++ test("rejects malformed month", async () => {+ const tool = BRAIN_TOOLS.find(+ (entry) => entry.name === "brain_monthly_review",+ );+ await expect(+ tool!.handler(ctx as any, { month: "2026-13" }),+ ).rejects.toMatchObject({+ code: -32602,+ });+ });+});diff --git a/tests/mcp/brain-retention.test.ts b/tests/mcp/brain-retention.test.tsnew file mode 100644index 00000000..baac1c33--- /dev/null+++ b/tests/mcp/brain-retention.test.ts@@ -0,0 +1,55 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, renameSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { processedSignalPath, signalPath } from "../../src/core/brain/paths.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";++let vault: string;+let ctx: { vault: string; configPath: string };++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-retention-mcp-"));+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault, {});+ ctx = { vault, configPath: join(vault, "config.yaml") };+ writeSignal(vault, {+ topic: "discarded-signal",+ signal: "negative",+ agent: "test",+ principle: "old one-off signal",+ created_at: "2026-04-01T00:00:00Z",+ date: "2026-04-01",+ slug: "discarded-signal",+ });+ renameSync(+ signalPath(vault, "2026-04-01", "discarded-signal"),+ processedSignalPath(vault, "2026-04-01", "discarded-signal"),+ );+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("brain_retention MCP tool", () => {+ test("is registered and returns recommendations", async () => {+ const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_retention");+ expect(tool).toBeDefined();+ const out = (await tool!.handler(ctx as any, {+ now: "2026-05-28T00:00:00Z",+ })) as Record<string, unknown>;+ expect((out["summary"] as Record<string, unknown>)["prune"]).toBe(1);+ });++ test("rejects malformed now", async () => {+ const tool = BRAIN_TOOLS.find((entry) => entry.name === "brain_retention");+ expect(tool).toBeDefined();+ await expect(tool!.handler(ctx as any, { now: "not-a-date" })).rejects.toMatchObject({+ code: -32602,+ });+ });+});diff --git a/tests/mcp/brain-review-candidates.test.ts b/tests/mcp/brain-review-candidates.test.tsindex 6fc394f5..1e5cfdb3 100644--- a/tests/mcp/brain-review-candidates.test.ts+++ b/tests/mcp/brain-review-candidates.test.ts@@ -41,7 +41,7 @@ describe("brain_review_candidates MCP tool", () => {expect(tool?.inputSchema).toBeDefined();});- test("returns the six fields, all empty on a fresh vault", async () => {+ test("returns the review fields, all empty on a fresh vault", async () => {const tool = BRAIN_TOOLS.find((t) => t.name === "brain_review_candidates");expect(tool).toBeDefined();// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -54,5 +54,6 @@ describe("brain_review_candidates MCP tool", () => {expect(out["would_supersede"]).toEqual([]);expect(out["clusters_below_threshold"]).toEqual([]);expect(out["gated_retires"]).toEqual([]);+ expect(out["intent_reviews"]).toEqual([]);});});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex dc9aee67..105311dd 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -19,7 +19,12 @@ const savedEnv: Record<string, string | undefined> = {};beforeEach(() => {tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-test-"));- for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {+ for (const k of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -163,9 +168,11 @@ describe("tool listing", () => {id: 2,method: "tools/list",})) as any;- const names = new Set(r.result.tools.map((t: { name: string }) => t.name));+ const names = r.result.tools+ .map((tool: { name: string }) => tool.name)+ .toSorted();expect(names).toEqual(- new Set([+ [// Core read/health (writable legacy tools removed in v0.9.0)."second_brain_status","second_brain_query",@@ -178,9 +185,13 @@ describe("tool listing", () => {// brain_moc_audit added in v0.10.17,// brain_timeline / brain_belief_evolution / brain_stale_scan /// brain_daily_brief / brain_weekly_synthesis added in v0.10.18,- // brain_agent_query / brain_agent_diff added in v0.15.0).+ // brain_agent_query / brain_agent_diff added in v0.15.0,+ // lifecycle review tools added in v0.17.0."brain_feedback","brain_dream",+ "brain_intent_review",+ "brain_retention",+ "brain_monthly_review","brain_review_candidates","brain_apply_evidence","brain_note",@@ -214,11 +225,11 @@ describe("tool listing", () => {"payment_request_consume",// Search (added in v0.10.0)."brain_search",- ]),+ ].toSorted(),);// Explicit grep: legacy writable tools are no longer advertised.- expect(names.has("event_log_append")).toBe(false);- expect(names.has("second_brain_capture")).toBe(false);+ expect(names.includes("event_log_append")).toBe(false);+ expect(names.includes("second_brain_capture")).toBe(false);for (const t of r.result.tools) {expect(t.inputSchema.type).toBe("object");}@@ -274,7 +285,9 @@ describe("tool calls", () => {expect(s.vault.ignore_source).toBeDefined();expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);expect(Array.isArray(s.vault.rules)).toBe(true);- expect(s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian")).toBe(true);+ expect(+ s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian"),+ ).toBe(true);expect(typeof s.vault.included.files).toBe("number");expect(typeof s.vault.included.dirs).toBe("number");expect(typeof s.vault.excluded.dirs).toBe("number");@@ -335,7 +348,9 @@ describe("tool calls", () => {const s = r.result.structuredContent;expect(s.limit).toBe(5);expect(s.total_pages).toBeGreaterThanOrEqual(1);- expect(s.pages.some((p: { title: string }) => p.title.includes("Sandbox"))).toBe(true);+ expect(+ s.pages.some((p: { title: string }) => p.title.includes("Sandbox")),+ ).toBe(true);});// `second_brain_capture` and `event_log_append` are no longer@@ -385,7 +400,11 @@ describe("tool calls", () => {{name: "bad_contract",description: "test tool",- inputSchema: { type: "object", properties: {}, additionalProperties: false },+ inputSchema: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },outputSchema: {type: "object",required: ["ok"],@@ -398,7 +417,9 @@ describe("tool calls", () => {const r = (await callTool(server, "bad_contract")) as any;expect(r.result.isError).toBe(true);expect(r.result.structuredContent).toBeUndefined();- expect(r.result.content[0].text).toContain("bad_contract output contract failed");+ expect(r.result.content[0].text).toContain(+ "bad_contract output contract failed",+ );});});@@ -433,16 +454,14 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- // v0.16.0: 3 core + 24 Brain (brain_health added in v0.14.0+ // v0.17.0: 3 core + 27 Brain (brain_health added in v0.14.0// Semantic Brain Health; brain_review_candidates added in v0.12.0// Brain Integrity Suite; brain_timeline / brain_belief_evolution /// brain_stale_scan / brain_daily_brief / brain_weekly_synthesis- // added v0.10.18)- // brain_agent_query / brain_agent_diff added in v0.15.0)- // brain_agent_query / brain_agent_diff added in v0.15.0;- // brain_pinned_context added in v0.16.0)- // + 8 Pay Memory + 1 Search = 36.- expect(list.result.tools.length).toBe(36);+ // added v0.10.18; brain_agent_query / brain_agent_diff added in+ // v0.15.0; brain_pinned_context added in v0.16.0; lifecycle review+ // tools added in v0.17.0) + 8 Pay Memory + 1 Search = 39.+ expect(list.result.tools.length).toBe(39);});test("returns parse error for invalid JSON", async () => {