Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat(brain): add o2b brain vitals scorecard + batch-concept-inflation lint (#135)
Johnsona99b0e7196ed
diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 3fff8524..1396f532 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -229,6 +229,7 @@ The schema pack gains four additive ontology fields (`labels`, `link_constraints```texto2b brain bridges discover [--max N] [--min-similarity X] | list | accept <source> <target> | dismiss <source> <target> - embedding-near link proposals over the vec index, reviewable artifact, accept writes one related: wikilinko2b brain clusters run [--min-size N] [--batch-size N] | list - graph-wide community detection; derived digests under Brain/clusters/, regenerated per run; --batch-size materializes in chunks with isolated, reported per-batch failures+o2b brain vitals [--orphan-threshold N] - aggregate governance scorecard over confirmed preferences: domain_diversity (scope entropy), connectivity_index (mean evidenced_by count), orphan_preferences (below threshold, default 2), gap_pressure (open concept-gap findings Γ· preference count, reused from doctor); records the vault_vitals metrico2b brain benchmark run --dataset <path> [--k N] [--expand] - hit@k + MRR against the live hybrid recall; records the recall_benchmark metrico2b brain tune run --dataset <path> [--k N] | status | reset - bounded self-tuning grid judged by the benchmark; persisted to Brain/search/tuning.jsono2b search <query> --expand deterministic lex/vec/hyde expansion of a bare query (stopword-stripped lex, entity-context vec line, template hyde passage)diff --git a/docs/metrics.md b/docs/metrics.mdindex 4d348458..13d650de 100644--- a/docs/metrics.md+++ b/docs/metrics.md@@ -64,6 +64,7 @@ writes, and a metric record is a summary, not a report.| `self_tuning` | `o2b brain tune run`, MCP `brain_tune` | `chosen`, `evaluated`, `best_mrr`, `dataset_hash` || `dream_stage` | `o2b brain dream stage` / `apply`, MCP `brain_dream` (since 1.0.0) | `action` (`stage`/`apply`), `run_id`, `proposals`, `sources`, `changed`; apply adds `new_unconfirmed`, `confirmed`, `retired` counts || `prompt_prefix` | decision-panel commit (opt-in `promptPrefixMetric`), context-pack consume (opt-in `promptPrefix`) | `kind` (`write_session`/`context_pack`), `prefix_hash` (sha-256 of the stable preamble), `prefix_chars`, `call_count`, `stable_count` |+| `vault_vitals` | `o2b brain vitals` | `preferences_scanned`, `domain_diversity`, `connectivity_index`, `orphan_count`, `gap_pressure` |Payload fields marked "(lane runs)" appear only on maintenance-laneemissions. All fields are additive-optional from a consumer's pointdiff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 44ac71a7..46b871cf 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -43,6 +43,7 @@ import {cmdBrainLabel,cmdBrainBridges,cmdBrainClusters,+ cmdBrainVitals,cmdBrainCoOccurrence,cmdBrainFileContext,cmdBrainBenchmark,@@ -221,6 +222,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainBridges(rest);case "clusters":return await cmdBrainClusters(rest);+ case "vitals":+ return await cmdBrainVitals(rest);case "co-occurrence":return await cmdBrainCoOccurrence(rest);case "file-context":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex a5aef669..81609e7d 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -52,6 +52,7 @@ Brain verbs (observing memory):label Controlled-vocabulary classification: assign, remove, show note labelsbridges Embedding-near link proposals: discover, list, accept, dismissclusters Link-graph communities: detect and materialize cluster notes+ vitals Aggregate governance scorecard: diversity, connectivity, gap pressureco-occurrence Suggest edges between entities co-referenced from the same notesfile-context Surface prior vault work that mentions a file pathbenchmark Recall quality benchmark: hit@k and MRR over a fixed dataset@@ -322,6 +323,15 @@ export const VERB_HELP: Record<string, string> = {"by internal degree, shared entities, density, no LLM prose - removes\n" +"stale generated notes, and records one communities metric. list reads\n" +"the generated notes back. Fail-soft without an index.\n",+ vitals:+ "usage: o2b brain vitals [--orphan-threshold N] [--vault <path>] [--json]\n" ++ "Aggregate governance scorecard over confirmed Brain/preferences/, four\n" ++ "numbers the per-item hygiene lints don't surface: domain_diversity\n" ++ "(normalised Shannon entropy of the scope distribution), connectivity_index\n" ++ "(mean evidenced_by count per preference), orphan_preferences (confirmed\n" ++ "preferences below --orphan-threshold evidence items, default 2), and\n" ++ "gap_pressure (open concept-gap findings, reused from `doctor`, divided by\n" ++ "preference count). Records one vault_vitals metric. Read-only.\n","co-occurrence":"usage: o2b brain co-occurrence [--min-co N] [--min-score X] [--limit N] [--write] [--vault <path>] [--json]\n" +"Suggest relationship edges between entities repeatedly co-referenced from\n" +diff --git a/src/cli/brain/verbs/health.ts b/src/cli/brain/verbs/health.tsindex 6a2890b2..9be4bea6 100644--- a/src/cli/brain/verbs/health.ts+++ b/src/cli/brain/verbs/health.ts@@ -35,6 +35,7 @@ export async function cmdBrainHealth(argv: string[]): Promise<number> {contradictions: [],conceptGaps: [],staleClaims: [],+ batchInflation: [],};if (flags["json"]) {@@ -55,10 +56,16 @@ export async function cmdBrainHealth(argv: string[]): Promise<number> {for (const s of sh.staleClaims) {process.stdout.write(`[stale-claim] ${s.id} (${s.ageDays}d since ${s.lastEvidenceAt})\n`);}+ for (const b of sh.batchInflation) {+ process.stdout.write(+ `[batch-inflation] ${b.count} confirmed ${b.windowStart}..${b.windowEnd}: ${b.ids.join(", ")}\n`,+ );+ }if (sh.contradictions.length === 0 &&sh.conceptGaps.length === 0 &&- sh.staleClaims.length === 0+ sh.staleClaims.length === 0 &&+ sh.batchInflation.length === 0) {ok("brain health: clean");}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 985a3661..acb5802b 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -27,6 +27,7 @@ export { cmdBrainForesight } from "./foresight.ts";export { cmdBrainLabel } from "./label.ts";export { cmdBrainBridges } from "./bridges.ts";export { cmdBrainClusters } from "./clusters.ts";+export { cmdBrainVitals } from "./vitals.ts";export { cmdBrainCoOccurrence } from "./co-occurrence.ts";export { cmdBrainFileContext } from "./file-context.ts";export { cmdBrainBenchmark } from "./benchmark.ts";diff --git a/src/cli/brain/verbs/vitals.ts b/src/cli/brain/verbs/vitals.tsnew file mode 100644index 00000000..5c93e57a--- /dev/null+++ b/src/cli/brain/verbs/vitals.ts@@ -0,0 +1,95 @@+/**+ * `o2b brain vitals` β print the aggregate governance health+ * scorecard (domain diversity, connectivity index, orphan+ * preferences, gap pressure) and record one `vault_vitals` metric.+ * Read-only over `Brain/preferences/`; reuses `runDoctor`'s+ * concept-gap count for `gap_pressure` rather than recomputing it.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage+ * errors.+ */++import { computeVaultVitals } from "../../../core/brain/vitals.ts";+import { appendMetric } from "../../../core/brain/metrics.ts";+import { isoSecond } from "../../../core/brain/time.ts";+import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";++const USAGE = "usage: o2b brain vitals [--orphan-threshold N] [--vault <path>] [--json]";++export async function cmdBrainVitals(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ "orphan-threshold": { type: "string" },+ json: { type: "boolean" },+ });+ const asJson = flags["json"] === true;+ if (positional.length !== 0) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }++ const orphanThreshold = parsePositiveInt(flags["orphan-threshold"] as string | undefined);+ if (orphanThreshold === false) {+ process.stderr.write("brain vitals: --orphan-threshold must be a positive integer\n");+ return 2;+ }++ const { vault } = brainVerbContext(flags);++ try {+ const report = computeVaultVitals(+ vault,+ orphanThreshold !== undefined ? { orphanThreshold } : {},+ );++ try {+ appendMetric(vault, {+ surface: "vault_vitals",+ runAt: isoSecond(new Date()),+ payload: {+ preferences_scanned: report.preferences_scanned,+ domain_diversity: report.domain_diversity,+ connectivity_index: report.connectivity_index,+ orphan_count: report.orphan_preferences.length,+ gap_pressure: report.gap_pressure,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }++ if (asJson) {+ okJson({+ preferences_scanned: report.preferences_scanned,+ domain_diversity: report.domain_diversity,+ connectivity_index: report.connectivity_index,+ gap_pressure: report.gap_pressure,+ orphan_preferences: report.orphan_preferences,+ scope_distribution: report.scope_distribution,+ });+ return 0;+ }++ ok(`vitals: ${report.preferences_scanned} confirmed preference(s) scanned`);+ ok(` domain_diversity: ${report.domain_diversity}`);+ ok(` connectivity_index: ${report.connectivity_index}`);+ ok(` gap_pressure: ${report.gap_pressure}`);+ ok(` orphan_preferences: ${report.orphan_preferences.length}`);+ for (const o of report.orphan_preferences) {+ ok(` [[${o.id}]] evidence=${o.evidence_count}${o.scope ? ` scope=${o.scope}` : ""}`);+ }+ ok(" scope_distribution:");+ for (const s of report.scope_distribution) {+ ok(` ${s.scope}: ${s.count}`);+ }+ return 0;+ } catch (exc) {+ return fail(`vitals failed: ${(exc as Error).message ?? exc}`);+ }+}++function parsePositiveInt(raw: string | undefined): number | undefined | false {+ if (raw === undefined) return undefined;+ const n = Number(raw);+ return Number.isInteger(n) && n > 0 ? n : false;+}diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex aa561dc0..b04c3f4a 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -583,6 +583,17 @@ function checkSemanticHealth(" Re-confirm or retire it.",});}+ for (const b of report.batchInflation) {+ issues.push({+ severity: "warning",+ code: "batch-concept-inflation",+ message:+ `${b.count} preferences confirmed within one window (${b.windowStart} to ${b.windowEnd}): ` ++ `${b.ids.map((id) => `[[${id}]]`).join(", ")} across topics ${b.topics.join(", ")}. ` ++ "A batch this size confirmed together usually means dedup/consolidation was skipped - " ++ "review for near-duplicates or preferences that should merge before the next dream pass.",+ });+ }return report;}diff --git a/src/core/brain/health/batch-inflation.ts b/src/core/brain/health/batch-inflation.tsnew file mode 100644index 00000000..1bed2a8a--- /dev/null+++ b/src/core/brain/health/batch-inflation.ts@@ -0,0 +1,110 @@+/**+ * Batch-inflation detector.+ *+ * A bulk or concurrent ingestion session can promote many distinct+ * preferences in a short window without pausing to check whether they+ * should have been consolidated first. The existing+ * `duplicate-preferences` lint only catches pairs that are already+ * near-identical (Jaccard >= 0.7 on principle tokens within the same+ * topic/scope); it says nothing about a *burst* of individually+ * distinct new preferences landing together, which is the actual+ * signal that a batch ingest skipped its own dedup/consolidation pass+ * before confirming. This detector flags confirmed preferences whose+ * `confirmed_at` timestamps cluster within a configured window at or+ * above a configured count - a burst, not a duplicate - so an+ * operator (or the next dream pass) can review whether the batch+ * should have collapsed into fewer preferences.+ *+ * Non-overlapping, deterministic, pure: preferences are sorted by+ * `confirmed_at`, walked with a window anchored at each unconsumed+ * preference, and each burst at or above the threshold is reported+ * once, resuming the scan after the burst's last member so adjacent+ * bursts never double-report the same preference.+ */++import { BRAIN_PREFERENCE_STATUS, type BrainPreferenceStatus } from "../types.ts";++const HOUR_MS = 60 * 60 * 1000;++/** Date-only ISO form (`YYYY-MM-DD`), which the doctor's checkIso allows. */+const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++/** Mirrors `stale-claim.ts`'s deterministic UTC-midnight expansion. */+function parseIsoUtc(value: string): number {+ const iso = ISO_DATE_ONLY_RE.test(value) ? `${value}T00:00:00Z` : value;+ return Date.parse(iso);+}++/** Narrow projection the detector needs; {@link BrainPreference} satisfies it. */+export interface PreferenceForBatchInflation {+ readonly id: string;+ readonly status: BrainPreferenceStatus;+ readonly confirmed_at: string | null;+ readonly topic: string;+ readonly scope?: string;+}++export interface BatchInflationFinding {+ readonly ids: ReadonlyArray<string>;+ readonly windowStart: string;+ readonly windowEnd: string;+ readonly count: number;+ readonly topics: ReadonlyArray<string>;+}++export interface DetectBatchInflationOptions {+ /** Burst window width in hours. Default 24. */+ readonly windowHours?: number;+ /** Minimum preferences confirmed within the window to count as a burst. Default 5. */+ readonly minBurstSize?: number;+}++interface TimedPref {+ readonly id: string;+ readonly topic: string;+ readonly ms: number;+}++export function detectBatchInflation(+ prefs: ReadonlyArray<PreferenceForBatchInflation>,+ opts: DetectBatchInflationOptions = {},+): BatchInflationFinding[] {+ const windowMs = (opts.windowHours ?? 24) * HOUR_MS;+ const minBurstSize = opts.minBurstSize ?? 5;++ const confirmed: TimedPref[] = prefs+ .filter(+ (p): p is PreferenceForBatchInflation & { confirmed_at: string } =>+ p.status === BRAIN_PREFERENCE_STATUS.confirmed && p.confirmed_at !== null,+ )+ .map((p) => ({ id: p.id, topic: p.topic, ms: parseIsoUtc(p.confirmed_at) }))+ .filter((p) => Number.isFinite(p.ms))+ .toSorted((a, b) => a.ms - b.ms || a.id.localeCompare(b.id));++ const out: BatchInflationFinding[] = [];+ let i = 0;+ while (i < confirmed.length) {+ // Grow the window from anchor i while the next member stays within+ // windowMs of confirmed[i] (fixed-anchor window, not a re-anchoring+ // slide - keeps bursts deterministic and non-overlapping).+ let j = i;+ while (j + 1 < confirmed.length && confirmed[j + 1]!.ms - confirmed[i]!.ms <= windowMs) {+ j++;+ }+ const size = j - i + 1;+ if (size >= minBurstSize) {+ const members = confirmed.slice(i, j + 1);+ out.push({+ ids: members.map((m) => m.id),+ windowStart: new Date(confirmed[i]!.ms).toISOString(),+ windowEnd: new Date(confirmed[j]!.ms).toISOString(),+ count: size,+ topics: [...new Set(members.map((m) => m.topic))].toSorted(),+ });+ i = j + 1; // non-overlapping: resume after this burst+ } else {+ i++;+ }+ }+ return out;+}diff --git a/src/core/brain/health/reconcile.ts b/src/core/brain/health/reconcile.tsindex b85ed212..7d3532e5 100644--- a/src/core/brain/health/reconcile.ts+++ b/src/core/brain/health/reconcile.ts@@ -23,9 +23,16 @@ import {type PreferenceForStaleClaim,type StaleClaimFinding,} from "./stale-claim.ts";+import {+ detectBatchInflation,+ type BatchInflationFinding,+ type PreferenceForBatchInflation,+} from "./batch-inflation.ts";/** A preference shape sufficient for every semantic-health detector. */-export type PreferenceForHealth = PreferenceForContradiction & PreferenceForStaleClaim;+export type PreferenceForHealth = PreferenceForContradiction &+ PreferenceForStaleClaim &+ PreferenceForBatchInflation;export interface SemanticHealthInput {readonly preferences: ReadonlyArray<PreferenceForHealth>;@@ -40,6 +47,8 @@ export interface SemanticHealthConfig {readonly contradictionJaccard: number;readonly conceptGapMinFrequency: number;readonly staleClaimMaxAgeDays: number;+ readonly batchInflationWindowHours?: number;+ readonly batchInflationMinBurstSize?: number;readonly now: Date;}@@ -50,6 +59,7 @@ export interface SemanticHealthReport {readonly contradictions: ReadonlyArray<ContradictionFinding>;readonly conceptGaps: ReadonlyArray<ConceptGapFinding>;readonly staleClaims: ReadonlyArray<StaleClaimFinding>;+ readonly batchInflation: ReadonlyArray<BatchInflationFinding>;readonly verdict: SemanticHealthVerdict;}@@ -67,14 +77,23 @@ export function reconcileSemanticHealth(maxAgeDays: config.staleClaimMaxAgeDays,now: config.now,});+ const batchInflation = detectBatchInflation(input.preferences, {+ ...(config.batchInflationWindowHours !== undefined+ ? { windowHours: config.batchInflationWindowHours }+ : {}),+ ...(config.batchInflationMinBurstSize !== undefined+ ? { minBurstSize: config.batchInflationMinBurstSize }+ : {}),+ });// A contradiction between two confirmed preferences is the most// serious finding - two active rules disagree, so an agent will apply- // a coin-flip. Gaps and stale claims are quality nudges, not active- // conflicts, so they only raise a watch.+ // a coin-flip. Gaps, stale claims, and batch-inflation bursts are+ // quality nudges, not active conflicts, so they only raise a watch.let verdict: SemanticHealthVerdict = "clean";if (contradictions.length > 0) verdict = "investigate";- else if (conceptGaps.length > 0 || staleClaims.length > 0) verdict = "watch";+ else if (conceptGaps.length > 0 || staleClaims.length > 0 || batchInflation.length > 0)+ verdict = "watch";- return { contradictions, conceptGaps, staleClaims, verdict };+ return { contradictions, conceptGaps, staleClaims, batchInflation, verdict };}diff --git a/src/core/brain/triggers/adapters.ts b/src/core/brain/triggers/adapters.tsindex 57918b0e..9a8bb7d8 100644--- a/src/core/brain/triggers/adapters.ts+++ b/src/core/brain/triggers/adapters.ts@@ -49,6 +49,21 @@ export function candidatesFromHealth(}),);}+ for (const finding of report.batchInflation) {+ out.push(+ Object.freeze({+ kind: "batch_inflation" as const,+ urgency: "low" as const,+ reason:+ `${finding.count} preferences confirmed together ` ++ `(${finding.windowStart} to ${finding.windowEnd}) across topics ${finding.topics.join(", ")}`,+ suggestedAction: "Review the batch for near-duplicates or preferences that should merge",+ sourceArtifacts: Object.freeze(finding.ids.map((id) => `[[${id}]]`)),+ contextSnippets: Object.freeze([`count: ${finding.count}`]),+ cooldownKey: `batch_inflation:${finding.ids[0]}:${finding.ids[finding.ids.length - 1]}`,+ }),+ );+ }return Object.freeze(out);}diff --git a/src/core/brain/triggers/types.ts b/src/core/brain/triggers/types.tsindex d03e26c5..57d93c3c 100644--- a/src/core/brain/triggers/types.ts+++ b/src/core/brain/triggers/types.ts@@ -32,6 +32,7 @@ export const TRIGGER_KINDS = ["contradiction","stale_claim","concept_gap",+ "batch_inflation","retention_action","knowledge_gap","open_question",diff --git a/src/core/brain/vitals.ts b/src/core/brain/vitals.tsnew file mode 100644index 00000000..b4a730e3--- /dev/null+++ b/src/core/brain/vitals.ts@@ -0,0 +1,153 @@+/**+ * Vault vitals β aggregate governance health scorecard.+ *+ * The existing hygiene surfaces (`doctor`, `health`, `moc-audit`) are+ * all per-item: one warning per duplicate pair, one finding per+ * contradiction, one bucket per MOC hub. None of them answer "is the+ * preference set as a whole spreading thin, well-evidenced, and+ * keeping up with its own gap backlog?" β a single scorecard over the+ * full `Brain/preferences/` set, four numbers:+ *+ * - `domain_diversity` β normalised Shannon entropy of the `scope`+ * distribution (0 = every preference shares+ * one scope, 1 = evenly spread).+ * - `connectivity_index` β mean `evidenced_by.length` per confirmed+ * preference (how well individual rules are+ * backed by originating signals).+ * - `orphan_preferences` β confirmed preferences below the evidence+ * threshold (thin backing, candidates for+ * re-confirmation or retirement).+ * - `gap_pressure` β open `concept-gap` findings (reused from+ * {@link runDoctor}'s semantic-health pass,+ * not recomputed here) divided by preference+ * count: are gaps piling up faster than+ * they're being distilled into preferences?+ *+ * Pure aggregation, no new detector logic and no filesystem writes.+ * Read-only; scope limited to `confirmed` preferences so trial+ * (`unconfirmed`) and `quarantine` records don't skew the averages β+ * same convention `checkLowEvidenceConfirmed` uses.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { brainDirs } from "./paths.ts";+import { parsePreference } from "./preference.ts";+import { runDoctor } from "./doctor.ts";+import { BRAIN_PREFERENCE_STATUS, type BrainPreference } from "./types.ts";++export interface VaultVitalsOptions {+ /** `evidenced_by.length` strictly below this counts as an orphan. Default 2. */+ readonly orphanThreshold?: number;+}++export interface VaultVitalsOrphan {+ readonly id: string;+ readonly scope: string | undefined;+ readonly evidence_count: number;+}++export interface VaultVitalsScopeCount {+ readonly scope: string;+ readonly count: number;+}++export interface VaultVitalsReport {+ readonly preferences_scanned: number;+ readonly domain_diversity: number;+ readonly connectivity_index: number;+ readonly orphan_preferences: ReadonlyArray<VaultVitalsOrphan>;+ readonly gap_pressure: number;+ readonly scope_distribution: ReadonlyArray<VaultVitalsScopeCount>;+}++function round2(n: number): number {+ return Math.round(n * 100) / 100;+}++/** Confirmed preferences only β mirrors `checkLowEvidenceConfirmed`'s scope. */+function readConfirmedPreferences(vault: string): BrainPreference[] {+ const dir = brainDirs(vault).preferences;+ if (!existsSync(dir)) return [];+ const out: BrainPreference[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;+ let pref: BrainPreference;+ try {+ pref = parsePreference(join(dir, name));+ } catch {+ continue; // schema errors are already surfaced by `o2b brain doctor`+ }+ if (pref.status === BRAIN_PREFERENCE_STATUS.confirmed) out.push(pref);+ }+ return out;+}++/** Normalised Shannon entropy of `scope` (missing scope groups as `"unscoped"`). */+function scopeDiversity(prefs: ReadonlyArray<BrainPreference>): {+ diversity: number;+ distribution: VaultVitalsScopeCount[];+} {+ const counts = new Map<string, number>();+ for (const p of prefs) {+ const scope = p.scope ?? "unscoped";+ counts.set(scope, (counts.get(scope) ?? 0) + 1);+ }+ const distribution = [...counts.entries()]+ .map(([scope, count]) => ({ scope, count }))+ .toSorted((a, b) => b.count - a.count || a.scope.localeCompare(b.scope));++ if (prefs.length === 0 || counts.size <= 1) return { diversity: 0, distribution };+ let entropy = 0;+ for (const count of counts.values()) {+ const p = count / prefs.length;+ entropy -= p * Math.log2(p);+ }+ const entropyMax = Math.log2(counts.size);+ return { diversity: entropyMax > 0 ? round2(entropy / entropyMax) : 0, distribution };+}++/**+ * Compute the vault vitals scorecard. `gap_pressure`'s numerator reuses+ * {@link runDoctor}'s semantic-health `conceptGaps` count rather than+ * re-running the detector β one source of truth for "how many gaps are+ * open". A doctor failure degrades `gap_pressure` to `0` rather than+ * failing the whole report: vitals is observability, not correctness.+ */+export function computeVaultVitals(+ vault: string,+ opts: VaultVitalsOptions = {},+): VaultVitalsReport {+ const orphanThreshold = opts.orphanThreshold ?? 2;+ const prefs = readConfirmedPreferences(vault);+ const { diversity, distribution } = scopeDiversity(prefs);++ const connectivity =+ prefs.length > 0+ ? round2(prefs.reduce((sum, p) => sum + p.evidenced_by.length, 0) / prefs.length)+ : 0;++ const orphans: VaultVitalsOrphan[] = prefs+ .filter((p) => p.evidenced_by.length < orphanThreshold)+ .map((p) => ({ id: p.id, scope: p.scope, evidence_count: p.evidenced_by.length }))+ .toSorted((a, b) => a.evidence_count - b.evidence_count || a.id.localeCompare(b.id));++ let gapCount = 0;+ try {+ gapCount = runDoctor(vault).semantic_health?.conceptGaps.length ?? 0;+ } catch {+ // Vitals is observability, not correctness β a doctor failure+ // should not block the rest of the report.+ }+ const gapPressure = prefs.length > 0 ? round2(gapCount / prefs.length) : 0;++ return {+ preferences_scanned: prefs.length,+ domain_diversity: diversity,+ connectivity_index: connectivity,+ orphan_preferences: orphans,+ gap_pressure: gapPressure,+ scope_distribution: distribution,+ };+}diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.tsindex d5baf40e..4af27b0b 100644--- a/src/mcp/brain/health-tools.ts+++ b/src/mcp/brain/health-tools.ts@@ -102,6 +102,13 @@ async function toolBrainHealth(last_evidence_at: s.lastEvidenceAt,age_days: s.ageDays,})),+ batch_inflation: (sh?.batchInflation ?? []).map((b) => ({+ ids: b.ids,+ window_start: b.windowStart,+ window_end: b.windowEnd,+ count: b.count,+ topics: b.topics,+ })),};}@@ -133,7 +140,7 @@ export const HEALTH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_health",description:- "Semantic-health report: contradictory confirmed preferences (opposite sign of record, same subject), recurring concepts with no dedicated preference, and confirmed preferences running on stale evidence. Returns the per-domain findings plus a clean/watch/investigate verdict. Read-only.",+ "Semantic-health report: contradictory confirmed preferences (opposite sign, same subject), recurring concepts with no dedicated preference, stale evidence, and preference-confirmation bursts (batch inflation). Per-domain findings plus a clean/watch/investigate verdict. Read-only.",inputSchema: {type: "object",properties: {diff --git a/tests/cli/brain-vitals.test.ts b/tests/cli/brain-vitals.test.tsnew file mode 100644index 00000000..57626721--- /dev/null+++ b/tests/cli/brain-vitals.test.ts@@ -0,0 +1,143 @@+/**+ * `o2b brain vitals` CLI surface: aggregate governance scorecard over+ * confirmed `Brain/preferences/` (domain diversity, connectivity+ * index, orphan preferences, gap pressure), plus the recorded+ * `vault_vitals` metric.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { listMetrics } from "../../src/core/brain/metrics.ts";+import { runCli } from "../helpers/run-cli.ts";++let vault: string;++function pref(+ slug: string,+ scope: string,+ evidencedBy: string[],+ status: "confirmed" | "unconfirmed" = "confirmed",+): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle for ${slug}`,+ created_at: "2026-05-20T00:00:00Z",+ confirmed_at: status === "confirmed" ? "2026-05-21T00:00:00Z" : null,+ unconfirmed_until: "2026-06-03T00:00:00Z",+ status,+ scope,+ evidenced_by: evidencedBy,+ applied_count: evidencedBy.length,+ violated_count: 0,+ last_evidence_at: "2026-05-22T00:00:00Z",+ confidence: "low",+ });+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-vitals-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("no preferences: zeroed report, no crash", async () => {+ const r = await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ expect(r.returncode).toBe(0);+ expect(JSON.parse(r.stdout)).toMatchObject({+ preferences_scanned: 0,+ domain_diversity: 0,+ connectivity_index: 0,+ gap_pressure: 0,+ orphan_preferences: [],+ });+});++test("single scope: zero diversity even with many preferences", async () => {+ pref("a", "coding", ["[[sig-1]]", "[[sig-2]]"]);+ pref("b", "coding", ["[[sig-3]]", "[[sig-4]]"]);+ const r = await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ const parsed = JSON.parse(r.stdout) as { domain_diversity: number; preferences_scanned: number };+ expect(parsed.preferences_scanned).toBe(2);+ expect(parsed.domain_diversity).toBe(0);+});++test("evenly split scopes: diversity approaches 1", async () => {+ pref("a", "coding", ["[[sig-1]]", "[[sig-2]]"]);+ pref("b", "personal", ["[[sig-3]]", "[[sig-4]]"]);+ const r = await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ const parsed = JSON.parse(r.stdout) as { domain_diversity: number };+ expect(parsed.domain_diversity).toBe(1);+});++test("connectivity_index averages evidenced_by length over confirmed prefs only", async () => {+ pref("a", "coding", ["[[sig-1]]", "[[sig-2]]", "[[sig-3]]"]); // 3+ pref("b", "coding", ["[[sig-4]]"]); // 1+ pref("c", "coding", ["[[sig-5]]", "[[sig-6]]"], "unconfirmed"); // excluded+ const r = await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ const parsed = JSON.parse(r.stdout) as {+ connectivity_index: number;+ preferences_scanned: number;+ };+ expect(parsed.preferences_scanned).toBe(2); // unconfirmed excluded+ expect(parsed.connectivity_index).toBe(2); // (3 + 1) / 2+});++test("orphan_preferences below --orphan-threshold, default 2", async () => {+ pref("thin", "coding", ["[[sig-1]]"]); // 1 < 2 -> orphan+ pref("solid", "coding", ["[[sig-2]]", "[[sig-3]]"]); // 2 -> not orphan+ const r = await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ const parsed = JSON.parse(r.stdout) as {+ orphan_preferences: Array<{ id: string; evidence_count: number }>;+ };+ expect(parsed.orphan_preferences).toHaveLength(1);+ expect(parsed.orphan_preferences[0]).toMatchObject({ id: "pref-thin", evidence_count: 1 });+});++test("--orphan-threshold overrides the default", async () => {+ pref("solid", "coding", ["[[sig-1]]", "[[sig-2]]", "[[sig-3]]"]); // 3+ const r = await runCli([+ "brain",+ "vitals",+ "--orphan-threshold",+ "4",+ "--vault",+ vault,+ "--json",+ ]);+ const parsed = JSON.parse(r.stdout) as { orphan_preferences: unknown[] };+ expect(parsed.orphan_preferences).toHaveLength(1); // 3 < 4 now counts+});++test("records one vault_vitals metric per run", async () => {+ pref("a", "coding", ["[[sig-1]]", "[[sig-2]]"]);+ await runCli(["brain", "vitals", "--vault", vault, "--json"]);+ const metrics = listMetrics(vault, { surface: "vault_vitals" });+ expect(metrics).toHaveLength(1);+ expect(metrics[0]!.payload).toMatchObject({+ preferences_scanned: 1,+ connectivity_index: 2,+ });+});++test("usage errors exit 2", async () => {+ const badThreshold = await runCli([+ "brain",+ "vitals",+ "--orphan-threshold",+ "0",+ "--vault",+ vault,+ ]);+ expect(badThreshold.returncode).toBe(2);+ const extraArg = await runCli(["brain", "vitals", "nope", "--vault", vault]);+ expect(extraArg.returncode).toBe(2);+});diff --git a/tests/core/brain/health/batch-inflation.test.ts b/tests/core/brain/health/batch-inflation.test.tsnew file mode 100644index 00000000..ad124eb4--- /dev/null+++ b/tests/core/brain/health/batch-inflation.test.ts@@ -0,0 +1,120 @@+/**+ * Batch-inflation detector.+ *+ * Distinct axis from `duplicate-preferences` (near-identical principle+ * text): this flags a *burst* of individually-distinct preferences all+ * confirmed within a short window, regardless of similarity.+ */++import { describe, expect, test } from "bun:test";++import { detectBatchInflation } from "../../../../src/core/brain/health/batch-inflation.ts";+import {+ BRAIN_PREFERENCE_STATUS,+ type BrainPreferenceStatus,+} from "../../../../src/core/brain/types.ts";++function pref(+ id: string,+ confirmedAt: string | null,+ topic = "t",+ status: BrainPreferenceStatus = BRAIN_PREFERENCE_STATUS.confirmed,+) {+ return { id, status, confirmed_at: confirmedAt, topic };+}++describe("detectBatchInflation", () => {+ test("a burst at or above minBurstSize within the window is flagged", () => {+ const findings = detectBatchInflation(+ [+ pref("pref-a", "2026-05-01T00:00:00Z"),+ pref("pref-b", "2026-05-01T01:00:00Z"),+ pref("pref-c", "2026-05-01T02:00:00Z"),+ ],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings).toHaveLength(1);+ expect(findings[0]!.ids).toEqual(["pref-a", "pref-b", "pref-c"]);+ expect(findings[0]!.count).toBe(3);+ });++ test("below minBurstSize is not flagged", () => {+ const findings = detectBatchInflation(+ [pref("pref-a", "2026-05-01T00:00:00Z"), pref("pref-b", "2026-05-01T01:00:00Z")],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings).toEqual([]);+ });++ test("preferences outside the window do not merge into one burst", () => {+ const findings = detectBatchInflation(+ [+ pref("pref-a", "2026-05-01T00:00:00Z"),+ pref("pref-b", "2026-05-01T01:00:00Z"),+ // 3 days later - outside a 24h window from pref-a.+ pref("pref-c", "2026-05-04T00:00:00Z"),+ ],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings).toEqual([]);+ });++ test("two separate bursts are reported non-overlapping", () => {+ const findings = detectBatchInflation(+ [+ pref("pref-a", "2026-05-01T00:00:00Z"),+ pref("pref-b", "2026-05-01T01:00:00Z"),+ pref("pref-c", "2026-05-01T02:00:00Z"),+ // second burst, well outside the first window+ pref("pref-d", "2026-05-10T00:00:00Z"),+ pref("pref-e", "2026-05-10T01:00:00Z"),+ pref("pref-f", "2026-05-10T02:00:00Z"),+ ],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings).toHaveLength(2);+ expect(findings[0]!.ids).toEqual(["pref-a", "pref-b", "pref-c"]);+ expect(findings[1]!.ids).toEqual(["pref-d", "pref-e", "pref-f"]);+ });++ test("unconfirmed preferences are excluded", () => {+ const findings = detectBatchInflation(+ [+ pref("pref-a", "2026-05-01T00:00:00Z"),+ pref("pref-b", "2026-05-01T01:00:00Z"),+ pref("pref-c", null, "t", BRAIN_PREFERENCE_STATUS.unconfirmed),+ ],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings).toEqual([]);+ });++ test("preferences with a null confirmed_at are excluded", () => {+ const findings = detectBatchInflation(+ [pref("pref-a", "2026-05-01T00:00:00Z"), pref("pref-b", null)],+ { windowHours: 24, minBurstSize: 1 },+ );+ expect(findings).toHaveLength(1);+ expect(findings[0]!.ids).toEqual(["pref-a"]);+ });++ test("default options: 24h window, burst size 5", () => {+ const findings = detectBatchInflation(+ Array.from({ length: 5 }, (_, i) => pref(`pref-${i}`, `2026-05-01T0${i}:00:00Z`)),+ );+ expect(findings).toHaveLength(1);+ expect(findings[0]!.count).toBe(5);+ });++ test("topics are deduped and sorted", () => {+ const findings = detectBatchInflation(+ [+ pref("pref-a", "2026-05-01T00:00:00Z", "zeta"),+ pref("pref-b", "2026-05-01T01:00:00Z", "alpha"),+ pref("pref-c", "2026-05-01T02:00:00Z", "alpha"),+ ],+ { windowHours: 24, minBurstSize: 3 },+ );+ expect(findings[0]!.topics).toEqual(["alpha", "zeta"]);+ });+});diff --git a/tests/core/brain/health/reconcile.test.ts b/tests/core/brain/health/reconcile.test.tsindex 1cda237d..69edcd2b 100644--- a/tests/core/brain/health/reconcile.test.ts+++ b/tests/core/brain/health/reconcile.test.ts@@ -30,6 +30,8 @@ function pref(principle: "",evidenced_by: [],last_evidence_at: null,+ confirmed_at: "2026-05-01T00:00:00Z",+ topic: "t",...over,};}@@ -121,4 +123,39 @@ describe("reconcileSemanticHealth", () => {expect(report.conceptGaps.map((g) => g.term)).toContain("kanban");expect(report.verdict).toBe("watch");});++ test("a burst of preferences confirmed together yields a watch verdict", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [+ pref({ id: "pref-a", confirmed_at: "2026-05-01T00:00:00Z" }),+ pref({ id: "pref-b", confirmed_at: "2026-05-01T00:10:00Z" }),+ ],+ signSignById: signs,+ corpusPrinciples: [],+ coveredTopics: [],+ },+ { ...config, batchInflationMinBurstSize: 2 },+ );+ expect(report.batchInflation).toHaveLength(1);+ expect(report.batchInflation[0]!.ids).toEqual(["pref-a", "pref-b"]);+ expect(report.verdict).toBe("watch");+ });++ test("below the burst threshold stays clean", () => {+ const report = reconcileSemanticHealth(+ {+ preferences: [+ pref({ id: "pref-a", confirmed_at: "2026-05-01T00:00:00Z" }),+ pref({ id: "pref-b", confirmed_at: "2026-05-01T00:10:00Z" }),+ ],+ signSignById: signs,+ corpusPrinciples: [],+ coveredTopics: [],+ },+ config, // default minBurstSize is 5+ );+ expect(report.batchInflation).toEqual([]);+ expect(report.verdict).toBe("clean");+ });});diff --git a/tests/core/brain/trigger-scan.test.ts b/tests/core/brain/trigger-scan.test.tsindex 614efd1e..f4eb2961 100644--- a/tests/core/brain/trigger-scan.test.ts+++ b/tests/core/brain/trigger-scan.test.ts@@ -32,6 +32,15 @@ const HEALTH: SemanticHealthReport = {],conceptGaps: [],staleClaims: [{ id: "pref-old", lastEvidenceAt: "2026-01-01T00:00:00Z", ageDays: 120 }],+ batchInflation: [+ {+ ids: ["pref-c", "pref-d"],+ windowStart: "2026-05-01T00:00:00.000Z",+ windowEnd: "2026-05-01T00:10:00.000Z",+ count: 2,+ topics: ["a", "b"],+ },+ ],};const RETENTION: RetentionReviewReport = {@@ -63,9 +72,9 @@ const RETENTION: RetentionReviewReport = {],};-test("candidatesFromHealth normalizes contradictions and stale claims", () => {+test("candidatesFromHealth normalizes contradictions, stale claims, and batch inflation", () => {const candidates = candidatesFromHealth(HEALTH);- expect(candidates).toHaveLength(2);+ expect(candidates).toHaveLength(3);const contradiction = candidates[0]!;expect(contradiction.kind).toBe("contradiction");expect(contradiction.urgency).toBe("high");@@ -75,6 +84,11 @@ test("candidatesFromHealth normalizes contradictions and stale claims", () => {const stale = candidates[1]!;expect(stale.kind).toBe("stale_claim");expect(stale.cooldownKey).toBe("stale_claim:pref-old");+ const inflation = candidates[2]!;+ expect(inflation.kind).toBe("batch_inflation");+ expect(inflation.urgency).toBe("low");+ expect(inflation.cooldownKey).toBe("batch_inflation:pref-c:pref-d");+ expect(inflation.sourceArtifacts).toEqual(["[[pref-c]]", "[[pref-d]]"]);});test("candidatesFromRetention keeps only park and prune actions", () => {