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.10.1: Brain body hygiene β€” evidence joined to preferences, reject --reason, signal suppression

Sol Aitkend06d030d58ec
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 247dba69..ad9db152 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.0",
+ "version": "0.10.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 1f5f3ccc..f47461fd 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.0",
+ "version": "0.10.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 52b0ffc6..3242994d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,97 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.10.1] - 2026-05-16
+
+Closes the "preference body is dead weight" gap. Every active and
+quarantined preference file now mirrors its log activity instead of
+shipping a fixed placeholder body; signal files stop emitting the
+`_(not provided)_` placeholder when no verbatim quote was passed; and
+`o2b brain reject` requires a `--reason` so the next dream pass can
+suppress new signals on the same topic. Tier-A item Β§6 of
+`Projects/OpenSecondBrain/Features/_summary` (`reject --reason` +
+signal suppression) is implemented in this patch.
+
+No vault migration is required β€” the first post-upgrade dream pass
+detects v0.9.x placeholder bodies and rewrites them to the new shape
+in place.
+
+### Added
+
+- **`## Recent applications` / `## Recent violations`** sections on
+ every preference and retired file. Dream collects the last 5
+ applied + last 3 violated rows from `Brain/log/` on every pass and
+ writes them as bulleted `[[artifact:lines]] β€” timestamp (agent)
+ [result] β€” note` entries. The data was already on disk in the
+ daily log; v0.10.1 joins it back to the rule.
+- **`src/core/brain/evidence.ts`** β€” read-only log scanner used by
+ dream and `moveToRetired`. Returns newest-first slices for a given
+ pref slug; sorts by timestamp; stops at `pref.created_at` so older
+ log days are never opened in vain.
+- **`o2b brain reject --reason "<text>"`** β€” `--reason` is now
+ mandatory. The text is persisted on the retired file as
+ `user_rejected_reason` and rendered in the `## Retired` body. CLI
+ exits 1 when `--reason` is missing.
+- **`signal-suppressed` log event + `signalSuppressed` event kind.**
+ When a fresh signal lands on a topic that has a retired pref with
+ `user_rejected_reason` set, dream drops the signal from the
+ candidate-pref planner, moves it to `processed/`, and emits one
+ audit row per signal linking back to the retired pref + the
+ original user reason.
+- **`wouldRewritePreference(vault, input)`** exported predicate β€”
+ twin of `writePreference`'s content-equality short-circuit. Lets
+ the dream pass decide whether a refresh entry is needed without
+ doing the write twice.
+- **`BrainEvidenceSummary`** type and `BrainSignalSuppressedLogEvent`
+ variant added to the discriminated union of log events.
+- Test file `tests/core/brain.body-hygiene.test.ts` β€” coverage for
+ Raw-section omission, preference-body shape, retired re-render,
+ signal suppression, and the v0.9.x β†’ v0.10.1 body migration.
+
+### Changed
+
+- **`renderPreferenceBody`** drops the redundant `## Principle`
+ duplicate and the `_(no evidence yet)_` / `_(not provided)_`
+ placeholder lines. Sections are emitted only when they have real
+ content; a brand-new pref with no log evidence yet has an empty
+ body, which is the honest representation.
+- **`renderSignalBody`** omits the `## Raw` section entirely when
+ no verbatim quote was passed instead of shipping the
+ `_(not provided)_` placeholder. Parsers stay tolerant of both
+ shapes (old placeholder, new absent section).
+- **`writePreference`** is now content-aware: when overwriting, it
+ reads the existing file, compares to the would-be rendered bytes,
+ and skips the rename if they match. Preserves the dream
+ "no rewrite on a no-op rerun" invariant even though dream now
+ recomputes the body on every pass.
+- **`moveToRetired`** re-renders the body from scratch (current
+ frontmatter + freshly collected log evidence) before appending
+ the `## Retired` block. The source file's body shape no longer
+ bleeds into the retired snapshot β€” a v0.9.x preference being
+ retired produces a v0.10.1 retired file.
+- **`dream`** plumbs the evidence slice through to every
+ `writePreference` and `moveToRetired` call. A pref whose
+ counters did not change is still considered for refresh if its
+ on-disk body differs from the rendered output (this is what
+ carries the v0.9.x body migration forward without a separate
+ migrate command).
+- **`brain-memory` skill** explicitly recommends passing `raw` with
+ the verbatim user quote and documents the `--reason` requirement
+ on `o2b brain reject`, with the warning that re-recording signals
+ on a user-rejected topic will be suppressed by the next dream.
+
+### Notes
+
+- The schema version on `Brain/_brain.yaml` stays unchanged. All
+ changes are additive at the data layer (`user_rejected_reason` is
+ an optional frontmatter field; `BrainEvidenceSummary` is a derived
+ render-time view, never persisted as its own file).
+- The Β§6 implementation in this release covers suppression only.
+ The follow-up "after 5 rejects of the same topic, auto-block" mode
+ from the _summary doc is deliberately out of scope β€” suppression
+ + the explicit `--reason` audit trail is enough to break the
+ reject β†’ re-grow loop the user observed.
+
## [0.10.0] - 2026-05-16
Full-text search over the vault as a deterministic, filesystem-first
@@ -1151,6 +1242,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[0.10.1]: https://github.com/itechmeat/open-second-brain/compare/v0.10.0...v0.10.1
[0.10.0]: https://github.com/itechmeat/open-second-brain/compare/v0.9.1...v0.10.0
[0.9.1]: https://github.com/itechmeat/open-second-brain/compare/v0.9.0...v0.9.1
[0.9.0]: https://github.com/itechmeat/open-second-brain/compare/v0.8.1...v0.9.0
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 0b2cddc5..c37bfffe 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.10.0",
+ "version": "0.10.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 763ad572..1c5d0718 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.0",
+ "version": "0.10.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 a76abe97..0e5872f1 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.0"
+version: "0.10.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 20153cf1..a9e99a34 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.0",
+ "version": "0.10.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 b6e76575..09fc1b63 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.0"
+version: "0.10.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 3d183f0b..46cd60d9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.10.0"
+version = "0.10.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/skills/brain-memory/SKILL.md b/skills/brain-memory/SKILL.md
index f23b207b..800439b3 100644
--- a/skills/brain-memory/SKILL.md
+++ b/skills/brain-memory/SKILL.md
@@ -23,6 +23,16 @@ Parameters:
- `principle`: one-line, imperative-voice agent-readable formulation. "Do not use internal abbreviations in user-facing copy unless explained first."
- `agent`: your runtime identity (`claude`, `codex`, `hermes`, OpenClaw plugin name, or the human's name if you are recording on their behalf).
+Optional but **strongly recommended**:
+
+- `raw`: the verbatim quote that triggered the signal. Without it the
+ signal file lands without a `## Raw` body β€” counters keep working,
+ but the audit trail loses the original phrasing. Pass the exact
+ sentence the user said (or the exact line of the artifact the
+ signal is about). v0.10.1 dropped the `_(not provided)_` placeholder
+ precisely so an absent `raw` is now visible: the file simply has no
+ body, which should be the rare case, not the norm.
+
Optional:
- `scope`: soft category for later application-scope matching β€” `writing`, `coding`, `process`, `design`, `infra`, `docs`. Pick the narrowest accurate one.
@@ -101,3 +111,4 @@ o2b brain apply-evidence \
- Never include secrets, tokens, API keys, or credentials in `principle`, `note`, or `source`.
- Do not edit historical signals, preferences, or log entries by hand β€” the `dream` pass is the only writer for transitions.
- Do not write into `Brain/.snapshots/` or `Brain/retired/` directly β€” those are managed by `dream` and `o2b brain reject` only.
+- `o2b brain reject` requires `--reason <text>` from v0.10.1 onward. The reason is persisted on the retired file as `user_rejected_reason`. The next dream pass will mark any future signal on the same `(topic, scope)` as `signal-suppressed` and move it straight to `processed/` β€” do not re-record the same signal hoping it will re-grow into a preference. If you genuinely disagree with a past reject, raise it with the user; do not route around it via `brain_feedback`.
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 94325491..3a3b3413 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -591,6 +591,16 @@ async function cmdBrainReject(argv: string[]): Promise<number> {
if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
return fail("brain reject missing required flag: --id");
}
+ // v0.10.1: `--reason` is now mandatory. The text is persisted on the
+ // retired file (`user_rejected_reason`) and used by dream to mark
+ // future signals on the same topic as `signal-suppressed`. Without
+ // it the suppression chain breaks and the reject is just a quiet
+ // delete β€” exactly the failure mode Β§6 of _summary calls out.
+ if (typeof flags["reason"] !== "string" || (flags["reason"] as string).trim() === "") {
+ return fail(
+ "brain reject missing required flag: --reason (free-form text; persisted on the retired file)",
+ );
+ }
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
const agent = resolveAgentName(config);
@@ -625,10 +635,12 @@ async function cmdBrainReject(argv: string[]): Promise<number> {
const todayDate = isoDate(now);
const retiredBy = `[[Brain/log/${todayDate}]]`;
+ const reasonText = String(flags["reason"]).trim();
try {
moveToRetired(vault, path, "user-rejected", {
now,
retired_by: retiredBy,
+ user_rejected_reason: reasonText,
});
} catch (exc) {
return fail(`failed to retire preference: ${(exc as Error).message ?? exc}`);
@@ -946,7 +958,7 @@ const VERB_HELP: Record<string, string> = {
"usage: o2b brain query --preference <id> | --topic <slug> | --since <ISO> [--vault <path>] [--json]\n" +
"Read-only lookup. One of --preference / --topic / --since is required.\n",
reject:
- "usage: o2b brain reject --id <pref-id> [--reason <text>] [--yes] [--vault <path>] [--json]\n" +
+ "usage: o2b brain reject --id <pref-id> --reason <text> [--yes] [--vault <path>] [--json]\n" +
"Move a preference to retired/ with reason 'user-rejected'. --yes required when pinned.\n",
pin:
"usage: o2b brain pin --id <pref-id> [--vault <path>] [--json]\n" +
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 26ecb846..15b2aef8 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -39,6 +39,7 @@ import { basename, join } from "node:path";
import { parseFrontmatter } from "../vault.ts";
import { regenerateActiveQuiet } from "./active.ts";
+import { collectEvidenceForSlug } from "./evidence.ts";
import {
appendLogEvent,
parseLogDay,
@@ -47,6 +48,7 @@ import {
import {
moveToRetired,
parsePreference,
+ wouldRewritePreference,
writePreference,
} from "./preference.ts";
import { parseSignal } from "./signal.ts";
@@ -98,6 +100,13 @@ export interface DreamRunSummary {
readonly contradictions: ReadonlyArray<string>;
/** Signal ids moved from inbox/ into inbox/processed/. */
readonly moved_to_processed: ReadonlyArray<string>;
+ /**
+ * Signal ids dropped by Β§6 signal-suppression β€” a user-rejected
+ * retired pref with the same topic blocked them from re-promotion.
+ * Each entry is just the signal id (the retired wikilink + reason
+ * land in the `signal-suppressed` log event).
+ */
+ readonly suppressed: ReadonlyArray<string>;
/** Snapshot file (absent on a no-op run). */
readonly snapshot_path?: string;
/** Log file the run summary landed in (absent on a no-op run). */
@@ -131,6 +140,13 @@ interface RetiredRecord {
readonly path: string;
readonly topic: string;
readonly id: string;
+ readonly scope?: string;
+ /**
+ * The free-form user reason passed to `o2b brain reject --reason`.
+ * Presence triggers signal-suppression for future signals on the
+ * same (topic, scope) β€” see Β§6 of the OSB features summary.
+ */
+ readonly user_rejected_reason?: string;
}
interface CorruptedEntry {
@@ -169,7 +185,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
// referenced by `last_evidence_at` plus today's file. Since the
// plan doesn't yet know dates, we scan the entire log/ directory.
const evidence = scanApplyEvidence(vault);
- const refresh = planRefresh(scan, evidence, cfg, now, plan);
+ const refresh = planRefresh(vault, scan, evidence, cfg, now, plan);
// 4. Plan retires (expired-unconfirmed, stale-no-evidence). Pinned
// preferences get a `retain-pinned` log event instead of a real
@@ -195,6 +211,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
plan.notedRedundant.length > 0 ||
plan.signalsToMove.size > 0 ||
plan.retainPinned.length > 0 ||
+ plan.signalsSuppressed.length > 0 ||
scan.corrupted.length > 0;
if (!changed) {
@@ -207,6 +224,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
retired: [],
contradictions: [...plan.contradictionTopics],
moved_to_processed: [],
+ suppressed: [],
...(dryRun ? { dry_run: true } : {}),
} satisfies DreamRunSummary);
}
@@ -236,6 +254,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
if (!dryRun) {
for (const np of plan.newUnconfirmed) {
+ // Fresh pref has no apply-evidence yet; recentApplied/recentViolated
+ // start empty and stay so until the next dream pass after the
+ // first `brain_apply_evidence` event.
writePreference(
vault,
{
@@ -248,6 +269,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
),
status: BRAIN_PREFERENCE_STATUS.unconfirmed,
evidenced_by: np.evidencedBy,
+ recentApplied: [],
+ recentViolated: [],
...(np.scope ? { scope: np.scope } : {}),
...(np.supersedes ? { supersedes: np.supersedes } : {}),
},
@@ -256,6 +279,13 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
}
for (const update of refresh.updated.values()) {
+ // Rebuild the evidence slice from the log on every pass so the
+ // pref body stays in sync with the counters even when the
+ // counters themselves stayed put (e.g. dropping the
+ // v0.9.x placeholder body during a no-counter-change run).
+ const ev = collectEvidenceForSlug(vault, update.slug, {
+ sinceIso: update.created_at,
+ });
writePreference(
vault,
{
@@ -272,6 +302,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
last_evidence_at: update.last_evidence_at,
confidence: update.confidence,
pinned: update.pinned,
+ recentApplied: ev.applied,
+ recentViolated: ev.violated,
...(update.scope ? { scope: update.scope } : {}),
},
{ overwrite: true },
@@ -350,6 +382,19 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
});
}
+ for (const suppressed of plan.signalsSuppressed) {
+ writeEvent(vault, {
+ timestamp: nextStamp(),
+ eventType: BRAIN_LOG_EVENT_KIND.signalSuppressed,
+ body: {
+ signal: suppressed.signal,
+ retired: suppressed.retired,
+ topic: suppressed.topic,
+ reason: suppressed.reason,
+ },
+ });
+ }
+
for (const retain of plan.retainPinned) {
// `retain-pinned` is not in the strict BrainLogEventKind enum
// (the design doc names a generic `retire` event with an
@@ -385,6 +430,11 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
if (plan.contradictionTopics.size > 0) {
summaryBody["contradictions"] = Array.from(plan.contradictionTopics);
}
+ if (plan.signalsSuppressed.length > 0) {
+ summaryBody["suppressed"] = plan.signalsSuppressed.map(
+ (s) => `${s.signal} ← ${s.retired}`,
+ );
+ }
writeEvent(vault, {
timestamp: nextStamp(),
@@ -418,6 +468,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
retired: plan.retires.map((r) => ({ id: `ret-${r.slug}`, reason: r.reason })),
contradictions: Array.from(plan.contradictionTopics),
moved_to_processed: moved,
+ suppressed: plan.signalsSuppressed.map((s) =>
+ s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),
+ ),
...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),
...(dryRun
? { dry_run: true }
@@ -475,14 +528,27 @@ function scanBrain(vault: string): ScanResult {
if (!name.endsWith(".md")) continue;
const full = join(dirs.retired, name);
// Retired files we only need for topic + id (for supersede
- // bookkeeping). We do a lightweight frontmatter parse to avoid
- // the strict folder invariant check failing on permissive setups.
+ // bookkeeping) plus the optional `user_rejected_reason` that
+ // drives signal-suppression (v0.10.1, _summary Β§6). We do a
+ // lightweight frontmatter parse to avoid the strict folder
+ // invariant check failing on permissive setups.
try {
const [meta] = parseFrontmatter(full);
const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";
const id = typeof meta["id"] === "string" ? meta["id"] : "";
+ const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;
+ const userReason =
+ typeof meta["user_rejected_reason"] === "string"
+ ? (meta["user_rejected_reason"] as string).trim()
+ : "";
if (topic && id) {
- retired.push({ path: full, topic, id });
+ retired.push({
+ path: full,
+ topic,
+ id,
+ ...(scope ? { scope } : {}),
+ ...(userReason ? { user_rejected_reason: userReason } : {}),
+ });
}
} catch {
corrupted.push({ path: full });
@@ -507,6 +573,20 @@ interface PlanState {
readonly signalsToMove: Map<string, SignalMovePlan>;
/** Topic slugs flagged contradicted but no transition this run. */
readonly contradictionTopics: Set<string>;
+ /**
+ * Signals dropped because their (topic, scope) matches a user-rejected
+ * retired pref carrying a `user_rejected_reason`. Each entry produces
+ * one `signal-suppressed` log event AND a move into `processed/` so
+ * the inbox does not accumulate.
+ */
+ readonly signalsSuppressed: SignalSuppressedPlan[];
+}
+
+interface SignalSuppressedPlan {
+ readonly signal: string;
+ readonly retired: string;
+ readonly reason: string;
+ readonly topic: string;
}
interface NewUnconfirmedPlan {
@@ -556,6 +636,7 @@ function emptyPlan(): PlanState {
retainPinned: [],
signalsToMove: new Map(),
contradictionTopics: new Set(),
+ signalsSuppressed: [],
};
}
@@ -612,9 +693,54 @@ function planTopics(
);
continue;
}
+ // v0.10.1 _summary Β§6: when a retired pref for this topic carries
+ // a `user_rejected_reason`, the user explicitly rejected the rule
+ // β€” re-growing it from fresh signals is exactly what they were
+ // asking us not to do. Suppress every matching signal, emit one
+ // `signal-suppressed` event per signal pointing at the retired
+ // pref + the reason, and move them straight to processed.
+ //
+ // Per-signal scope match: an unscoped suppressor swallows every
+ // signal on the topic; a scoped suppressor only swallows signals
+ // sharing its scope (a signal without scope still matches an
+ // unscoped suppressor but never a scoped one). Multiple retired
+ // prefs on the same topic are tried in order β€” the first matching
+ // suppressor wins. Non-matching signals fall through and remain
+ // eligible for candidate-pref planning below.
+ const suppressors = (retiredByTopic.get(topic) ?? []).filter(
+ (r) => !!r.user_rejected_reason,
+ );
+ let candidateSigs: SignalRecord[] = sigs;
+ if (suppressors.length > 0) {
+ const remaining: SignalRecord[] = [];
+ for (const sig of sigs) {
+ const suppressor = suppressors.find((r) => {
+ if (!r.scope) return true;
+ if (!sig.signal.scope) return false;
+ return r.scope === sig.signal.scope;
+ });
+ if (!suppressor) {
+ remaining.push(sig);
+ continue;
+ }
+ plan.signalsSuppressed.push({
+ signal: `[[${sig.signal.id}]]`,
+ retired: `[[${suppressor.id}]]`,
+ reason: suppressor.user_rejected_reason!,
+ topic,
+ });
+ recordSignalMove(plan, sig);
+ }
+ if (remaining.length === 0) continue;
+ candidateSigs = remaining;
+ }
// No active pref for this topic β†’ either promote or note
// contradiction.
- const windowedSigs = filterWithinWindow(sigs, cfg.dream.contradiction_window_days, now);
+ const windowedSigs = filterWithinWindow(
+ candidateSigs,
+ cfg.dream.contradiction_window_days,
+ now,
+ );
const positives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive);
const negatives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative);
const dominant = positives.length >= negatives.length ? positives : negatives;
@@ -912,6 +1038,7 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {
}
function planRefresh(
+ vault: string,
scan: ScanResult,
evidence: ApplyEvidenceEntry[],
cfg: BrainConfig,
@@ -1014,21 +1141,22 @@ function planRefresh(
now,
);
- // Only emit an update if something actually changed. This matters
- // for the idempotency invariant: a no-op rerun on the same fixture
- // must not rewrite preference files (the file mtime would change
- // but byte content would be identical; writing anyway is wasted
- // I/O and triggers an unnecessary log entry).
- const changed =
+ // Idempotency on a no-op rerun: skip refresh for prefs where
+ // counters AND status are unchanged AND the on-disk body already
+ // matches what we would render with current evidence. The second
+ // half (body comparison) is what carries the v0.10.1 migration
+ // forward β€” a pref whose counters are stable but whose body
+ // still has the v0.9.x placeholder will fail the body check and
+ // get rewritten on the next pass.
+ const countersChanged =
applied !== rec.pref.applied_count ||
violated !== rec.pref.violated_count ||
lastEvidence !== rec.pref.last_evidence_at ||
status !== rec.pref.status ||
confirmedAt !== rec.pref.confirmed_at ||
confidenceValue !== rec.pref.confidence;
- if (!changed) continue;
- updated.set(slug, {
+ const prospective = {
slug,
topic: rec.pref.topic,
...(rec.pref.scope ? { scope: rec.pref.scope } : {}),
@@ -1043,7 +1171,25 @@ function planRefresh(
last_evidence_at: lastEvidence,
confidence: confidenceValue,
pinned: rec.pref.pinned,
- });
+ };
+
+ if (!countersChanged) {
+ const ev2 = collectEvidenceForSlug(vault, slug, {
+ sinceIso: rec.pref.created_at,
+ });
+ if (
+ !wouldRewritePreference(vault, {
+ ...prospective,
+ recentApplied: ev2.applied,
+ recentViolated: ev2.violated,
+ })
+ ) {
+ // Counters and body both unchanged β€” true no-op for this pref.
+ continue;
+ }
+ }
+
+ updated.set(slug, prospective);
}
return { confirmed, updated };
diff --git a/src/core/brain/evidence.ts b/src/core/brain/evidence.ts
new file mode 100644
index 00000000..49e52e8d
--- /dev/null
+++ b/src/core/brain/evidence.ts
@@ -0,0 +1,141 @@
+/**
+ * Evidence aggregation: scan `Brain/log/<YYYY-MM-DD>.md` and surface
+ * the apply-evidence rows that target a given preference. Used by
+ * `dream` to rebuild the `## Recent applications` / `## Recent
+ * violations` sections of every preference and retired file on each
+ * pass, so the file mirrors what the counters say.
+ *
+ * Pure read: no I/O outside reading log files.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+
+import { brainDirs } from "./paths.ts";
+import { parseLogDay } from "./log.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ type BrainApplyResult,
+ type BrainEvidenceSummary,
+} from "./types.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+
+/** Strip `[[` / `]]` plus a trailing `|alt` segment. */
+function unwrap(wikilink: string): string {
+ return normaliseWikilinkTarget(wikilink) ?? wikilink.trim();
+}
+
+function eqId(eventPrefRef: string, slug: string): boolean {
+ const bare = unwrap(eventPrefRef);
+ return bare === `pref-${slug}` || bare === `ret-${slug}`;
+}
+
+/** Sorted list of `YYYY-MM-DD` log days actually on disk. Newest first. */
+export function listLogDays(vault: string): string[] {
+ const dir = brainDirs(vault).log;
+ if (!existsSync(dir)) return [];
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return [];
+ }
+ const days: string[] = [];
+ for (const name of entries) {
+ if (!name.endsWith(".md")) continue;
+ const day = name.slice(0, -3);
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) continue;
+ days.push(day);
+ }
+ days.sort();
+ days.reverse();
+ return days;
+}
+
+export interface CollectEvidenceOptions {
+ /** Maximum `applied` rows to return. Default 5. */
+ readonly maxApplied?: number;
+ /** Maximum `violated`/`outdated` rows to return. Default 3. */
+ readonly maxViolated?: number;
+ /**
+ * Stop scanning at this ISO timestamp (inclusive). **Required** β€”
+ * the caller MUST pass the preference's `created_at` so we never
+ * harvest log rows that predate the pref's existence (which would
+ * be a different rule under the same slug history). Pass an empty
+ * string to opt out and scan every available log day (only useful
+ * for vault-wide ad-hoc tooling).
+ */
+ readonly sinceIso: string;
+}
+
+export interface CollectedEvidence {
+ readonly applied: ReadonlyArray<BrainEvidenceSummary>;
+ readonly violated: ReadonlyArray<BrainEvidenceSummary>;
+}
+
+/**
+ * Walk log files newest-first, collecting at most `maxApplied`
+ * `apply-evidence applied` rows and at most `maxViolated`
+ * `violated` / `outdated` rows that target `pref-<slug>` (or its
+ * `ret-<slug>` post-retire identity).
+ *
+ * Stops early once both quotas are full.
+ */
+export function collectEvidenceForSlug(
+ vault: string,
+ slug: string,
+ opts: CollectEvidenceOptions,
+): CollectedEvidence {
+ const maxApplied = opts.maxApplied ?? 5;
+ const maxViolated = opts.maxViolated ?? 3;
+ // Empty string is the documented "no cutoff" escape hatch.
+ const cutoff = opts.sinceIso.length > 0 ? opts.sinceIso : null;
+
+ const applied: BrainEvidenceSummary[] = [];
+ const violated: BrainEvidenceSummary[] = [];
+
+ for (const day of listLogDays(vault)) {
+ if (cutoff && day < cutoff.slice(0, 10)) break;
+ const { entries } = parseLogDay(vault, day);
+ // parseLogDay returns entries in file order (oldest first). We want
+ // newest first across the whole vault, so iterate in reverse.
+ for (let i = entries.length - 1; i >= 0; i--) {
+ const e = entries[i]!;
+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;
+ if (cutoff && e.timestamp < cutoff) continue;
+ const prefRef = e.body["preference"];
+ if (typeof prefRef !== "string" || !eqId(prefRef, slug)) continue;
+ const result = e.body["result"];
+ if (typeof result !== "string") continue;
+ const artifact = typeof e.body["artifact"] === "string" ? e.body["artifact"] : "";
+ const agent = typeof e.body["agent"] === "string" ? e.body["agent"] : undefined;
+ const note = typeof e.body["note"] === "string" ? e.body["note"] : undefined;
+ const row: BrainEvidenceSummary = Object.freeze({
+ timestamp: e.timestamp,
+ artifact,
+ result: result as BrainApplyResult,
+ ...(agent !== undefined ? { agent } : {}),
+ ...(note !== undefined ? { note } : {}),
+ });
+ if (result === BRAIN_APPLY_RESULT.applied) {
+ if (applied.length < maxApplied) applied.push(row);
+ } else if (
+ result === BRAIN_APPLY_RESULT.violated ||
+ result === BRAIN_APPLY_RESULT.outdated
+ ) {
+ if (violated.length < maxViolated) violated.push(row);
+ }
+ if (applied.length >= maxApplied && violated.length >= maxViolated) {
+ return Object.freeze({
+ applied: Object.freeze(applied),
+ violated: Object.freeze(violated),
+ });
+ }
+ }
+ }
+
+ return Object.freeze({
+ applied: Object.freeze(applied),
+ violated: Object.freeze(violated),
+ });
+}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 17905f35..af269520 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -33,11 +33,15 @@
* complete before the old one disappears.
*/
-import { existsSync, unlinkSync } from "node:fs";
+import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import type { FrontmatterMap } from "../types.ts";
-import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
+import {
+ formatFrontmatter,
+ parseFrontmatter,
+ writeFrontmatterAtomic,
+} from "../vault.ts";
import {
brainDirs,
preferencePath,
@@ -49,6 +53,7 @@ import {
BRAIN_PREFERENCE_STATUS,
BRAIN_RETIRED_REASON,
type BrainConfidence,
+ type BrainEvidenceSummary,
type BrainPreference,
type BrainPreferenceStatus,
type BrainRetired,
@@ -105,6 +110,17 @@ export interface WritePreferenceInput {
readonly extraTags?: ReadonlyArray<string>;
/** Free-form "How to apply" prose (rendered as a section). */
readonly howToApply?: string;
+ /**
+ * Recent `apply-evidence applied` rows for this pref, derived from
+ * `Brain/log/`. Newest first. Used by {@link renderPreferenceBody}
+ * to render `## Recent applications` so the file mirrors what the
+ * counters say.
+ */
+ readonly recentApplied?: ReadonlyArray<BrainEvidenceSummary>;
+ /**
+ * Recent `apply-evidence violated` / `outdated` rows. Newest first.
+ */
+ readonly recentViolated?: ReadonlyArray<BrainEvidenceSummary>;
}
export interface WritePreferenceOptions {
@@ -121,6 +137,22 @@ export interface MoveToRetiredOptions {
readonly now: Date;
readonly retired_by: string;
readonly superseded_by?: string;
+ /**
+ * Free-form reason supplied by `o2b brain reject --reason <text>`.
+ * Persisted to the retired frontmatter as `user_rejected_reason`
+ * and rendered in the `## Retired` body block. Required by the CLI
+ * for `user-rejected` retires; left undefined for automatic
+ * retire-reasons emitted by dream.
+ */
+ readonly user_rejected_reason?: string;
+ /**
+ * Pre-collected evidence slice to render into the retired snapshot.
+ * Dream passes this to avoid re-scanning the log when it already
+ * computed evidence during the refresh phase; the CLI reject path
+ * leaves it undefined and {@link moveToRetired} collects internally.
+ */
+ readonly evidenceApplied?: ReadonlyArray<BrainEvidenceSummary>;
+ readonly evidenceViolated?: ReadonlyArray<BrainEvidenceSummary>;
}
export interface MoveToRetiredResult {
@@ -171,6 +203,23 @@ export function writePreference(
const metadata = preferenceFrontmatter(input, id);
const body = renderPreferenceBody(input);
+ // Content-level idempotency: skip the rename when the file would be
+ // byte-identical. Keeps the dream invariant "a no-op rerun must not
+ // rewrite preference files" even after v0.10.1 expanded what dream
+ // recomputes per pass (evidence slices), and it spares Syncthing
+ // peers from spurious sync events.
+ if (options.overwrite && existsSync(path)) {
+ try {
+ const next = formatFrontmatter(metadata, body);
+ const prev = readFileSync(path, "utf8");
+ if (next === prev) return { path, id };
+ } catch {
+ // Fall through to the atomic write β€” a read failure should not
+ // prevent a legitimate update.
+ }
+ }
+
+
writeFrontmatterAtomic(path, metadata, body, {
overwrite: options.overwrite ?? false,
existsErrorKind: "preference",
@@ -180,6 +229,40 @@ export function writePreference(
return { path, id };
}
+/**
+ * Predicate twin of {@link writePreference}'s content-equality
+ * short-circuit. Returns `true` iff calling `writePreference(vault,
+ * input, { overwrite: true })` would change the on-disk bytes
+ * (file missing, or file present with different content). The dream
+ * pass uses this to decide whether a pref needs to land in the
+ * refresh set β€” emitting a refresh entry triggers a snapshot + log
+ * event, so we must not emit one if the rewrite would be a no-op.
+ *
+ * Cheap: one stat + one readFileSync + one render of frontmatter +
+ * body. Caller-side cost is negligible compared with the writePref
+ * + log overhead avoided when the body is up to date.
+ */
+export function wouldRewritePreference(
+ vault: string,
+ input: WritePreferenceInput,
+): boolean {
+ const slug = validateSlug(input.slug);
+ const path = preferencePath(vault, slug);
+ if (!existsSync(path)) return true;
+ try {
+ const id = `pref-${slug}`;
+ const metadata = preferenceFrontmatter(input, id);
+ const body = renderPreferenceBody(input);
+ const next = formatFrontmatter(metadata, body);
+ const prev = readFileSync(path, "utf8");
+ return next !== prev;
+ } catch {
+ // Conservative: a read or render failure should not silently
+ // mark the file as up-to-date.
+ return true;
+ }
+}
+
function preferenceFrontmatter(
input: WritePreferenceInput,
id: string,
@@ -238,22 +321,67 @@ function composePreferenceTags(input: WritePreferenceInput): string[] {
return out;
}
+/**
+ * Render the preference body. Sections are emitted **only when they
+ * have real content** β€” v0.10.1 removes the always-empty placeholder
+ * blocks (`_(no evidence yet)_`, `_(not provided)_`) that the v0.9.x
+ * shape used to ship. Principle text is intentionally NOT duplicated:
+ * frontmatter is the single source for that field.
+ *
+ * Sections, in order:
+ *
+ * - `## Origin` β€” wikilinks from `evidenced_by` (one bullet each).
+ * Omitted when the array is empty (e.g. `--force-confirmed`).
+ * - `## Recent applications` β€” last N `apply-evidence applied` rows,
+ * newest first. Each bullet: `[[artifact]] β€” ts (agent) β€” note`.
+ * Omitted when zero.
+ * - `## Recent violations` β€” same shape for `violated` / `outdated`.
+ * Omitted when zero.
+ * - `## How to apply` β€” only when `howToApply` is non-empty prose
+ * supplied by the caller; never auto-filled.
+ *
+ * If all sections are skipped, the body is empty and {@link
+ * writeFrontmatterAtomic} writes a frontmatter-only file.
+ */
function renderPreferenceBody(input: WritePreferenceInput): string {
- const lines: string[] = [];
- lines.push("## Principle", "", input.principle.trim(), "");
- lines.push("## Origin", "");
+ const sections: string[] = [];
+
if (input.evidenced_by.length > 0) {
- for (const ev of input.evidenced_by) lines.push(`- ${ev}`);
- } else {
- lines.push("_(no evidence yet)_");
+ const block: string[] = ["## Origin", ""];
+ for (const ev of input.evidenced_by) block.push(`- ${ev}`);
+ sections.push(block.join("\n"));
}
- lines.push("");
- lines.push("## How to apply", "");
+
+ if (input.recentApplied && input.recentApplied.length > 0) {
+ sections.push(renderEvidenceSection("Recent applications", input.recentApplied));
+ }
+
+ if (input.recentViolated && input.recentViolated.length > 0) {
+ sections.push(renderEvidenceSection("Recent violations", input.recentViolated));
+ }
+
const guidance = input.howToApply?.trim();
if (guidance) {
- lines.push(guidance.replace(/\r\n?/g, "\n").replace(/\s+$/g, ""));
- } else {
- lines.push("_(not provided)_");
+ const normalised = guidance.replace(/\r\n?/g, "\n").replace(/\s+$/g, "");
+ sections.push(["## How to apply", "", normalised].join("\n"));
+ }
+
+ return sections.join("\n\n");
+}
+
+function renderEvidenceSection(
+ heading: string,
+ rows: ReadonlyArray<BrainEvidenceSummary>,
+): string {
+ const lines: string[] = [`## ${heading}`, ""];
+ for (const ev of rows) {
+ const parts: string[] = [`- ${ev.artifact}`, `β€” ${ev.timestamp}`];
+ if (ev.agent) parts.push(`(${ev.agent})`);
+ if (ev.result === "violated" || ev.result === "outdated") {
+ parts.push(`[${ev.result}]`);
+ }
+ if (ev.note) parts.push(`β€” ${ev.note.replace(/\s+/g, " ").trim()}`);
+ lines.push(parts.join(" "));
}
return lines.join("\n");
}
@@ -401,6 +529,9 @@ export function parseRetired(path: string): BrainRetired {
...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])
? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }
: {}),
+ ...(optionalScalarString(meta, "user_rejected_reason") !== undefined
+ ? { user_rejected_reason: optionalScalarString(meta, "user_rejected_reason") }
+ : {}),
};
return Object.freeze(result);
}
@@ -490,6 +621,9 @@ export function moveToRetired(
if (opts.superseded_by?.trim()) {
newMeta["superseded_by"] = opts.superseded_by.trim();
}
+ if (opts.user_rejected_reason?.trim()) {
+ newMeta["user_rejected_reason"] = opts.user_rejected_reason.trim();
+ }
// Add the prior `pref-<slug>` basename as an Obsidian alias on the
// retired file. Wikilinks in append-only logs and signal frontmatter
@@ -505,7 +639,48 @@ export function moveToRetired(
newMeta["aliases"] = [oldId, ...existingAliases];
}
- const newBody = appendRetiredSection(body, reason, opts);
+ // Re-render the body from scratch so the retired file carries the
+ // v0.10.1 shape (only sections with content), even if the source
+ // pref was last written in the v0.9.x placeholder format. Evidence
+ // is collected from the live log so the snapshot reflects how the
+ // rule was actually used right up to retirement.
+ const renderInput: WritePreferenceInput = {
+ slug,
+ topic: requireString(meta, "topic", prefPath),
+ principle: requireString(meta, "principle", prefPath),
+ created_at: requireString(meta, "created_at", prefPath),
+ unconfirmed_until: requireString(meta, "unconfirmed_until", prefPath),
+ status: BRAIN_PREFERENCE_STATUS.confirmed, // body render is status-agnostic
+ evidenced_by: optionalStringArray(meta, "evidenced_by"),
+ ...(opts.evidenceApplied !== undefined
+ ? { recentApplied: opts.evidenceApplied }
+ : {}),
+ ...(opts.evidenceViolated !== undefined
+ ? { recentViolated: opts.evidenceViolated }
+ : {}),
+ };
+ // moveToRetired is also called outside dream (CLI reject) β€” when the
+ // caller did not pre-fetch evidence, we collect it here so the
+ // retired file is the canonical historical snapshot in both paths.
+ let renderInputWithEvidence: WritePreferenceInput = renderInput;
+ if (renderInput.recentApplied === undefined && renderInput.recentViolated === undefined) {
+ // Late-bound import to avoid a cyclic dependency: evidence.ts
+ // imports nothing from preference.ts at module load time.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const ev = (require("./evidence.ts") as typeof import("./evidence.ts")).collectEvidenceForSlug(
+ vault,
+ slug,
+ { sinceIso: renderInput.created_at },
+ );
+ renderInputWithEvidence = {
+ ...renderInput,
+ recentApplied: ev.applied,
+ recentViolated: ev.violated,
+ };
+ }
+ const renderedBody = renderPreferenceBody(renderInputWithEvidence);
+ const newBody = appendRetiredSection(renderedBody, reason, opts);
+ void body; // original source body is intentionally discarded β€” see above.
writeFrontmatterAtomic(newPath, newMeta, newBody, {
overwrite: false,
@@ -542,6 +717,13 @@ function appendRetiredSection(
if (opts.superseded_by?.trim()) {
block.push(`Superseded by: ${opts.superseded_by.trim()}`);
}
+ if (opts.user_rejected_reason?.trim()) {
+ // Multi-line user prose: collapse internal newlines so the rendered
+ // block stays a flat bullet list. Long-form context belongs in the
+ // log entry, not in the retired body.
+ const reasonLine = opts.user_rejected_reason.trim().replace(/\s+/g, " ");
+ block.push(`User reason: ${reasonLine}`);
+ }
return trimmed + block.join("\n") + "\n";
}
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index 0a28ffc3..1cd6f370 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -313,20 +313,20 @@ function composeSignalTags(input: WriteSignalInput): string[] {
}
/**
- * Render the body. The "## Raw" section is always present so the file
- * shape is identical regardless of whether `raw` was provided β€”
- * deterministic write is part of the contract.
+ * Render the body. The "## Raw" section is emitted **only** when the
+ * caller actually provided a verbatim quote. A signal recorded without
+ * `raw` (the common case for tests and corner runs) used to ship a
+ * `_(not provided)_` placeholder; v0.10.1 drops that placeholder so
+ * the file is honest about its contents β€” no body at all when there is
+ * none. Parsers stay tolerant of both shapes (old placeholder and new
+ * absent section).
*/
function renderSignalBody(input: WriteSignalInput): string {
- const lines: string[] = ["## Raw", ""];
- if (input.raw && input.raw.trim()) {
- // Normalise line endings and trailing whitespace so two callers
- // passing semantically-equal text produce byte-identical output.
- lines.push(input.raw.replace(/\r\n?/g, "\n").replace(/\s+$/g, ""));
- } else {
- lines.push("_(not provided)_");
- }
- return lines.join("\n");
+ if (!input.raw || !input.raw.trim()) return "";
+ // Normalise line endings and trailing whitespace so two callers
+ // passing semantically-equal text produce byte-identical output.
+ const body = input.raw.replace(/\r\n?/g, "\n").replace(/\s+$/g, "");
+ return ["## Raw", "", body].join("\n");
}
function extractRawSection(body: string): string | undefined {
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 12fface8..5e3d019f 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -106,6 +106,15 @@ export const BRAIN_LOG_EVENT_KIND = {
pin: "pin",
unpin: "unpin",
rollback: "rollback",
+ /**
+ * `signal-suppressed` β€” a fresh signal landed on a topic that the
+ * user explicitly retired via `o2b brain reject <pref> --reason`.
+ * Dream emits one event per suppressed signal and does NOT count it
+ * toward a new candidate preference. The audit row carries the
+ * original retired-pref wikilink + the user's reason so the
+ * suppression decision is recoverable.
+ */
+ signalSuppressed: "signal-suppressed",
} as const;
export type BrainLogEventKind =
(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -226,6 +235,28 @@ export interface BrainRetired {
readonly confidence: BrainConfidence;
readonly pinned: boolean;
readonly aliases?: ReadonlyArray<string>;
+ /**
+ * When the retire transition was driven by `o2b brain reject`, the
+ * operator-supplied free-form reason is mirrored here so future dream
+ * passes can render it in `## Why retired` and so signal-suppression
+ * can quote the original objection. `null` for non-`user-rejected`
+ * retires.
+ */
+ readonly user_rejected_reason?: string | null;
+}
+
+/**
+ * One row of evidence (applied / violated / outdated) extracted from
+ * `Brain/log/<date>.md` for a specific preference. Pure derived view β€”
+ * `dream` reconstructs the recent slice on every run from the canonical
+ * log, never persisted as its own file.
+ */
+export interface BrainEvidenceSummary {
+ readonly timestamp: string;
+ readonly artifact: string;
+ readonly result: BrainApplyResult;
+ readonly agent?: string;
+ readonly note?: string;
}
// ----- Log events -----------------------------------------------------------
@@ -304,6 +335,22 @@ export interface BrainNotedRedundantLogEvent extends BrainLogEventBase {
readonly signal: string;
}
+/**
+ * `signal-suppressed` entry β€” fresh signal landed on a topic that
+ * the user previously rejected via `o2b brain reject --reason`. The
+ * dream pass dropped it from the candidate-pref planner and moved
+ * the file to `processed/`. Persisted with a wikilink to the
+ * retired pref + the original user-supplied reason so the audit
+ * trail is complete.
+ */
+export interface BrainSignalSuppressedLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.signalSuppressed;
+ readonly signal: string;
+ readonly retired: string;
+ readonly topic: string;
+ readonly reason: string;
+}
+
/** `skip-corrupted-frontmatter` β€” a file dream couldn't parse. */
export interface BrainSkipCorruptedLogEvent extends BrainLogEventBase {
readonly kind: typeof BRAIN_LOG_EVENT_KIND.skipCorruptedFrontmatter;
@@ -333,6 +380,7 @@ export type BrainLogEvent =
| BrainPromoteLogEvent
| BrainRetireLogEvent
| BrainNotedRedundantLogEvent
+ | BrainSignalSuppressedLogEvent
| BrainSkipCorruptedLogEvent
| BrainPinLogEvent
| BrainRollbackLogEvent;
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index d8c8a6af..cef67d95 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -501,12 +501,31 @@ describe("brain reject", () => {
expect(r.stderr).toContain("--id");
});
- test("unknown pref exits 2", async () => {
+ test("missing --reason exits 1 (mandatory from v0.10.1)", async () => {
await bootstrap();
const r = await runCli(
["brain", "reject", "--vault", vault, "--id", "pref-ghost"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("--reason");
+ });
+
+ test("unknown pref exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ [
+ "brain",
+ "reject",
+ "--vault",
+ vault,
+ "--id",
+ "pref-ghost",
+ "--reason",
+ "ghost",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
expect(r.returncode).toBe(2);
expect(r.stderr).toContain("preference not found");
});
@@ -538,7 +557,16 @@ describe("brain reject", () => {
expect(pin.returncode).toBe(0);
const r = await runCli(
- ["brain", "reject", "--vault", vault, "--id", "pref-important"],
+ [
+ "brain",
+ "reject",
+ "--vault",
+ vault,
+ "--id",
+ "pref-important",
+ "--reason",
+ "no longer relevant",
+ ],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(1);
@@ -581,11 +609,19 @@ describe("brain reject", () => {
"--id",
"pref-important",
"--yes",
+ "--reason",
+ "no longer the right call",
],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(r.returncode).toBe(0);
expect(existsSync(join(vault, "Brain", "retired", "ret-important.md"))).toBe(true);
+ // Β§6: the user reason must land on the retired file's frontmatter.
+ const ret = readFileSync(
+ join(vault, "Brain", "retired", "ret-important.md"),
+ "utf8",
+ );
+ expect(ret).toContain("user_rejected_reason: no longer the right call");
});
});
diff --git a/tests/core/brain.body-hygiene.test.ts b/tests/core/brain.body-hygiene.test.ts
new file mode 100644
index 00000000..a0699410
--- /dev/null
+++ b/tests/core/brain.body-hygiene.test.ts
@@ -0,0 +1,381 @@
+/**
+ * v0.10.1 β€” body hygiene + signal suppression.
+ *
+ * Coverage:
+ * - signal `## Raw` section is OMITTED when `raw` is missing (no
+ * more `_(not provided)_` placeholder shipped on disk).
+ * - preference body skips empty sections, drops the redundant
+ * `## Principle` duplicate, and renders `## Recent applications`
+ * / `## Recent violations` from the supplied evidence arrays.
+ * - retired body is re-rendered from scratch on retire so the
+ * v0.10.1 shape is applied regardless of the source file format.
+ * - `o2b brain reject --reason` persists the text on the retired
+ * file as `user_rejected_reason`; dream's next pass emits
+ * `signal-suppressed` and moves the offending signal to
+ * `processed/`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { dream } from "../../src/core/brain/dream.ts";
+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import {
+ brainDirs,
+ preferencePath,
+ retiredPath,
+ signalPath,
+} from "../../src/core/brain/paths.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-body-hygiene-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("signal body β€” no placeholder Raw", () => {
+ test("Raw section is omitted entirely when `raw` is not provided", () => {
+ writeSignal(vault, {
+ topic: "no-raw-here",
+ slug: "no-raw-here",
+ date: "2026-05-16",
+ created_at: "2026-05-16T10:00:00Z",
+ signal: "negative",
+ agent: "claude",
+ principle: "Something",
+ });
+ const content = readFileSync(
+ signalPath(vault, "2026-05-16", "no-raw-here"),
+ "utf8",
+ );
+ expect(content).not.toContain("## Raw");
+ expect(content).not.toContain("_(not provided)_");
+ });
+
+ test("Raw section is rendered when `raw` is provided", () => {
+ writeSignal(vault, {
+ topic: "with-raw",
+ slug: "with-raw",
+ date: "2026-05-16",
+ created_at: "2026-05-16T10:00:00Z",
+ signal: "negative",
+ agent: "claude",
+ principle: "Something",
+ raw: "verbatim user quote",
+ });
+ const content = readFileSync(
+ signalPath(vault, "2026-05-16", "with-raw"),
+ "utf8",
+ );
+ expect(content).toContain("## Raw");
+ expect(content).toContain("verbatim user quote");
+ });
+});
+
+describe("preference body β€” only sections with content", () => {
+ test("no Principle/Origin/HowToApply duplicate dead weight", () => {
+ writePreference(vault, {
+ slug: "lean",
+ topic: "lean",
+ principle: "Be lean",
+ created_at: "2026-05-16T10:00:00Z",
+ unconfirmed_until: "2026-05-30T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ recentApplied: [],
+ recentViolated: [],
+ });
+ const content = readFileSync(preferencePath(vault, "lean"), "utf8");
+ expect(content).not.toContain("## Principle");
+ expect(content).not.toContain("_(no evidence yet)_");
+ expect(content).not.toContain("_(not provided)_");
+ expect(content).not.toContain("## How to apply");
+ });
+
+ test("Origin renders wikilinks when evidenced_by is non-empty", () => {
+ writePreference(vault, {
+ slug: "with-origin",
+ topic: "with-origin",
+ principle: "P",
+ created_at: "2026-05-16T10:00:00Z",
+ unconfirmed_until: "2026-05-30T10:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: ["[[sig-2026-05-16-a]]", "[[sig-2026-05-16-b]]"],
+ });
+ const content = readFileSync(preferencePath(vault, "with-origin"), "utf8");
+ expect(content).toContain("## Origin");
+ expect(content).toContain("- [[sig-2026-05-16-a]]");
+ expect(content).toContain("- [[sig-2026-05-16-b]]");
+ });
+
+ test("Recent applications / violations render in priority order", () => {
+ writePreference(vault, {
+ slug: "tracked",
+ topic: "tracked",
+ principle: "P",
+ created_at: "2026-05-16T10:00:00Z",
+ unconfirmed_until: "2026-05-30T10:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ recentApplied: [
+ {
+ timestamp: "2026-05-16T13:00:00Z",
+ artifact: "[[docs/a.md:1-10]]",
+ result: "applied",
+ agent: "claude",
+ },
+ ],
+ recentViolated: [
+ {
+ timestamp: "2026-05-16T14:00:00Z",
+ artifact: "[[docs/b.md]]",
+ result: "violated",
+ note: "missed it",
+ },
+ ],
+ });
+ const content = readFileSync(preferencePath(vault, "tracked"), "utf8");
+ expect(content).toContain("## Recent applications");
+ expect(content).toContain("[[docs/a.md:1-10]]");
+ expect(content).toContain("## Recent violations");
+ expect(content).toContain("[[docs/b.md]]");
+ expect(content).toContain("missed it");
+ });
+});
+
+describe("retired body β€” re-rendered to v0.10.1 shape on retire", () => {
+ test("v0.9.x placeholder body in source is replaced before append-Retired", () => {
+ // Hand-craft a pref file in the old v0.9.x format with placeholder
+ // body. The retire path must NOT carry those placeholders forward.
+ const dirs = brainDirs(vault);
+ mkdirSync(dirs.preferences, { recursive: true });
+ const path = preferencePath(vault, "legacy");
+ writeFileSync(
+ path,
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-legacy",
+ "created_at: 2026-05-10T00:00:00Z",
+ "confirmed_at: 2026-05-10T00:00:00Z",
+ "unconfirmed_until: 2026-05-24T00:00:00Z",
+ "tags: [brain, brain/preference, brain/topic/legacy]",
+ "topic: legacy",
+ "status: confirmed",
+ "principle: legacy rule",
+ "evidenced_by: []",
+ "applied_count: 0",
+ "violated_count: 0",
+ "last_evidence_at: null",
+ "confidence: low",
+ "pinned: false",
+ "---",
+ "",
+ "## Principle",
+ "",
+ "legacy rule",
+ "",
+ "## Origin",
+ "",
+ "_(no evidence yet)_",
+ "",
+ "## How to apply",
+ "",
+ "_(not provided)_",
+ ].join("\n"),
+ "utf8",
+ );
+ moveToRetired(vault, path, "user-rejected", {
+ now: new Date("2026-05-16T10:00:00Z"),
+ retired_by: "[[Brain/log/2026-05-16]]",
+ user_rejected_reason: "irrelevant now",
+ });
+ const ret = readFileSync(retiredPath(vault, "legacy"), "utf8");
+ expect(ret).not.toContain("_(no evidence yet)_");
+ expect(ret).not.toContain("_(not provided)_");
+ expect(ret).toContain("## Retired");
+ expect(ret).toContain("user_rejected_reason: irrelevant now");
+ expect(ret).toContain("User reason: irrelevant now");
+ });
+});
+
+describe("Β§6 signal suppression", () => {
+ test("a fresh signal on a user-rejected topic is suppressed and moved", () => {
+ // Seed: a user-rejected retired pref with reason on the same topic.
+ const dirs = brainDirs(vault);
+ mkdirSync(dirs.retired, { recursive: true });
+ writeFileSync(
+ retiredPath(vault, "noisy"),
+ [
+ "---",
+ "kind: brain-retired",
+ "id: ret-noisy",
+ "status: retired",
+ "retired_at: 2026-05-10T00:00:00Z",
+ "retired_reason: user-rejected",
+ "retired_by: '[[Brain/log/2026-05-10]]'",
+ "created_at: 2026-05-09T00:00:00Z",
+ "tags: [brain, brain/retired, brain/topic/noisy]",
+ "topic: noisy",
+ "principle: stop spamming",
+ "evidenced_by: []",
+ "applied_count: 0",
+ "violated_count: 0",
+ "last_evidence_at: null",
+ "confidence: low",
+ "pinned: false",
+ "user_rejected_reason: rule was wrong",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+
+ // Three fresh signals on the same topic that would otherwise
+ // cross the candidate_threshold.
+ for (let i = 1; i <= 3; i++) {
+ writeSignal(vault, {
+ topic: "noisy",
+ slug: `noisy-${i}`,
+ date: "2026-05-16",
+ created_at: `2026-05-16T10:0${i}:00Z`,
+ signal: "negative",
+ agent: "claude",
+ principle: "be noisy",
+ });
+ }
+
+ const summary = dream(vault, { now: new Date("2026-05-16T12:00:00Z") });
+ expect(summary.changed).toBe(true);
+ expect(summary.suppressed.length).toBe(3);
+ // No new pref must be created.
+ expect(summary.new_unconfirmed).toEqual([]);
+ // Signals must be out of inbox/ and into processed/.
+ expect(summary.moved_to_processed.length).toBe(3);
+ // Log carries the typed event.
+ const logPath = join(vault, "Brain", "log", "2026-05-16.md");
+ const log = readFileSync(logPath, "utf8");
+ expect(log).toContain("signal-suppressed");
+ expect(log).toContain("[[ret-noisy]]");
+ expect(log).toContain("rule was wrong");
+ });
+
+ test("scoped suppressor does NOT swallow signals on a different scope", () => {
+ // Retired pref scoped to `writing`.
+ const dirs = brainDirs(vault);
+ mkdirSync(dirs.retired, { recursive: true });
+ writeFileSync(
+ retiredPath(vault, "scoped"),
+ [
+ "---",
+ "kind: brain-retired",
+ "id: ret-scoped",
+ "status: retired",
+ "retired_at: 2026-05-10T00:00:00Z",
+ "retired_reason: user-rejected",
+ "retired_by: '[[Brain/log/2026-05-10]]'",
+ "created_at: 2026-05-09T00:00:00Z",
+ "tags: [brain, brain/retired, brain/topic/scoped, brain/scope/writing]",
+ "topic: scoped",
+ "scope: writing",
+ "principle: writing-scoped rule",
+ "evidenced_by: []",
+ "applied_count: 0",
+ "violated_count: 0",
+ "last_evidence_at: null",
+ "confidence: low",
+ "pinned: false",
+ "user_rejected_reason: writing-scope was the issue",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+
+ // Three fresh signals on the SAME topic but a DIFFERENT scope.
+ for (let i = 1; i <= 3; i++) {
+ writeSignal(vault, {
+ topic: "scoped",
+ slug: `scoped-${i}`,
+ date: "2026-05-16",
+ created_at: `2026-05-16T10:0${i}:00Z`,
+ signal: "negative",
+ agent: "claude",
+ principle: "different-scope rule",
+ scope: "coding",
+ });
+ }
+
+ const summary = dream(vault, { now: new Date("2026-05-16T12:00:00Z") });
+ expect(summary.suppressed.length).toBe(0);
+ // A new pref is created (slug is suffixed because ret-scoped reserves
+ // the bare slug, hence pref-scoped-2).
+ expect(summary.new_unconfirmed.some((id) => id.startsWith("pref-scoped"))).toBe(
+ true,
+ );
+ const logPath = join(vault, "Brain", "log", "2026-05-16.md");
+ const log = readFileSync(logPath, "utf8");
+ expect(log).not.toContain("signal-suppressed");
+ });
+});
+
+describe("dream β€” body migration of v0.9.x preferences", () => {
+ test("first pass after upgrade rewrites placeholder body to v0.10.1 shape", () => {
+ // Pretend a v0.9.x pref already lives on disk with the legacy body.
+ const dirs = brainDirs(vault);
+ mkdirSync(dirs.preferences, { recursive: true });
+ const path = preferencePath(vault, "migrate-me");
+ writeFileSync(
+ path,
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-migrate-me",
+ "created_at: 2026-05-10T00:00:00Z",
+ "confirmed_at: 2026-05-10T00:00:00Z",
+ "unconfirmed_until: 2026-05-24T00:00:00Z",
+ "tags: [brain, brain/preference, brain/topic/migrate-me]",
+ "topic: migrate-me",
+ "status: confirmed",
+ "principle: migrate me",
+ 'evidenced_by: ["[[sig-2026-05-09-migrate-me]]"]',
+ "applied_count: 0",
+ "violated_count: 0",
+ "last_evidence_at: null",
+ "confidence: low",
+ "pinned: false",
+ "---",
+ "",
+ "## Principle",
+ "",
+ "migrate me",
+ "",
+ "## Origin",
+ "",
+ "_(no evidence yet)_",
+ "",
+ "## How to apply",
+ "",
+ "_(not provided)_",
+ ].join("\n"),
+ "utf8",
+ );
+ dream(vault, { now: new Date("2026-05-16T12:00:00Z") });
+ const after = readFileSync(path, "utf8");
+ expect(after).not.toContain("_(no evidence yet)_");
+ expect(after).not.toContain("_(not provided)_");
+ expect(after).not.toContain("## Principle");
+ // Origin section is preserved because evidenced_by is non-empty.
+ expect(after).toContain("## Origin");
+ expect(after).toContain("[[sig-2026-05-09-migrate-me]]");
+ });
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index d74aacd7..bc310525 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -64,6 +64,7 @@ describe("BRAIN_* const enums", () => {
"promote",
"retire",
"noted-redundant",
+ "signal-suppressed",
"skip-corrupted-frontmatter",
"pin",
"unpin",