Skip to content

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

TypeScript

v0.9.1: active.md, MCP resources, quarantine, doctor hygiene lints

Sol Aitkena7b6955b4fba
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index bbb6c5e8..e8660784 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.9.0",
+ "version": "0.9.1",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 81d82fb6..319bbf03 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.9.0",
+ "version": "0.9.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c50f29d7..0d8caadc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,172 @@ 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.9.1] - 2026-05-15
+
+Active-preferences digest, MCP Resources, and a visibility expansion
+across status, digest, and backlinks. Closes `BRAIN-FUT-006`
+(active-preference injection per turn) and ships the read-only
+"visibility family" from the project's feature summary (Β§3 status,
+Β§8 backlinks, Β§13 hot preferences). Adds a `quarantine` preference
+status that catches rules whose recent evidence has turned dominantly
+negative without yet crossing the rebuttal threshold.
+
+### Added
+
+- **`Brain/active.md`** β€” an auto-generated digest of every confirmed
+ preference, every quarantined preference (with applied/violated
+ counters), and the three most recently retired entries. Pure
+ derivation, no LLM. Regenerated at the tail of every `dream` run
+ and after `o2b brain pin`/`unpin`. The writer is idempotent: when
+ the rendered body matches the existing file, no I/O happens.
+- **SessionStart hook** (`hooks/active-inject.ts`) with matcher
+ `startup|resume|clear`. Reads `Brain/active.md` and emits it as
+ `additionalContext` so the agent sees current rules at the start
+ of every session. Fails closed: any error path exits 0 with no
+ output so the runtime proceeds unaffected.
+- **PostCompact hook** with matcher `manual|auto`. Re-injects the
+ same `Brain/active.md` body after `/compact` (manual or
+ background), so the agent does not lose its preferences view
+ partway through long sessions. Same script as SessionStart β€” the
+ hook event name is taken from the payload so one script covers
+ both surfaces.
+- **MCP Resources** capability on the MCP server. Two concrete URIs:
+ - `osb://preferences/active` β€” body of `Brain/active.md`. Auto-
+ generated on first read if the file does not exist yet (fresh
+ vault with prefs but no dream).
+ - `osb://digest/latest` β€” `renderDigest({format: "markdown"})`
+ output, same as the `brain_digest` tool's default window.
+
+ Three URI templates:
+ - `osb://preference/{id}` β€” body of `pref-{id}.md`, with fallback
+ to `ret-{id}.md` when the active copy is gone. Accepts the bare
+ slug or the prefixed id.
+ - `osb://topic/{slug}` β€” synthesised markdown of every signal,
+ the current preference (or retired), and the most recent log
+ entries for the topic.
+ - `osb://log/{date}` β€” body of `Brain/log/<date>.md`.
+
+ The MCP initialize response advertises
+ `capabilities.resources = { listChanged: false, subscribe: false }`.
+- **`quarantine` preference status** (closes design summary Β§20).
+ Entry: a `confirmed` preference whose recomputed counters satisfy
+ `violated_count β‰₯ applied_count AND applied_count >
+ confidence.low_max_applied` transitions to `quarantine`. The rule
+ is still listed in `Brain/active.md` (under its own section), but
+ the digest surfaces it separately. Exit: a new `violated`
+ evidence event since the last `dream` snapshot retires the rule
+ with `retired_reason: quarantine-violated`; or a fresh
+ `applied_count > violated_count` returns it to `confirmed`. Pinned
+ quarantine preferences emit `retain-pinned` instead of retiring,
+ consistent with other automatic retires.
+- New `BRAIN_RETIRED_REASON.quarantineViolated = "quarantine-violated"`
+ enum value distinct from `rebutted` (which counts opposite-sign
+ signals, not evidence events).
+- **Backlink index** (`src/core/brain/backlinks.ts`). A single read
+ pass over `preferences/`, `retired/`, `inbox/`, `inbox/processed/`,
+ and `log/` produces an inverted reference map: target id β†’ list of
+ sources that wikilink to it, with `field` and (for log entries) the
+ event timestamp. Self-references and duplicate (source, target)
+ pairs are deduplicated. Powers digest Β§13 and the `brain_backlinks`
+ surfaces.
+- **`brain_backlinks` MCP tool** + `o2b brain backlinks <id>` CLI verb.
+ Returns the count plus a list of `{source, source_kind, field,
+ timestamp?}` records for any Brain artifact id (preference,
+ retired, or signal).
+- **`osb://backlinks/{id}` MCP resource template** β€” markdown render
+ of inbound references grouped by source kind. Same data as the
+ tool; the resource surface is for MCP hosts that prefer pull-style
+ access.
+- **Hot sections in `brain_digest`** (closes Β§13). Two new sections
+ in both Markdown and JSON outputs:
+ - **Top applied** β€” top-5 confirmed/quarantine preferences by
+ `applied_count` desc (zero-applied excluded). JSON field:
+ `top_applied`.
+ - **Top referenced** β€” top-5 preferences by inbound backlink
+ count (using the index above). JSON field: `top_referenced`.
+
+ The sections render only on non-empty windows so `--silent-if-empty`
+ exit semantics are preserved; JSON always emits the arrays so
+ programmatic consumers can read them regardless of window state.
+- **`broken-backlinks` lint** in `brain_doctor`. Walks the backlink
+ index and reports any source that still references a `pref-*`,
+ `ret-*`, or `sig-*` target whose file no longer exists. Warning
+ severity (not error), since the underlying state isn't corrupted
+ β€” the source artifact's pointer just went stale.
+- **`brain` section in `second_brain_status`**. The existing MCP
+ tool now includes a `brain: { present, counts, last_dream_at,
+ last_apply_evidence_at, sanity }` field. Counts cover
+ inbox/preferences (split by status)/retired/log_days/snapshots.
+ `sanity.signals_awaiting_dream` is non-zero when inbox signals
+ predate the `unconfirmed_window_days` cutoff β€” a one-glance "you
+ need to run `dream`" signal.
+- **`osb://status` concrete MCP resource** β€” the same snapshot
+ rendered as markdown for direct pull by MCP hosts.
+
+### Changed
+
+- `regenerateActive(vault)` is now called at the tail of every
+ `dream` invocation (both `changed: false` and `changed: true`
+ paths), gated on `dryRun: false`. Failure is logged to stderr and
+ swallowed β€” the rest of `dream`'s work is independent.
+- `setPinned` calls `regenerateActive` after a successful flip so
+ the `pinned` flag visible in the digest matches the new state
+ immediately. Same swallow-and-warn fallback as in `dream`.
+- `renderDigest` JSON shape gains `top_applied` and `top_referenced`
+ arrays. `schema_version` stays at `1` β€” both fields default to
+ empty arrays, so existing readers that ignore unknown fields
+ remain compatible.
+- **Input sanitisation** for Brain writers. The Pay Memory redactor
+ is promoted to `src/core/redactor.ts` (Pay Memory keeps the import
+ path) and joined by a new `normaliseTextField` helper that strips
+ C0 control characters (except `\t` / `\n`), folds `U+2028` /
+ `U+2029` line separators to `\n`, NFC-normalises, and caps length.
+ `writeSignal` runs `principle` (cap 512, single-line), `scope`
+ (cap 128, single-line), `raw` (cap 4096), and `source[]` items
+ (cap 512) through redact + normalise. `appendApplyEvidence`
+ applies the same to `artifact` (cap 512, single-line) and `note`
+ (cap 4096). Inputs that sanitise down to empty (e.g. pure C0
+ bytes) raise the existing `missing field` error rather than
+ smuggling into YAML.
+- **`outdated` apply-evidence result** (`BRAIN_APPLY_RESULT.outdated`).
+ Records that a preference's scope still matched the artifact but
+ the rule itself is obsolete in this context (framework migration,
+ convention change). Dream interprets any `outdated` event as a
+ retire trigger with new reason
+ `BRAIN_RETIRED_REASON.supersededByContext` =
+ `"superseded-by-context"`. Pin protects against decay-driven
+ retires only; an `outdated` event is an explicit context shift
+ and bypasses the pin. CLI and MCP tool schema accept the new
+ enum value.
+- **Claim-level provenance in apply-evidence artifacts**. The
+ `artifact` wikilink optionally carries an inclusive 1-based line
+ range: `[[src/cli/main.ts:120-145]]` (range) or
+ `[[src/cli/main.ts:42]]` (single line). New
+ `parseArtifactRef(value)` helper in
+ `src/core/brain/wikilink.ts` extracts `{target, range?,
+ malformedRange?}`. The writer accepts the syntax verbatim; the
+ parser is used by downstream readers (lint, future fragment
+ display).
+- **`brain_doctor` hygiene lints** (closes the remaining Β§11 items
+ from the project's feature summary):
+ - `duplicate-preferences` β€” pairwise jaccard β‰₯ 0.7 on principle
+ tokens within each `(topic, scope)` bucket of confirmed /
+ quarantine preferences.
+ - `low-evidence-confirmed` β€” confirmed pref with
+ `applied_count ≀ low_max_applied` and `confirmed_at` older
+ than `unconfirmed_window_days`.
+ - `pinned-without-recent-evidence` β€” pinned pref with no
+ `last_evidence_at` or with evidence older than
+ `stale_evidence_days`.
+ - `malformed-evidence-range` β€” apply-evidence artifact uses
+ range syntax but the range fails validation (non-numeric,
+ reversed, zero-based, dangling dash).
+ - `orphan-evidence` β€” apply-evidence artifact wikilink doesn't
+ resolve to any file in the vault (basename match via
+ `listVaultPages`).
+- `runDoctor` accepts an `opts.now` for deterministic age-based
+ testing. CLI `--strict` semantics unchanged.
+
## [0.9.0] - 2026-05-15
Brain: a new top-level vault layer for observing, accreting memory.
diff --git a/docs/mcp.md b/docs/mcp.md
index 0d44daee..3042c97d 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -78,6 +78,44 @@ All tool results contain both an unstructured `content` text block (a JSON
serialization of the structured payload) and a `structuredContent` object so
clients that prefer typed results can use it directly.
+## Resources
+
+The server also exposes a `resources` capability for hosts that prefer
+pull-style access (no tool call, no arguments). Three concrete URIs
+come back from `resources/list`:
+
+- `osb://preferences/active` β€” body of `Brain/active.md`, the auto-
+ generated digest of confirmed + quarantined preferences plus the
+ last three retired entries. Auto-regenerated on first read if the
+ file does not exist yet.
+- `osb://digest/latest` β€” same body as the `brain_digest` tool's
+ default (24h) Markdown window.
+- `osb://status` β€” Brain operational snapshot: counts (inbox /
+ preferences by status / retired / log_days / snapshots), last
+ `dream` and `apply-evidence` timestamps, and a sanity flag for
+ signals awaiting `dream`. Same data the `second_brain_status`
+ tool returns under its `brain` field, rendered as markdown.
+
+Four templated URIs come back from `resources/templates/list`:
+
+- `osb://preference/{id}` β€” body of `pref-{id}.md`, with fallback to
+ `ret-{id}.md` when the active copy is gone. Accepts the bare slug
+ (`my-rule`) or the prefixed form (`pref-my-rule` / `ret-my-rule`).
+- `osb://topic/{slug}` β€” synthesised markdown of every signal, the
+ current preference (or retired), and the most recent log entries
+ for the topic.
+- `osb://log/{date}` β€” body of `Brain/log/<date>.md` (date is
+ `YYYY-MM-DD`).
+- `osb://backlinks/{id}` β€” inbound references to the given Brain
+ artifact id, rendered as a count plus a list grouped by source
+ kind. Same data as the `brain_backlinks` tool.
+
+`resources/read` accepts both shapes uniformly and returns
+`text/markdown` content. Malformed slug/date arguments produce
+`INVALID_PARAMS`; missing files produce a tool-level error envelope
+with a `not found` message β€” same shape as `brain_query`'s
+`BrainNotFoundError`.
+
## Run from the CLI
```bash
diff --git a/docs/plans/2026-05-15-brain-roadmap.md b/docs/plans/2026-05-15-brain-roadmap.md
index aabac248..d161ea41 100644
--- a/docs/plans/2026-05-15-brain-roadmap.md
+++ b/docs/plans/2026-05-15-brain-roadmap.md
@@ -113,18 +113,20 @@ The document is **trigger-based**, not schedule-based. Each item has an explicit
### BRAIN-FUT-006 β€” Active-preference injection via per-turn hook
-**Trigger to pull forward:**
-- β‰₯10 confirmed preferences in `Brain/preferences/`, AND
-- Observed cases where the agent did not apply a relevant active preference in a task despite the `brain-memory` skill being loaded.
-
-**Dependencies:** v0.9 ships. Reuses existing Hermes `pre_llm_call` channel, Claude Code system-prompt prepend, and Codex pre-message hook.
-
-**Scope sketch:**
-- A shared module (per-runtime plugin, e.g. `~/.hermes/plugins/brain-preference-injector/`) reads `Brain/preferences/` filtered to `status: confirmed` and to scopes matching the current task topic; injects a compact summary into the per-turn system prompt.
-- Hard token budget on the injection (e.g. 500 tokens) to avoid context-window bloat.
-- Pinned preferences ordered first; high-confidence next; remainder may be elided if over budget.
-
-**Why deferred:** with zero confirmed preferences the injection is empty. Even with a few, the noise-to-signal ratio is unfavourable. The trigger waits until the injection actually carries useful content.
+**Status: shipped in v0.9.1.** Implemented via a file-based pattern
+rather than the per-turn token-budgeted injection sketched below: the
+deterministic `dream` pass regenerates `Brain/active.md` (a derived
+view of confirmed + quarantined preferences plus the last three
+retired entries) and the SessionStart + PostCompact hook injects that
+file's body as `additionalContext` on every session boundary and
+after `/compact`. MCP hosts can pull the same body on demand via
+`osb://preferences/active`. See the v0.9.1 CHANGELOG entry for the
+full surface and `docs/mcp.md` for the resource URIs.
+
+The token-budgeted per-turn variant is no longer planned β€” the
+session-boundary cadence is cheap and sufficient. If a future
+profile shows the per-turn budget is necessary, it can be reopened
+under a new ID with the actual measured data.
## Integration
diff --git a/hooks/active-inject.ts b/hooks/active-inject.ts
new file mode 100644
index 00000000..895f4cbc
--- /dev/null
+++ b/hooks/active-inject.ts
@@ -0,0 +1,85 @@
+#!/usr/bin/env -S bun
+/**
+ * SessionStart / PostCompact hook: inject the current `Brain/active.md`
+ * digest as `additionalContext` so the agent sees the live set of
+ * confirmed and quarantined preferences without explicitly calling
+ * `brain_query` first.
+ *
+ * Contract (identical for Claude Code and Codex):
+ * stdin: hook payload JSON. The vault path is resolved from the
+ * persisted Open Second Brain config (env `VAULT_DIR` β†’ config
+ * `vault:` field), not from the payload β€” both runtimes route the
+ * hook through the same `o2b-hook` PATH-shim, so this stays
+ * runtime-agnostic.
+ * stdout: JSON of the shape
+ * {
+ * "hookSpecificOutput": {
+ * "hookEventName": "SessionStart" | "PostCompact",
+ * "additionalContext": "<rendered Brain/active.md body>"
+ * }
+ * }
+ *
+ * Quiet on every failure mode (no config, no vault, no `Brain/active.md`,
+ * malformed payload, missing file): the hook exits 0 with no output and
+ * the runtime proceeds as if the hook never ran. A SessionStart that
+ * silently fails is far less harmful than one that aborts the session
+ * with a stderr trace. The agent simply does not get the per-session
+ * preferences nudge β€” exactly the v0.9.0 behaviour.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+
+import { resolveVault } from "../src/core/config.ts";
+import { brainActivePath } from "../src/core/brain/paths.ts";
+import { asHookPayload, readHookInput } from "./lib/stdin.ts";
+
+async function main(): Promise<void> {
+ let payload;
+ try {
+ payload = asHookPayload(await readHookInput());
+ } catch {
+ return;
+ }
+
+ // The hook is registered separately for each event; the payload's
+ // `hook_event_name` tells us which one fired. Echo the same name
+ // back unchanged so the runtime correlates request and response
+ // β€” including any future event we have not yet enumerated here.
+ // Default to `SessionStart` only when the field is missing entirely
+ // (e.g. an empty stdin payload, or a runtime that doesn't populate
+ // the name); a coerced unknown value would silently misreport
+ // which event fired.
+ const hookEventName =
+ typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0
+ ? payload.hook_event_name
+ : "SessionStart";
+
+ const vault = resolveVault();
+ if (vault === null) return;
+
+ const activePath = brainActivePath(vault);
+ if (!existsSync(activePath)) return;
+
+ let body: string;
+ try {
+ body = readFileSync(activePath, "utf8");
+ } catch {
+ return;
+ }
+
+ const trimmed = body.trim();
+ if (trimmed.length === 0) return;
+
+ const out = {
+ hookSpecificOutput: {
+ hookEventName,
+ additionalContext: trimmed,
+ },
+ };
+ process.stdout.write(JSON.stringify(out) + "\n");
+}
+
+main().catch(() => {
+ // Never crash the runtime; the session start should proceed
+ // regardless of any hook misbehaviour.
+});
diff --git a/hooks/hooks.json b/hooks/hooks.json
index 9c32dc13..f0fe2496 100644
--- a/hooks/hooks.json
+++ b/hooks/hooks.json
@@ -12,6 +12,32 @@
}
]
}
+ ],
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "o2b-hook active-inject",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting active preferences"
+ }
+ ]
+ }
+ ],
+ "PostCompact": [
+ {
+ "matcher": "manual|auto",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "o2b-hook active-inject",
+ "timeout": 10,
+ "statusMessage": "OSB: re-injecting active preferences after compact"
+ }
+ ]
+ }
]
}
}
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index aeb74aa7..36b1793b 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.9.0",
+ "version": "0.9.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index c95bbb1d..352c01dc 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.9.0",
+ "version": "0.9.1",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index 63776787..3d11dd35 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.9.0"
+version: "0.9.1"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index fe68f172..ca4bc433 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.9.0",
+ "version": "0.9.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 5a823bc6..62c134b1 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.9.0"
+version: "0.9.1"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index da7b4fb2..32469c6e 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.9.0"
+version = "0.9.1"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index b5b916d6..94325491 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -30,6 +30,8 @@ import {
resolveAgentName,
resolveVault,
} from "../core/config.ts";
+import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
+import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
import { bootstrapBrain } from "../core/brain/init.ts";
import {
appendApplyEvidence,
@@ -408,8 +410,14 @@ async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
const resultStr = String(flags["result"]);
- if (resultStr !== "applied" && resultStr !== "violated") {
- return fail(`--result must be 'applied' or 'violated'; got ${resultStr}`);
+ if (
+ resultStr !== "applied" &&
+ resultStr !== "violated" &&
+ resultStr !== "outdated"
+ ) {
+ return fail(
+ `--result must be 'applied', 'violated', or 'outdated'; got ${resultStr}`,
+ );
}
try {
@@ -808,6 +816,42 @@ async function cmdBrainRollback(argv: string[]): Promise<number> {
return 0;
}
+async function cmdBrainBacklinks(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const id = positional[0];
+ if (!id) {
+ return fail("brain backlinks requires a target id (e.g. pref-foo, ret-bar, sig-...)");
+ }
+ // Run the input through the same normaliser the index uses so a
+ // wikilink-shaped argument (`[[pref-foo]]`, `pref-foo.md`) resolves.
+ const target = normaliseWikilinkTarget(id);
+ const index = buildBacklinkIndex(vault);
+ const refs = index.get(target) ?? [];
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify({ id: target, count: refs.length, refs }, null, 2) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(`Backlinks to ${target}: ${refs.length}\n`);
+ if (refs.length === 0) return 0;
+ for (const r of refs) {
+ const ts = r.timestamp ? ` @ ${r.timestamp}` : "";
+ process.stdout.write(
+ ` ${r.source} (${r.sourceKind}, field: ${r.field})${ts}\n`,
+ );
+ }
+ return 0;
+}
+
async function cmdBrainDoctor(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
@@ -871,6 +915,7 @@ Brain verbs (observing memory):
unpin Clear the pinned flag (idempotent)
rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes)
doctor Validate Brain invariants (--strict promotes warnings to exit 2)
+ backlinks List inbound references to a Brain artifact id
Common flags:
--vault <path> Override the configured vault
@@ -891,7 +936,7 @@ const VERB_HELP: Record<string, string> = {
"usage: o2b brain dream [--vault <path>] [--dry-run] [--now <ISO-8601>] [--json]\n" +
"Runs the deterministic dreaming algorithm. Idempotent on rerun.\n",
"apply-evidence":
- "usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated\n" +
+ "usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
" [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
"Appends a single event to today's log. Missing preference exits 2.\n",
digest:
@@ -916,6 +961,9 @@ const VERB_HELP: Record<string, string> = {
doctor:
"usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +
"Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n",
+ backlinks:
+ "usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
+ "List inbound references to the given Brain artifact id (preference, retired, signal).\n",
};
// ── Public entry point ──────────────────────────────────────────────────────
@@ -973,6 +1021,8 @@ export async function handleBrainSubcommand(
return await cmdBrainRollback(rest);
case "doctor":
return await cmdBrainDoctor(rest);
+ case "backlinks":
+ return await cmdBrainBacklinks(rest);
default:
process.stderr.write(`error: unknown brain verb: ${verb}\n`);
process.stdout.write(BRAIN_HELP);
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
new file mode 100644
index 00000000..2d078c27
--- /dev/null
+++ b/src/core/brain/active.ts
@@ -0,0 +1,297 @@
+/**
+ * `Brain/active.md` β€” the auto-generated active-preferences digest.
+ *
+ * The file is a derived view of `Brain/preferences/` (status `confirmed`
+ * and `quarantine`) plus the three most recent entries in
+ * `Brain/retired/`. It is regenerated at the tail of every `dream`
+ * pass and after CLI verbs that mutate preferences directly (pin,
+ * unpin, future reject). It is read by:
+ *
+ * - the SessionStart / PostCompact hook β†’ injected as
+ * `additionalContext` so the agent sees current rules at the start
+ * of every session and after `/compact`;
+ * - the MCP resource `osb://preferences/active` so MCP-capable hosts
+ * can pull it on demand.
+ *
+ * Properties:
+ *
+ * - **Pure derivation.** No LLM, no network, no clock-dependent
+ * content beyond the `generated_at` stamp. Identical inputs
+ * produce identical *bodies* β€” the function only varies the
+ * frontmatter timestamp.
+ * - **Idempotent write.** The body (everything below the
+ * frontmatter) is compared against the existing file's body
+ * before writing. When equal, the file is left untouched so a
+ * no-op `dream` rerun does not bump mtime or cause Obsidian to
+ * re-render the open tab.
+ * - **Atomic write.** Uses `atomicWriteFileSync` so a crash
+ * mid-render leaves the previous version intact.
+ *
+ * Anchored in the v0.9.1 plan ("Brain/active.md + SessionStart /
+ * PostCompact hook + MCP resources") which closes BRAIN-FUT-006.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { parseFrontmatter } from "../vault.ts";
+import { parsePreference, parseRetired } from "./preference.ts";
+import { brainActivePath, brainDirs } from "./paths.ts";
+import { isoSecond } from "./time.ts";
+import {
+ BRAIN_PREFERENCE_STATUS,
+ type BrainPreference,
+ type BrainRetired,
+} from "./types.ts";
+
+const RECENTLY_RETIRED_COUNT = 3;
+
+const FRONTMATTER_KIND = "brain-active";
+
+export interface RegenerateActiveOptions {
+ /** Wall clock for `generated_at`. Defaults to `new Date()`. */
+ readonly now?: Date;
+}
+
+export interface RegenerateActiveResult {
+ /** Absolute path of the written file. */
+ readonly path: string;
+ /** Whether the rendered body differed from the previous file content. */
+ readonly changed: boolean;
+ readonly counts: {
+ readonly confirmed: number;
+ readonly quarantine: number;
+ readonly retired_recent: number;
+ };
+}
+
+/**
+ * Regenerate `<vault>/Brain/active.md`. Returns whether the body
+ * actually changed (callers don't need to skip the call themselves β€”
+ * the function makes the right decision internally).
+ *
+ * Errors thrown by individual preference / retired parsers are caught
+ * and the offending file is omitted from the render. The function
+ * does not raise on parse failures because a single corrupted
+ * frontmatter must not break the agent's view of every healthy rule.
+ * Corruption is the domain of `brain_doctor`; this writer's job is to
+ * surface what is currently knowable.
+ */
+export function regenerateActive(
+ vault: string,
+ opts: RegenerateActiveOptions = {},
+): RegenerateActiveResult {
+ const now = opts.now ?? new Date();
+ const path = brainActivePath(vault);
+
+ const preferences = readActivePreferences(vault);
+ const retiredRecent = readRecentlyRetired(vault, RECENTLY_RETIRED_COUNT);
+
+ const confirmed = preferences
+ .filter((p) => p.status === BRAIN_PREFERENCE_STATUS.confirmed)
+ .sort(sortByConfidenceThenId);
+ const quarantine = preferences
+ .filter((p) => p.status === BRAIN_PREFERENCE_STATUS.quarantine)
+ .sort(sortByIdAscending);
+
+ const body = renderBody({
+ confirmed,
+ quarantine,
+ retiredRecent,
+ });
+
+ // `readExistingBody` returns the trimmed body (parseFrontmatter
+ // trims internally), so compare against the trimmed render for an
+ // apples-to-apples byte check.
+ const existingBody = readExistingBody(path);
+ const changed = existingBody === null || existingBody !== body.trim();
+ if (changed) {
+ const document = renderDocument(body, isoSecond(now));
+ atomicWriteFileSync(path, document);
+ }
+
+ return {
+ path,
+ changed,
+ counts: {
+ confirmed: confirmed.length,
+ quarantine: quarantine.length,
+ retired_recent: retiredRecent.length,
+ },
+ };
+}
+
+/**
+ * Wrapper around {@link regenerateActive} that swallows failures with a
+ * stderr warning. Used by `dream` and `setPinned` β€” both treat the
+ * digest as a derived view: when its write fails (disk full,
+ * permissions, etc.), the real state-changing work is still valid
+ * and the next call will retry. We don't want a missing summary file
+ * to mask the success of the underlying operation.
+ *
+ * Exported as the single source of truth for fire-and-warn semantics
+ * so the same swallow shape isn't copy-pasted at each call site.
+ */
+export function regenerateActiveQuiet(
+ vault: string,
+ opts: RegenerateActiveOptions = {},
+): void {
+ try {
+ regenerateActive(vault, opts);
+ } catch (err) {
+ process.stderr.write(
+ `warning: regenerate active.md failed: ${(err as Error).message}\n`,
+ );
+ }
+}
+
+// ----- Scan helpers --------------------------------------------------------
+
+function readActivePreferences(vault: string): BrainPreference[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.preferences)) return [];
+ const out: BrainPreference[] = [];
+ for (const name of readdirSync(dirs.preferences)) {
+ if (!name.endsWith(".md")) continue;
+ const full = join(dirs.preferences, name);
+ try {
+ out.push(parsePreference(full));
+ } catch {
+ // Corrupted or status/folder-mismatched file β€” silently omit
+ // here. `brain_doctor` is the surface that flags it. See the
+ // module docblock for the rationale.
+ }
+ }
+ return out;
+}
+
+function readRecentlyRetired(vault: string, limit: number): BrainRetired[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.retired)) return [];
+ const out: BrainRetired[] = [];
+ for (const name of readdirSync(dirs.retired)) {
+ if (!name.endsWith(".md")) continue;
+ const full = join(dirs.retired, name);
+ try {
+ out.push(parseRetired(full));
+ } catch {
+ // Same rationale as readActivePreferences.
+ }
+ }
+ out.sort((a, b) => {
+ const ta = Date.parse(a.retired_at);
+ const tb = Date.parse(b.retired_at);
+ if (Number.isNaN(ta) || Number.isNaN(tb)) return 0;
+ return tb - ta; // newest first
+ });
+ return out.slice(0, limit);
+}
+
+// ----- Render helpers ------------------------------------------------------
+
+interface RenderInput {
+ readonly confirmed: ReadonlyArray<BrainPreference>;
+ readonly quarantine: ReadonlyArray<BrainPreference>;
+ readonly retiredRecent: ReadonlyArray<BrainRetired>;
+}
+
+function renderBody(input: RenderInput): string {
+ const out: string[] = [];
+ out.push("# Active Brain Preferences");
+ out.push("");
+ out.push("Auto-generated by `dream`. Do not edit β€” changes will be overwritten.");
+ out.push("");
+
+ out.push(`## Confirmed (${input.confirmed.length})`);
+ out.push("");
+ if (input.confirmed.length === 0) {
+ out.push("_No confirmed preferences yet._");
+ } else {
+ for (const p of input.confirmed) out.push(renderConfirmedLine(p));
+ }
+ out.push("");
+
+ if (input.quarantine.length > 0) {
+ out.push(`## Quarantine (${input.quarantine.length})`);
+ out.push("");
+ out.push(
+ "_Probationary rules β€” still active, but recent evidence is dominantly negative. One further `violated` evidence event retires the rule._",
+ );
+ out.push("");
+ for (const p of input.quarantine) out.push(renderQuarantineLine(p));
+ out.push("");
+ }
+
+ if (input.retiredRecent.length > 0) {
+ out.push(`## Recently retired (last ${input.retiredRecent.length})`);
+ out.push("");
+ for (const r of input.retiredRecent) out.push(renderRetiredLine(r));
+ out.push("");
+ }
+
+ // Trim trailing blank line so consecutive renders compare cleanly.
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
+ return out.join("\n") + "\n";
+}
+
+function renderConfirmedLine(p: BrainPreference): string {
+ const tags: string[] = [];
+ if (p.scope) tags.push(`scope: ${p.scope}`);
+ tags.push(`confidence: ${p.confidence}`);
+ if (p.pinned) tags.push("pinned");
+ return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
+}
+
+function renderQuarantineLine(p: BrainPreference): string {
+ const tags: string[] = [];
+ if (p.scope) tags.push(`scope: ${p.scope}`);
+ tags.push(`applied: ${p.applied_count} / violated: ${p.violated_count}`);
+ if (p.pinned) tags.push("pinned");
+ return `- \`${p.id}\` (${tags.join(", ")}) β€” ${p.principle}`;
+}
+
+function renderRetiredLine(r: BrainRetired): string {
+ const date = r.retired_at.slice(0, 10);
+ return `- \`${r.id}\` β€” ${r.retired_reason} on ${date}`;
+}
+
+function renderDocument(body: string, generatedAt: string): string {
+ const lines: string[] = [
+ "---",
+ `kind: ${FRONTMATTER_KIND}`,
+ `generated_at: ${generatedAt}`,
+ "---",
+ "",
+ body.trimEnd(),
+ "",
+ ];
+ return lines.join("\n");
+}
+
+function readExistingBody(path: string): string | null {
+ if (!existsSync(path)) return null;
+ try {
+ const [, body] = parseFrontmatter(path);
+ // `parseFrontmatter` returns the body already stripped of the
+ // frontmatter block and leading separator newline. We compare
+ // against `renderBody`'s output, which also lacks frontmatter β€”
+ // both sides go through the same trim semantics so the
+ // idempotency check is byte-correct without bespoke regex work.
+ return body;
+ } catch {
+ return null;
+ }
+}
+
+function sortByConfidenceThenId(a: BrainPreference, b: BrainPreference): number {
+ const order = { high: 0, medium: 1, low: 2 } as const;
+ const ca = order[a.confidence];
+ const cb = order[b.confidence];
+ if (ca !== cb) return ca - cb;
+ return a.id.localeCompare(b.id);
+}
+
+function sortByIdAscending(a: BrainPreference, b: BrainPreference): number {
+ return a.id.localeCompare(b.id);
+}
diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.ts
index a8dc8860..d3877c79 100644
--- a/src/core/brain/apply-evidence.ts
+++ b/src/core/brain/apply-evidence.ts
@@ -31,6 +31,7 @@
import { existsSync } from "node:fs";
+import { sanitiseTextField } from "../redactor.ts";
import { appendLogEvent, type AppendLogEventResult, type BrainLogEntry } from "./log.ts";
import { parsePreference } from "./preference.ts";
import { preferencePath, validateSlug } from "./paths.ts";
@@ -41,6 +42,9 @@ import {
type BrainApplyResult,
} from "./types.ts";
+const ARTIFACT_MAX_LEN = 512;
+const NOTE_MAX_LEN = 4096;
+
/**
* Thrown by {@link appendApplyEvidence} when the targeted preference
* does not exist on disk. The CLI surfaces this as exit code 2 (not an
@@ -114,7 +118,17 @@ export function appendApplyEvidence(
if (!input.pref_id || !input.pref_id.trim()) {
throw new Error("apply-evidence missing field: pref_id");
}
- if (!input.artifact || !input.artifact.trim()) {
+ // Sanitise free-form fields up-front so a pure-control-char input
+ // falls into the "missing-field" branch instead of into YAML.
+ const artifact = sanitiseTextField(input.artifact, {
+ maxLen: ARTIFACT_MAX_LEN,
+ singleLine: true,
+ });
+ const note =
+ input.note !== undefined
+ ? sanitiseTextField(input.note, { maxLen: NOTE_MAX_LEN })
+ : undefined;
+ if (!artifact || !artifact.trim()) {
throw new Error("apply-evidence missing field: artifact");
}
if (!input.agent || !input.agent.trim()) {
@@ -122,10 +136,11 @@ export function appendApplyEvidence(
}
if (
input.result !== BRAIN_APPLY_RESULT.applied &&
- input.result !== BRAIN_APPLY_RESULT.violated
+ input.result !== BRAIN_APPLY_RESULT.violated &&
+ input.result !== BRAIN_APPLY_RESULT.outdated
) {
throw new Error(
- `apply-evidence field 'result' must be 'applied' or 'violated'; got ${JSON.stringify(input.result)}`,
+ `apply-evidence field 'result' must be 'applied', 'violated', or 'outdated'; got ${JSON.stringify(input.result)}`,
);
}
@@ -157,12 +172,12 @@ export function appendApplyEvidence(
// input are omitted so the file stays as small as possible.
const body: Record<string, string> = {
preference: wikilink,
- artifact: input.artifact.trim(),
+ artifact: artifact.trim(),
agent: input.agent.trim(),
result: input.result,
};
- const note = input.note?.trim();
- if (note) body["note"] = note;
+ const trimmedNote = note?.trim();
+ if (trimmedNote) body["note"] = trimmedNote;
const entry: BrainLogEntry = {
timestamp,
diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.ts
new file mode 100644
index 00000000..e413e025
--- /dev/null
+++ b/src/core/brain/backlinks.ts
@@ -0,0 +1,228 @@
+/**
+ * Backlink index over the Brain layer.
+ *
+ * A "backlink" is any reference from one Brain artifact to another's
+ * id via the Obsidian wikilink form `[[<id>]]`. The index inverts this
+ * graph: given a target id, return every source that points at it.
+ *
+ * Sources walked:
+ *
+ * - `Brain/preferences/pref-*.md` β€” frontmatter (`supersedes`,
+ * `evidenced_by[]`) and the body prose (any embedded `[[...]]`).
+ * - `Brain/retired/ret-*.md` β€” same fields, plus `superseded_by` and
+ * `retired_by`.
+ * - `Brain/log/<YYYY-MM-DD>.md` β€” every event whose payload references
+ * a preference (`preference`, `signal`, `superseded_by`, `run_id`,
+ * etc.). The log is append-only so we don't lose history.
+ *
+ * The index is recomputed on demand (no on-disk cache). The cost is
+ * O(N+L) parse work per build where N is preferences+retired+signals
+ * and L is total log entries. For typical vaults this is a small
+ * fraction of `dream`'s cost; a smarter cache can land later if a
+ * profile shows it pays.
+ *
+ * Pure read. Skips files that fail to parse β€” `brain_doctor` is the
+ * surface that flags malformed artifacts, not this aggregator.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { extractWikilinks, parseFrontmatter } from "../vault.ts";
+import { parseLogDay } from "./log.ts";
+import { brainDirs } from "./paths.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+
+// ----- Public types --------------------------------------------------------
+
+export type BacklinkSourceKind =
+ | "preference"
+ | "retired"
+ | "signal"
+ | `log-${string}`;
+
+export interface BacklinkRef {
+ /** Source id (basename without `.md`, e.g. `pref-foo`, `ret-bar`, `sig-2026-05-14-baz`). */
+ readonly source: string;
+ /** Where the reference lives. `log-<kind>` for log entries (e.g. `log-apply-evidence`). */
+ readonly sourceKind: BacklinkSourceKind;
+ /** Field name carrying the reference (`principle`, `supersedes`, body text, etc.). */
+ readonly field: string;
+ /** ISO-8601 timestamp for log entries; absent for preference/retired sources. */
+ readonly timestamp?: string;
+}
+
+/** Frozen target β†’ refs map. Keys are normalised wikilink targets. */
+export type BacklinkIndex = ReadonlyMap<string, ReadonlyArray<BacklinkRef>>;
+
+// ----- Public API ----------------------------------------------------------
+
+/**
+ * Build the inverted reference index for the current Brain state.
+ *
+ * The returned map is frozen and each entry's array is frozen too β€”
+ * callers cannot mutate the shared index. Recompute by calling this
+ * function again; there is no incremental update path on purpose.
+ */
+export function buildBacklinkIndex(vault: string): BacklinkIndex {
+ const dirs = brainDirs(vault);
+ const map = new Map<string, BacklinkRef[]>();
+ // Dedup key: `<source>\x00<target>`. Preference body mirrors
+ // frontmatter `evidenced_by` (rendered as "## Origin" bullets), so a
+ // naive walk double-counts every pref→signal edge. We keep the
+ // first-seen field (frontmatter) and drop later duplicates.
+ const seen = new Set<string>();
+
+ const push = (target: string, ref: BacklinkRef): void => {
+ const norm = normaliseWikilinkTarget(target);
+ if (!norm || norm === ref.source) return; // skip self-refs and empties
+ const key = `${ref.source}\x00${norm}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ const arr = map.get(norm);
+ if (arr) arr.push(ref);
+ else map.set(norm, [ref]);
+ };
+
+ collectPreferences(dirs.preferences, "preference", push);
+ collectPreferences(dirs.retired, "retired", push);
+ collectSignals(dirs.inbox, push);
+ collectSignals(dirs.processed, push);
+ collectLog(vault, dirs.log, push);
+
+ // Freeze each entry's array so downstream callers can't mutate the
+ // shared index.
+ const frozen = new Map<string, ReadonlyArray<BacklinkRef>>();
+ for (const [k, v] of map) frozen.set(k, Object.freeze(v));
+ return frozen;
+}
+
+/**
+ * Convenience: count of inbound references for one target id. Equal to
+ * `(index.get(target) ?? []).length`. Kept as a named helper so call
+ * sites that only need the count don't fight `undefined`.
+ */
+export function backlinkCount(index: BacklinkIndex, target: string): number {
+ const norm = normaliseWikilinkTarget(target);
+ return index.get(norm)?.length ?? 0;
+}
+
+// ----- Collectors ----------------------------------------------------------
+
+function collectPreferences(
+ dir: string,
+ kind: "preference" | "retired",
+ push: (target: string, ref: BacklinkRef) => void,
+): void {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const full = join(dir, name);
+ const source = name.slice(0, -".md".length);
+ // Single read: pull both frontmatter and body in one pass so we
+ // don't pay 2Γ— readFileSync per preference on every index build.
+ // Field extraction is defensive β€” schema enforcement is the
+ // doctor's job, not the backlink scanner's.
+ let meta: Record<string, unknown>;
+ let body: string;
+ try {
+ [meta, body] = parseFrontmatter(full);
+ } catch {
+ continue;
+ }
+
+ const evidenced = meta["evidenced_by"];
+ if (Array.isArray(evidenced)) {
+ for (const e of evidenced) {
+ if (typeof e === "string") {
+ push(e, { source, sourceKind: kind, field: "evidenced_by" });
+ }
+ }
+ }
+ const supersedes = meta["supersedes"];
+ if (typeof supersedes === "string" && supersedes.length > 0) {
+ push(supersedes, { source, sourceKind: kind, field: "supersedes" });
+ }
+ if (kind === "retired") {
+ const supersededBy = meta["superseded_by"];
+ if (typeof supersededBy === "string" && supersededBy.length > 0) {
+ push(supersededBy, { source, sourceKind: kind, field: "superseded_by" });
+ }
+ const retiredBy = meta["retired_by"];
+ if (typeof retiredBy === "string" && retiredBy.length > 0) {
+ push(retiredBy, { source, sourceKind: kind, field: "retired_by" });
+ }
+ }
+ for (const target of extractWikilinks(body)) {
+ push(target, { source, sourceKind: kind, field: "body" });
+ }
+ }
+}
+
+function collectSignals(
+ dir: string,
+ push: (target: string, ref: BacklinkRef) => void,
+): void {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const full = join(dir, name);
+ if (!name.startsWith("sig-")) continue;
+ const source = name.slice(0, -".md".length);
+ try {
+ const [meta, body] = parseFrontmatter(full);
+ const sources = meta["source"];
+ const list = Array.isArray(sources) ? sources : sources ? [String(sources)] : [];
+ for (const t of list) push(t, { source, sourceKind: "signal", field: "source" });
+ for (const target of extractWikilinks(body)) {
+ push(target, { source, sourceKind: "signal", field: "body" });
+ }
+ } catch {
+ continue;
+ }
+ }
+}
+
+function collectLog(
+ vault: string,
+ dir: string,
+ push: (target: string, ref: BacklinkRef) => void,
+): void {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".md")) continue;
+ const date = name.slice(0, -".md".length);
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
+ const source = `log-${date}`;
+ let entries;
+ try {
+ entries = parseLogDay(vault, date).entries;
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ // Walk every payload value, pulling wikilink targets out of
+ // scalar fields and string arrays alike. We don't whitelist
+ // which fields can carry references β€” the payload key becomes
+ // the `field` so callers can filter per-event-kind downstream.
+ //
+ // A payload value carries a wikilink either as the `[[...]]`
+ // form or as bare text that happens to be a Brain id
+ // (`pref-...`, `ret-...`, `sig-...`, `dream-...`). Both shapes
+ // route through the same push.
+ for (const [field, value] of Object.entries(e.body)) {
+ const values = Array.isArray(value) ? value : [value];
+ for (const v of values) {
+ if (typeof v !== "string") continue;
+ if (!v.startsWith("[[") && !/^(pref|ret|sig|dream)-/.test(v)) continue;
+ push(v, {
+ source,
+ sourceKind: `log-${e.eventType}`,
+ field,
+ timestamp: e.timestamp,
+ });
+ }
+ }
+ }
+ }
+}
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index 369b1cf7..0939ed2d 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -38,6 +38,7 @@
import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
+import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";
import { brainDirs, vaultRelative } from "./paths.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
import { parsePreference, parseRetired } from "./preference.ts";
@@ -45,6 +46,7 @@ import { parseLogDay, type BrainLogEntry } from "./log.ts";
import {
BRAIN_APPLY_RESULT,
BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
BRAIN_RETIRED_REASON,
} from "./types.ts";
import type {
@@ -121,6 +123,34 @@ export interface DigestJsonContradiction {
readonly description: string;
}
+/**
+ * "Hot" preference by lifetime evidence-application count. Reflects
+ * the rules carrying real weight right now, regardless of whether
+ * anything about them changed in the window. Source: current state
+ * of `Brain/preferences/` (confirmed + quarantine).
+ */
+export interface DigestJsonTopApplied {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly applied_count: number;
+ readonly violated_count: number;
+ readonly confidence: BrainConfidence | string;
+ readonly status: string;
+}
+
+/**
+ * Preference with the most inbound wikilink references in the vault.
+ * Source: the lifetime backlink index over preferences/retired/log.
+ * Higher count β†’ the rule is mentioned in more contexts.
+ */
+export interface DigestJsonTopReferenced {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly backlink_count: number;
+}
+
export interface DigestJson {
readonly schema_version: 1;
readonly generated_at: string;
@@ -138,8 +168,16 @@ export interface DigestJson {
readonly retired: ReadonlyArray<DigestJsonRetired>;
readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;
readonly contradictions: ReadonlyArray<DigestJsonContradiction>;
+ readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
+ readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
}
+/**
+ * How many entries to keep in each "hot" digest section. Small fixed
+ * value β€” the digest is meant to be skimmable, not exhaustive.
+ */
+const HOT_SECTION_LIMIT = 5;
+
// ----- Entry point ----------------------------------------------------------
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
@@ -182,6 +220,8 @@ export function renderDigest(
retired: data.retired,
confidence_shifts: data.confidence_shifts,
contradictions: data.contradictions,
+ top_applied: data.top_applied,
+ top_referenced: data.top_referenced,
};
return Object.freeze({
content: JSON.stringify(payload, null, 2) + "\n",
@@ -204,6 +244,8 @@ interface DigestData {
readonly retired: ReadonlyArray<DigestJsonRetired>;
readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;
readonly contradictions: ReadonlyArray<DigestJsonContradiction>;
+ readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
+ readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
}
function collectDigestData(
@@ -277,15 +319,71 @@ function collectDigestData(
confirmed.sort((a, b) => a.id.localeCompare(b.id));
retiredEntries.sort((a, b) => a.id.localeCompare(b.id));
+ const top_applied = pickTopApplied(preferences);
+ const top_referenced = pickTopReferenced(vault, preferences);
+
return {
new_unconfirmed,
confirmed,
retired: retiredEntries,
confidence_shifts: confidenceShifts,
contradictions,
+ top_applied,
+ top_referenced,
};
}
+function pickTopApplied(
+ preferences: ReadonlyArray<PreferenceWithPath>,
+): ReadonlyArray<DigestJsonTopApplied> {
+ const active = preferences.filter(
+ ({ pref }) =>
+ (pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||
+ pref.status === BRAIN_PREFERENCE_STATUS.quarantine) &&
+ pref.applied_count > 0,
+ );
+ active.sort((a, b) => {
+ const diff = b.pref.applied_count - a.pref.applied_count;
+ if (diff !== 0) return diff;
+ // Stable secondary key: id ascending. Without it the same input on
+ // two filesystems (different readdir order) could swap ties.
+ return a.pref.id.localeCompare(b.pref.id);
+ });
+ return active.slice(0, HOT_SECTION_LIMIT).map(({ pref }) => ({
+ id: pref.id,
+ topic: pref.topic,
+ scope: pref.scope ?? null,
+ applied_count: pref.applied_count,
+ violated_count: pref.violated_count,
+ confidence: pref.confidence,
+ status: pref.status,
+ }));
+}
+
+function pickTopReferenced(
+ vault: string,
+ preferences: ReadonlyArray<PreferenceWithPath>,
+): ReadonlyArray<DigestJsonTopReferenced> {
+ const index = buildBacklinkIndex(vault);
+ const scored = preferences
+ .map(({ pref }) => ({
+ pref,
+ count: backlinkCount(index, pref.id),
+ }))
+ .filter((x) => x.count > 0);
+ scored.sort((a, b) => {
+ const diff = b.count - a.count;
+ if (diff !== 0) return diff;
+ return a.pref.id.localeCompare(b.pref.id);
+ });
+ return scored.slice(0, HOT_SECTION_LIMIT).map(({ pref, count }) => ({
+ id: pref.id,
+ topic: pref.topic,
+ scope: pref.scope ?? null,
+ backlink_count: count,
+ }));
+}
+
function isEmpty(data: DigestData): boolean {
return (
data.new_unconfirmed.length === 0 &&
@@ -577,6 +675,24 @@ function renderMarkdown(
}
lines.push("");
}
+ if (data.top_applied.length > 0) {
+ lines.push(`## Top applied (${data.top_applied.length})`, "");
+ for (const item of data.top_applied) {
+ const scope = item.scope ?? "β€”";
+ const stats = `applied: ${item.applied_count}, violated: ${item.violated_count}`;
+ const tags = item.status === "quarantine" ? " [quarantine]" : "";
+ lines.push(`- [[${item.id}]] β€” ${scope}, ${stats}${tags}`);
+ }
+ lines.push("");
+ }
+ if (data.top_referenced.length > 0) {
+ lines.push(`## Top referenced (${data.top_referenced.length})`, "");
+ for (const item of data.top_referenced) {
+ const scope = item.scope ?? "β€”";
+ lines.push(`- [[${item.id}]] β€” ${scope}, ${item.backlink_count} inbound`);
+ }
+ lines.push("");
+ }
if (data.confidence_shifts.length > 0) {
lines.push("## Confidence shifts", "");
for (const item of data.confidence_shifts) {
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 8e564725..babe04c2 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -39,21 +39,27 @@
import { existsSync, readdirSync } from "node:fs";
import { basename, join } from "node:path";
-import { extractWikilinks, parseFrontmatter } from "../vault.ts";
+import { extractWikilinks, listVaultBasenames, parseFrontmatter } from "../vault.ts";
+import { buildBacklinkIndex } from "./backlinks.ts";
+import { parseLogDay } from "./log.ts";
import {
BRAIN_CONFIG_SUPPORTED_VERSIONS,
BrainConfigError,
loadBrainConfigDetailed,
} from "./policy.ts";
import { brainConfigPath, brainDirs } from "./paths.ts";
-import { parseLogDay } from "./log.ts";
import {
BrainStatusFolderMismatchError,
parsePreference,
parseRetired,
} from "./preference.ts";
import { parseSignal } from "./signal.ts";
-import { normaliseWikilinkTarget } from "./wikilink.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ type BrainConfig,
+} from "./types.ts";
+import { normaliseWikilinkTarget, parseArtifactRef } from "./wikilink.ts";
// ----- Public types ---------------------------------------------------------
@@ -79,6 +85,12 @@ export interface RunDoctorOptions {
* not the contents of the report.
*/
readonly strict?: boolean;
+ /**
+ * Wall clock used by age-based lints (`low-evidence-confirmed`,
+ * `pinned-without-recent-evidence`). Defaults to `new Date()`.
+ * Tests pin this for determinism.
+ */
+ readonly now?: Date;
}
export interface RunDoctorResult {
@@ -92,8 +104,6 @@ export function runDoctor(
vault: string,
opts: RunDoctorOptions = {},
): RunDoctorResult {
- void opts; // `strict` is a CLI exit-code concern, not a content one.
-
const issues: DoctorIssue[] = [];
const dirs = brainDirs(vault);
@@ -132,6 +142,49 @@ export function runDoctor(
// 7. Log header parsing β€” surface warnings from `parseLogDay`.
checkLogs(vault, issues);
+ // 8. Broken-backlinks lint β€” any preference / retired / log entry
+ // that wikilinks to a Brain artifact id (`pref-...`, `ret-...`,
+ // `sig-...`) whose file no longer exists. Surfaces at warning
+ // severity: a dangling reference is a real data-hygiene problem
+ // but doesn't block the dream loop, so the digest / cron want
+ // to see it without failing the run.
+ checkBrokenBacklinks(vault, issues, knownBasenames);
+
+ // 9. Hygiene lints β€” duplicate prefs, low-evidence confirmed, pinned
+ // without recent evidence, malformed apply-evidence ranges,
+ // orphan apply-evidence artifacts. Each is non-blocking (warning
+ // severity) and config/clock dependent. We swallow per-lint
+ // failures so one broken scan doesn't mask the others.
+ const now = opts.now ?? new Date();
+ let cfg;
+ try {
+ cfg = loadBrainConfigDetailed(vault).config;
+ } catch {
+ cfg = undefined;
+ }
+ // Build snapshots once and feed every new lint that needs them.
+ // Each `try` boundary is per-lint so one broken read doesn't mask
+ // others, but we don't re-parse the same files five times anymore.
+ const prefRecords = readAllPreferenceRecords(vault);
+ const logRecords = readAllLogRecords(vault);
+ if (cfg) {
+ try {
+ checkDuplicatePreferences(prefRecords, issues);
+ } catch { /* doctor never throws */ }
+ try {
+ checkLowEvidenceConfirmed(prefRecords, issues, cfg, now);
+ } catch { /* doctor never throws */ }
+ try {
+ checkPinnedWithoutRecentEvidence(prefRecords, issues, cfg, now);
+ } catch { /* doctor never throws */ }
+ }
+ try {
+ checkMalformedEvidenceRange(logRecords, issues);
+ } catch { /* doctor never throws */ }
+ try {
+ checkOrphanEvidence(vault, logRecords, issues);
+ } catch { /* doctor never throws */ }
+
// Partition by severity. Stable sort preserves discovery order which
// is convenient for tests asserting on `path`+`code`.
const warnings = issues.filter((i) => i.severity === "warning");
@@ -491,6 +544,313 @@ function checkWikilinks(
* inside `Brain/`. The set is keyed by basename (without `.md`) so
* Obsidian's basename match works.
*/
+function checkBrokenBacklinks(
+ vault: string,
+ issues: DoctorIssue[],
+ knownBasenames: ReadonlySet<string>,
+): void {
+ // Only attempt the check when there's something to scan β€” an empty
+ // Brain layer naturally has no backlinks, and `buildBacklinkIndex`
+ // would already return an empty map, but we save the parse pass.
+ if (knownBasenames.size === 0) return;
+ const index = buildBacklinkIndex(vault);
+ for (const [target, refs] of index) {
+ // We only flag references whose target *should* live in this
+ // Brain (i.e. an artifact id we manage). Wikilinks pointing
+ // outside the Brain layer are user prose and not our concern.
+ if (!/^(pref|ret|sig)-/.test(target)) continue;
+ if (knownBasenames.has(target)) continue;
+ const sources = Array.from(new Set(refs.map((r) => r.source))).sort();
+ issues.push({
+ severity: "warning",
+ code: "broken-backlinks",
+ message:
+ `[[${target}]] is referenced by ${sources.length} source(s) but no file with that ` +
+ `basename exists under Brain/: ${sources.join(", ")}`,
+ });
+ }
+}
+
+// ----- Hygiene lints (Β§11) -------------------------------------------------
+
+const JACCARD_DUPLICATE_THRESHOLD = 0.7;
+
+interface PreferenceRecord {
+ readonly path: string;
+ readonly pref: import("./types.ts").BrainPreference;
+}
+
+interface LogRecord {
+ readonly date: string;
+ readonly entries: ReadonlyArray<import("./log.ts").BrainLogEntry>;
+}
+
+/**
+ * Build a single pre-parsed snapshot of `Brain/preferences/` so the
+ * three pref-walking lints don't each re-parse the directory.
+ * Files that fail to parse are silently omitted β€” schema errors are
+ * already reported by {@link checkPreferences}.
+ */
+function readAllPreferenceRecords(vault: string): ReadonlyArray<PreferenceRecord> {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.preferences)) return [];
+ const out: PreferenceRecord[] = [];
+ for (const name of readdirSync(dirs.preferences)) {
+ if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;
+ const path = join(dirs.preferences, name);
+ try {
+ out.push({ path, pref: parsePreference(path) });
+ } catch {
+ // schema error β€” reported by checkPreferences
+ }
+ }
+ return out;
+}
+
+/**
+ * Build a single pre-parsed snapshot of `Brain/log/` so the two
+ * log-walking lints don't each re-parse the directory.
+ */
+function readAllLogRecords(vault: string): ReadonlyArray<LogRecord> {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return [];
+ const out: LogRecord[] = [];
+ for (const name of readdirSync(dirs.log)) {
+ if (!name.endsWith(".md")) continue;
+ const date = name.slice(0, -".md".length);
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
+ try {
+ out.push({ date, entries: parseLogDay(vault, date).entries });
+ } catch {
+ // parse error β€” surfaced separately by checkLogs
+ }
+ }
+ return out;
+}
+
+const TOKEN_STOPWORDS: ReadonlySet<string> = new Set();
+
+/**
+ * `duplicate-preferences`: pairwise jaccard similarity of `principle`
+ * tokens within each `(topic, scope)` bucket of confirmed/quarantine
+ * prefs. Pairs with similarity β‰₯ `JACCARD_DUPLICATE_THRESHOLD` are
+ * flagged. Unconfirmed and retired prefs are excluded β€” they're
+ * meant to be replaced or already are.
+ */
+function checkDuplicatePreferences(
+ records: ReadonlyArray<PreferenceRecord>,
+ issues: DoctorIssue[],
+): void {
+ interface PrefEntry {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | undefined;
+ readonly tokens: ReadonlySet<string>;
+ }
+ const entries: PrefEntry[] = [];
+ for (const { pref } of records) {
+ if (
+ pref.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ pref.status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) continue;
+ entries.push({
+ id: pref.id,
+ topic: pref.topic,
+ scope: pref.scope,
+ tokens: tokenise(pref.principle),
+ });
+ }
+ // Group by (topic, scope). Same scope-undefined falls in its own bucket.
+ const buckets = new Map<string, PrefEntry[]>();
+ for (const e of entries) {
+ const key = `${e.topic}\x00${e.scope ?? ""}`;
+ const arr = buckets.get(key) ?? [];
+ arr.push(e);
+ buckets.set(key, arr);
+ }
+ for (const [, bucket] of buckets) {
+ if (bucket.length < 2) continue;
+ for (let i = 0; i < bucket.length; i++) {
+ for (let j = i + 1; j < bucket.length; j++) {
+ const a = bucket[i]!;
+ const b = bucket[j]!;
+ const sim = jaccard(a.tokens, b.tokens);
+ if (sim >= JACCARD_DUPLICATE_THRESHOLD) {
+ issues.push({
+ severity: "warning",
+ code: "duplicate-preferences",
+ message:
+ `[[${a.id}]] and [[${b.id}]] in topic '${a.topic}'` +
+ `${a.scope ? ` (scope: ${a.scope})` : ""}` +
+ ` look like duplicates (jaccard ${sim.toFixed(2)} of principle tokens).` +
+ " Consider merging.",
+ });
+ }
+ }
+ }
+ }
+}
+
+/**
+ * `low-evidence-confirmed`: a confirmed pref whose `applied_count` is
+ * still at or below `low_max_applied` long after its trial window
+ * (`unconfirmed_window_days`). Catches prefs that promoted on the
+ * minimum evidence but never saw real use β€” candidates for review.
+ */
+function checkLowEvidenceConfirmed(
+ records: ReadonlyArray<PreferenceRecord>,
+ issues: DoctorIssue[],
+ cfg: BrainConfig,
+ now: Date,
+): void {
+ const cutoffMs = now.getTime() - cfg.dream.unconfirmed_window_days * 24 * 3600 * 1000;
+ for (const { pref } of records) {
+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;
+ if (pref.applied_count > cfg.confidence.low_max_applied) continue;
+ if (!pref.confirmed_at) continue;
+ const confirmedMs = Date.parse(pref.confirmed_at);
+ if (!Number.isFinite(confirmedMs)) continue;
+ if (confirmedMs >= cutoffMs) continue;
+ issues.push({
+ severity: "warning",
+ code: "low-evidence-confirmed",
+ message:
+ `[[${pref.id}]] is confirmed but applied_count=${pref.applied_count} ≀ ` +
+ `low_max_applied=${cfg.confidence.low_max_applied} after ${cfg.dream.unconfirmed_window_days}+ days.` +
+ " The rule hasn't seen real use β€” review or retire.",
+ });
+ }
+}
+
+/**
+ * `pinned-without-recent-evidence`: a pinned pref whose
+ * `last_evidence_at` is null or older than `stale_evidence_days`. The
+ * pin protects the rule from automatic retire, but the data shows it
+ * isn't actively backed β€” alert the user.
+ */
+function checkPinnedWithoutRecentEvidence(
+ records: ReadonlyArray<PreferenceRecord>,
+ issues: DoctorIssue[],
+ cfg: BrainConfig,
+ now: Date,
+): void {
+ const cutoffMs = now.getTime() - cfg.retire.stale_evidence_days * 24 * 3600 * 1000;
+ for (const { pref } of records) {
+ if (!pref.pinned) continue;
+ if (!pref.last_evidence_at) {
+ issues.push({
+ severity: "warning",
+ code: "pinned-without-recent-evidence",
+ message:
+ `[[${pref.id}]] is pinned but has never received apply-evidence.` +
+ " Confirm the pin is intentional.",
+ });
+ continue;
+ }
+ const lastMs = Date.parse(pref.last_evidence_at);
+ if (!Number.isFinite(lastMs)) continue;
+ if (lastMs >= cutoffMs) continue;
+ issues.push({
+ severity: "warning",
+ code: "pinned-without-recent-evidence",
+ message:
+ `[[${pref.id}]] is pinned but last_evidence_at=${pref.last_evidence_at} is older than ` +
+ `stale_evidence_days=${cfg.retire.stale_evidence_days}. Pin may be outdated.`,
+ });
+ }
+}
+
+/**
+ * `malformed-evidence-range`: walks every `apply-evidence` event,
+ * runs the artifact wikilink through {@link parseArtifactRef}, and
+ * flags any malformed range suffix (`:abc-def`, `:120-100`, etc.).
+ * The event itself remains valid β€” only the range is malformed.
+ */
+function checkMalformedEvidenceRange(
+ records: ReadonlyArray<LogRecord>,
+ issues: DoctorIssue[],
+): void {
+ for (const { entries } of records) {
+ for (const e of entries) {
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ const artifact = e.body["artifact"];
+ if (typeof artifact !== "string") continue;
+ const parsed = parseArtifactRef(artifact);
+ if (parsed.malformedRange) {
+ issues.push({
+ severity: "warning",
+ code: "malformed-evidence-range",
+ message:
+ `apply-evidence at ${e.timestamp} references artifact ${parsed.raw}` +
+ ` with malformed range '${parsed.rangeText}'.` +
+ " Use `[[file:N-N]]` (inclusive, 1-based) or `[[file:N]]`.",
+ });
+ }
+ }
+ }
+}
+
+/**
+ * `orphan-evidence`: walks every `apply-evidence` event and verifies
+ * the artifact wikilink resolves to some file in the vault. Obsidian
+ * wikilinks resolve by basename; we use the cheap basename-only
+ * walker from `vault.ts` (no frontmatter parse).
+ *
+ * This is the only doctor lint that walks the entire vault (not just
+ * `Brain/`). It's an on-demand check; doctor isn't called per-turn.
+ */
+function checkOrphanEvidence(
+ vault: string,
+ records: ReadonlyArray<LogRecord>,
+ issues: DoctorIssue[],
+): void {
+ let basenames: ReadonlySet<string>;
+ try {
+ basenames = listVaultBasenames(vault);
+ } catch {
+ return;
+ }
+ for (const { entries } of records) {
+ for (const e of entries) {
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ const artifact = e.body["artifact"];
+ if (typeof artifact !== "string") continue;
+ const target = parseArtifactRef(artifact).target;
+ if (!target) continue;
+ if (basenames.has(target)) continue;
+ issues.push({
+ severity: "warning",
+ code: "orphan-evidence",
+ message:
+ `apply-evidence at ${e.timestamp} references artifact [[${target}]]` +
+ " but no file with that basename exists in the vault.",
+ });
+ }
+ }
+}
+
+function tokenise(text: string): ReadonlySet<string> {
+ // Lowercase + split on whitespace + punctuation; no language-
+ // specific stopwords (Brain principles in this project are
+ // routinely multilingual and an English-only list would either
+ // under-filter or skew the similarity score on non-English text).
+ return new Set(
+ text
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}_-]+/u)
+ .filter((t) => t.length > 1 && !TOKEN_STOPWORDS.has(t)),
+ );
+}
+
+function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
+ if (a.size === 0 && b.size === 0) return 0;
+ let intersection = 0;
+ for (const t of a) if (b.has(t)) intersection++;
+ const union = a.size + b.size - intersection;
+ if (union === 0) return 0;
+ return intersection / union;
+}
+
function collectAllBasenames(vault: string): ReadonlySet<string> {
const out = new Set<string>();
const dirs = brainDirs(vault);
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 2f6f7bee..26ecb846 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -38,6 +38,7 @@ import { existsSync, readdirSync, renameSync } from "node:fs";
import { basename, join } from "node:path";
import { parseFrontmatter } from "../vault.ts";
+import { regenerateActiveQuiet } from "./active.ts";
import {
appendLogEvent,
parseLogDay,
@@ -197,6 +198,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
scan.corrupted.length > 0;
if (!changed) {
+ if (!dryRun) regenerateActiveQuiet(vault, { now });
return Object.freeze({
run_id: runId,
changed: false,
@@ -405,6 +407,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
`warning: prune snapshots failed: ${(err as Error).message}\n`,
);
}
+ regenerateActiveQuiet(vault, { now });
}
return Object.freeze({
@@ -887,7 +890,11 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
const prefRaw = e.body["preference"];
const result = e.body["result"];
if (typeof prefRaw !== "string" || typeof result !== "string") continue;
- if (result !== BRAIN_APPLY_RESULT.applied && result !== BRAIN_APPLY_RESULT.violated) continue;
+ if (
+ result !== BRAIN_APPLY_RESULT.applied &&
+ result !== BRAIN_APPLY_RESULT.violated &&
+ result !== BRAIN_APPLY_RESULT.outdated
+ ) continue;
// Parse `[[pref-slug]]` β†’ slug.
const target = parseWikilink(prefRaw);
if (!target || !target.startsWith("pref-")) continue;
@@ -936,9 +943,28 @@ function planRefresh(
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 lastEvidence = ev.length > 0 ? ev[ev.length - 1]!.timestamp : null;
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
+ // the rule itself is obsolete (framework migration, convention
+ // change). Pin protects against decay-based retires but NOT
+ // against context-driven ones β€” pinning means "I want this
+ // rule"; an `outdated` event means "context says this rule no
+ // longer applies anywhere." Honour the explicit signal.
+ //
+ // Idempotency: once retired, the pref moves to `retired/` and
+ // future dream passes don't re-process it from `preferences/`.
+ if (outdatedCount > 0) {
+ plan.retires.push({
+ slug,
+ reason: BRAIN_RETIRED_REASON.supersededByContext,
+ });
+ continue;
+ }
+
let status = rec.pref.status;
let confirmedAt = rec.pref.confirmed_at;
if (status === BRAIN_PREFERENCE_STATUS.unconfirmed && firstApplied) {
@@ -947,6 +973,39 @@ function planRefresh(
confirmed.add(slug);
}
+ // Quarantine transitions β€” only applicable to already-confirmed
+ // and already-quarantined preferences. An unconfirmed pref still
+ // promotes via the firstApplied branch above; quarantine entry is
+ // measured against `confirmed` counts. Detailed semantics live on
+ // `BRAIN_PREFERENCE_STATUS.quarantine` in `types.ts`.
+ if (
+ status === BRAIN_PREFERENCE_STATUS.confirmed &&
+ violated >= applied &&
+ applied > cfg.confidence.low_max_applied
+ ) {
+ status = BRAIN_PREFERENCE_STATUS.quarantine;
+ } else if (status === BRAIN_PREFERENCE_STATUS.quarantine) {
+ const newViolated = violated > rec.pref.violated_count;
+ if (newViolated) {
+ if (isPinned(rec.pref)) {
+ plan.retainPinned.push({
+ preference: `[[${rec.pref.id}]]`,
+ reason: BRAIN_RETIRED_REASON.quarantineViolated,
+ });
+ } else {
+ plan.retires.push({
+ slug,
+ reason: BRAIN_RETIRED_REASON.quarantineViolated,
+ });
+ // Skip refresh β€” moveToRetired will read the on-disk
+ // counters when it builds the retired snapshot.
+ continue;
+ }
+ } else if (applied > violated) {
+ status = BRAIN_PREFERENCE_STATUS.confirmed;
+ }
+ }
+
const confidenceValue = computeConfidence(
applied,
violated,
@@ -1070,8 +1129,15 @@ function planAutoRetires(
continue;
}
- // Confirmed β†’ stale-no-evidence check.
- if (effectiveStatus === BRAIN_PREFERENCE_STATUS.confirmed) {
+ // Confirmed/quarantine β†’ stale-no-evidence check. Quarantine
+ // is "still active" (design summary Β§20) so the time-based decay
+ // applies to it identically β€” a pref sitting idle with no
+ // evidence eventually retires whether confidence was healthy or
+ // probationary at the time the clock ran out.
+ if (
+ effectiveStatus === BRAIN_PREFERENCE_STATUS.confirmed ||
+ effectiveStatus === BRAIN_PREFERENCE_STATUS.quarantine
+ ) {
if (!effectiveLastEvidence) {
// Confirmed with no evidence at all? Shouldn't happen, but
// gate on the same staleness rule using `confirmed_at`. We
diff --git a/src/core/brain/index.ts b/src/core/brain/index.ts
index b711d784..92c2eb62 100644
--- a/src/core/brain/index.ts
+++ b/src/core/brain/index.ts
@@ -52,6 +52,7 @@ export {
brainDirs,
brainConfigPath,
brainManualPath,
+ brainActivePath,
signalPath,
processedSignalPath,
preferencePath,
@@ -68,6 +69,26 @@ export {
vaultRelative,
} from "./paths.ts";
+// ----- Active-preferences digest --------------------------------------------
+export { regenerateActive, regenerateActiveQuiet } from "./active.ts";
+export type { RegenerateActiveOptions, RegenerateActiveResult } from "./active.ts";
+
+// ----- Backlink index -------------------------------------------------------
+export { buildBacklinkIndex, backlinkCount } from "./backlinks.ts";
+export type {
+ BacklinkIndex,
+ BacklinkRef,
+ BacklinkSourceKind,
+} from "./backlinks.ts";
+
+// ----- Operational status ---------------------------------------------------
+export { computeBrainStatus } from "./status.ts";
+export type {
+ BrainStatusSnapshot,
+ BrainStatusCounts,
+ ComputeBrainStatusOptions,
+} from "./status.ts";
+
export type {
BrainDirs,
AllocateSlugOptions,
@@ -97,4 +118,9 @@ export type {
export { isoSecond, isoDate } from "./time.ts";
// ----- Wikilink helpers -----------------------------------------------------
-export { normaliseWikilinkTarget, parseWikilink } from "./wikilink.ts";
+export {
+ normaliseWikilinkTarget,
+ parseWikilink,
+ parseArtifactRef,
+} from "./wikilink.ts";
+export type { ArtifactRange, ArtifactRefParse } from "./wikilink.ts";
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 7ccb20c6..064af87e 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -81,6 +81,16 @@ export function brainManualPath(vault: string): string {
return ensureInsideVault(join(brainDirs(vault).brain, "_BRAIN.md"), vault);
}
+/**
+ * Path of the auto-generated active-preferences digest written by
+ * `dream` and CLI verbs that mutate preference state. Read by the
+ * `SessionStart` / `PostCompact` hook and exposed as the MCP resource
+ * `osb://preferences/active`.
+ */
+export function brainActivePath(vault: string): string {
+ return ensureInsideVault(join(brainDirs(vault).brain, "active.md"), vault);
+}
+
/** Active-signal path: `Brain/inbox/sig-<date>-<slug>.md`. */
export function signalPath(vault: string, date: string, slug: string): string {
const d = validateIsoDate(date);
diff --git a/src/core/brain/pin.ts b/src/core/brain/pin.ts
index d98b3a9b..de105517 100644
--- a/src/core/brain/pin.ts
+++ b/src/core/brain/pin.ts
@@ -30,6 +30,7 @@
import { existsSync } from "node:fs";
import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
+import { regenerateActiveQuiet } from "./active.ts";
import { appendLogEvent, type BrainLogEntry } from "./log.ts";
import { parsePreference } from "./preference.ts";
import { preferencePath, validateSlug } from "./paths.ts";
@@ -127,6 +128,7 @@ export function setPinned(
},
};
appendLogEvent(vault, entry);
+ regenerateActiveQuiet(vault, { now });
return { path, changed: true };
}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index c2638943..17905f35 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -156,10 +156,11 @@ export function writePreference(
}
if (
input.status !== BRAIN_PREFERENCE_STATUS.unconfirmed &&
- input.status !== BRAIN_PREFERENCE_STATUS.confirmed
+ input.status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ input.status !== BRAIN_PREFERENCE_STATUS.quarantine
) {
throw new Error(
- `preference field 'status' must be 'unconfirmed' or 'confirmed'; got ${JSON.stringify(input.status)}`,
+ `preference field 'status' must be 'unconfirmed', 'confirmed', or 'quarantine'; got ${JSON.stringify(input.status)}`,
);
}
@@ -559,7 +560,12 @@ function enforceStatusFolderInvariant(
if (expectedFolder === "preferences") {
// We accept `preferences` as the canonical folder. A status of
// `retired` here is the mismatch case the design doc Β§4 calls out.
- if (parent === "preferences" && status !== BRAIN_PREFERENCE_STATUS.unconfirmed && status !== BRAIN_PREFERENCE_STATUS.confirmed) {
+ if (
+ parent === "preferences" &&
+ status !== BRAIN_PREFERENCE_STATUS.unconfirmed &&
+ status !== BRAIN_PREFERENCE_STATUS.confirmed &&
+ status !== BRAIN_PREFERENCE_STATUS.quarantine
+ ) {
throw new BrainStatusFolderMismatchError(
"preference file frontmatter status does not match preferences/ folder",
path,
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index 308b8d7d..0a28ffc3 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -25,6 +25,7 @@
*/
import type { FrontmatterMap } from "../types.ts";
+import { sanitiseTextField } from "../redactor.ts";
import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
import { allocateSlug, brainDirs, validateIsoDate } from "./paths.ts";
import {
@@ -98,18 +99,26 @@ export function writeSignal(
input: WriteSignalInput,
options: WriteSignalOptions = {},
): WriteSignalResult {
+ // Sanitise free-form fields BEFORE the required-field check so an
+ // input that is purely C0-control characters lands in the
+ // "missing-field" branch rather than smuggling itself into YAML.
+ // `topic`, `slug`, `agent`, `date`, `signal` are constrained by
+ // their own validators (slug rules / ISO date / enum) and are
+ // already rejected if they carry junk β€” don't double-process them.
+ const sanitised = sanitiseSignalInput(input);
+
for (const field of REQUIRED_INPUT_FIELDS) {
- const value = input[field];
+ const value = sanitised[field];
if (value === undefined || value === null || String(value).trim() === "") {
throw new Error(`signal missing field: ${String(field)}`);
}
}
if (
- input.signal !== BRAIN_SIGNAL_SIGN.positive &&
- input.signal !== BRAIN_SIGNAL_SIGN.negative
+ sanitised.signal !== BRAIN_SIGNAL_SIGN.positive &&
+ sanitised.signal !== BRAIN_SIGNAL_SIGN.negative
) {
throw new Error(
- `signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(input.signal)}`,
+ `signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(sanitised.signal)}`,
);
}
@@ -117,38 +126,38 @@ export function writeSignal(
const allocated = allocateSlug({
vault,
targetDir: dirs.inbox,
- prefix: signalPrefix(input.date),
- slug: input.slug,
+ prefix: signalPrefix(sanitised.date),
+ slug: sanitised.slug,
maxAttempts: options.maxSlugAttempts,
});
// The on-disk id always equals the filename basename, including any
// `-2`/`-3` collision suffix. We surface that as the canonical id and
// duplicate it inside the frontmatter so manual `mv` keeps the link.
- const id = `${signalPrefix(input.date)}-${allocated.slug}`;
+ const id = `${signalPrefix(sanitised.date)}-${allocated.slug}`;
- const tags = composeSignalTags(input);
+ const tags = composeSignalTags(sanitised);
const metadata: FrontmatterMap = {
kind: "brain-signal",
id,
- created_at: input.created_at,
+ created_at: sanitised.created_at,
tags: [...tags],
- topic: input.topic.trim(),
- signal: input.signal,
- agent: input.agent.trim(),
- principle: input.principle.trim(),
+ topic: sanitised.topic.trim(),
+ signal: sanitised.signal,
+ agent: sanitised.agent.trim(),
+ principle: sanitised.principle.trim(),
};
// Optional fields: keep the file lean. The parser tolerates absence and
// returns `undefined` on the interface β€” no `_(not provided)_` for
// metadata.
- if (input.scope && input.scope.trim()) {
- metadata["scope"] = input.scope.trim();
+ if (sanitised.scope && sanitised.scope.trim()) {
+ metadata["scope"] = sanitised.scope.trim();
}
- if (input.source && input.source.length > 0) {
- metadata["source"] = [...input.source];
+ if (sanitised.source && sanitised.source.length > 0) {
+ metadata["source"] = [...sanitised.source];
}
- const body = renderSignalBody(input);
+ const body = renderSignalBody(sanitised);
writeFrontmatterAtomic(allocated.path, metadata, body, {
overwrite: false,
existsErrorKind: "signal",
@@ -158,6 +167,43 @@ export function writeSignal(
return { path: allocated.path, id };
}
+// ----- Sanitisation --------------------------------------------------------
+
+/**
+ * Hard caps for free-form fields. `principle` is rendered as a
+ * single-line YAML scalar in frontmatter; `note`/`raw` shapes can
+ * carry paragraphs. `scope` is a short slug-adjacent tag.
+ */
+const PRINCIPLE_MAX_LEN = 512;
+const SCOPE_MAX_LEN = 128;
+const RAW_MAX_LEN = 4096;
+const SOURCE_ITEM_MAX_LEN = 512;
+
+function sanitiseSignalInput(input: WriteSignalInput): WriteSignalInput {
+ const principle = sanitiseTextField(input.principle, {
+ maxLen: PRINCIPLE_MAX_LEN,
+ singleLine: true,
+ });
+ const scope = input.scope
+ ? sanitiseTextField(input.scope, { maxLen: SCOPE_MAX_LEN, singleLine: true })
+ : input.scope;
+ const raw = input.raw
+ ? sanitiseTextField(input.raw, { maxLen: RAW_MAX_LEN })
+ : input.raw;
+ const source = input.source
+ ? input.source.map((s) =>
+ sanitiseTextField(s, { maxLen: SOURCE_ITEM_MAX_LEN, singleLine: true }),
+ )
+ : input.source;
+ return {
+ ...input,
+ principle,
+ ...(scope !== undefined ? { scope } : {}),
+ ...(raw !== undefined ? { raw } : {}),
+ ...(source !== undefined ? { source } : {}),
+ };
+}
+
/**
* Read a signal file from disk and validate its frontmatter against the
* `BrainSignal` contract. Returns a frozen object β€” the parsed shape is
diff --git a/src/core/brain/status.ts b/src/core/brain/status.ts
new file mode 100644
index 00000000..18bc2b83
--- /dev/null
+++ b/src/core/brain/status.ts
@@ -0,0 +1,245 @@
+/**
+ * Brain operational status snapshot.
+ *
+ * One function: {@link computeBrainStatus} walks `Brain/` and returns
+ * counts, last-activity timestamps, and a single sanity flag. Pure
+ * read β€” nothing is mutated, nothing is parsed deeply (we cap I/O at
+ * `readdirSync` for counts and one `parseLogDay` per log file for
+ * timestamps).
+ *
+ * Used by:
+ *
+ * - the MCP `second_brain_status` tool (extended `brain` field)
+ * - the MCP resource `osb://status` (markdown render)
+ *
+ * Callers that want the timestamps but not the counts can read either
+ * field independently β€” the shape is shallow.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../vault.ts";
+import { brainDirs } from "./paths.ts";
+import { parseLogDay } from "./log.ts";
+import { loadBrainConfig } from "./policy.ts";
+import { parseSignal } from "./signal.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+} from "./types.ts";
+
+// ----- Public types --------------------------------------------------------
+
+export interface BrainStatusCounts {
+ readonly inbox: number;
+ readonly inbox_processed: number;
+ readonly preferences: number;
+ readonly preferences_by_status: Readonly<Record<string, number>>;
+ readonly retired: number;
+ readonly log_days: number;
+ readonly snapshots: number;
+}
+
+export interface BrainStatusSnapshot {
+ /** Whether `<vault>/Brain/` exists at all. */
+ readonly present: boolean;
+ readonly counts: BrainStatusCounts;
+ readonly last_dream_at: string | null;
+ readonly last_apply_evidence_at: string | null;
+ readonly sanity: {
+ /**
+ * Number of signals in `inbox/` whose `created_at` predates
+ * `now - dream.unconfirmed_window_days`. A non-zero value means
+ * dream hasn't been run for at least an entire trial window and
+ * the signals risk silent expiry.
+ */
+ readonly signals_awaiting_dream: number;
+ };
+}
+
+export interface ComputeBrainStatusOptions {
+ /** Wall clock for staleness math. Defaults to `new Date()`. */
+ readonly now?: Date;
+}
+
+// ----- Public API ----------------------------------------------------------
+
+export function computeBrainStatus(
+ vault: string,
+ opts: ComputeBrainStatusOptions = {},
+): BrainStatusSnapshot {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.brain)) {
+ return Object.freeze({
+ present: false,
+ counts: {
+ inbox: 0,
+ inbox_processed: 0,
+ preferences: 0,
+ preferences_by_status: Object.freeze({}),
+ retired: 0,
+ log_days: 0,
+ snapshots: 0,
+ },
+ last_dream_at: null,
+ last_apply_evidence_at: null,
+ sanity: { signals_awaiting_dream: 0 },
+ });
+ }
+
+ const counts = countArtifacts(vault);
+ const { lastDreamAt, lastApplyEvidenceAt } = scanLogTimestamps(vault);
+ const signalsAwaitingDream = countSignalsAwaitingDream(vault, opts.now ?? new Date());
+
+ return Object.freeze({
+ present: true,
+ counts,
+ last_dream_at: lastDreamAt,
+ last_apply_evidence_at: lastApplyEvidenceAt,
+ sanity: Object.freeze({ signals_awaiting_dream: signalsAwaitingDream }),
+ });
+}
+
+// ----- Implementation ------------------------------------------------------
+
+function countArtifacts(vault: string): BrainStatusCounts {
+ const dirs = brainDirs(vault);
+ const inbox = countMd(dirs.inbox);
+ const inbox_processed = countMd(dirs.processed);
+ const retired = countMd(dirs.retired);
+ const log_days = countMd(dirs.log);
+ const snapshots = countZst(dirs.snapshots);
+
+ // Per-status preference counts: read frontmatter line `status:` only
+ // β€” no full parse β€” to keep this cheap. Unknown values bucket under
+ // `unknown` so the doctor's parse errors are still visible upstream.
+ const preferences_by_status: Record<string, number> = {};
+ let preferences = 0;
+ if (existsSync(dirs.preferences)) {
+ for (const name of readdirSync(dirs.preferences)) {
+ if (!name.endsWith(".md")) continue;
+ if (!name.startsWith("pref-")) continue;
+ preferences++;
+ const status = readFrontmatterStatus(`${dirs.preferences}/${name}`);
+ preferences_by_status[status] = (preferences_by_status[status] ?? 0) + 1;
+ }
+ }
+ // Always include the canonical bucket names with 0 so consumers
+ // don't need to defensively `?? 0`.
+ for (const s of Object.values(BRAIN_PREFERENCE_STATUS)) {
+ preferences_by_status[s] = preferences_by_status[s] ?? 0;
+ }
+
+ return {
+ inbox,
+ inbox_processed,
+ preferences,
+ preferences_by_status: Object.freeze(preferences_by_status),
+ retired,
+ log_days,
+ snapshots,
+ };
+}
+
+function countMd(dir: string): number {
+ if (!existsSync(dir)) return 0;
+ let n = 0;
+ for (const name of readdirSync(dir)) {
+ if (name.endsWith(".md")) n++;
+ }
+ return n;
+}
+
+function countZst(dir: string): number {
+ if (!existsSync(dir)) return 0;
+ let n = 0;
+ for (const name of readdirSync(dir)) {
+ if (name.endsWith(".tar.zst")) n++;
+ }
+ return n;
+}
+
+function readFrontmatterStatus(path: string): string {
+ // Use the canonical frontmatter parser instead of a regex sniff so
+ // quoted values (`status: "confirmed"`) and other legal YAML
+ // shapes round-trip correctly. Files we can't parse bucket under
+ // `unknown` β€” doctor surfaces them as schema errors elsewhere.
+ try {
+ const [meta] = parseFrontmatter(path);
+ const status = meta["status"];
+ return typeof status === "string" && status.length > 0 ? status : "unknown";
+ } catch {
+ return "unknown";
+ }
+}
+
+function scanLogTimestamps(vault: string): {
+ lastDreamAt: string | null;
+ lastApplyEvidenceAt: string | null;
+} {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return { lastDreamAt: null, lastApplyEvidenceAt: null };
+ const days = readdirSync(dirs.log)
+ .filter((n) => n.endsWith(".md") && /^\d{4}-\d{2}-\d{2}\.md$/.test(n))
+ .map((n) => n.slice(0, -".md".length))
+ .sort()
+ .reverse(); // newest day first
+
+ let lastDreamAt: string | null = null;
+ let lastApplyEvidenceAt: string | null = null;
+ for (const date of days) {
+ // We only need the most-recent timestamp of each kind, so once
+ // both are set we can stop scanning older files.
+ let entries;
+ try {
+ entries = parseLogDay(vault, date).entries;
+ } catch {
+ continue;
+ }
+ for (let i = entries.length - 1; i >= 0; i--) {
+ const e = entries[i]!;
+ if (lastDreamAt === null && e.eventType === BRAIN_LOG_EVENT_KIND.dream) {
+ lastDreamAt = e.timestamp;
+ }
+ if (
+ lastApplyEvidenceAt === null &&
+ e.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence
+ ) {
+ lastApplyEvidenceAt = e.timestamp;
+ }
+ if (lastDreamAt !== null && lastApplyEvidenceAt !== null) break;
+ }
+ if (lastDreamAt !== null && lastApplyEvidenceAt !== null) break;
+ }
+ return { lastDreamAt, lastApplyEvidenceAt };
+}
+
+function countSignalsAwaitingDream(vault: string, now: Date): number {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.inbox)) return 0;
+ let windowDays: number;
+ try {
+ windowDays = loadBrainConfig(vault).dream.unconfirmed_window_days;
+ } catch {
+ return 0; // Config absent: doctor will flag; status reports 0.
+ }
+ const cutoffMs = now.getTime() - windowDays * 24 * 3600 * 1000;
+ let stale = 0;
+ for (const name of readdirSync(dirs.inbox)) {
+ if (!name.endsWith(".md")) continue;
+ if (!name.startsWith("sig-")) continue;
+ // Read the authoritative `created_at` from frontmatter β€” filename
+ // is a hint but the timestamp is the source of truth (slug
+ // collisions and manual `mv` operations can desync the two).
+ let createdAtMs: number;
+ try {
+ createdAtMs = Date.parse(parseSignal(join(dirs.inbox, name)).created_at);
+ } catch {
+ continue; // Unparseable signal β€” doctor's domain, not status's.
+ }
+ if (!Number.isFinite(createdAtMs)) continue;
+ if (createdAtMs < cutoffMs) stale++;
+ }
+ return stale;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index fef15064..12fface8 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -28,6 +28,15 @@ export type BrainSignalSign =
export const BRAIN_PREFERENCE_STATUS = {
unconfirmed: "unconfirmed",
confirmed: "confirmed",
+ // Probation state for a previously-confirmed preference whose recent
+ // evidence is dominantly negative (violated_count β‰₯ applied_count AND
+ // applied_count > low_max_applied). The rule is still active and is
+ // listed in `Brain/active.md`, but the digest surfaces it in a
+ // separate section. A single additional `violated` evidence event
+ // retires the preference with `retired_reason: quarantine-violated`;
+ // an `applied` event that restores `applied_count > violated_count`
+ // sends it back to `confirmed`.
+ quarantine: "quarantine",
} as const;
export type BrainPreferenceStatus =
(typeof BRAIN_PREFERENCE_STATUS)[keyof typeof BRAIN_PREFERENCE_STATUS];
@@ -45,6 +54,17 @@ export const BRAIN_RETIRED_REASON = {
expiredUnconfirmed: "expired-unconfirmed",
rebutted: "rebutted",
userRejected: "user-rejected",
+ // Quarantined preference (see BRAIN_PREFERENCE_STATUS.quarantine) that
+ // received at least one further `violated` evidence event. Distinct
+ // from `rebutted`, which fires when opposite-sign *signals* (not
+ // evidence) accumulate above the candidate threshold.
+ quarantineViolated: "quarantine-violated",
+ // Preference retired because an apply-evidence event marked it
+ // `outdated` β€” the rule's scope still matches but the artifact
+ // shows that the rule itself is obsolete (framework migration,
+ // convention change). Single `outdated` event is enough; the
+ // evidence is interpreted as a definitive contextual rebuttal.
+ supersededByContext: "superseded-by-context",
} as const;
export type BrainRetiredReason =
(typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];
@@ -52,6 +72,13 @@ export type BrainRetiredReason =
export const BRAIN_APPLY_RESULT = {
applied: "applied",
violated: "violated",
+ // The rule matched the artifact's scope but is no longer current β€”
+ // a framework migration, convention change, or upstream rewrite
+ // makes the preference obsolete in this specific application.
+ // Dream interprets any `outdated` evidence as a retire trigger
+ // (reason `superseded-by-context`); pinned prefs emit a
+ // `retain-pinned` log entry instead.
+ outdated: "outdated",
} as const;
export type BrainApplyResult =
(typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.ts
index 2bf345bc..fab00b32 100644
--- a/src/core/brain/wikilink.ts
+++ b/src/core/brain/wikilink.ts
@@ -46,14 +46,23 @@ export function normaliseWikilinkTarget(value: string): string {
// Strip surrounding wikilink brackets, retaining only the target.
const wm = /^\[\[([^\]]+)\]\]/.exec(s);
if (wm) s = wm[1]!.trim();
- // Drop alias / anchor suffixes (`foo|bar` or `foo#section`).
+ return stripBasenameDecoration(s);
+}
+
+/**
+ * Drop `|alias`, `#anchor`, leading folder segments, and trailing
+ * `.md` from a wikilink body (everything between `[[` and `]]`).
+ * Shared between {@link normaliseWikilinkTarget} and
+ * {@link parseArtifactRef} β€” they apply the same Obsidian-flavoured
+ * resolution rules to the post-bracket part of the link.
+ */
+function stripBasenameDecoration(body: string): string {
+ let s = body.trim();
const pipe = s.indexOf("|");
if (pipe >= 0) s = s.slice(0, pipe).trim();
const hash = s.indexOf("#");
if (hash >= 0) s = s.slice(0, hash).trim();
- // Strip a leading folder if any (Obsidian links resolve by basename).
s = basename(s);
- // Strip a trailing `.md` if the user supplied a filename.
if (s.endsWith(".md")) s = s.slice(0, -".md".length);
return s;
}
@@ -75,3 +84,119 @@ export function parseWikilink(value: string): string | null {
if (!m) return null;
return normaliseWikilinkTarget(m[1]!);
}
+
+/**
+ * Inclusive 1-based line range extracted from an artifact wikilink
+ * (`[[file:120-145]]` β†’ `{start: 120, end: 145}`). Single-line form
+ * (`[[file:120]]`) returns `{start: 120, end: 120}`.
+ */
+export interface ArtifactRange {
+ readonly start: number;
+ readonly end: number;
+}
+
+/**
+ * Parse result for an `artifact` field in an `apply-evidence` event.
+ *
+ * `target` is the normalised wikilink basename (same shape as
+ * {@link normaliseWikilinkTarget} returns). `range` is present iff a
+ * well-formed `:N` or `:N-N` suffix was supplied. `malformedRange` is
+ * `true` when a range suffix was supplied but failed validation β€”
+ * the artifact is still recorded verbatim by the writer; the
+ * `brain_doctor` lint surfaces the failure separately so callers can
+ * fix it without losing the underlying event.
+ *
+ * Original input is preserved as `raw` so the lint message can quote
+ * exactly what the user wrote.
+ */
+export interface ArtifactRefParse {
+ readonly raw: string;
+ readonly target: string;
+ readonly range?: ArtifactRange;
+ readonly malformedRange?: true;
+ /** When the range suffix is present (well-formed or not). */
+ readonly rangeText?: string;
+}
+
+const RANGE_SUFFIX_RE = /^(.*):([^:]*)$/;
+
+/**
+ * Parse the `artifact` field of an apply-evidence event.
+ *
+ * Accepts:
+ * - bare wikilink `[[file]]`
+ * - decorated `[[Folder/file.md|Alias]]`
+ * - **range form** `[[file:120-145]]` or `[[file:120]]`
+ * - bare (non-wikilink) text, in which case `target` is the
+ * normalised input minus any range suffix
+ *
+ * Returns a parse β€” `target` is always present (possibly empty for
+ * empty input). `range` and `malformedRange` are mutually exclusive.
+ */
+export function parseArtifactRef(value: string): ArtifactRefParse {
+ const raw = value;
+ // Extract the inside of `[[…]]` if present; otherwise treat the
+ // whole input as the target body. Keep the colon suffix here so we
+ // can peel the range BEFORE the basename collapse β€” `Folder/file:120`
+ // otherwise has its colon swallowed by `path.basename`.
+ let body = value.trim();
+ let wasWikilink = false;
+ const wm = /^\[\[([^\]]+)\]\]$/.exec(body);
+ if (wm) {
+ body = wm[1]!.trim();
+ wasWikilink = true;
+ }
+ // Drop `|alias` before the range probe β€” otherwise the alias text
+ // sits between the colon-range and the end of the string and the
+ // suffix regex picks up the alias instead.
+ const pipe = body.indexOf("|");
+ if (pipe >= 0) body = body.slice(0, pipe).trim();
+
+ // Peel `:range` off the END before applying normaliseWikilinkTarget.
+ // The numeric heuristic keeps Windows-style paths (`C:foo`) and
+ // IPv6 addresses out of the range branch.
+ let preRange = body;
+ let rangeText: string | undefined;
+ const rm = RANGE_SUFFIX_RE.exec(body);
+ if (rm) {
+ const candidate = rm[2]!.trim();
+ if (wasWikilink || /^[0-9-]+$/.test(candidate)) {
+ preRange = rm[1]!.trim();
+ rangeText = candidate;
+ }
+ }
+
+ // Delegate the alias/anchor/folder/.md strip to the canonical
+ // wikilink normaliser so both call sites stay in sync.
+ const target = normaliseWikilinkTarget(preRange);
+
+ if (rangeText === undefined) {
+ return { raw, target };
+ }
+
+ const range = validateRangeText(rangeText);
+ if (range === null) {
+ return { raw, target, rangeText, malformedRange: true };
+ }
+ return { raw, target, rangeText, range };
+}
+
+function validateRangeText(text: string): ArtifactRange | null {
+ // Accepts `N` or `N-N`, both with 1-based positive integers and
+ // `end >= start`. Anything else fails (zero, negative numbers,
+ // reversed range, dangling dashes).
+ const single = /^\d+$/.exec(text);
+ if (single) {
+ const n = parseInt(text, 10);
+ if (n <= 0) return null;
+ return { start: n, end: n };
+ }
+ const pair = /^(\d+)-(\d+)$/.exec(text);
+ if (!pair) return null;
+ const start = parseInt(pair[1]!, 10);
+ const end = parseInt(pair[2]!, 10);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
+ if (start <= 0 || end <= 0) return null;
+ if (end < start) return null;
+ return { start, end };
+}
diff --git a/src/core/pay-memory/redactor.ts b/src/core/pay-memory/redactor.ts
index 314002a2..421d84f2 100644
--- a/src/core/pay-memory/redactor.ts
+++ b/src/core/pay-memory/redactor.ts
@@ -1,126 +1,16 @@
/**
- * Best-effort redactor for raw payment-tool output before it lands in a
- * Markdown receipt.
+ * Pay Memory redactor β€” thin re-export of the shared `src/core/redactor.ts`.
*
- * Six secret-bearing keys are recognized in four assignment shapes:
- *
- * key=value env-style assignments
- * key: value YAML / log lines / single-line `key: token`
- * "key": "value" JSON object entries
- * Authorization: Bearer <token> HTTP authorization header (special case)
- *
- * Each match keeps the key (and surrounding quoting) and replaces the value
- * with the literal `***REDACTED***`. The transform is intentionally narrow β€”
- * the receipt body still carries a disclaimer that the agent must visually
- * inspect output before posting it externally.
- */
-
-const PLACEHOLDER = "***REDACTED***";
-
-/**
- * Maximum input size accepted by `redactRawOutput`. Receipts have no
- * legitimate reason to embed multi-megabyte payloads β€” a runaway pipe of
- * server logs is the realistic cause of an oversize input. Capping at
- * 256 KB keeps the four-pass regex pipeline bounded and avoids a DoS
- * vector for whoever's caller is feeding the redactor.
+ * The implementation lives in `src/core/redactor.ts` so the Brain
+ * writers (`writeSignal`, `appendApplyEvidence`) can share the same
+ * secret-key list and assignment shapes without depending on the Pay
+ * Memory subtree. This file remains as the import path Pay Memory
+ * code historically used; new callers should import from
+ * `src/core/redactor.ts` directly.
*/
-export const MAX_REDACTOR_INPUT = 256 * 1024;
-const TRUNCATION_MARKER =
- "\n\n[…truncated for size; original exceeded 256 KB. Inspect `pay` raw output before sharing.]\n";
-
-/**
- * Canonical list of secret-bearing field names. Each entry is the
- * underscore-separated canonical form; the regex builder below makes
- * `_` and `-` interchangeable and `_` optional, so a single entry
- * `api_key` covers `api_key` / `apikey` / `api-key` automatically. Don't
- * add the visual variants here β€” they're already covered.
- */
-export const SECRET_KEYS: ReadonlyArray<string> = [
- "api_key",
- "token",
- "access_token",
- "refresh_token",
- "bearer",
- "secret",
- "client_secret",
- "authorization",
- "private_key",
- "password",
- "passwd",
- "pwd",
- "credential",
- "credentials",
- "session_token",
-];
-
-const KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");
-
-// `key=value` (env-style): value runs to whitespace or end of line.
-const ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
-
-// `key: value` outside of JSON quoting. Excludes the `"key": ...` JSON shape
-// and the `Authorization: Bearer X` header (handled below). Value runs to end
-// of line; quoted values are matched as a unit so we replace just the inside.
-const COLON_VALUE_RE = new RegExp(
- `(?<!")\\b(${KEY_PATTERN})(\\s*:\\s*)("[^"]*"|'[^']*'|[^\\r\\n]+)`,
- "gi",
-);
-
-// `"key": "value"` JSON entries. Matches the value (string, number, true/false).
-const JSON_ENTRY_RE = new RegExp(
- `("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`,
- "gi",
-);
-
-// `Authorization: Bearer <token>` HTTP header form. The COLON_VALUE_RE above
-// already redacts `authorization: ...` lines, but a header on its own line of
-// the form `Authorization: Bearer <token>` is so common that we keep the
-// "Bearer" prefix human-readable and only replace the token after it.
-const BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
-
-export function redactRawOutput(text: string): string {
- if (!text) return text;
-
- let out =
- text.length > MAX_REDACTOR_INPUT
- ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER
- : text;
-
- // Order matters: handle JSON entries first so the COLON_VALUE_RE doesn't
- // also match inside JSON pairs (the negative-lookbehind keeps it off the
- // `"key":` portion, but if we ran COLON_VALUE_RE first, a value like
- // `"token": "abc123"` could be partially mangled).
- out = out.replace(JSON_ENTRY_RE, (_match, keyPart: string, value: string) => {
- if (value.startsWith('"')) return `${keyPart}"${PLACEHOLDER}"`;
- return `${keyPart}${PLACEHOLDER}`;
- });
-
- out = out.replace(ENV_RE, (_match, key: string, sep: string) => {
- return `${key}${sep}${PLACEHOLDER}`;
- });
-
- // Bearer headers BEFORE the generic colon rule. Otherwise the
- // `authorization: ...` clause in COLON_VALUE_RE would consume the entire
- // `Bearer <token>` value first, leaving the helpful `Bearer ` prefix
- // stripped from the receipt. Running BEARER_RE first replaces the token
- // alone; the COLON pass below then skips any value that already contains
- // the placeholder so the prefix survives.
- out = out.replace(BEARER_RE, (_match, prefix: string) => `${prefix}${PLACEHOLDER}`);
-
- out = out.replace(COLON_VALUE_RE, (match, key: string, sep: string, value: string) => {
- // Already-redacted values (e.g. `Authorization: Bearer ***REDACTED***`
- // from the BEARER pass above) are passed through verbatim β€” re-running
- // the colon rule on them would clobber the `Bearer ` prefix that we
- // intentionally preserved.
- if (value.includes(PLACEHOLDER)) return match;
- if (value.startsWith('"') && value.endsWith('"')) {
- return `${key}${sep}"${PLACEHOLDER}"`;
- }
- if (value.startsWith("'") && value.endsWith("'")) {
- return `${key}${sep}'${PLACEHOLDER}'`;
- }
- return `${key}${sep}${PLACEHOLDER}`;
- });
- return out;
-}
+export {
+ MAX_REDACTOR_INPUT,
+ SECRET_KEYS,
+ redactRawOutput,
+} from "../redactor.ts";
diff --git a/src/core/redactor.ts b/src/core/redactor.ts
new file mode 100644
index 00000000..3b057608
--- /dev/null
+++ b/src/core/redactor.ts
@@ -0,0 +1,209 @@
+/**
+ * Best-effort secret redactor + text-field normaliser shared across
+ * Pay Memory and Brain writers.
+ *
+ * The redactor catches six secret-bearing keys in four assignment
+ * shapes:
+ *
+ * key=value env-style assignments
+ * key: value YAML / log lines / single-line `key: token`
+ * "key": "value" JSON object entries
+ * Authorization: Bearer <token> HTTP authorization header (special case)
+ *
+ * Each match keeps the key (and surrounding quoting) and replaces the
+ * value with the literal `***REDACTED***`. The transform is
+ * intentionally narrow β€” receipts and signals carry a disclaimer that
+ * the agent must visually inspect output before posting externally.
+ *
+ * `normaliseTextField` is the shared input sanitiser for fields that
+ * land in YAML frontmatter or single-line Markdown bullets. It strips
+ * C0 control characters (except `\n` and `\t`), folds the unicode line
+ * separators `U+2028` / `U+2029` to `\n`, NFC-normalises, and caps
+ * length to `maxLen`. The function never throws β€” out-of-spec input
+ * is silently coerced into something safe to persist. A misrecorded
+ * signal is worse than a missed one (the dream pass picks up patterns
+ * from repeats); a YAML-poisoning signal is worse than either.
+ */
+
+const PLACEHOLDER = "***REDACTED***";
+
+/**
+ * Maximum input size accepted by `redactRawOutput`. Receipts have no
+ * legitimate reason to embed multi-megabyte payloads β€” a runaway pipe
+ * of server logs is the realistic cause of an oversize input. Capping
+ * at 256 KB keeps the four-pass regex pipeline bounded and avoids a
+ * DoS vector for whoever's caller is feeding the redactor.
+ */
+export const MAX_REDACTOR_INPUT = 256 * 1024;
+const TRUNCATION_MARKER =
+ "\n\n[…truncated for size; original exceeded 256 KB. Inspect raw output before sharing.]\n";
+
+/**
+ * Canonical list of secret-bearing field names. Each entry is the
+ * underscore-separated canonical form; the regex builder below makes
+ * `_` and `-` interchangeable and `_` optional, so a single entry
+ * `api_key` covers `api_key` / `apikey` / `api-key` automatically.
+ * Don't add the visual variants here β€” they're already covered.
+ */
+export const SECRET_KEYS: ReadonlyArray<string> = [
+ "api_key",
+ "token",
+ "access_token",
+ "refresh_token",
+ "bearer",
+ "secret",
+ "client_secret",
+ "authorization",
+ "private_key",
+ "password",
+ "passwd",
+ "pwd",
+ "credential",
+ "credentials",
+ "session_token",
+];
+
+const KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");
+
+// `key=value` (env-style): value runs to whitespace or end of line.
+const ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
+
+// `key: value` outside of JSON quoting. Excludes the `"key": ...` JSON
+// shape and the `Authorization: Bearer X` header (handled below).
+const COLON_VALUE_RE = new RegExp(
+ `(?<!")\\b(${KEY_PATTERN})(\\s*:\\s*)("[^"]*"|'[^']*'|[^\\r\\n]+)`,
+ "gi",
+);
+
+// `"key": "value"` JSON entries.
+const JSON_ENTRY_RE = new RegExp(
+ `("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`,
+ "gi",
+);
+
+// `Authorization: Bearer <token>` header. COLON_VALUE_RE already
+// redacts `authorization: ...` lines, but the canonical HTTP header is
+// common enough that we preserve the `Bearer ` prefix for readability
+// and only replace the token portion.
+const BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
+
+export function redactRawOutput(text: string): string {
+ if (!text) return text;
+
+ let out =
+ text.length > MAX_REDACTOR_INPUT
+ ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER
+ : text;
+
+ // Order matters: handle JSON entries first so the COLON_VALUE_RE
+ // doesn't also match inside JSON pairs (the negative-lookbehind
+ // keeps it off the `"key":` portion, but if we ran COLON_VALUE_RE
+ // first, a value like `"token": "abc123"` could be partially
+ // mangled).
+ out = out.replace(JSON_ENTRY_RE, (_match, keyPart: string, value: string) => {
+ if (value.startsWith('"')) return `${keyPart}"${PLACEHOLDER}"`;
+ return `${keyPart}${PLACEHOLDER}`;
+ });
+
+ out = out.replace(ENV_RE, (_match, key: string, sep: string) => {
+ return `${key}${sep}${PLACEHOLDER}`;
+ });
+
+ // Bearer headers BEFORE the generic colon rule.
+ out = out.replace(BEARER_RE, (_match, prefix: string) => `${prefix}${PLACEHOLDER}`);
+
+ out = out.replace(COLON_VALUE_RE, (match, key: string, sep: string, value: string) => {
+ if (value.includes(PLACEHOLDER)) return match;
+ if (value.startsWith('"') && value.endsWith('"')) {
+ return `${key}${sep}"${PLACEHOLDER}"`;
+ }
+ if (value.startsWith("'") && value.endsWith("'")) {
+ return `${key}${sep}'${PLACEHOLDER}'`;
+ }
+ return `${key}${sep}${PLACEHOLDER}`;
+ });
+
+ return out;
+}
+
+// ----- Text-field normaliser ------------------------------------------------
+
+/**
+ * C0 control characters (U+0000…U+001F) are illegal in YAML scalars
+ * except for `\t` (` `) and `\n` (`
+`). U+007F (DEL) is
+ * similarly hazardous. Strip everything in that range outside the
+ * two allowed control bytes β€” those are what we encounter in normal
+ * text and want to preserve verbatim.
+ */
+const FORBIDDEN_C0_RE = /[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]/g;
+
+/**
+ * The Unicode line separator (U+2028) and paragraph separator
+ * (U+2029) are technically legal but render as line breaks in most
+ * editors and confuse one-line YAML scalars. Fold both to `\n` so
+ * a downstream Markdown reader sees normal line breaks.
+ */
+const UNICODE_LINE_SEP_RE = /[\u2028\u2029]/g;
+
+export interface NormaliseTextFieldOptions {
+ /** Hard upper bound on output length in UTF-16 code units. */
+ readonly maxLen: number;
+ /**
+ * When `true`, also strip newlines and tabs β€” appropriate for
+ * single-line fields like `principle` or `scope` where a stray
+ * newline would corrupt the YAML scalar.
+ */
+ readonly singleLine?: boolean;
+}
+
+/**
+ * Normalise a free-form text field for safe persistence in Brain
+ * frontmatter or apply-evidence log payloads. Never throws β€” invalid
+ * input is coerced to a safe shape (empty string for non-strings,
+ * truncation for over-length input).
+ *
+ * Pipeline:
+ * 1. Coerce non-string to empty.
+ * 2. Strip forbidden C0 controls (everything except `\t`/`\n`).
+ * 3. Fold U+2028 / U+2029 to `\n`.
+ * 4. If `singleLine`, collapse `\n`/`\r`/`\t` runs to a single space.
+ * 5. NFC-normalise so combining characters don't trip the length cap.
+ * 6. Truncate to `maxLen`.
+ *
+ * Trim is left to the caller β€” the writer for a given field decides
+ * whether leading / trailing whitespace is significant.
+ */
+export function normaliseTextField(
+ value: unknown,
+ opts: NormaliseTextFieldOptions,
+): string {
+ if (typeof value !== "string") return "";
+ let s = value.replace(FORBIDDEN_C0_RE, "");
+ s = s.replace(UNICODE_LINE_SEP_RE, "\n");
+ if (opts.singleLine) {
+ s = s.replace(/[\r\n\t]+/g, " ");
+ } else {
+ // Normalise CRLF to LF so multi-line fields don't carry Windows
+ // line endings into YAML or Markdown.
+ s = s.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
+ }
+ s = s.normalize("NFC");
+ if (s.length > opts.maxLen) {
+ s = s.slice(0, opts.maxLen);
+ }
+ return s;
+}
+
+/**
+ * Convenience: redact + normalise in one call. Used by the Brain
+ * writers (`writeSignal`, `appendApplyEvidence`) to keep field
+ * sanitisation consistent across surfaces.
+ */
+export function sanitiseTextField(
+ value: unknown,
+ opts: NormaliseTextFieldOptions,
+): string {
+ if (typeof value !== "string") return "";
+ return normaliseTextField(redactRawOutput(value), opts);
+}
diff --git a/src/core/vault.ts b/src/core/vault.ts
index a61fbcc1..d8cf2ea0 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -230,6 +230,55 @@ export function listVaultPages(vaultDir: string, opts: ListVaultPagesOptions = {
return pages;
}
+/**
+ * Cheap basename-only walker over a vault directory. Returns the set
+ * of `.md` basenames (without extension) β€” no frontmatter parsing.
+ *
+ * Used where callers only need existence-by-basename (Obsidian
+ * wikilink resolution semantics) and the YAML parse cost of
+ * {@link listVaultPages} is unwarranted.
+ */
+export function listVaultBasenames(
+ vaultDir: string,
+ opts: ListVaultPagesOptions = {},
+): Set<string> {
+ const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
+ const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
+ const out = new Set<string>();
+ walkBasenames(vaultDir, vaultDir, skipDirs, skipFiles, out);
+ return out;
+}
+
+function walkBasenames(
+ root: string,
+ dir: string,
+ skipDirs: Set<string>,
+ skipFiles: Set<string>,
+ out: Set<string>,
+): void {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (skipDirs.has(entry.name)) continue;
+ walkBasenames(root, full, skipDirs, skipFiles, out);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (!entry.name.toLowerCase().endsWith(".md")) continue;
+ if (skipFiles.has(entry.name.toLowerCase())) continue;
+ const rel = relative(root, full);
+ const parts = rel.split(/[\\/]/);
+ if (parts.some((p) => skipDirs.has(p))) continue;
+ out.add(stem(entry.name));
+ }
+}
+
function walk(
root: string,
dir: string,
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 74f2684f..8c50e6e2 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -40,6 +40,8 @@ import {
BrainPreferenceNotFoundError,
type AppendApplyEvidenceInput,
} from "../core/brain/apply-evidence.ts";
+import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
+import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
import {
renderDigest,
type DigestFormat,
@@ -356,11 +358,12 @@ async function toolBrainApplyEvidence(
const resultRaw = coerceStr(args, "result", true)!;
if (
resultRaw !== BRAIN_APPLY_RESULT.applied &&
- resultRaw !== BRAIN_APPLY_RESULT.violated
+ resultRaw !== BRAIN_APPLY_RESULT.violated &&
+ resultRaw !== BRAIN_APPLY_RESULT.outdated
) {
throw new MCPError(
INVALID_PARAMS,
- `argument 'result' must be 'applied' or 'violated'`,
+ `argument 'result' must be 'applied', 'violated', or 'outdated'`,
);
}
const agentArg = coerceStr(args, "agent", false);
@@ -488,6 +491,32 @@ async function toolBrainQuery(
};
}
+// ----- brain_backlinks -----------------------------------------------------
+
+async function toolBrainBacklinks(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const id = coerceStr(args, "id", true)!;
+ // The index is keyed by normalised wikilink targets. Run callers'
+ // input through the same normaliser so `pref-foo`, `[[pref-foo]]`,
+ // `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all
+ // resolve to the same lookup.
+ const target = normaliseWikilinkTarget(id);
+ const index = buildBacklinkIndex(ctx.vault);
+ const refs = index.get(target) ?? [];
+ return {
+ id: target,
+ count: refs.length,
+ refs: refs.map((r) => ({
+ source: r.source,
+ source_kind: r.sourceKind,
+ field: r.field,
+ ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),
+ })),
+ };
+}
+
// ----- brain_doctor --------------------------------------------------------
async function toolBrainDoctor(
@@ -733,7 +762,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_apply_evidence",
description:
- "Record whether an active preference was applied or violated against a freshly-produced durable artifact. Appends one event to `Brain/log/<today>.md`.",
+ "Record whether an active preference was applied, violated, or marked outdated against a freshly-produced durable artifact. Appends one event to `Brain/log/<today>.md`. A single `outdated` event triggers retire on the next dream pass.",
inputSchema: {
type: "object",
properties: {
@@ -745,13 +774,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
artifact: {
type: "string",
description:
- "Wikilink identifying the artifact, e.g. `[[Daily/2026.05.14#section]]` or `[[src/cli/main.ts]]`.",
+ "Wikilink identifying the artifact. Accepts an optional inclusive line-range suffix for claim-level provenance, e.g. `[[src/cli/main.ts:120-145]]` or `[[src/cli/main.ts:42]]`.",
},
result: {
type: "string",
- enum: ["applied", "violated"],
+ enum: ["applied", "violated", "outdated"],
description:
- "`applied` if the rule held in this artifact, `violated` if it was broken.",
+ "`applied` if the rule held in this artifact, `violated` if it was broken, `outdated` if the rule's scope still matches but the artifact shows the rule itself is obsolete (e.g. framework migration).",
},
agent: {
type: "string",
@@ -851,4 +880,22 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainDoctor,
},
+ {
+ name: "brain_backlinks",
+ description:
+ "List inbound references to a Brain artifact id (preference, retired, or signal). Returns every source that points at the id via wikilink, in any preference/retired frontmatter field, body prose, signal source, or log payload. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Target id (e.g. `pref-foo`, `ret-bar`, `sig-2026-05-14-baz`). Wikilink decoration is stripped if present.",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainBacklinks,
+ },
]);
diff --git a/src/mcp/resources.ts b/src/mcp/resources.ts
new file mode 100644
index 00000000..5538ea5e
--- /dev/null
+++ b/src/mcp/resources.ts
@@ -0,0 +1,501 @@
+/**
+ * MCP Resources surface (introduced in v0.9.1).
+ *
+ * Resources let an MCP host pull a piece of Brain state by URI instead
+ * of asking the agent to call `brain_query` first. The five URI shapes
+ * we ship are:
+ *
+ * osb://preferences/active β€” Brain/active.md (auto-generated by dream)
+ * osb://digest/latest β€” current `renderDigest({format: "markdown"})`
+ * osb://preference/{id} β€” Brain/preferences/pref-{id}.md OR
+ * Brain/retired/ret-{id}.md when the
+ * preferences/ copy is gone
+ * osb://topic/{slug} β€” synthesized markdown summary of every
+ * signal + the current pref / retired
+ * for the topic slug
+ * osb://log/{date} β€” Brain/log/<date>.md as-is
+ *
+ * The first two are concrete resources (returned by `resources/list`).
+ * The last three are templates (returned by `resources/templates/list`).
+ * `resources/read` accepts both shapes uniformly.
+ *
+ * Implementation notes:
+ *
+ * - All slug / id / date arguments are validated through the existing
+ * `validateSlug` / `validateIsoDate` helpers. A bad value is an
+ * `INVALID_PARAMS` error, NOT a 404 β€” we want client bugs to be
+ * visibly different from genuinely-missing files.
+ * - Read responses are text/markdown. We avoid serializing structured
+ * data here because the rest of the MCP surface already does that
+ * via tools; resources are the "give me the markdown body" channel.
+ * - Missing files produce `INTERNAL_ERROR` with a `not found` message
+ * β€” same shape as `brain_query`'s `BrainNotFoundError` so callers
+ * can treat both surfaces consistently.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+
+import { regenerateActive } from "../core/brain/active.ts";
+import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
+import type { BacklinkRef } from "../core/brain/backlinks.ts";
+import { renderDigest } from "../core/brain/digest.ts";
+import {
+ computeBrainStatus,
+ type BrainStatusSnapshot,
+} from "../core/brain/status.ts";
+import {
+ brainActivePath,
+ logPath,
+ preferencePath,
+ retiredPath,
+ validateIsoDate,
+ validateSlug,
+} from "../core/brain/paths.ts";
+import {
+ BrainNotFoundError,
+ queryByPreference,
+ queryByTopic,
+} from "../core/brain/query.ts";
+import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";
+import type {
+ BrainPreference,
+ BrainRetired,
+} from "../core/brain/types.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
+
+export interface ResourceContext {
+ readonly vault: string;
+}
+
+export interface ResourceDescriptor {
+ readonly uri: string;
+ readonly name: string;
+ readonly description: string;
+ readonly mimeType: string;
+}
+
+export interface ResourceTemplateDescriptor {
+ readonly uriTemplate: string;
+ readonly name: string;
+ readonly description: string;
+ readonly mimeType: string;
+}
+
+export interface ResourceContent {
+ readonly uri: string;
+ readonly mimeType: string;
+ readonly text: string;
+}
+
+const MIME_MARKDOWN = "text/markdown";
+
+const CONCRETE: ReadonlyArray<ResourceDescriptor> = [
+ {
+ uri: "osb://preferences/active",
+ name: "Active Brain preferences",
+ description:
+ "Auto-generated digest of confirmed and quarantined preferences plus the three most recently retired entries. Regenerated at the tail of every dream run.",
+ mimeType: MIME_MARKDOWN,
+ },
+ {
+ uri: "osb://digest/latest",
+ name: "Latest Brain digest",
+ description:
+ "Same body as `brain_digest` (default window: last 24h). Markdown.",
+ mimeType: MIME_MARKDOWN,
+ },
+ {
+ uri: "osb://status",
+ name: "Brain operational status",
+ description:
+ "Counts (inbox/preferences/retired/log/snapshots), last-activity timestamps, and a sanity flag for signals awaiting dream. Markdown.",
+ mimeType: MIME_MARKDOWN,
+ },
+];
+
+const TEMPLATES: ReadonlyArray<ResourceTemplateDescriptor> = [
+ {
+ uriTemplate: "osb://preference/{id}",
+ name: "Brain preference by id",
+ description:
+ "Body of the matching `pref-{id}.md` (or `ret-{id}.md` when the active copy is gone).",
+ mimeType: MIME_MARKDOWN,
+ },
+ {
+ uriTemplate: "osb://topic/{slug}",
+ name: "Brain topic summary",
+ description:
+ "Markdown synthesis of every signal (active + processed), the current preference (or retired), and the most recent log mentions for the topic slug.",
+ mimeType: MIME_MARKDOWN,
+ },
+ {
+ uriTemplate: "osb://log/{date}",
+ name: "Brain daily log",
+ description:
+ "Body of `Brain/log/<date>.md` (YYYY-MM-DD).",
+ mimeType: MIME_MARKDOWN,
+ },
+ {
+ uriTemplate: "osb://backlinks/{id}",
+ name: "Brain backlinks for id",
+ description:
+ "Inbound references to the given Brain artifact id (preference, retired, or signal). Rendered as a count plus a grouped list of sources.",
+ mimeType: MIME_MARKDOWN,
+ },
+];
+
+export function listResources(): ReadonlyArray<ResourceDescriptor> {
+ return CONCRETE;
+}
+
+export function listResourceTemplates(): ReadonlyArray<ResourceTemplateDescriptor> {
+ return TEMPLATES;
+}
+
+export function readResource(ctx: ResourceContext, uri: string): ResourceContent {
+ const parsed = parseUri(uri);
+ switch (parsed.kind) {
+ case "active":
+ return readActive(ctx, uri);
+ case "digestLatest":
+ return readDigestLatest(ctx, uri);
+ case "status":
+ return readStatus(ctx, uri);
+ case "preference":
+ return readPreference(ctx, uri, parsed.id);
+ case "topic":
+ return readTopic(ctx, uri, parsed.slug);
+ case "log":
+ return readLog(ctx, uri, parsed.date);
+ case "backlinks":
+ return readBacklinks(ctx, uri, parsed.id);
+ }
+}
+
+// ----- URI parsing ---------------------------------------------------------
+
+type Parsed =
+ | { readonly kind: "active" }
+ | { readonly kind: "digestLatest" }
+ | { readonly kind: "status" }
+ | { readonly kind: "preference"; readonly id: string }
+ | { readonly kind: "topic"; readonly slug: string }
+ | { readonly kind: "log"; readonly date: string }
+ | { readonly kind: "backlinks"; readonly id: string };
+
+function parseUri(uri: string): Parsed {
+ if (typeof uri !== "string" || !uri.startsWith("osb://")) {
+ throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);
+ }
+ const remainder = uri.slice("osb://".length);
+ // Resources have at most one slash for the templated variants
+ // (`preference/foo`). We don't accept deeper paths.
+ const parts = remainder.split("/");
+ const head = parts[0] ?? "";
+ if (head === "preferences" && parts[1] === "active" && parts.length === 2) {
+ return { kind: "active" };
+ }
+ if (head === "digest" && parts[1] === "latest" && parts.length === 2) {
+ return { kind: "digestLatest" };
+ }
+ if (head === "status" && parts.length === 1) {
+ return { kind: "status" };
+ }
+ if (head === "preference" && parts.length === 2) {
+ return { kind: "preference", id: parts[1]! };
+ }
+ if (head === "topic" && parts.length === 2) {
+ return { kind: "topic", slug: parts[1]! };
+ }
+ if (head === "log" && parts.length === 2) {
+ return { kind: "log", date: parts[1]! };
+ }
+ if (head === "backlinks" && parts.length === 2) {
+ return { kind: "backlinks", id: parts[1]! };
+ }
+ throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);
+}
+
+// ----- Readers -------------------------------------------------------------
+
+function readActive(ctx: ResourceContext, uri: string): ResourceContent {
+ const path = brainActivePath(ctx.vault);
+ // First read attempt: the file usually exists because dream
+ // regenerates it. On a fresh vault that has never been dreamed, the
+ // file may not exist yet β€” generate it on demand so the resource is
+ // always meaningful. We do NOT auto-generate on every read (that
+ // would shift expensive work onto a hot path); only on the first
+ // read of a missing file.
+ if (!existsSync(path)) {
+ try {
+ regenerateActive(ctx.vault);
+ } catch (err) {
+ throw new MCPError(
+ INTERNAL_ERROR,
+ `active.md not present and on-demand regeneration failed: ${(err as Error).message}`,
+ );
+ }
+ }
+ return readMarkdown(uri, path);
+}
+
+function readDigestLatest(ctx: ResourceContext, uri: string): ResourceContent {
+ const rendered = renderDigest(ctx.vault, { format: "markdown" });
+ return {
+ uri,
+ mimeType: MIME_MARKDOWN,
+ text: rendered.content,
+ };
+}
+
+function readStatus(ctx: ResourceContext, uri: string): ResourceContent {
+ const snapshot = computeBrainStatus(ctx.vault);
+ return {
+ uri,
+ mimeType: MIME_MARKDOWN,
+ text: renderStatusMarkdown(snapshot),
+ };
+}
+
+function readPreference(
+ ctx: ResourceContext,
+ uri: string,
+ rawId: string,
+): ResourceContent {
+ if (!rawId.trim()) {
+ throw new MCPError(INVALID_PARAMS, `resource id must not be empty: ${uri}`);
+ }
+ // Accept `pref-foo`, `ret-foo`, or the bare slug. Strip the prefix
+ // (if any) for `validateSlug` β€” that helper rejects `..` traversal
+ // and other shape problems with a clear INVALID_PARAMS-shaped
+ // message, which is a better diagnosis than a downstream
+ // "not found" error. The prefixed form is then handed to
+ // queryByPreference, which handles the active β†’ retired fallback.
+ const slug = rawId.startsWith("pref-")
+ ? rawId.slice("pref-".length)
+ : rawId.startsWith("ret-")
+ ? rawId.slice("ret-".length)
+ : rawId;
+ try {
+ validateSlug(slug);
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, (err as Error).message);
+ }
+ const normalized = rawId.startsWith("pref-") || rawId.startsWith("ret-")
+ ? rawId
+ : `pref-${rawId}`;
+ let result;
+ try {
+ result = queryByPreference(ctx.vault, normalized);
+ } catch (err) {
+ if (err instanceof BrainNotFoundError) {
+ throw new MCPError(INTERNAL_ERROR, err.message);
+ }
+ throw err;
+ }
+ // queryByPreference returns the parsed object but not its path; we
+ // re-derive the path from the resolved id so we can hand back the
+ // raw markdown body (the resource contract is "give me the file",
+ // not "give me a structured projection").
+ const resolvedId = result.preference.id;
+ const resolvedSlug = resolvedId.startsWith("pref-")
+ ? resolvedId.slice("pref-".length)
+ : resolvedId.slice("ret-".length);
+ const filePath = resolvedId.startsWith("pref-")
+ ? preferencePath(ctx.vault, resolvedSlug)
+ : retiredPath(ctx.vault, resolvedSlug);
+ return readMarkdown(uri, filePath);
+}
+
+function readTopic(
+ ctx: ResourceContext,
+ uri: string,
+ rawSlug: string,
+): ResourceContent {
+ if (!rawSlug.trim()) {
+ throw new MCPError(INVALID_PARAMS, `topic slug must not be empty: ${uri}`);
+ }
+ validateSlug(rawSlug);
+ let result;
+ try {
+ result = queryByTopic(ctx.vault, rawSlug);
+ } catch (err) {
+ if (err instanceof BrainNotFoundError) {
+ throw new MCPError(INTERNAL_ERROR, err.message);
+ }
+ throw err;
+ }
+ return {
+ uri,
+ mimeType: MIME_MARKDOWN,
+ text: renderTopicMarkdown(rawSlug, result),
+ };
+}
+
+function readLog(
+ ctx: ResourceContext,
+ uri: string,
+ rawDate: string,
+): ResourceContent {
+ validateIsoDate(rawDate);
+ const path = logPath(ctx.vault, rawDate);
+ if (!existsSync(path)) {
+ throw new MCPError(INTERNAL_ERROR, `no log file for date '${rawDate}'`);
+ }
+ return readMarkdown(uri, path);
+}
+
+function readBacklinks(
+ ctx: ResourceContext,
+ uri: string,
+ rawId: string,
+): ResourceContent {
+ if (!rawId.trim()) {
+ throw new MCPError(INVALID_PARAMS, `backlinks target must not be empty: ${uri}`);
+ }
+ // Normalise to the same form the index keys use so `[[pref-foo]]`,
+ // `pref-foo`, and `Brain/preferences/pref-foo.md` all resolve.
+ const target = normaliseWikilinkTarget(rawId);
+ const index = buildBacklinkIndex(ctx.vault);
+ const refs = index.get(target) ?? [];
+ return {
+ uri,
+ mimeType: MIME_MARKDOWN,
+ text: renderBacklinksMarkdown(target, refs),
+ };
+}
+
+// ----- Helpers -------------------------------------------------------------
+
+function readMarkdown(uri: string, path: string): ResourceContent {
+ const text = readFileSync(path, "utf8");
+ return { uri, mimeType: MIME_MARKDOWN, text };
+}
+
+/**
+ * Render the topic-query result as a compact markdown document. Kept
+ * here (not in `query.ts`) because the markdown shape is a
+ * resource-surface concern; callers that want the structured form can
+ * still invoke `queryByTopic` directly.
+ */
+function renderStatusMarkdown(s: BrainStatusSnapshot): string {
+ const lines: string[] = [];
+ lines.push("# Brain status");
+ lines.push("");
+ if (!s.present) {
+ lines.push("_Brain layer not present in this vault. Run `o2b brain init` first._");
+ return lines.join("\n") + "\n";
+ }
+ lines.push("## Counts");
+ lines.push("");
+ lines.push(`- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed})`);
+ lines.push(`- preferences: ${s.counts.preferences}`);
+ for (const [status, n] of Object.entries(s.counts.preferences_by_status).sort()) {
+ lines.push(` - ${status}: ${n}`);
+ }
+ lines.push(`- retired: ${s.counts.retired}`);
+ lines.push(`- log days: ${s.counts.log_days}`);
+ lines.push(`- snapshots: ${s.counts.snapshots}`);
+ lines.push("");
+ lines.push("## Activity");
+ lines.push("");
+ lines.push(`- last dream: ${s.last_dream_at ?? "_(never)_"}`);
+ lines.push(`- last apply-evidence: ${s.last_apply_evidence_at ?? "_(never)_"}`);
+ lines.push("");
+ if (s.sanity.signals_awaiting_dream > 0) {
+ lines.push("## Sanity");
+ lines.push("");
+ lines.push(
+ `- **${s.sanity.signals_awaiting_dream}** signal(s) in inbox/ predate the unconfirmed_window β€” run \`o2b brain dream\`.`,
+ );
+ lines.push("");
+ }
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
+ return lines.join("\n") + "\n";
+}
+
+function renderBacklinksMarkdown(
+ target: string,
+ refs: ReadonlyArray<BacklinkRef>,
+): string {
+ const lines: string[] = [];
+ lines.push(`# Backlinks to \`${target}\``);
+ lines.push("");
+ lines.push(`Total inbound references: ${refs.length}`);
+ lines.push("");
+ if (refs.length === 0) {
+ lines.push("_No inbound references found._");
+ return lines.join("\n") + "\n";
+ }
+ // Group by source-kind so the reader sees structure rather than a
+ // flat list β€” the same source kind (e.g. multiple log apply-evidence
+ // events) clusters together.
+ const byKind = new Map<string, BacklinkRef[]>();
+ for (const r of refs) {
+ const arr = byKind.get(r.sourceKind) ?? [];
+ arr.push(r);
+ byKind.set(r.sourceKind, arr);
+ }
+ for (const [kind, group] of byKind) {
+ lines.push(`## ${kind} (${group.length})`);
+ lines.push("");
+ for (const r of group) {
+ const suffix = r.timestamp ? ` β€” ${r.timestamp}` : "";
+ lines.push(`- \`${r.source}\` (field: \`${r.field}\`)${suffix}`);
+ }
+ lines.push("");
+ }
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
+ return lines.join("\n") + "\n";
+}
+
+function renderTopicMarkdown(
+ slug: string,
+ result: ReturnType<typeof queryByTopic>,
+): string {
+ const lines: string[] = [];
+ lines.push(`# Brain topic: ${slug}`);
+ lines.push("");
+ const pref = result.preference;
+ if (pref) {
+ if (pref.id.startsWith("ret-")) {
+ const r = pref as BrainRetired;
+ const date = r.retired_at.slice(0, 10);
+ lines.push("## Retired preference (no current active)");
+ lines.push("");
+ lines.push(`- \`${r.id}\` β€” retired_reason: \`${r.retired_reason}\` on ${date}`);
+ lines.push(` - ${r.principle}`);
+ } else {
+ const p = pref as BrainPreference;
+ lines.push("## Current preference");
+ lines.push("");
+ lines.push(
+ `- \`${p.id}\` β€” status: \`${p.status}\`, confidence: \`${p.confidence}\``,
+ );
+ lines.push(` - ${p.principle}`);
+ }
+ lines.push("");
+ }
+ const sigs = result.signals;
+ if (sigs.length > 0) {
+ lines.push(`## Signals (${sigs.length})`);
+ lines.push("");
+ for (const s of sigs) {
+ lines.push(
+ `- \`${s.id}\` β€” ${s.signal} signal by ${s.agent} at ${s.created_at}`,
+ );
+ }
+ lines.push("");
+ }
+ const log = result.all_log_events;
+ if (log.length > 0) {
+ lines.push(`## Recent log entries (${log.length})`);
+ lines.push("");
+ for (const e of log) {
+ lines.push(`- ${e.timestamp} β€” \`${e.eventType}\``);
+ }
+ lines.push("");
+ }
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
+ return lines.join("\n") + "\n";
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 5dec330e..4197a44e 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -17,6 +17,11 @@ import {
SERVER_NAME,
SERVER_VERSION,
} from "./protocol.ts";
+import {
+ listResources,
+ listResourceTemplates,
+ readResource,
+} from "./resources.ts";
import { buildToolTable, findTool, type ServerContext, type ToolDefinition } from "./tools.ts";
export interface MCPServerOptions {
@@ -109,6 +114,12 @@ export class MCPServer {
result = this.handleToolsList();
} else if (method === "tools/call") {
result = await this.handleToolsCall(params);
+ } else if (method === "resources/list") {
+ result = this.handleResourcesList();
+ } else if (method === "resources/templates/list") {
+ result = this.handleResourcesTemplatesList();
+ } else if (method === "resources/read") {
+ result = this.handleResourcesRead(params);
} else if (method.startsWith("notifications/")) {
return null;
} else {
@@ -133,7 +144,10 @@ export class MCPServer {
const defaultAgent = resolveAgentName(this.configPath ?? undefined);
return {
protocolVersion: negotiated,
- capabilities: { tools: { listChanged: false } },
+ capabilities: {
+ tools: { listChanged: false },
+ resources: { listChanged: false, subscribe: false },
+ },
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
instructions: buildInstructions(defaultAgent),
};
@@ -149,6 +163,23 @@ export class MCPServer {
};
}
+ private handleResourcesList(): Record<string, unknown> {
+ return { resources: listResources() };
+ }
+
+ private handleResourcesTemplatesList(): Record<string, unknown> {
+ return { resourceTemplates: listResourceTemplates() };
+ }
+
+ private handleResourcesRead(params: Record<string, unknown>): Record<string, unknown> {
+ const uri = params["uri"];
+ if (typeof uri !== "string") {
+ throw new MCPError(INVALID_PARAMS, "resources/read requires a string `uri`");
+ }
+ const content = readResource({ vault: this.vault }, uri);
+ return { contents: [content] };
+ }
+
private async handleToolsCall(params: Record<string, unknown>): Promise<Record<string, unknown>> {
const name = params["name"];
if (typeof name !== "string") {
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 317a2560..66e7c8c4 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -25,6 +25,7 @@ import {
resolveAgentName,
resolveTimezone,
} from "../core/config.ts";
+import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
import { appendEvent, validateEventTime } from "../core/event-log.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
@@ -166,6 +167,9 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
const discovery = discoverConfig(ctx.configPath ?? undefined);
const vaultExists = isDir(ctx.vault);
const configKeys = Object.keys(discovery.data).sort();
+ // Safe to call on a vault that has no Brain layer yet β€” returns
+ // `present: false` with zero counts.
+ const brain = vaultExists ? computeBrainStatus(ctx.vault) : null;
return {
config_path: String(discovery.path),
config_exists: discovery.exists,
@@ -173,6 +177,7 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
config: redactMapping(discovery.data),
vault_path: ctx.vault,
vault_exists: vaultExists,
+ ...(brain ? { brain } : {}),
};
}
diff --git a/tests/core/brain.active.test.ts b/tests/core/brain.active.test.ts
new file mode 100644
index 00000000..f008ad41
--- /dev/null
+++ b/tests/core/brain.active.test.ts
@@ -0,0 +1,209 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { regenerateActive } from "../../src/core/brain/active.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainActivePath, preferencePath } from "../../src/core/brain/paths.ts";
+import {
+ moveToRetired,
+ writePreference,
+} from "../../src/core/brain/preference.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-active-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-active-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function readActive(): string {
+ return readFileSync(brainActivePath(vault), "utf8");
+}
+
+function seedConfirmed(slug: string, principle: string, confidence: "low" | "medium" | "high"): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: confidence === "high" ? 10 : 3,
+ violated_count: 0,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence,
+ scope: "writing",
+ });
+}
+
+function seedQuarantine(slug: string, principle: string): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "quarantine",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 5,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence: "low",
+ scope: "coding",
+ });
+}
+
+describe("regenerateActive β€” empty Brain", () => {
+ test("produces a file with the Confirmed header and a placeholder line", () => {
+ const result = regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+
+ expect(existsSync(result.path)).toBe(true);
+ expect(result.counts).toEqual({ confirmed: 0, quarantine: 0, retired_recent: 0 });
+
+ const body = readActive();
+ expect(body).toContain("kind: brain-active");
+ expect(body).toContain("generated_at: 2026-05-15T10:00:00Z");
+ expect(body).toContain("# Active Brain Preferences");
+ expect(body).toContain("## Confirmed (0)");
+ expect(body).toContain("_No confirmed preferences yet._");
+ expect(body).not.toContain("## Quarantine");
+ expect(body).not.toContain("## Recently retired");
+ });
+});
+
+describe("regenerateActive β€” content rendering", () => {
+ test("renders sections sorted by confidence high→low then id", () => {
+ seedConfirmed("zebra", "Lowest-priority alphabetically last rule", "low");
+ seedConfirmed("apple", "High-confidence rule", "high");
+ seedConfirmed("middle", "Medium-confidence rule", "medium");
+
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ const body = readActive();
+
+ const confirmedSection = body.split("## Confirmed")[1] ?? "";
+ const appleIdx = confirmedSection.indexOf("pref-apple");
+ const middleIdx = confirmedSection.indexOf("pref-middle");
+ const zebraIdx = confirmedSection.indexOf("pref-zebra");
+ expect(appleIdx).toBeLessThan(middleIdx);
+ expect(middleIdx).toBeLessThan(zebraIdx);
+
+ expect(body).toContain("## Confirmed (3)");
+ expect(body).toContain("`pref-apple` (scope: writing, confidence: high)");
+ expect(body).toContain("`pref-zebra` (scope: writing, confidence: low)");
+ });
+
+ test("renders Quarantine section with counters and recovery hint", () => {
+ seedQuarantine("flaky-rule", "Probationary rule");
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ const body = readActive();
+ expect(body).toContain("## Quarantine (1)");
+ expect(body).toContain("applied: 3 / violated: 5");
+ expect(body).toContain("scope: coding");
+ expect(body).toContain("Probationary rule");
+ expect(body).toContain("One further `violated` evidence event retires the rule");
+ });
+
+ test("renders Recently retired sorted by retired_at desc, capped at 3", () => {
+ seedConfirmed("oldest", "P1", "low");
+ seedConfirmed("middle-r", "P2", "low");
+ seedConfirmed("newest", "P3", "low");
+ seedConfirmed("fourth", "P4", "low");
+ moveToRetired(vault, preferencePath(vault, "oldest"), "stale-no-evidence", {
+ now: new Date("2026-05-01T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-01]]",
+ });
+ moveToRetired(vault, preferencePath(vault, "middle-r"), "rebutted", {
+ now: new Date("2026-05-10T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-10]]",
+ });
+ moveToRetired(vault, preferencePath(vault, "newest"), "user-rejected", {
+ now: new Date("2026-05-12T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-12]]",
+ });
+ moveToRetired(vault, preferencePath(vault, "fourth"), "quarantine-violated", {
+ now: new Date("2026-05-14T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-14]]",
+ });
+
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ const body = readActive();
+ expect(body).toContain("## Recently retired (last 3)");
+ // Capped at 3 β†’ "oldest" is omitted.
+ expect(body).not.toContain("ret-oldest");
+ // The other three appear in desc-by-retired_at order.
+ const fourthIdx = body.indexOf("ret-fourth");
+ const newestIdx = body.indexOf("ret-newest");
+ const middleIdx = body.indexOf("ret-middle-r");
+ expect(fourthIdx).toBeLessThan(newestIdx);
+ expect(newestIdx).toBeLessThan(middleIdx);
+ expect(body).toContain("ret-fourth` β€” quarantine-violated on 2026-05-14");
+ });
+});
+
+describe("regenerateActive β€” idempotency", () => {
+ test("second call with identical state does not rewrite the file", () => {
+ seedConfirmed("stable", "Stable rule", "medium");
+ const firstNow = new Date("2026-05-15T10:00:00Z");
+ const first = regenerateActive(vault, { now: firstNow });
+ expect(first.changed).toBe(true);
+ const mtimeBefore = statSync(first.path).mtimeMs;
+
+ // Sleep a tick so mtime would shift if a rewrite happens. (1ms is
+ // below the granularity of some filesystems; we don't depend on
+ // wall-clock delta β€” we depend on `changed: false` and on the
+ // mtime not advancing across the call.)
+ const secondNow = new Date("2026-05-15T11:00:00Z");
+ const second = regenerateActive(vault, { now: secondNow });
+ expect(second.changed).toBe(false);
+ const mtimeAfter = statSync(second.path).mtimeMs;
+ expect(mtimeAfter).toBe(mtimeBefore);
+ });
+
+ test("body changes when a new pref appears", () => {
+ seedConfirmed("a", "Rule A", "medium");
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+
+ seedConfirmed("b", "Rule B", "medium");
+ const result = regenerateActive(vault, { now: new Date("2026-05-15T11:00:00Z") });
+ expect(result.changed).toBe(true);
+ const body = readActive();
+ expect(body).toContain("pref-a");
+ expect(body).toContain("pref-b");
+ });
+});
+
+describe("regenerateActive β€” corruption tolerance", () => {
+ test("a corrupted preference file is omitted from the render, not fatal", () => {
+ seedConfirmed("healthy", "Healthy rule", "high");
+ // Drop a broken file directly into preferences/.
+ atomicWriteFileSync(preferencePath(vault, "corrupted"), "not valid frontmatter\n");
+
+ const result = regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+ expect(result.counts.confirmed).toBe(1);
+ const body = readActive();
+ expect(body).toContain("pref-healthy");
+ expect(body).not.toContain("pref-corrupted");
+ });
+});
diff --git a/tests/core/brain.apply-evidence.test.ts b/tests/core/brain.apply-evidence.test.ts
index 7e9c36d6..d9f80e4d 100644
--- a/tests/core/brain.apply-evidence.test.ts
+++ b/tests/core/brain.apply-evidence.test.ts
@@ -163,7 +163,7 @@ describe("appendApplyEvidence β€” log file creation on first event", () => {
result: "neutral" as unknown as "applied",
agent: "claude",
}),
- ).toThrow(/must be 'applied' or 'violated'/);
+ ).toThrow(/must be 'applied', 'violated', or 'outdated'/);
});
test("missing required input fields throw naming the field", () => {
@@ -194,3 +194,61 @@ describe("appendApplyEvidence β€” log file creation on first event", () => {
).toThrow(/missing field: agent/);
});
});
+
+describe("appendApplyEvidence β€” sanitisation (Β§7)", () => {
+ test("redacts secrets in artifact and note", () => {
+ prefFixture("redact-target");
+ appendApplyEvidence(
+ vault,
+ {
+ pref_id: "redact-target",
+ artifact: "[[file]] token: abcdef",
+ result: "applied",
+ agent: "claude",
+ note: 'logged with api_key=hunter2 here',
+ },
+ { now: new Date("2026-05-15T10:00:00Z") },
+ );
+ const { entries } = parseLogDay(vault, "2026-05-15");
+ const ev = entries.find((e) => e.eventType === "apply-evidence");
+ expect(ev).toBeDefined();
+ const artifact = String(ev!.body["artifact"] ?? "");
+ expect(artifact).toContain("***REDACTED***");
+ expect(artifact).not.toContain("abcdef");
+ const note = String(ev!.body["note"] ?? "");
+ expect(note).toContain("***REDACTED***");
+ expect(note).not.toContain("hunter2");
+ });
+
+ test("strips C0 controls in artifact and caps note length", () => {
+ prefFixture("cap-target");
+ appendApplyEvidence(
+ vault,
+ {
+ pref_id: "cap-target",
+ artifact: "[[fi\x07le]]",
+ result: "applied",
+ agent: "claude",
+ note: "x".repeat(8000),
+ },
+ { now: new Date("2026-05-15T11:00:00Z") },
+ );
+ const { entries } = parseLogDay(vault, "2026-05-15");
+ const ev = entries.find((e) => e.eventType === "apply-evidence");
+ expect(ev).toBeDefined();
+ expect(String(ev!.body["artifact"])).not.toContain("\x07");
+ expect(String(ev!.body["note"]).length).toBeLessThanOrEqual(4096);
+ });
+
+ test("rejects when sanitisation strips artifact down to empty", () => {
+ prefFixture("empty-artifact");
+ expect(() =>
+ appendApplyEvidence(vault, {
+ pref_id: "empty-artifact",
+ artifact: "\x00\x07",
+ result: "applied",
+ agent: "claude",
+ }),
+ ).toThrow(/missing field: artifact/);
+ });
+});
diff --git a/tests/core/brain.backlinks.test.ts b/tests/core/brain.backlinks.test.ts
new file mode 100644
index 00000000..1e8382f7
--- /dev/null
+++ b/tests/core/brain.backlinks.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ backlinkCount,
+ buildBacklinkIndex,
+} from "../../src/core/brain/backlinks.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writePreference, moveToRetired } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { appendApplyEvidence } from "../../src/core/brain/apply-evidence.ts";
+import { preferencePath } from "../../src/core/brain/paths.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-backlinks-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-backlinks-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+describe("buildBacklinkIndex β€” empty Brain", () => {
+ test("returns an empty index", () => {
+ const idx = buildBacklinkIndex(vault);
+ expect(idx.size).toBe(0);
+ expect(backlinkCount(idx, "pref-foo")).toBe(0);
+ });
+});
+
+describe("buildBacklinkIndex β€” preference evidenced_by", () => {
+ test("indexes signal refs from evidenced_by[]", () => {
+ writeSignal(vault, {
+ topic: "rule",
+ signal: "negative",
+ agent: "claude",
+ principle: "test",
+ created_at: "2026-05-14T10:00:00Z",
+ date: "2026-05-14",
+ slug: "alpha",
+ });
+ writePreference(vault, {
+ slug: "rule",
+ topic: "rule",
+ principle: "test",
+ created_at: "2026-05-14T11:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-2026-05-14-alpha]]"],
+ });
+
+ const idx = buildBacklinkIndex(vault);
+ expect(backlinkCount(idx, "sig-2026-05-14-alpha")).toBe(1);
+ const refs = idx.get("sig-2026-05-14-alpha")!;
+ expect(refs[0]!.source).toBe("pref-rule");
+ expect(refs[0]!.sourceKind).toBe("preference");
+ expect(refs[0]!.field).toBe("evidenced_by");
+ });
+});
+
+describe("buildBacklinkIndex β€” retired bookkeeping", () => {
+ test("indexes superseded_by / retired_by on retired entries", () => {
+ writePreference(vault, {
+ slug: "old",
+ topic: "old",
+ principle: "old",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-15T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ });
+ writePreference(vault, {
+ slug: "new",
+ topic: "old",
+ principle: "new",
+ created_at: "2026-05-10T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-11T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ });
+ moveToRetired(vault, preferencePath(vault, "old"), "rebutted", {
+ now: new Date("2026-05-12T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-12]]",
+ superseded_by: "[[pref-new]]",
+ });
+
+ const idx = buildBacklinkIndex(vault);
+ // ret-old references pref-new via superseded_by
+ expect(backlinkCount(idx, "pref-new")).toBeGreaterThanOrEqual(1);
+ const refs = idx.get("pref-new")!;
+ const supersededRef = refs.find((r) => r.field === "superseded_by");
+ expect(supersededRef).toBeDefined();
+ expect(supersededRef!.source).toBe("ret-old");
+ expect(supersededRef!.sourceKind).toBe("retired");
+ });
+});
+
+describe("buildBacklinkIndex β€” log apply-evidence entries", () => {
+ test("indexes preference references from log payloads", () => {
+ writePreference(vault, {
+ slug: "logged",
+ topic: "logged",
+ principle: "rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ appendApplyEvidence(
+ vault,
+ { pref_id: "logged", artifact: "[[some-file]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-05T10:00:00Z") },
+ );
+
+ const idx = buildBacklinkIndex(vault);
+ expect(backlinkCount(idx, "pref-logged")).toBeGreaterThanOrEqual(1);
+ const refs = idx.get("pref-logged")!;
+ const logRef = refs.find((r) => r.sourceKind === "log-apply-evidence");
+ expect(logRef).toBeDefined();
+ expect(logRef!.source).toMatch(/^log-\d{4}-\d{2}-\d{2}$/);
+ expect(logRef!.timestamp).toBe("2026-05-05T10:00:00Z");
+ });
+});
+
+describe("buildBacklinkIndex β€” self-reference skip", () => {
+ test("does not record a pref as a backlink to itself", () => {
+ writePreference(vault, {
+ slug: "self",
+ topic: "self",
+ principle: "rule referencing [[pref-self]] in body",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("pref-self") ?? [];
+ expect(refs.find((r) => r.source === "pref-self")).toBeUndefined();
+ });
+});
+
+describe("buildBacklinkIndex β€” frozen result", () => {
+ test("returned arrays are frozen", () => {
+ writePreference(vault, {
+ slug: "frozen",
+ topic: "frozen",
+ principle: "test",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-2026-05-01-x]]"],
+ });
+ const idx = buildBacklinkIndex(vault);
+ const refs = idx.get("sig-2026-05-01-x");
+ expect(refs).toBeDefined();
+ expect(() => (refs as Array<unknown>).push({} as never)).toThrow();
+ });
+});
diff --git a/tests/core/brain.digest.test.ts b/tests/core/brain.digest.test.ts
index fc2fe190..5921d80e 100644
--- a/tests/core/brain.digest.test.ts
+++ b/tests/core/brain.digest.test.ts
@@ -352,3 +352,123 @@ describe("validation", () => {
).toThrow(RangeError);
});
});
+
+describe("top_applied / top_referenced sections", () => {
+ test("top_applied includes confirmed/quarantine prefs sorted by applied_count desc", () => {
+ writePreference(
+ tmp,
+ basePref("hot-a", {
+ status: "confirmed",
+ confirmed_at: "2026-05-01T00:00:00Z",
+ applied_count: 10,
+ violated_count: 1,
+ confidence: "high",
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("hot-b", {
+ status: "confirmed",
+ confirmed_at: "2026-05-01T00:00:00Z",
+ applied_count: 5,
+ confidence: "medium",
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("quarantine-c", {
+ status: "quarantine",
+ confirmed_at: "2026-05-01T00:00:00Z",
+ applied_count: 3,
+ violated_count: 4,
+ confidence: "low",
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("never-applied", {
+ status: "confirmed",
+ confirmed_at: "2026-05-01T00:00:00Z",
+ applied_count: 0,
+ }),
+ );
+
+ // Trigger a non-empty window so the markdown path renders (Top
+ // sections only render when there were window-changes β€” confirmed
+ // earlier in this same window provides that.).
+ const r = renderDigest(tmp, {
+ since: new Date("2026-04-30T00:00:00Z"),
+ until: new Date("2026-05-05T00:00:00Z"),
+ format: "json",
+ });
+ const json = JSON.parse(r.content) as DigestJson;
+ expect(json.top_applied.map((x) => x.id)).toEqual([
+ "pref-hot-a",
+ "pref-hot-b",
+ "pref-quarantine-c",
+ ]);
+ expect(json.top_applied[0]!.applied_count).toBe(10);
+ expect(json.top_applied[2]!.status).toBe("quarantine");
+ // applied_count: 0 prefs are excluded.
+ expect(json.top_applied.find((x) => x.id === "pref-never-applied")).toBeUndefined();
+ });
+
+ test("Markdown renders Top applied with the quarantine tag", () => {
+ writePreference(
+ tmp,
+ basePref("hot", {
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 7,
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("quar", {
+ status: "quarantine",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 3,
+ violated_count: 4,
+ }),
+ );
+ const r = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "markdown" });
+ expect(r.content).toContain("## Top applied (2)");
+ expect(r.content).toContain("[[pref-hot]]");
+ expect(r.content).toContain("[[pref-quar]]");
+ expect(r.content).toContain("[quarantine]");
+ });
+
+ test("top_referenced counts inbound wikilinks per pref", () => {
+ writePreference(
+ tmp,
+ basePref("target", {
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 1,
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("source-1", {
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 1,
+ evidenced_by: ["[[pref-target]]"],
+ }),
+ );
+ writePreference(
+ tmp,
+ basePref("source-2", {
+ status: "confirmed",
+ confirmed_at: SINCE.toISOString(),
+ applied_count: 1,
+ evidenced_by: ["[[pref-target]]"],
+ }),
+ );
+ const r = renderDigest(tmp, { since: SINCE, until: UNTIL, format: "json" });
+ const json = JSON.parse(r.content) as DigestJson;
+ const targetEntry = json.top_referenced.find((x) => x.id === "pref-target");
+ expect(targetEntry).toBeDefined();
+ expect(targetEntry!.backlink_count).toBeGreaterThanOrEqual(2);
+ });
+});
diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.ts
index 3c9e5076..01f0dca4 100644
--- a/tests/core/brain.doctor.test.ts
+++ b/tests/core/brain.doctor.test.ts
@@ -408,3 +408,326 @@ describe("missing config", () => {
expect(res.errors.some((e) => e.code === "config-missing")).toBe(true);
});
});
+
+describe("duplicate-preferences lint", () => {
+ test("flags two confirmed prefs in the same (topic, scope) bucket with similar principles", () => {
+ writePreference(tmp, {
+ slug: "a",
+ topic: "tidy",
+ principle: "Be tidy and consistent in writing",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ scope: "writing",
+ });
+ writePreference(tmp, {
+ slug: "b",
+ topic: "tidy",
+ principle: "Be tidy and consistent when writing",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ scope: "writing",
+ });
+ const res = runDoctor(tmp);
+ const dup = res.warnings.find((w) => w.code === "duplicate-preferences");
+ expect(dup).toBeDefined();
+ expect(dup!.message).toContain("pref-a");
+ expect(dup!.message).toContain("pref-b");
+ });
+
+ test("does NOT flag prefs in different topics even with identical principles", () => {
+ writePreference(tmp, {
+ slug: "x",
+ topic: "alpha",
+ principle: "Identical principle text here",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ });
+ writePreference(tmp, {
+ slug: "y",
+ topic: "beta",
+ principle: "Identical principle text here",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ });
+ const res = runDoctor(tmp);
+ expect(
+ res.warnings.find((w) => w.code === "duplicate-preferences"),
+ ).toBeUndefined();
+ });
+});
+
+describe("low-evidence-confirmed lint", () => {
+ test("flags confirmed pref with applied_count ≀ low_max_applied past trial window", () => {
+ // Default config: low_max_applied=2, unconfirmed_window_days=14.
+ writePreference(tmp, {
+ slug: "stagnant",
+ topic: "stagnant",
+ principle: "Got promoted but never applied",
+ created_at: "2026-04-01T00:00:00Z",
+ unconfirmed_until: "2026-04-15T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-04-05T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1, // ≀ low_max_applied (2)
+ });
+ const now = new Date("2026-05-15T00:00:00Z"); // 40 days past confirmed_at
+ const res = runDoctor(tmp, { now });
+ const low = res.warnings.find((w) => w.code === "low-evidence-confirmed");
+ expect(low).toBeDefined();
+ expect(low!.message).toContain("pref-stagnant");
+ });
+
+ test("does NOT flag prefs still within the trial window", () => {
+ writePreference(tmp, {
+ slug: "fresh",
+ topic: "fresh",
+ principle: "Just promoted",
+ created_at: "2026-05-10T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-10T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ });
+ const now = new Date("2026-05-12T00:00:00Z"); // 2 days past confirmed
+ const res = runDoctor(tmp, { now });
+ expect(
+ res.warnings.find((w) => w.code === "low-evidence-confirmed"),
+ ).toBeUndefined();
+ });
+});
+
+describe("pinned-without-recent-evidence lint", () => {
+ test("flags pinned pref with no evidence", () => {
+ writePreference(tmp, {
+ slug: "pinned-empty",
+ topic: "pinned-empty",
+ principle: "Pinned but never applied",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 0,
+ last_evidence_at: null,
+ pinned: true,
+ });
+ const res = runDoctor(tmp);
+ const w = res.warnings.find((x) => x.code === "pinned-without-recent-evidence");
+ expect(w).toBeDefined();
+ expect(w!.message).toContain("pref-pinned-empty");
+ });
+
+ test("flags pinned pref with stale evidence past stale_evidence_days", () => {
+ // Default config: stale_evidence_days=30.
+ writePreference(tmp, {
+ slug: "pinned-stale",
+ topic: "pinned-stale",
+ principle: "Pinned but stale",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-15T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-01-05T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 5,
+ last_evidence_at: "2026-01-10T00:00:00Z",
+ pinned: true,
+ });
+ const now = new Date("2026-05-15T00:00:00Z"); // 125 days past last evidence
+ const res = runDoctor(tmp, { now });
+ expect(
+ res.warnings.find((w) => w.code === "pinned-without-recent-evidence"),
+ ).toBeDefined();
+ });
+
+ test("does NOT flag unpinned prefs", () => {
+ writePreference(tmp, {
+ slug: "unpinned-stale",
+ topic: "unpinned-stale",
+ principle: "Stale but not pinned",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-15T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-01-05T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 5,
+ last_evidence_at: "2026-01-10T00:00:00Z",
+ pinned: false,
+ });
+ const now = new Date("2026-05-15T00:00:00Z");
+ const res = runDoctor(tmp, { now });
+ expect(
+ res.warnings.find((w) => w.code === "pinned-without-recent-evidence"),
+ ).toBeUndefined();
+ });
+});
+
+describe("malformed-evidence-range lint", () => {
+ test("flags an apply-evidence with reversed start-end", () => {
+ // Hand-craft a log entry; we don't need a real pref file because
+ // doctor's lint walks log entries directly.
+ writeFileSync(
+ logPath(tmp, "2026-05-14"),
+ `---
+kind: brain-log
+date: 2026-05-14
+tags: [brain, brain/log]
+---
+
+# Brain Log β€” 2026-05-14
+
+## 10:00:00Z β€” apply-evidence
+
+- preference: [[pref-foo]]
+- artifact: [[file:120-100]]
+- agent: claude
+- result: applied
+`,
+ "utf8",
+ );
+ const res = runDoctor(tmp);
+ const w = res.warnings.find((x) => x.code === "malformed-evidence-range");
+ expect(w).toBeDefined();
+ expect(w!.message).toContain("120-100");
+ });
+
+ test("does NOT flag well-formed ranges or bare wikilinks", () => {
+ writeFileSync(
+ logPath(tmp, "2026-05-14"),
+ `---
+kind: brain-log
+date: 2026-05-14
+tags: [brain, brain/log]
+---
+
+# Brain Log β€” 2026-05-14
+
+## 10:00:00Z β€” apply-evidence
+
+- preference: [[pref-foo]]
+- artifact: [[file:120-145]]
+- agent: claude
+- result: applied
+
+## 11:00:00Z β€” apply-evidence
+
+- preference: [[pref-bar]]
+- artifact: [[other]]
+- agent: claude
+- result: applied
+`,
+ "utf8",
+ );
+ const res = runDoctor(tmp);
+ expect(
+ res.warnings.find((w) => w.code === "malformed-evidence-range"),
+ ).toBeUndefined();
+ });
+});
+
+describe("orphan-evidence lint", () => {
+ test("flags an apply-evidence whose artifact wikilink doesn't resolve", () => {
+ writeFileSync(
+ logPath(tmp, "2026-05-14"),
+ `---
+kind: brain-log
+date: 2026-05-14
+tags: [brain, brain/log]
+---
+
+# Brain Log β€” 2026-05-14
+
+## 10:00:00Z β€” apply-evidence
+
+- preference: [[pref-foo]]
+- artifact: [[missing-vault-page]]
+- agent: claude
+- result: applied
+`,
+ "utf8",
+ );
+ const res = runDoctor(tmp);
+ const w = res.warnings.find((x) => x.code === "orphan-evidence");
+ expect(w).toBeDefined();
+ expect(w!.message).toContain("missing-vault-page");
+ });
+});
+
+describe("broken backlinks", () => {
+ test("flags a wikilink target that no longer exists as a file", () => {
+ // pref-alive references sig-missing, but no such signal file exists.
+ writePreference(tmp, {
+ slug: "alive",
+ topic: "alive",
+ principle: "Live rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-missing]]"],
+ });
+
+ const res = runDoctor(tmp);
+ const broken = res.warnings.filter((w) => w.code === "broken-backlinks");
+ expect(broken.length).toBeGreaterThan(0);
+ const sigMissing = broken.find((w) => w.message.includes("[[sig-missing]]"));
+ expect(sigMissing).toBeDefined();
+ expect(sigMissing!.message).toContain("pref-alive");
+ });
+
+ test("does not flag references whose targets exist", () => {
+ writeSignal(tmp, {
+ topic: "real",
+ signal: "negative",
+ agent: "claude",
+ principle: "test",
+ created_at: "2026-05-01T10:00:00Z",
+ date: "2026-05-01",
+ slug: "present",
+ });
+ writePreference(tmp, {
+ slug: "real",
+ topic: "real",
+ principle: "test",
+ created_at: "2026-05-01T11:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-2026-05-01-present]]"],
+ });
+ const res = runDoctor(tmp);
+ expect(res.warnings.filter((w) => w.code === "broken-backlinks")).toHaveLength(0);
+ });
+
+ test("ignores wikilinks pointing outside the Brain namespace", () => {
+ // Writing a preference whose principle mentions a Daily/-style
+ // wikilink that doesn't match the pref-/ret-/sig- prefix policy.
+ // The body wikilink resolves to a non-Brain id and we must NOT
+ // flag it β€” Daily and AI Wiki references are user prose.
+ writePreference(tmp, {
+ slug: "with-prose",
+ topic: "with-prose",
+ principle: "Refer to [[Some Wiki Page]] for details",
+ created_at: "2026-05-01T11:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ const res = runDoctor(tmp);
+ expect(res.warnings.filter((w) => w.code === "broken-backlinks")).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain.dream.test.ts b/tests/core/brain.dream.test.ts
index ffa87973..898c8da3 100644
--- a/tests/core/brain.dream.test.ts
+++ b/tests/core/brain.dream.test.ts
@@ -533,3 +533,296 @@ describe("dream β€” empty Brain (no signals, no prefs)", () => {
expect(existsSync(brainConfigPath(vault))).toBe(true);
});
});
+
+// ----- Quarantine ---------------------------------------------------------
+//
+// Default brain config (`policy.ts`): low_max_applied = 2. The entry
+// condition is `violated_count β‰₯ applied_count AND applied_count >
+// low_max_applied`, so the smallest fixture needs applied β‰₯ 3 with
+// violated β‰₯ applied. We seed evidence directly through the log.
+
+describe("dream β€” quarantine entry", () => {
+ test("confirmed pref crosses violatedβ‰₯applied with applied>low_max β†’ quarantine", () => {
+ writePreference(vault, {
+ slug: "quarantine-target",
+ topic: "quarantine-target",
+ principle: "Trial rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: "low",
+ });
+ // 3 applied + 3 violated β†’ entry condition met (applied=3 > 2 and violated=3 β‰₯ applied=3).
+ for (let i = 0; i < 3; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "quarantine-target", artifact: "[[a]]", result: "applied", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 3}T10:00:00Z`) },
+ );
+ }
+ for (let i = 0; i < 3; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "quarantine-target", artifact: "[[b]]", result: "violated", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 6}T10:00:00Z`) },
+ );
+ }
+
+ const res = dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ expect(res.changed).toBe(true);
+
+ const pref = parsePreference(preferencePath(vault, "quarantine-target"));
+ expect(pref.status).toBe("quarantine");
+ expect(pref.applied_count).toBe(3);
+ expect(pref.violated_count).toBe(3);
+ // The pref stays in preferences/, NOT retired.
+ expect(listPreferences()).toContain("pref-quarantine-target.md");
+ expect(listRetired()).not.toContain("ret-quarantine-target.md");
+ });
+
+ test("low_max_applied gating β€” applied=2 with violated=2 stays confirmed", () => {
+ writePreference(vault, {
+ slug: "below-threshold",
+ topic: "below-threshold",
+ principle: "Trial rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 0,
+ violated_count: 0,
+ last_evidence_at: null,
+ confidence: "low",
+ });
+ for (let i = 0; i < 2; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "below-threshold", artifact: "[[a]]", result: "applied", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 3}T10:00:00Z`) },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "below-threshold", artifact: "[[b]]", result: "violated", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 5}T10:00:00Z`) },
+ );
+ }
+
+ dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ const pref = parsePreference(preferencePath(vault, "below-threshold"));
+ expect(pref.status).toBe("confirmed");
+ });
+});
+
+describe("dream β€” quarantine β†’ retired (quarantine-violated)", () => {
+ test("new violated event on quarantine pref retires it", () => {
+ // Seed an already-quarantined pref directly: writePreference
+ // accepts the new status. applied=3, violated=3 is the persisted
+ // snapshot. Then add one more violated event in the log so
+ // dream sees violated > rec.pref.violated_count.
+ writePreference(vault, {
+ slug: "to-retire",
+ topic: "to-retire",
+ principle: "Probationary rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "quarantine",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 3,
+ last_evidence_at: "2026-05-08T00:00:00Z",
+ confidence: "low",
+ });
+ // Mirror those counters in the log so the recompute matches the
+ // persisted snapshot, then add the trigger event.
+ for (let i = 0; i < 3; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "to-retire", artifact: "[[a]]", result: "applied", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 3}T10:00:00Z`) },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "to-retire", artifact: "[[b]]", result: "violated", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 6}T10:00:00Z`) },
+ );
+ }
+ appendApplyEvidence(
+ vault,
+ { pref_id: "to-retire", artifact: "[[c]]", result: "violated", agent: "claude" },
+ { now: new Date("2026-05-09T10:00:00Z") },
+ );
+
+ const res = dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ expect(res.changed).toBe(true);
+ expect(listPreferences()).not.toContain("pref-to-retire.md");
+ expect(listRetired()).toContain("ret-to-retire.md");
+
+ const retired = parseRetired(retiredPath(vault, "to-retire"));
+ expect(retired.retired_reason).toBe("quarantine-violated");
+ expect(res.retired.map((r) => r.reason)).toContain("quarantine-violated");
+ });
+
+ test("pinned quarantine pref logs retain-pinned instead of retiring", () => {
+ writePreference(vault, {
+ slug: "pinned-quar",
+ topic: "pinned-quar",
+ principle: "Pinned rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "quarantine",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 3,
+ last_evidence_at: "2026-05-08T00:00:00Z",
+ confidence: "low",
+ pinned: true,
+ });
+ for (let i = 0; i < 3; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "pinned-quar", artifact: "[[a]]", result: "applied", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 3}T10:00:00Z`) },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "pinned-quar", artifact: "[[b]]", result: "violated", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 6}T10:00:00Z`) },
+ );
+ }
+ appendApplyEvidence(
+ vault,
+ { pref_id: "pinned-quar", artifact: "[[c]]", result: "violated", agent: "claude" },
+ { now: new Date("2026-05-09T10:00:00Z") },
+ );
+
+ dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ expect(listPreferences()).toContain("pref-pinned-quar.md");
+ expect(listRetired()).not.toContain("ret-pinned-quar.md");
+ const log = parseLogDay(vault, "2026-05-10");
+ const blocked = log.entries.find(
+ (e) =>
+ e.eventType === "retire" &&
+ e.body["preference"] === "[[pref-pinned-quar]]" &&
+ e.body["blocked"] === "pinned",
+ );
+ expect(blocked).toBeDefined();
+ expect(blocked!.body["reason"]).toBe("quarantine-violated");
+ });
+});
+
+describe("dream β€” outdated evidence retires with superseded-by-context", () => {
+ test("single outdated event retires a confirmed pref", () => {
+ writePreference(vault, {
+ slug: "context-shift",
+ topic: "context-shift",
+ principle: "Recoverable rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 4,
+ violated_count: 0,
+ last_evidence_at: "2026-05-08T00:00:00Z",
+ confidence: "medium",
+ });
+ appendApplyEvidence(
+ vault,
+ { pref_id: "context-shift", artifact: "[[x]]", result: "outdated", agent: "claude" },
+ { now: new Date("2026-05-09T10:00:00Z") },
+ );
+
+ const res = dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ expect(res.changed).toBe(true);
+ expect(listPreferences()).not.toContain("pref-context-shift.md");
+ expect(listRetired()).toContain("ret-context-shift.md");
+ const retired = parseRetired(retiredPath(vault, "context-shift"));
+ expect(retired.retired_reason).toBe("superseded-by-context");
+ expect(res.retired.map((r) => r.reason)).toContain("superseded-by-context");
+ });
+
+ test("pinned pref also retires on outdated β€” pin doesn't protect against context shifts", () => {
+ writePreference(vault, {
+ slug: "pinned-outdated",
+ topic: "pinned-outdated",
+ principle: "Pinned rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 0,
+ last_evidence_at: "2026-05-08T00:00:00Z",
+ confidence: "medium",
+ pinned: true,
+ });
+ appendApplyEvidence(
+ vault,
+ { pref_id: "pinned-outdated", artifact: "[[x]]", result: "outdated", agent: "claude" },
+ { now: new Date("2026-05-09T10:00:00Z") },
+ );
+
+ const res = dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ expect(res.changed).toBe(true);
+ expect(listPreferences()).not.toContain("pref-pinned-outdated.md");
+ expect(listRetired()).toContain("ret-pinned-outdated.md");
+ });
+});
+
+describe("dream β€” quarantine β†’ confirmed (recovery)", () => {
+ test("applied > violated returns quarantine pref to confirmed", () => {
+ writePreference(vault, {
+ slug: "recover",
+ topic: "recover",
+ principle: "Recoverable rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "quarantine",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 3,
+ last_evidence_at: "2026-05-08T00:00:00Z",
+ confidence: "low",
+ });
+ for (let i = 0; i < 3; i++) {
+ appendApplyEvidence(
+ vault,
+ { pref_id: "recover", artifact: "[[a]]", result: "applied", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 3}T10:00:00Z`) },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "recover", artifact: "[[b]]", result: "violated", agent: "claude" },
+ { now: new Date(`2026-05-0${i + 6}T10:00:00Z`) },
+ );
+ }
+ // Two fresh applied events flip the balance: applied=5 > violated=3.
+ appendApplyEvidence(
+ vault,
+ { pref_id: "recover", artifact: "[[c]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-09T10:00:00Z") },
+ );
+ appendApplyEvidence(
+ vault,
+ { pref_id: "recover", artifact: "[[d]]", result: "applied", agent: "claude" },
+ { now: new Date("2026-05-09T11:00:00Z") },
+ );
+
+ dream(vault, { now: new Date("2026-05-10T00:00:00Z") });
+ const pref = parsePreference(preferencePath(vault, "recover"));
+ expect(pref.status).toBe("confirmed");
+ expect(pref.applied_count).toBe(5);
+ expect(pref.violated_count).toBe(3);
+ expect(listRetired()).not.toContain("ret-recover.md");
+ });
+});
diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.ts
index 7fbb3cb2..3b7b7bb2 100644
--- a/tests/core/brain.signal.test.ts
+++ b/tests/core/brain.signal.test.ts
@@ -208,3 +208,52 @@ describe("writeSignal β€” slug collision allocator", () => {
expect(c.id).toBe("sig-2026-05-14-no-internal-abbrev-3");
});
});
+
+describe("writeSignal β€” sanitisation (Β§7)", () => {
+ test("redacts secrets in principle / scope / raw", () => {
+ const r = writeSignal(
+ tmp,
+ baseInput({
+ slug: "sec",
+ principle: "do not put api_key=hunter2 anywhere",
+ scope: "writing token: abcd",
+ raw: 'config = {"client_secret": "shhh"}',
+ }),
+ );
+ const round = parseSignal(r.path);
+ expect(round.principle).toContain("***REDACTED***");
+ expect(round.principle).not.toContain("hunter2");
+ expect(round.scope).toContain("***REDACTED***");
+ expect(round.scope).not.toContain("abcd");
+ expect(round.raw).toContain("***REDACTED***");
+ expect(round.raw).not.toContain("shhh");
+ });
+
+ test("strips C0 controls and folds U+2028/U+2029 in principle", () => {
+ // U+2028 = line separator. C0 byte 0x07 (BEL) should be stripped.
+ const r = writeSignal(
+ tmp,
+ baseInput({
+ slug: "ctrl",
+ principle: "be\x07tidy line2",
+ }),
+ );
+ const round = parseSignal(r.path);
+ expect(round.principle).not.toContain("\x07");
+ // singleLine collapses the folded LF to space.
+ expect(round.principle).toBe("betidy line2");
+ });
+
+ test("caps principle at 512 chars", () => {
+ const huge = "a".repeat(2000);
+ const r = writeSignal(tmp, baseInput({ slug: "big", principle: huge }));
+ const round = parseSignal(r.path);
+ expect(round.principle.length).toBeLessThanOrEqual(512);
+ });
+
+ test("rejects when sanitisation strips principle down to empty", () => {
+ expect(() =>
+ writeSignal(tmp, baseInput({ slug: "empty", principle: "\x00\x01\x07" })),
+ ).toThrow(/signal missing field: principle/);
+ });
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index cc1a790b..d74aacd7 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -30,6 +30,7 @@ describe("BRAIN_* const enums", () => {
test("BRAIN_PREFERENCE_STATUS values", () => {
expect(BRAIN_PREFERENCE_STATUS.unconfirmed).toBe("unconfirmed");
expect(BRAIN_PREFERENCE_STATUS.confirmed).toBe("confirmed");
+ expect(BRAIN_PREFERENCE_STATUS.quarantine).toBe("quarantine");
});
test("BRAIN_CONFIDENCE values", () => {
@@ -38,16 +39,19 @@ describe("BRAIN_* const enums", () => {
expect(BRAIN_CONFIDENCE.high).toBe("high");
});
- test("BRAIN_RETIRED_REASON covers all four reasons from Β§7.4", () => {
+ test("BRAIN_RETIRED_REASON covers every reason emitted by dream / CLI", () => {
expect(BRAIN_RETIRED_REASON.staleNoEvidence).toBe("stale-no-evidence");
expect(BRAIN_RETIRED_REASON.expiredUnconfirmed).toBe("expired-unconfirmed");
expect(BRAIN_RETIRED_REASON.rebutted).toBe("rebutted");
expect(BRAIN_RETIRED_REASON.userRejected).toBe("user-rejected");
+ expect(BRAIN_RETIRED_REASON.quarantineViolated).toBe("quarantine-violated");
+ expect(BRAIN_RETIRED_REASON.supersededByContext).toBe("superseded-by-context");
});
test("BRAIN_APPLY_RESULT values", () => {
expect(BRAIN_APPLY_RESULT.applied).toBe("applied");
expect(BRAIN_APPLY_RESULT.violated).toBe("violated");
+ expect(BRAIN_APPLY_RESULT.outdated).toBe("outdated");
});
test("BRAIN_LOG_EVENT_KIND covers every event type listed in Β§5.5 / Β§7.4", () => {
diff --git a/tests/core/brain.wikilink.test.ts b/tests/core/brain.wikilink.test.ts
new file mode 100644
index 00000000..ca1f95a1
--- /dev/null
+++ b/tests/core/brain.wikilink.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ normaliseWikilinkTarget,
+ parseArtifactRef,
+ parseWikilink,
+} from "../../src/core/brain/wikilink.ts";
+
+describe("normaliseWikilinkTarget β€” existing helper", () => {
+ test("strips wikilink decoration, alias, anchor, folder, .md", () => {
+ expect(normaliseWikilinkTarget("[[Folder/file.md|Alias]]")).toBe("file");
+ expect(normaliseWikilinkTarget("[[file#section]]")).toBe("file");
+ });
+});
+
+describe("parseWikilink", () => {
+ test("returns target only when input is exactly a wikilink", () => {
+ expect(parseWikilink("[[foo]]")).toBe("foo");
+ expect(parseWikilink("see [[foo]]")).toBeNull();
+ expect(parseWikilink("foo")).toBeNull();
+ });
+});
+
+describe("parseArtifactRef β€” bare wikilink", () => {
+ test("returns target with no range", () => {
+ const r = parseArtifactRef("[[file]]");
+ expect(r.target).toBe("file");
+ expect(r.range).toBeUndefined();
+ expect(r.malformedRange).toBeUndefined();
+ });
+
+ test("normalises folder / .md / alias / anchor", () => {
+ expect(parseArtifactRef("[[Folder/file.md|Alias]]").target).toBe("file");
+ expect(parseArtifactRef("[[file#section]]").target).toBe("file");
+ });
+
+ test("accepts bare text (no `[[…]]`) as a target", () => {
+ expect(parseArtifactRef("blog-post").target).toBe("blog-post");
+ });
+});
+
+describe("parseArtifactRef β€” well-formed ranges", () => {
+ test("colon-N-N parses to inclusive range", () => {
+ const r = parseArtifactRef("[[file:120-145]]");
+ expect(r.target).toBe("file");
+ expect(r.range).toEqual({ start: 120, end: 145 });
+ expect(r.malformedRange).toBeUndefined();
+ expect(r.rangeText).toBe("120-145");
+ });
+
+ test("colon-N (single line) parses to start === end", () => {
+ const r = parseArtifactRef("[[file:42]]");
+ expect(r.range).toEqual({ start: 42, end: 42 });
+ });
+
+ test("range works with folder + .md", () => {
+ const r = parseArtifactRef("[[src/feature.ts:10-20]]");
+ expect(r.target).toBe("feature.ts");
+ expect(r.range).toEqual({ start: 10, end: 20 });
+ });
+
+ test("range survives alias suffix", () => {
+ const r = parseArtifactRef("[[file:10-20|Excerpt]]");
+ expect(r.target).toBe("file");
+ expect(r.range).toEqual({ start: 10, end: 20 });
+ });
+});
+
+describe("parseArtifactRef β€” malformed ranges", () => {
+ test("non-numeric range marks malformedRange", () => {
+ const r = parseArtifactRef("[[file:abc-def]]");
+ expect(r.target).toBe("file");
+ expect(r.malformedRange).toBe(true);
+ expect(r.range).toBeUndefined();
+ expect(r.rangeText).toBe("abc-def");
+ });
+
+ test("reversed start/end marks malformedRange", () => {
+ const r = parseArtifactRef("[[file:120-100]]");
+ expect(r.target).toBe("file");
+ expect(r.range).toBeUndefined();
+ expect(r.malformedRange).toBe(true);
+ expect(r.rangeText).toBe("120-100");
+ });
+
+ test("zero-start marks malformedRange (lines are 1-based)", () => {
+ const r = parseArtifactRef("[[file:0-10]]");
+ expect(r.malformedRange).toBe(true);
+ });
+
+ test("dangling dash marks malformedRange", () => {
+ const r = parseArtifactRef("[[file:120-]]");
+ expect(r.malformedRange).toBe(true);
+ });
+
+ test("empty range marks malformedRange", () => {
+ const r = parseArtifactRef("[[file:]]");
+ expect(r.target).toBe("file");
+ expect(r.malformedRange).toBe(true);
+ expect(r.range).toBeUndefined();
+ expect(r.rangeText).toBe("");
+ });
+});
+
+describe("parseArtifactRef β€” raw is preserved", () => {
+ test("raw equals the original input verbatim", () => {
+ const input = "[[file:120-145]]";
+ expect(parseArtifactRef(input).raw).toBe(input);
+ });
+
+ test("raw equals the original even on malformed range", () => {
+ const input = "[[file:120-100]]";
+ expect(parseArtifactRef(input).raw).toBe(input);
+ });
+});
diff --git a/tests/core/redactor.test.ts b/tests/core/redactor.test.ts
new file mode 100644
index 00000000..a602c3f4
--- /dev/null
+++ b/tests/core/redactor.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ normaliseTextField,
+ redactRawOutput,
+ sanitiseTextField,
+} from "../../src/core/redactor.ts";
+
+describe("redactRawOutput (cross-module backward compat)", () => {
+ test("masks api_key in env-style assignment", () => {
+ expect(redactRawOutput("api_key=abcd1234")).toContain("api_key=***REDACTED***");
+ });
+
+ test("masks token in YAML-style colon assignment", () => {
+ expect(redactRawOutput("token: abcdef")).toContain("token: ***REDACTED***");
+ });
+
+ test("preserves `Bearer ` prefix while masking the token", () => {
+ const out = redactRawOutput("Authorization: Bearer eyJhbGci...");
+ expect(out).toContain("Bearer ***REDACTED***");
+ });
+});
+
+describe("normaliseTextField", () => {
+ test("returns empty string for non-string input", () => {
+ expect(normaliseTextField(123 as unknown, { maxLen: 10 })).toBe("");
+ expect(normaliseTextField(null, { maxLen: 10 })).toBe("");
+ expect(normaliseTextField(undefined, { maxLen: 10 })).toBe("");
+ });
+
+ test("strips forbidden C0 control characters but keeps tab and newline", () => {
+ const input = "ok\x00\x01\x07\x08\x0B\x0C\x0E\x1F\x7Fbye";
+ expect(normaliseTextField(input, { maxLen: 100 })).toBe("okbye");
+
+ const multi = "a\tb\nc";
+ expect(normaliseTextField(multi, { maxLen: 100 })).toBe("a\tb\nc");
+ });
+
+ test("folds U+2028 / U+2029 to \\n", () => {
+ // U+2028 line separator, U+2029 paragraph separator.
+ const input = "line1
line2
line3";
+ expect(normaliseTextField(input, { maxLen: 100 })).toBe("line1\nline2\nline3");
+ });
+
+ test("singleLine collapses \\n / \\r / \\t runs to single space", () => {
+ const input = "a\n\nb\tc\r\nd";
+ expect(normaliseTextField(input, { maxLen: 100, singleLine: true })).toBe(
+ "a b c d",
+ );
+ });
+
+ test("non-singleLine normalises CRLF/CR to LF", () => {
+ expect(normaliseTextField("a\r\nb\rc", { maxLen: 100 })).toBe("a\nb\nc");
+ });
+
+ test("caps length to maxLen", () => {
+ expect(normaliseTextField("a".repeat(20), { maxLen: 5 })).toBe("aaaaa");
+ });
+
+ test("NFC-normalises combining characters", () => {
+ // "Γ©" composed (1 code unit) vs decomposed (2 code units).
+ const decomposed = "é"; // e + combining acute
+ expect(normaliseTextField(decomposed, { maxLen: 100 })).toBe("Γ©");
+ });
+
+ test("never throws on garbled UTF-16 surrogates", () => {
+ const lonely = "ok\uD800bad";
+ expect(() => normaliseTextField(lonely, { maxLen: 100 })).not.toThrow();
+ });
+});
+
+describe("sanitiseTextField", () => {
+ test("composes redact + normalise + cap", () => {
+ const input = "principle with api_key=secret123 and U+2028
here";
+ const out = sanitiseTextField(input, { maxLen: 100, singleLine: true });
+ expect(out).toContain("***REDACTED***");
+ expect(out).not.toContain("secret123");
+ expect(out).not.toContain("
");
+ });
+
+ test("returns empty for non-string input", () => {
+ expect(sanitiseTextField(undefined, { maxLen: 10 })).toBe("");
+ });
+});
diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.ts
new file mode 100644
index 00000000..bd3e4d50
--- /dev/null
+++ b/tests/hooks/active-inject.test.ts
@@ -0,0 +1,156 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HOOK = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "hooks",
+ "active-inject.ts",
+);
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hook-active-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-hook-active-cfg-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+interface RunResult {
+ readonly stdout: string;
+ readonly stderr: string;
+ readonly exit: number;
+}
+
+async function runHook(
+ payload: unknown,
+ env: Record<string, string> = {},
+): Promise<RunResult> {
+ // Bun.spawn env replaces (does not merge with) process.env when
+ // provided. We explicitly forward PATH so `bun run` can resolve its
+ // own toolchain on $PATH-only systems.
+ const inherited: Record<string, string> = {
+ PATH: process.env["PATH"] ?? "",
+ HOME: configHome,
+ };
+ const proc = Bun.spawn(["bun", "run", HOOK], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...inherited, ...env },
+ });
+ proc.stdin.write(JSON.stringify(payload));
+ await proc.stdin.end();
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const exit = await proc.exited;
+ return { stdout, stderr, exit };
+}
+
+function writeActive(body: string): void {
+ writeFileSync(join(vault, "Brain", "active.md"), body, "utf8");
+}
+
+describe("active-inject hook", () => {
+ test("injects active.md content as SessionStart additionalContext", async () => {
+ writeActive(
+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` β€” Rule body\n",
+ );
+
+ const r = await runHook(
+ {
+ hook_event_name: "SessionStart",
+ session_id: "abc",
+ },
+ { VAULT_DIR: vault },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout.endsWith("\n")).toBe(true);
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.hookEventName).toBe("SessionStart");
+ expect(out.hookSpecificOutput.additionalContext).toContain("# Active Brain Preferences");
+ expect(out.hookSpecificOutput.additionalContext).toContain("pref-foo");
+ });
+
+ test("echoes PostCompact as the hookEventName when fired post-compact", async () => {
+ writeActive(
+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (0)\n\n_No confirmed preferences yet._\n",
+ );
+
+ const r = await runHook(
+ {
+ hook_event_name: "PostCompact",
+ },
+ { VAULT_DIR: vault },
+ );
+ expect(r.exit).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.hookSpecificOutput.hookEventName).toBe("PostCompact");
+ expect(out.hookSpecificOutput.additionalContext).toContain("# Active Brain Preferences");
+ });
+
+ test("stays silent when Brain/active.md does not exist", async () => {
+ const r = await runHook(
+ { hook_event_name: "SessionStart" },
+ { VAULT_DIR: vault },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ });
+
+ test("stays silent when vault cannot be resolved (no config, no env)", async () => {
+ const r = await runHook({ hook_event_name: "SessionStart" });
+ // No VAULT_DIR, no config in $HOME β†’ resolveVault returns null.
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ });
+
+ test("stays silent on empty payload", async () => {
+ writeActive(
+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\nbody\n",
+ );
+ const proc = Bun.spawn(["bun", "run", HOOK], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ HOME: configHome,
+ VAULT_DIR: vault,
+ },
+ });
+ await proc.stdin.end();
+ const stdout = await new Response(proc.stdout).text();
+ const exit = await proc.exited;
+ expect(exit).toBe(0);
+ // Empty stdin β†’ readHookInput returns null β†’ asHookPayload returns
+ // {} β†’ we use the default "SessionStart" event name and still
+ // inject. The contract is to be useful when called by a runtime
+ // that doesn't pre-populate `hook_event_name`.
+ expect(stdout).not.toBe("");
+ const out = JSON.parse(stdout);
+ expect(out.hookSpecificOutput.hookEventName).toBe("SessionStart");
+ });
+
+ test("stays silent when active.md is empty whitespace only", async () => {
+ writeActive(" \n \n");
+ const r = await runHook(
+ { hook_event_name: "SessionStart" },
+ { VAULT_DIR: vault },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ });
+});
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index 3e7ace43..9cc36327 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -612,7 +612,7 @@ describe("deprecated MCP tools β€” advertised list", () => {
expect(names.has("second_brain_capture")).toBe(false);
});
- test("all six Brain tools are advertised", () => {
+ test("all Brain tools are advertised", () => {
const names = new Set(buildToolTable().map((t) => t.name));
for (const expected of [
"brain_feedback",
@@ -621,8 +621,68 @@ describe("deprecated MCP tools β€” advertised list", () => {
"brain_digest",
"brain_query",
"brain_doctor",
+ "brain_backlinks",
]) {
expect(names.has(expected)).toBe(true);
}
});
});
+
+// ---------------------------------------------------------------------------
+// brain_backlinks
+// ---------------------------------------------------------------------------
+
+describe("brain_backlinks", () => {
+ test("returns inbound refs for a referenced preference", async () => {
+ const server = makeServer();
+ await initialize(server);
+ writePreference(vault, {
+ slug: "tgt",
+ topic: "t",
+ principle: "target rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ });
+ writePreference(vault, {
+ slug: "src",
+ topic: "s",
+ principle: "source rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[pref-tgt]]"],
+ });
+
+ const r = (await call(server, "brain_backlinks", { id: "pref-tgt" })) as any;
+ const s = r.result.structuredContent;
+ expect(s.id).toBe("pref-tgt");
+ // pref-src references pref-tgt once (evidenced_by). The pref body
+ // mirrors evidenced_by under `## Origin`, but the index dedupes
+ // by (source, target) so the count is exactly 1.
+ expect(s.count).toBe(1);
+ const sources = s.refs.map((x: any) => x.source);
+ expect(sources).toContain("pref-src");
+ });
+
+ test("count is zero when nobody references the id", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_backlinks", { id: "pref-orphan" })) as any;
+ const s = r.result.structuredContent;
+ expect(s.id).toBe("pref-orphan");
+ expect(s.count).toBe(0);
+ expect(s.refs).toEqual([]);
+ });
+
+ test("missing id raises an INVALID_PARAMS error envelope", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_backlinks", {})) as any;
+ // Missing required arg is INVALID_PARAMS at the JSON-RPC layer
+ // (the handler throws MCPError before producing a tool result).
+ expect(r.error).toBeDefined();
+ expect(r.error.message).toContain("id");
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 423cf9c5..41260491 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -148,13 +148,14 @@ describe("tool listing", () => {
"second_brain_status",
"second_brain_query",
"vault_health",
- // Brain (v0.9.0).
+ // Brain (v0.9.0; brain_backlinks added in v0.9.1).
"brain_feedback",
"brain_dream",
"brain_apply_evidence",
"brain_digest",
"brain_query",
"brain_doctor",
+ "brain_backlinks",
// Pay Memory (unchanged).
"payment_memory_init",
"payment_receipt_append",
@@ -191,6 +192,23 @@ describe("tool calls", () => {
expect(s.config_keys).toContain("vault_path");
});
+ test("second_brain_status includes a `brain` section with counts and activity", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "vault_path: /tmp/vault\n");
+ // Brain layer absent β†’ `brain.present` is `false` with zero counts.
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_status"))! as any;
+ const s = r.result.structuredContent;
+ expect(s.brain).toBeDefined();
+ expect(s.brain.present).toBe(false);
+ expect(s.brain.counts.preferences).toBe(0);
+ expect(s.brain.last_dream_at).toBeNull();
+ expect(s.brain.sanity.signals_awaiting_dream).toBe(0);
+ });
+
test("second_brain_query filters and limits", async () => {
const vault = createSandboxVault(tmp);
const server = new MCPServer({ vault });
@@ -268,7 +286,7 @@ describe("stdio loop", () => {
expect(init.id).toBe(1);
expect(list.id).toBe(2);
// v0.9.0: 3 core (status/query/health) + 6 Brain + 8 Pay Memory = 17.
- expect(list.result.tools.length).toBe(17);
+ expect(list.result.tools.length).toBe(18);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/resources.test.ts b/tests/mcp/resources.test.ts
new file mode 100644
index 00000000..49837e99
--- /dev/null
+++ b/tests/mcp/resources.test.ts
@@ -0,0 +1,456 @@
+/**
+ * MCP Resources end-to-end tests.
+ *
+ * The resource surface is dispatched through the same JSON-RPC pipeline
+ * as `tools/call`. We exercise:
+ * - `initialize` reports the `resources` capability
+ * - `resources/list` returns the two concrete URIs
+ * - `resources/templates/list` returns the three templates
+ * - `resources/read` succeeds for each shape and fails cleanly on
+ * unknown URIs / missing files / malformed slug-or-date arguments.
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+} from "../../src/mcp/index.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import {
+ brainActivePath,
+ logPath,
+ preferencePath,
+} from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { regenerateActive } from "../../src/core/brain/active.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+let tmp: string;
+let vault: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-res-"));
+ vault = join(tmp, "vault");
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-res-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const k of ["VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+function makeServer(): MCPServer {
+ return new MCPServer({ vault, configPath });
+}
+
+async function initialize(server: MCPServer): Promise<any> {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "resources-test", version: "0" },
+ },
+ });
+}
+
+async function listResources(server: MCPServer): Promise<any> {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "resources/list",
+ params: {},
+ });
+}
+
+async function listTemplates(server: MCPServer): Promise<any> {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 3,
+ method: "resources/templates/list",
+ params: {},
+ });
+}
+
+async function read(server: MCPServer, uri: string): Promise<any> {
+ return server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 4,
+ method: "resources/read",
+ params: { uri },
+ });
+}
+
+describe("MCP resources β€” capabilities and discovery", () => {
+ test("initialize reports the resources capability", async () => {
+ const server = makeServer();
+ const r = await initialize(server);
+ expect(r.result.capabilities.resources).toEqual({
+ listChanged: false,
+ subscribe: false,
+ });
+ });
+
+ test("resources/list returns the concrete URIs with metadata", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await listResources(server);
+ const uris = r.result.resources.map((x: any) => x.uri).sort();
+ expect(uris).toEqual([
+ "osb://digest/latest",
+ "osb://preferences/active",
+ "osb://status",
+ ]);
+ for (const desc of r.result.resources) {
+ expect(desc.mimeType).toBe("text/markdown");
+ expect(typeof desc.name).toBe("string");
+ expect(typeof desc.description).toBe("string");
+ }
+ });
+
+ test("resources/templates/list returns the templated URIs", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await listTemplates(server);
+ const templates = r.result.resourceTemplates.map((t: any) => t.uriTemplate).sort();
+ expect(templates).toEqual([
+ "osb://backlinks/{id}",
+ "osb://log/{date}",
+ "osb://preference/{id}",
+ "osb://topic/{slug}",
+ ]);
+ });
+});
+
+describe("MCP resources β€” read osb://preferences/active", () => {
+ test("returns the active.md body", async () => {
+ writePreference(vault, {
+ slug: "rule-a",
+ topic: "rule-a",
+ principle: "Be tidy",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 5,
+ violated_count: 0,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence: "medium",
+ });
+ regenerateActive(vault, { now: new Date("2026-05-15T10:00:00Z") });
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://preferences/active");
+ expect(r.result.contents).toHaveLength(1);
+ const c = r.result.contents[0];
+ expect(c.uri).toBe("osb://preferences/active");
+ expect(c.mimeType).toBe("text/markdown");
+ expect(c.text).toContain("pref-rule-a");
+ expect(c.text).toContain("Be tidy");
+ });
+
+ test("regenerates active.md on demand when missing", async () => {
+ // Fresh vault with prefs but no dream β†’ active.md does not exist
+ // yet. The first read should produce it.
+ writePreference(vault, {
+ slug: "rule-b",
+ topic: "rule-b",
+ principle: "Stay calm",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 0,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence: "low",
+ });
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://preferences/active");
+ expect(r.result.contents[0].text).toContain("pref-rule-b");
+ });
+});
+
+describe("MCP resources β€” read osb://digest/latest", () => {
+ test("returns rendered digest markdown (empty window is non-empty markdown)", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://digest/latest");
+ expect(r.result.contents[0].mimeType).toBe("text/markdown");
+ expect(typeof r.result.contents[0].text).toBe("string");
+ expect(r.result.contents[0].text.length).toBeGreaterThan(0);
+ });
+});
+
+describe("MCP resources β€” read osb://preference/{id}", () => {
+ test("returns the active pref body, accepting bare slug or prefixed id", async () => {
+ writePreference(vault, {
+ slug: "named-rule",
+ topic: "named-rule",
+ principle: "Body",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-09T00:00:00Z",
+ confidence: "low",
+ });
+ const server = makeServer();
+ await initialize(server);
+ const slug = await read(server, "osb://preference/named-rule");
+ const prefixed = await read(server, "osb://preference/pref-named-rule");
+ expect(slug.result.contents[0].text).toContain("named-rule");
+ expect(prefixed.result.contents[0].text).toBe(slug.result.contents[0].text);
+ });
+
+ test("falls back to retired/<id> when active is gone", async () => {
+ // Drop a retired stub directly.
+ const retiredDir = join(vault, "Brain", "retired");
+ writeFileSync(
+ join(retiredDir, "ret-old-thing.md"),
+ `---
+kind: brain-retired
+id: ret-old-thing
+status: retired
+retired_at: 2026-05-10T00:00:00Z
+retired_reason: rebutted
+retired_by: "[[Brain/log/2026-05-10]]"
+created_at: 2026-05-01T00:00:00Z
+tags: [brain, brain/retired]
+topic: old-thing
+principle: A stale rule
+evidenced_by: []
+applied_count: 0
+violated_count: 0
+last_evidence_at: null
+confidence: low
+pinned: false
+---
+
+Body.
+`,
+ "utf8",
+ );
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://preference/old-thing");
+ expect(r.result.contents[0].text).toContain("retired_reason: rebutted");
+ });
+
+ test("missing id raises a tool error", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://preference/does-not-exist");
+ expect(r.error).toBeDefined();
+ expect(r.error.message).toContain("no preference or retired entry");
+ });
+
+ test("malformed slug raises INVALID_PARAMS", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://preference/..");
+ expect(r.error).toBeDefined();
+ // validateSlug throws "slug must not contain '..' traversal".
+ expect(r.error.message.toLowerCase()).toMatch(/slug|invalid|traversal/);
+ });
+});
+
+describe("MCP resources β€” read osb://topic/{slug}", () => {
+ test("returns a markdown summary of signals + current preference", async () => {
+ writeSignal(vault, {
+ topic: "tidy",
+ signal: "negative",
+ agent: "claude",
+ principle: "Be tidy",
+ created_at: "2026-05-14T10:00:00Z",
+ date: "2026-05-14",
+ slug: "first",
+ scope: "writing",
+ });
+ writePreference(vault, {
+ slug: "tidy",
+ topic: "tidy",
+ principle: "Be tidy",
+ created_at: "2026-05-14T11:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-2026-05-14-first]]"],
+ });
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://topic/tidy");
+ const text = r.result.contents[0].text as string;
+ expect(text).toContain("# Brain topic: tidy");
+ expect(text).toContain("pref-tidy");
+ expect(text).toContain("sig-2026-05-14-first");
+ });
+});
+
+describe("MCP resources β€” read osb://log/{date}", () => {
+ test("returns the log file body when present", async () => {
+ const path = logPath(vault, "2026-05-14");
+ writeFileSync(path, "# Brain Log β€” 2026-05-14\n\nhello\n", "utf8");
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://log/2026-05-14");
+ expect(r.result.contents[0].text).toContain("hello");
+ });
+
+ test("missing date raises a tool error", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://log/2026-05-14");
+ expect(r.error).toBeDefined();
+ expect(r.error.message).toContain("no log file for date");
+ });
+
+ test("malformed date raises INVALID_PARAMS", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://log/not-a-date");
+ expect(r.error).toBeDefined();
+ });
+});
+
+describe("MCP resources β€” read osb://status", () => {
+ test("returns markdown with counts and activity sections", async () => {
+ writePreference(vault, {
+ slug: "alpha",
+ topic: "alpha",
+ principle: "Rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ });
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://status");
+ const text = r.result.contents[0].text as string;
+ expect(text).toContain("# Brain status");
+ expect(text).toContain("## Counts");
+ expect(text).toContain("preferences: 1");
+ expect(text).toContain("confirmed: 1");
+ expect(text).toContain("## Activity");
+ });
+});
+
+describe("MCP resources β€” read osb://backlinks/{id}", () => {
+ test("renders count + grouped sources for a referenced pref", async () => {
+ writePreference(vault, {
+ slug: "target",
+ topic: "t",
+ principle: "Target rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: [],
+ applied_count: 1,
+ });
+ writePreference(vault, {
+ slug: "source",
+ topic: "s",
+ principle: "Source rule",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-30T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ evidenced_by: ["[[pref-target]]"],
+ applied_count: 1,
+ });
+
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://backlinks/pref-target");
+ const text = r.result.contents[0].text as string;
+ expect(text).toContain("# Backlinks to `pref-target`");
+ expect(text).toContain("Total inbound references:");
+ expect(text).toContain("pref-source");
+ });
+
+ test("renders zero-state message for targets with no backlinks", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://backlinks/pref-nothing");
+ const text = r.result.contents[0].text as string;
+ expect(text).toContain("# Backlinks to `pref-nothing`");
+ expect(text).toContain("Total inbound references: 0");
+ expect(text).toContain("_No inbound references found._");
+ });
+});
+
+describe("MCP resources β€” unknown URI", () => {
+ test("returns INVALID_PARAMS for an unsupported scheme", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "http://example.com/x");
+ expect(r.error).toBeDefined();
+ expect(r.error.message).toContain("unsupported resource uri");
+ });
+
+ test("returns INVALID_PARAMS for an unrecognised osb:// shape", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await read(server, "osb://nonsense/x");
+ expect(r.error).toBeDefined();
+ });
+
+ test("rejects non-string uri argument", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 5,
+ method: "resources/read",
+ params: { uri: 42 },
+ });
+ expect(r!.error).toBeDefined();
+ });
+
+ // Helper-only branch β€” silence unused warning.
+ void brainActivePath;
+ void preferencePath;
+});