Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: audit brain federation for record-level divergence, not just cursor positions (#4519)

[._.]/ Adam Eivy8a929a2c01ae
diff --git a/client/src/components/instances/BrainParityPanel.jsx b/client/src/components/instances/BrainParityPanel.jsx
new file mode 100644
index 0000000000..e66ee64e76
--- /dev/null
+++ b/client/src/components/instances/BrainParityPanel.jsx
@@ -0,0 +1,190 @@
+/**
+ * Brain parity audit for one peer (issue #4519).
+ *
+ * The sync-status badges above this panel report delta-log CURSOR positions —
+ * "we've pulled everything you published". They cannot tell you whether the two
+ * brains actually hold the same records, so a peer that silently dropped a
+ * record (or never synced this direction at all) still reads "synced". This
+ * panel runs the record-level audit and names what's out of parity.
+ *
+ * Deliberately on demand: the audit exchanges a full manifest, which no routine
+ * 60s sync cycle should pay for. Stored results (from the last run) render
+ * immediately on load; the button re-runs it.
+ */
+
+import { useState } from 'react';
+import { ChevronDown, ChevronRight, ScanSearch, RefreshCw } from 'lucide-react';
+import Pill from '../ui/Pill';
+import { runBrainParityCheck } from '../../services/api';
+import { timeAgo } from '../../utils/formatters';
+
+// Statuses in the order they're worth reading: what we hold and they don't,
+// what they hold and we don't, then same-id-different-clock drift.
+const STATUS_META = [
+ { key: 'local-only', label: 'only here', tone: 'warning' },
+ { key: 'peer-only', label: 'only there', tone: 'warning' },
+ { key: 'diverged', label: 'diverged', tone: 'warning' },
+];
+
+const REASON_HELP = {
+ 'peer-not-found': 'This peer is no longer in the registry.',
+ 'peer-unreachable': 'The peer did not answer. Parity is unknown until it is back online.',
+ 'peer-too-old': 'This peer predates the reconcile endpoints. Update it to audit parity.',
+ 'fetch-failed': 'The peer answered with an error. Parity is unknown.',
+};
+
+const REASON_LABELS = {
+ 'peer-not-found': 'peer removed',
+ 'peer-unreachable': 'unreachable',
+ 'peer-too-old': 'older peer',
+ 'fetch-failed': 'check failed',
+};
+
+const outOfParityCount = (summary) =>
+ STATUS_META.reduce((total, { key }) => total + (summary?.[key] ?? 0), 0);
+
+/**
+ * One-line verdict for the collapsed header.
+ *
+ * A checksum mismatch with zero out-of-parity records is its own finding, not a
+ * clean result: the two sides hold the same record ids with the same clocks but
+ * different contents, which only the whole-brain checksum can see.
+ */
+function verdict(report) {
+ if (!report) return { label: 'not checked', tone: 'note' };
+ if (report.available === false) return { label: REASON_LABELS[report.reason] || 'unavailable', tone: 'note' };
+ const outOfParity = outOfParityCount(report.summary);
+ if (outOfParity > 0) return { label: `${outOfParity} out of parity`, tone: 'warning' };
+ if (report.checksums?.match === false) return { label: 'content mismatch', tone: 'warning' };
+ return { label: 'in parity', tone: 'success' };
+}
+
+export default function BrainParityPanel({ peer, report: storedReport }) {
+ const [expanded, setExpanded] = useState(false);
+ const [running, setRunning] = useState(false);
+ // A fresh run supersedes the stored report for this card. Kept in local state
+ // (not pushed to the peer record) because a parity report is a point-in-time
+ // audit result, not peer configuration.
+ const [freshReport, setFreshReport] = useState(null);
+ const [error, setError] = useState(null);
+
+ const report = freshReport ?? storedReport ?? null;
+ const { label, tone } = verdict(report);
+
+ const runCheck = async () => {
+ setRunning(true);
+ setError(null);
+ // `silent` — this panel renders its own inline error rather than toasting,
+ // since an unreachable peer is an expected outcome of an audit.
+ const result = await runBrainParityCheck(peer.id, { silent: true }).catch(() => null);
+ const next = result?.reports?.[0] ?? null;
+ if (next) {
+ setFreshReport(next);
+ setExpanded(true);
+ } else {
+ setError('Parity check failed. Try again once the peer is reachable.');
+ }
+ setRunning(false);
+ };
+
+ const types = (report?.byType || []).filter((entry) => entry.records?.length > 0);
+
+ return (
+ <div className="mt-2 pt-2 border-t border-port-border/50">
+ <div className="flex items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ className="flex items-center gap-1.5 flex-1 text-left group"
+ aria-expanded={expanded}
+ >
+ {expanded ? <ChevronDown size={12} className="text-gray-500" /> : <ChevronRight size={12} className="text-gray-500" />}
+ <ScanSearch size={12} className="text-gray-500" />
+ <span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium group-hover:text-gray-400 transition-colors">
+ Brain parity
+ </span>
+ <Pill tone={tone} size="xs" bordered={false} className="ml-auto">{label}</Pill>
+ </button>
+ <button
+ type="button"
+ onClick={runCheck}
+ disabled={running}
+ className="inline-flex items-center gap-1 text-[10px] text-port-accent bg-port-accent/10 hover:bg-port-accent/20 rounded px-1.5 py-0.5 transition-colors disabled:opacity-50"
+ title="Compare every brain record with this peer — on demand, not part of the sync cycle"
+ >
+ <RefreshCw size={10} className={running ? 'animate-spin' : ''} />
+ {running ? 'Checking…' : 'Check'}
+ </button>
+ </div>
+
+ {expanded && (
+ <div className="mt-2 space-y-2 text-xs">
+ {error && <p className="text-port-warning">{error}</p>}
+
+ {!report && !error && (
+ <p className="text-gray-500">
+ Sync badges above show delta-log positions, not verified record-level parity. Run a check to compare
+ every brain record with this peer.
+ </p>
+ )}
+
+ {report?.available === false && (
+ <p className="text-gray-500">{REASON_HELP[report.reason] || 'Parity could not be determined.'}</p>
+ )}
+
+ {report?.available && (
+ <>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Pill tone="muted" size="xs" bordered={false}>{report.summary.total} records compared</Pill>
+ {STATUS_META.map(({ key, label: statusLabel, tone: statusTone }) => (
+ report.summary[key] > 0 && (
+ <Pill key={key} tone={statusTone} size="xs" bordered={false}>
+ {report.summary[key]} {statusLabel}
+ </Pill>
+ )
+ ))}
+ {outOfParityCount(report.summary) === 0 && (
+ <Pill tone="success" size="xs" bordered={false}>every record matches</Pill>
+ )}
+ </div>
+
+ {report.checksums?.match === false && outOfParityCount(report.summary) === 0 && (
+ <p className="text-port-warning">
+ Every record id and timestamp matches, but the whole-brain checksums differ — at least one record
+ body differs between the two installs. The next sync cycle will pull the peer&apos;s copy.
+ </p>
+ )}
+
+ {types.length > 0 && (
+ <ul className="space-y-1">
+ {types.map((entry) => (
+ <li key={entry.type}>
+ <div className="flex items-center gap-1.5">
+ <span className="text-gray-300">{entry.type}</span>
+ {STATUS_META.map(({ key, label: statusLabel }) => (
+ entry.counts[key] > 0 && (
+ <span key={key} className="text-[10px] text-gray-500">
+ {entry.counts[key]} {statusLabel}
+ </span>
+ )
+ ))}
+ </div>
+ <div className="mt-0.5 text-[10px] text-gray-600 font-mono break-all">
+ {entry.records.map((record) => record.id).join(', ')}
+ {entry.truncated && ' … (stored sample — re-run for the full list)'}
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {report.checkedAt && (
+ <p className="text-[10px] text-gray-600">Checked {timeAgo(report.checkedAt)}</p>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/instances/BrainParityPanel.test.jsx b/client/src/components/instances/BrainParityPanel.test.jsx
new file mode 100644
index 0000000000..a024bb9a07
--- /dev/null
+++ b/client/src/components/instances/BrainParityPanel.test.jsx
@@ -0,0 +1,137 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ runBrainParityCheck: vi.fn(),
+}));
+
+import { runBrainParityCheck } from '../../services/api';
+import BrainParityPanel from './BrainParityPanel';
+
+const PEER = { id: 'peer-local-1', instanceId: 'inst-peer-1', name: 'Example Peer' };
+
+const summary = (overrides = {}) => ({
+ total: 0,
+ 'in-parity': 0,
+ 'local-only': 0,
+ 'peer-only': 0,
+ diverged: 0,
+ ...overrides,
+});
+
+const report = (overrides = {}) => ({
+ peerId: 'peer-local-1',
+ peerInstanceId: 'inst-peer-1',
+ checkedAt: new Date().toISOString(),
+ available: true,
+ checksums: { local: 'a', peer: 'a', match: true },
+ summary: summary(),
+ byType: [],
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('BrainParityPanel', () => {
+ it('reads "not checked" with no stored report', () => {
+ render(<BrainParityPanel peer={PEER} report={null} />);
+ expect(screen.getByText('not checked')).toBeInTheDocument();
+ });
+
+ it('summarizes a clean stored report as in parity', () => {
+ render(<BrainParityPanel peer={PEER} report={report({ summary: summary({ total: 12, 'in-parity': 12 }) })} />);
+ expect(screen.getByText('in parity')).toBeInTheDocument();
+ });
+
+ it('counts every out-of-parity class in the header', () => {
+ render(
+ <BrainParityPanel
+ peer={PEER}
+ report={report({ summary: summary({ total: 10, 'in-parity': 6, 'local-only': 2, 'peer-only': 1, diverged: 1 }) })}
+ />,
+ );
+ expect(screen.getByText('4 out of parity')).toBeInTheDocument();
+ });
+
+ it('flags a checksum mismatch even when every record id and clock lines up', async () => {
+ const user = userEvent.setup();
+ render(
+ <BrainParityPanel
+ peer={PEER}
+ report={report({
+ summary: summary({ total: 5, 'in-parity': 5 }),
+ checksums: { local: 'a', peer: 'b', match: false },
+ })}
+ />,
+ );
+
+ expect(screen.getByText('content mismatch')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /Brain parity/ }));
+ expect(screen.getByText(/whole-brain checksums differ/)).toBeInTheDocument();
+ });
+
+ it('lists the diverged record ids per entity type once expanded', async () => {
+ const user = userEvent.setup();
+ render(
+ <BrainParityPanel
+ peer={PEER}
+ report={report({
+ summary: summary({ total: 3, 'in-parity': 1, 'local-only': 1, 'peer-only': 1 }),
+ byType: [{
+ type: 'people',
+ counts: summary({ total: 3, 'in-parity': 1, 'local-only': 1, 'peer-only': 1 }),
+ records: [{ id: 'rec-only-here', status: 'local-only' }, { id: 'rec-only-there', status: 'peer-only' }],
+ }],
+ })}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', { name: /Brain parity/ }));
+
+ expect(screen.getByText('people')).toBeInTheDocument();
+ expect(screen.getByText(/rec-only-here, rec-only-there/)).toBeInTheDocument();
+ });
+
+ it('explains an unreachable peer instead of reporting divergence', async () => {
+ const user = userEvent.setup();
+ render(<BrainParityPanel peer={PEER} report={{ available: false, reason: 'peer-unreachable' }} />);
+
+ expect(screen.getByText('unreachable')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /Brain parity/ }));
+ expect(screen.getByText(/did not answer/)).toBeInTheDocument();
+ });
+
+ it('runs the check on demand and shows the fresh result', async () => {
+ const user = userEvent.setup();
+ runBrainParityCheck.mockResolvedValue({
+ reports: [report({ summary: summary({ total: 4, 'in-parity': 3, 'peer-only': 1 }) })],
+ });
+
+ render(<BrainParityPanel peer={PEER} report={null} />);
+ await user.click(screen.getByRole('button', { name: /Check/ }));
+
+ expect(runBrainParityCheck).toHaveBeenCalledWith('peer-local-1', { silent: true });
+ await waitFor(() => expect(screen.getByText('1 out of parity')).toBeInTheDocument());
+ // Auto-expands so the result is readable without a second click.
+ expect(screen.getByText('4 records compared')).toBeInTheDocument();
+ });
+
+ it('surfaces an inline error when the check fails, without toasting', async () => {
+ const user = userEvent.setup();
+ runBrainParityCheck.mockRejectedValue(new Error('boom'));
+
+ render(<BrainParityPanel peer={PEER} report={null} />);
+ await user.click(screen.getByRole('button', { name: /Brain parity/ }));
+ await user.click(screen.getByRole('button', { name: /Check/ }));
+
+ await waitFor(() => expect(screen.getByText(/Parity check failed/)).toBeInTheDocument());
+ });
+
+ it('does not run the audit just because the panel rendered', () => {
+ render(<BrainParityPanel peer={PEER} report={null} />);
+ expect(runBrainParityCheck).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 806ae984f9..30c91f76b2 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -18,11 +18,13 @@ import {
getNetworkExposure,
listPeerSubscriptions,
getPeerFullSyncCoverage,
+ getBrainParityReports,
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';
+import BrainParityPanel from '../components/instances/BrainParityPanel';
import { timeAgo, timeUntil } from '../utils/formatters';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
@@ -1093,7 +1095,7 @@ function PeerAuthEditor({ peer, onRefresh }) {
);
}
-function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
+function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReport }) {
const [editingName, setEditingName] = useState(false);
const [name, setName] = useState('');
const [probing, setProbing] = useState(false);
@@ -1365,6 +1367,8 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
<SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} syncing={syncing} />
+ <BrainParityPanel peer={peer} report={parityReport} />
+
<PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />
{peer.status === 'online' && (
<PeerAgentsSection peerId={peer.id} peerName={peer.name} />
@@ -1379,6 +1383,10 @@ export default function Instances() {
const [syncStatus, setSyncStatus] = useState(null);
const [tailnetInfo, setTailnetInfo] = useState(null);
const [networkExposure, setNetworkExposure] = useState(null);
+ // Last stored brain-parity audit per peer, keyed by peer instanceId. Read
+ // once here rather than per card: it's a single local-file read, and every
+ // card needs a slice of it. Running a check is on-demand per card.
+ const [parityReports, setParityReports] = useState({});
const [loading, setLoading] = useState(true);
const fetchData = useCallback(async () => {
@@ -1398,7 +1406,11 @@ export default function Instances() {
Promise.all([
fetchData(),
getTailnetInfo().then(setTailnetInfo).catch(() => setTailnetInfo(null)),
- getNetworkExposure({ silent: true }).then(setNetworkExposure).catch(() => setNetworkExposure(null))
+ getNetworkExposure({ silent: true }).then(setNetworkExposure).catch(() => setNetworkExposure(null)),
+ // Stored results only — the audit itself never runs on page load.
+ getBrainParityReports({ silent: true })
+ .then((data) => setParityReports(data?.reports ?? {}))
+ .catch(() => setParityReports({}))
]).finally(() => setLoading(false));
socket.emit('instances:subscribe');
@@ -1448,7 +1460,14 @@ export default function Instances() {
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
{peers.map(peer => (
- <PeerCard key={peer.id} peer={peer} onRefresh={fetchData} syncStatus={syncStatus} tailnetInfo={tailnetInfo} />
+ <PeerCard
+ key={peer.id}
+ peer={peer}
+ onRefresh={fetchData}
+ syncStatus={syncStatus}
+ tailnetInfo={tailnetInfo}
+ parityReport={parityReports[peer.instanceId] ?? null}
+ />
))}
</div>
</div>
diff --git a/client/src/services/README.md b/client/src/services/README.md
index e9e7e0f546..13bd36912e 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -70,7 +70,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
-| `apiBrain.js` | Brain (second-brain) search + ingest + edit. |
+| `apiBrain.js` | Brain (second-brain) search + ingest + edit, plus the federation parity audit (`getBrainParityReports`, `runBrainParityCheck`). |
| `apiMemory.js` | Memory CRUD. |
| `apiNotes.js` | Notes vault. |
| `apiDigitalTwin.js` | Digital twin status + summary. |
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 3f9738cd6a..445bae3a20 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -365,3 +365,15 @@ export const updateYoutubeIngestSettings = (settings, options = {}) => request('
});
export const youtubeIngestEventsUrl = (jobId) =>
`/api/brain/youtube/ingest/${encodeURIComponent(jobId)}/events`;
+
+// --- Brain federation parity audit (#4519) ---
+// `getBrainParityReports` reads the last stored per-peer result (no peer I/O);
+// `runBrainParityCheck` performs the audit — pass a local peer id for one peer,
+// omit it to sweep every federating peer. `silent: true` is available for
+// callers that own their error UI.
+export const getBrainParityReports = (options = {}) => request('/brain/reconcile/parity', options);
+export const runBrainParityCheck = (peerId, options = {}) => request('/brain/reconcile/parity', {
+ method: 'POST',
+ body: JSON.stringify(peerId ? { peerId } : {}),
+ ...options
+});
diff --git a/docs/API.md b/docs/API.md
index 11627c2ac1..edc55f8d5e 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -299,6 +299,9 @@ See [Agent Context (MCP)](./features/agent-context.md) for setup, transport head
| GET | `/brain/settings` | Get Brain settings |
| PUT | `/brain/settings` | Update Brain settings |
| GET | `/brain/summary` | Get brain statistics summary |
+| GET | `/brain/reconcile/manifest` | Per-record parity manifest (`{ id, updatedAt, deleted }` per entity type) a peer audits against — ids and clocks only, no record bodies |
+| GET | `/brain/reconcile/parity` | Last stored parity report per peer (local read, no peer I/O) |
+| POST | `/brain/reconcile/parity` | Run the record-level parity audit — body `{ peerId? }`, omitted sweeps every federating peer |
### Brain Links
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index c67acf1126..8093d81dec 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -98,6 +98,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.
- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
+- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).
---
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index ce14efe02c..b19b3127d5 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -545,6 +545,14 @@ export const brainSyncPushSchema = z.object({
changes: z.array(brainSyncChangeSchema).min(1).max(1000)
});
+// Brain parity check body (POST /api/brain/reconcile/parity). `peerId` is the
+// LOCAL peer-registry id (the same id `/api/instances/peers/:id/sync` takes, so
+// the Instances card can pass the peer it already holds). Omitted runs the sweep
+// across every federating peer.
+export const brainParityCheckSchema = z.object({
+ peerId: z.string().min(1).max(200).optional()
+});
+
// Brain bridge-sync body (POST /api/brain/bridge-sync). `refresh` forces a
// re-embed of already-mapped records — the recovery path for memory entries
// that diverged before the per-record sync:applied signal existed (issue
diff --git a/server/routes/brainSync.js b/server/routes/brainSync.js
index 5a4d17d329..42ca3a830e 100644
--- a/server/routes/brainSync.js
+++ b/server/routes/brainSync.js
@@ -11,12 +11,14 @@ import { validateRequest } from '../lib/validation.js';
import {
brainSyncQuerySchema,
brainSyncPushSchema,
- brainBridgeSyncSchema
+ brainBridgeSyncSchema,
+ brainParityCheckSchema
} from '../lib/brainValidation.js';
import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';
import * as brainSyncLog from '../services/brainSyncLog.js';
import * as brainSync from '../services/brainSync.js';
import * as brainReconcile from '../services/brainReconcile.js';
+import * as brainParity from '../services/brainParity.js';
const router = Router();
@@ -88,4 +90,37 @@ router.get('/reconcile/snapshot', asyncHandler(async (req, res) => {
res.json(snapshot);
}));
+/**
+ * GET /api/brain/reconcile/manifest
+ * Per-record parity manifest for a peer's audit run — #4519. One row per record
+ * per entity type, `{ id, updatedAt, deleted }`, tombstones included. Ids and
+ * LWW clocks ONLY: no record bodies, no names, so a peer auditing parity never
+ * pulls brain content it wouldn't otherwise receive. Far cheaper than
+ * /reconcile/snapshot, which older peers fall back to.
+ */
+router.get('/reconcile/manifest', asyncHandler(async (_req, res) => {
+ res.json(await brainParity.buildBrainManifest());
+}));
+
+/**
+ * GET /api/brain/reconcile/parity
+ * The last stored parity report per peer, keyed by peer instanceId. Reads a
+ * local file — no peer I/O — so the Instances page can render parity state on
+ * load without fanning out to every peer.
+ */
+router.get('/reconcile/parity', asyncHandler(async (_req, res) => {
+ res.json({ reports: await brainParity.getBrainParityReports() });
+}));
+
+/**
+ * POST /api/brain/reconcile/parity
+ * Run a record-level parity audit. Body `{ peerId? }` — one peer, or every
+ * federating peer when omitted. Distinct from the sync cycle by design: a
+ * routine sync must never pay for a full manifest exchange.
+ */
+router.post('/reconcile/parity', asyncHandler(async (req, res) => {
+ const { peerId } = validateRequest(brainParityCheckSchema, req.body ?? {});
+ res.json(await brainParity.runBrainParityCheck({ peerId }));
+}));
+
export default router;
diff --git a/server/routes/brainSync.test.js b/server/routes/brainSync.test.js
new file mode 100644
index 0000000000..338bd06738
--- /dev/null
+++ b/server/routes/brainSync.test.js
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Heavy service deps are mocked so route wiring + validation stays cheap and
+// never reaches the live brain store or a real peer.
+vi.mock('../services/brainMemoryBridge.js', () => ({
+ syncAllBrainData: vi.fn(),
+ getEmbeddingCoverage: vi.fn(),
+}));
+vi.mock('../services/brainSyncLog.js', () => ({
+ getChangesSince: vi.fn(),
+}));
+vi.mock('../services/brainSync.js', () => ({
+ applyRemoteChanges: vi.fn(),
+}));
+vi.mock('../services/brainReconcile.js', () => ({
+ getBrainChecksum: vi.fn(),
+ getBrainSnapshot: vi.fn(),
+}));
+vi.mock('../services/brainParity.js', () => ({
+ buildBrainManifest: vi.fn(),
+ getBrainParityReports: vi.fn(),
+ runBrainParityCheck: vi.fn(),
+}));
+
+import * as brainParity from '../services/brainParity.js';
+import brainSyncRoutes from './brainSync.js';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/brain', brainSyncRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /api/brain/reconcile/manifest', () => {
+ it('serves the parity manifest a peer audits against', async () => {
+ brainParity.buildBrainManifest.mockResolvedValue({ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }] } });
+
+ const res = await request(buildApp()).get('/api/brain/reconcile/manifest');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }] } });
+ });
+});
+
+describe('GET /api/brain/reconcile/parity', () => {
+ it('returns the stored per-peer reports without contacting a peer', async () => {
+ brainParity.getBrainParityReports.mockResolvedValue({ 'inst-peer-1': { summary: { total: 2 } } });
+
+ const res = await request(buildApp()).get('/api/brain/reconcile/parity');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ reports: { 'inst-peer-1': { summary: { total: 2 } } } });
+ expect(brainParity.runBrainParityCheck).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/brain/reconcile/parity', () => {
+ beforeEach(() => {
+ brainParity.runBrainParityCheck.mockResolvedValue({ reports: [] });
+ });
+
+ it('runs the check for one peer', async () => {
+ const res = await request(buildApp())
+ .post('/api/brain/reconcile/parity')
+ .send({ peerId: 'peer-local-1' });
+
+ expect(res.status).toBe(200);
+ expect(brainParity.runBrainParityCheck).toHaveBeenCalledWith({ peerId: 'peer-local-1' });
+ });
+
+ it('sweeps every peer when peerId is omitted', async () => {
+ const res = await request(buildApp()).post('/api/brain/reconcile/parity').send({});
+
+ expect(res.status).toBe(200);
+ expect(brainParity.runBrainParityCheck).toHaveBeenCalledWith({ peerId: undefined });
+ });
+
+ it('accepts a body-less POST', async () => {
+ const res = await request(buildApp()).post('/api/brain/reconcile/parity');
+
+ expect(res.status).toBe(200);
+ expect(brainParity.runBrainParityCheck).toHaveBeenCalledWith({ peerId: undefined });
+ });
+
+ it('rejects a non-string peerId', async () => {
+ const res = await request(buildApp())
+ .post('/api/brain/reconcile/parity')
+ .send({ peerId: 42 });
+
+ expect(res.status).toBe(400);
+ expect(brainParity.runBrainParityCheck).not.toHaveBeenCalled();
+ });
+
+ it('rejects an empty peerId rather than silently sweeping every peer', async () => {
+ const res = await request(buildApp())
+ .post('/api/brain/reconcile/parity')
+ .send({ peerId: '' });
+
+ expect(res.status).toBe(400);
+ expect(brainParity.runBrainParityCheck).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/brainParity.js b/server/services/brainParity.js
new file mode 100644
index 0000000000..ac3c898239
--- /dev/null
+++ b/server/services/brainParity.js
@@ -0,0 +1,346 @@
+/**
+ * Brain Parity Check (federation anti-entropy AUDIT)
+ *
+ * `brainReconcile.js` already *heals* divergence: every sync cycle compares a
+ * whole-brain checksum with the peer and, on a mismatch, pulls the full
+ * snapshot and LWW-merges it. That converges state, but it is silent and
+ * PULL-only — it reports nothing per record, and it can only fix records the
+ * OTHER side holds. If our peer never runs its own cycle toward us (sync
+ * disabled that direction, brain category off, an install that has been offline
+ * for a month), the two brains stay divergent and both cards still read
+ * "synced", because the Instances page shows delta-log cursor positions, not
+ * verified row-level parity (issue #4519).
+ *
+ * This module is the audit layer that makes divergence VISIBLE:
+ *
+ * - `buildBrainManifest()` — one lightweight row per record per type,
+ * `{ id, updatedAt, deleted }`, tombstones included. Ids and clocks only —
+ * deliberately NO record bodies or names, so the manifest a peer pulls
+ * carries no brain content.
+ * - `checkPeerBrainParity(peer)` — fetch the peer's manifest, diff it against
+ * ours PER TYPE with the shared `computeRecordIntegrity`, and classify each
+ * record as in-parity / local-only / peer-only / diverged. Also compares the
+ * whole-brain checksum, which catches the one case a manifest can't:
+ * matching ids AND matching `updatedAt` but different record bodies (a
+ * partial write, or a field a peer's older schema silently dropped).
+ * - `runBrainParityCheck({ peerId })` — the operation the user (or a future
+ * schedule) triggers: run the check against one peer or every sync-enabled
+ * peer, persist the results, return them.
+ * - `getBrainParityReports()` — the last stored result per peer, so the
+ * Instances page can render parity state without re-hitting every peer.
+ *
+ * Deliberately NOT wired into the sync cycle: it is a distinct on-demand
+ * operation so a routine sync never pays for a full manifest exchange.
+ *
+ * Backward compatible in both directions. A peer too old to serve
+ * `/api/brain/reconcile/manifest` (404) is reported as `peer-too-old` rather
+ * than as divergence, and older peers simply never call our manifest route.
+ */
+
+import { readJSONFile, ensureDir, atomicWrite, dataPath, PATHS } from '../lib/fileUtils.js';
+import { computeRecordIntegrity, INTEGRITY_STATUS } from '../lib/syncIntegrity.js';
+import { peerBaseUrl } from '../lib/peerUrl.js';
+import { peerFetch } from '../lib/peerHttpClient.js';
+import * as brainStorage from './brainStorage.js';
+import * as brainReconcile from './brainReconcile.js';
+import { getPeers } from './instances.js';
+
+const { BRAIN_ENTITY_TYPES } = brainStorage;
+
+const REPORTS_FILE = dataPath('brain_parity_reports.json');
+
+// How many out-of-parity record ids to PERSIST per type. The live response
+// carries the full list; the stored copy is what the Instances page renders on
+// load, and a badly diverged install could otherwise write tens of thousands of
+// ids into a file re-read on every page load. `truncated` tells the UI the
+// stored sample is partial so it can prompt for a fresh run.
+const STORED_RECORDS_PER_TYPE = 25;
+
+// Peer fetches are bounded so an unresponsive peer can't wedge an audit run.
+// Generous relative to the sync cycle's 15s budget: the snapshot fallback below
+// pulls a peer's ENTIRE brain, which is legitimately slow on a large install.
+const PEER_FETCH_TIMEOUT_MS = 30000;
+
+const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
+
+/**
+ * Build this instance's brain manifest: `{ types: { [type]: [row] } }` where a
+ * row is `{ id, updatedAt, deleted }`. Tombstones are included (deleted:true) so
+ * a delete one side applied and the other missed surfaces as a real difference
+ * instead of looking like a local-only record.
+ */
+export async function buildBrainManifest() {
+ const types = {};
+ for (const type of [...BRAIN_ENTITY_TYPES].sort()) {
+ const records = await brainStorage.getRawRecords(type);
+ types[type] = Object.keys(records).sort().map((id) => {
+ const record = records[id];
+ return {
+ id,
+ updatedAt: record?.updatedAt ?? null,
+ deleted: record?._deleted === true,
+ };
+ });
+ }
+ return { types };
+}
+
+/**
+ * Coerce an untrusted peer manifest into `{ [type]: [row] }`.
+ *
+ * The peer response is untrusted the same way `sharing/integrity` treats its
+ * manifest: `computeRecordIntegrity` reads `r.id` and keys a Map on it, so a
+ * malformed row (null, a scalar, an id-less object) would throw and 500 the
+ * caller. Rows are rebuilt field-by-field rather than passed through, because
+ * `computeRecordIntegrity` also inspects `assetHashes`/`metadataMissing` — a
+ * peer that sent those (a newer version, or a hostile one) could otherwise push
+ * a brain record into an asset status that has no meaning here and no counter.
+ * Unknown types are dropped rather than reported — a newer peer with an entity
+ * store we don't have yet is not divergence, it's a version gap.
+ */
+function normalizeRemoteManifest(body) {
+ const out = {};
+ const types = body?.types;
+ if (!types || typeof types !== 'object') return out;
+ for (const type of BRAIN_ENTITY_TYPES) {
+ const rows = types[type];
+ if (!Array.isArray(rows)) continue;
+ out[type] = rows
+ .filter((r) => r && typeof r === 'object' && isNonEmptyStr(r.id))
+ .map((r) => ({ id: r.id, updatedAt: r.updatedAt ?? null, deleted: r.deleted === true }));
+ }
+ return out;
+}
+
+/**
+ * Derive a manifest from a full `/reconcile/snapshot` payload.
+ *
+ * The fallback for a peer that predates the manifest route: it already serves
+ * the whole raw record map for anti-entropy, and the manifest is a projection of
+ * exactly that. Heavier over the wire, but it means parity is auditable against
+ * every peer that supports reconcile at all, not just upgraded ones.
+ */
+function manifestFromSnapshot(snapshot) {
+ const out = {};
+ const records = snapshot?.records;
+ if (!records || typeof records !== 'object') return out;
+ for (const type of BRAIN_ENTITY_TYPES) {
+ const byId = records[type];
+ if (!byId || typeof byId !== 'object') continue;
+ out[type] = Object.entries(byId)
+ .filter(([, rec]) => rec && typeof rec === 'object')
+ .map(([id, rec]) => ({ id, updatedAt: rec.updatedAt ?? null, deleted: rec._deleted === true }));
+ }
+ return out;
+}
+
+async function fetchPeerJson(peer, path) {
+ const res = await peerFetch(
+ `${peerBaseUrl(peer)}${path}`,
+ { signal: AbortSignal.timeout(PEER_FETCH_TIMEOUT_MS) },
+ peer,
+ ).catch(() => null);
+ // Distinguish unreachable (peerFetch threw → null) from a 404 (peer online but
+ // running older code). Collapsing them would tell the user "upgrade the peer"
+ // when the peer is simply down, and vice versa.
+ if (!res) return { reason: 'peer-unreachable', body: null };
+ if (res.status === 404) return { reason: 'peer-too-old', body: null };
+ if (!res.ok) return { reason: 'fetch-failed', body: null };
+ const body = await res.json().catch(() => null);
+ if (!body) return { reason: 'fetch-failed', body: null };
+ return { reason: null, body };
+}
+
+/**
+ * Pull the peer's manifest, falling back to projecting one out of the peer's
+ * full reconcile snapshot when it is too old to expose the manifest route.
+ */
+async function fetchRemoteManifest(peer) {
+ const direct = await fetchPeerJson(peer, '/api/brain/reconcile/manifest');
+ if (!direct.reason) return { reason: null, byType: normalizeRemoteManifest(direct.body) };
+ if (direct.reason !== 'peer-too-old') return { reason: direct.reason, byType: null };
+
+ const snapshot = await fetchPeerJson(peer, '/api/brain/reconcile/snapshot');
+ if (snapshot.reason) {
+ // The snapshot route missing too means the peer has no reconcile support at
+ // all — still "too old", just further back.
+ return { reason: snapshot.reason === 'peer-too-old' ? 'peer-too-old' : snapshot.reason, byType: null };
+ }
+ return { reason: null, byType: manifestFromSnapshot(snapshot.body) };
+}
+
+const emptyCounts = () => ({
+ total: 0,
+ [INTEGRITY_STATUS.IN_PARITY]: 0,
+ [INTEGRITY_STATUS.LOCAL_ONLY]: 0,
+ [INTEGRITY_STATUS.PEER_ONLY]: 0,
+ [INTEGRITY_STATUS.DIVERGED]: 0,
+});
+
+const addCounts = (into, from) => {
+ for (const key of Object.keys(into)) into[key] += from[key] ?? 0;
+ return into;
+};
+
+/**
+ * Diff a local manifest against a remote one, per entity type.
+ *
+ * Per-TYPE rather than one flat pass: brain ids are only unique within a store,
+ * so a single global diff could pair an `ideas` record with an unrelated
+ * `people` record that happened to share an id. Diffing per type also gives the
+ * UI its breakdown for free.
+ *
+ * Returns `{ summary, byType }`, where `byType` lists only the records that are
+ * NOT in parity — the actionable set. A type in full parity is still reported
+ * (with its counts) so "checked and clean" is distinguishable from "not checked".
+ */
+export function diffBrainManifests(localByType, remoteByType) {
+ const summary = emptyCounts();
+ const byType = [];
+
+ for (const type of [...BRAIN_ENTITY_TYPES].sort()) {
+ const local = localByType?.[type] ?? [];
+ const remote = remoteByType?.[type] ?? [];
+ if (local.length === 0 && remote.length === 0) continue;
+
+ const rows = computeRecordIntegrity(local, remote);
+ const counts = emptyCounts();
+ const records = [];
+ for (const row of rows) {
+ counts.total += 1;
+ if (counts[row.status] !== undefined) counts[row.status] += 1;
+ if (row.status !== INTEGRITY_STATUS.IN_PARITY) records.push({ id: row.id, status: row.status });
+ }
+ addCounts(summary, counts);
+ byType.push({ type, counts, records });
+ }
+
+ return { summary, byType };
+}
+
+/**
+ * Compare the whole-brain checksums.
+ *
+ * This is the signal the manifest cannot produce: two peers can hold the same
+ * ids with the same `updatedAt` and still differ in a record BODY (a partial
+ * write, a field an older peer's schema dropped on apply). `match: false` with
+ * zero divergent records in the manifest diff means exactly that — worth
+ * surfacing rather than reporting a clean bill of health.
+ *
+ * A peer too old to serve `/reconcile/checksum` yields `peer: null,
+ * match: null` — unknown, never a false "diverged".
+ */
+async function compareChecksums(peer) {
+ const [local, remote] = await Promise.all([
+ brainReconcile.getBrainChecksum().catch(() => null),
+ fetchPeerJson(peer, '/api/brain/reconcile/checksum'),
+ ]);
+ const peerChecksum = isNonEmptyStr(remote.body?.checksum) ? remote.body.checksum : null;
+ return {
+ local: local ?? null,
+ peer: peerChecksum,
+ match: local && peerChecksum ? local === peerChecksum : null,
+ };
+}
+
+/**
+ * Run a full record-level parity check against ONE peer.
+ *
+ * @param {object} peer - Peer registry record.
+ * @returns {Promise<object>} report — see module docblock for the shape.
+ */
+export async function checkPeerBrainParity(peer) {
+ const base = {
+ peerId: peer?.id ?? null,
+ peerInstanceId: peer?.instanceId ?? null,
+ peerName: peer?.name ?? null,
+ checkedAt: new Date().toISOString(),
+ };
+
+ const remote = await fetchRemoteManifest(peer);
+ if (remote.reason) {
+ return { ...base, available: false, reason: remote.reason, checksums: null, summary: emptyCounts(), byType: [] };
+ }
+
+ // Only reached once the peer answered — an unreachable peer never costs a
+ // read of every brain store. The manifest build and the checksum comparison
+ // each walk the whole brain, so run them together rather than back to back.
+ const [local, checksums] = await Promise.all([buildBrainManifest(), compareChecksums(peer)]);
+ const { summary, byType } = diffBrainManifests(local.types, remote.byType);
+
+ return { ...base, available: true, checksums, summary, byType };
+}
+
+async function loadReports() {
+ const stored = await readJSONFile(REPORTS_FILE, {});
+ return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {};
+}
+
+async function saveReports(reports) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(REPORTS_FILE, reports);
+}
+
+/** Cap the per-type record lists before persisting. See STORED_RECORDS_PER_TYPE. */
+function forStorage(report) {
+ return {
+ ...report,
+ byType: report.byType.map((t) => ({
+ ...t,
+ records: t.records.slice(0, STORED_RECORDS_PER_TYPE),
+ truncated: t.records.length > STORED_RECORDS_PER_TYPE,
+ })),
+ };
+}
+
+/**
+ * The last stored parity report per peer, keyed by the peer's `instanceId`
+ * (the stable cross-machine identity the sync cursors are keyed by, so a peer
+ * re-added to the registry keeps its history).
+ */
+export async function getBrainParityReports() {
+ return loadReports();
+}
+
+/**
+ * Run the parity check and persist the results.
+ *
+ * @param {{ peerId?: string }} [opts] - Local peer-registry id. Omitted runs
+ * every federating peer.
+ * @returns {Promise<{ reports: object[] }>}
+ */
+export async function runBrainParityCheck({ peerId } = {}) {
+ const peers = await getPeers().catch(() => []);
+ // The sweep deliberately does NOT filter on the peer's brain sync CATEGORY.
+ // A peer whose brain category was turned off (or never turned on) is exactly
+ // where silent divergence accumulates — filtering it out would hide the case
+ // the audit exists to find. An un-probed peer (no instanceId) is skipped
+ // because there is no stable key to file its report under.
+ const targets = isNonEmptyStr(peerId)
+ ? peers.filter((p) => p.id === peerId)
+ : peers.filter((p) => p.syncEnabled !== false && isNonEmptyStr(p.instanceId));
+
+ if (isNonEmptyStr(peerId) && targets.length === 0) {
+ return { reports: [{ peerId, available: false, reason: 'peer-not-found', checkedAt: new Date().toISOString() }] };
+ }
+
+ const stored = await loadReports();
+ const reports = [];
+
+ // Sequential, not Promise.all: each peer costs a manifest fetch plus a full
+ // read of every local brain store, and a user with several peers shouldn't
+ // fan that out at once.
+ for (const peer of targets) {
+ const report = await checkPeerBrainParity(peer);
+ reports.push(report);
+ const key = report.peerInstanceId || report.peerId;
+ if (key) stored[key] = forStorage(report);
+ const detail = report.available
+ ? `${report.summary[INTEGRITY_STATUS.LOCAL_ONLY]} local-only, ${report.summary[INTEGRITY_STATUS.PEER_ONLY]} peer-only, ${report.summary[INTEGRITY_STATUS.DIVERGED]} diverged`
+ : report.reason;
+ console.log(`🧠🔍 Brain parity vs ${peer.name || peer.id}: ${detail}`);
+ }
+
+ if (reports.length > 0) await saveReports(stored);
+ return { reports };
+}
diff --git a/server/services/brainParity.test.js b/server/services/brainParity.test.js
new file mode 100644
index 0000000000..b8c44f5a54
--- /dev/null
+++ b/server/services/brainParity.test.js
@@ -0,0 +1,384 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// brainStorage / brainReconcile / instances are the data + transport layers;
+// mock them so the parity diff is exercised in isolation, matching the mock
+// style the other brain sync suites use.
+vi.mock('./brainStorage.js', () => ({
+ BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox', 'songs'],
+ getRawRecords: vi.fn(),
+}));
+vi.mock('./brainReconcile.js', () => ({
+ getBrainChecksum: vi.fn().mockResolvedValue('local-checksum'),
+}));
+vi.mock('./instances.js', () => ({
+ getPeers: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('../lib/peerUrl.js', () => ({
+ peerBaseUrl: (peer) => `https://${peer.host}:5555`,
+}));
+vi.mock('../lib/peerHttpClient.js', () => ({
+ peerFetch: vi.fn(),
+}));
+vi.mock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn().mockResolvedValue({}),
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn().mockResolvedValue(undefined),
+ dataPath: (name) => `/tmp/portos-test-data/${name}`,
+ PATHS: { data: '/tmp/portos-test-data' },
+}));
+
+import * as brainStorage from './brainStorage.js';
+import * as brainReconcile from './brainReconcile.js';
+import { getPeers } from './instances.js';
+import { peerFetch } from '../lib/peerHttpClient.js';
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import {
+ buildBrainManifest,
+ diffBrainManifests,
+ checkPeerBrainParity,
+ runBrainParityCheck,
+ getBrainParityReports,
+} from './brainParity.js';
+
+const PEER = { id: 'peer-local-1', instanceId: 'inst-peer-1', name: 'Example Peer', host: 'peer.example.com', syncEnabled: true };
+
+// Default: every store empty unless a test overrides a specific type.
+function stores(overrides = {}) {
+ brainStorage.getRawRecords.mockImplementation(async (type) => overrides[type] ?? {});
+}
+
+// Build a fetch response double. `peerFetch` resolves it; a null resolution
+// models an unreachable peer.
+const jsonResponse = (body, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => body });
+
+/**
+ * Route peerFetch by URL suffix so a test only declares the endpoints it cares
+ * about. Anything undeclared 404s (i.e. "peer too old for that route").
+ */
+function peerRoutes(routes) {
+ peerFetch.mockImplementation(async (url) => {
+ for (const [suffix, response] of Object.entries(routes)) {
+ if (url.endsWith(suffix)) return typeof response === 'function' ? response() : response;
+ }
+ return jsonResponse(null, 404);
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ brainReconcile.getBrainChecksum.mockResolvedValue('local-checksum');
+ readJSONFile.mockResolvedValue({});
+ stores();
+});
+
+describe('buildBrainManifest', () => {
+ it('emits id + updatedAt + deleted per record, tombstones included', async () => {
+ stores({
+ people: {
+ p2: { id: 'p2', updatedAt: '2026-01-02T00:00:00.000Z', name: 'Bob' },
+ p1: { id: 'p1', updatedAt: '2026-01-01T00:00:00.000Z', name: 'Alice' },
+ p3: { _deleted: true, updatedAt: '2026-01-03T00:00:00.000Z', deletedAt: '2026-01-03T00:00:00.000Z' },
+ },
+ });
+
+ const { types } = await buildBrainManifest();
+
+ // Sorted by id so two installs serialize identically.
+ expect(types.people).toEqual([
+ { id: 'p1', updatedAt: '2026-01-01T00:00:00.000Z', deleted: false },
+ { id: 'p2', updatedAt: '2026-01-02T00:00:00.000Z', deleted: false },
+ { id: 'p3', updatedAt: '2026-01-03T00:00:00.000Z', deleted: true },
+ ]);
+ });
+
+ it('carries no record content — ids and clocks only', async () => {
+ stores({ ideas: { i1: { id: 'i1', updatedAt: '2026-01-01T00:00:00.000Z', title: 'Secret idea', body: 'private' } } });
+
+ const { types } = await buildBrainManifest();
+
+ expect(Object.keys(types.ideas[0]).sort()).toEqual(['deleted', 'id', 'updatedAt']);
+ expect(JSON.stringify(types)).not.toContain('Secret idea');
+ });
+
+ it('covers every brain entity type', async () => {
+ const { types } = await buildBrainManifest();
+ expect(Object.keys(types).sort()).toEqual([...brainStorage.BRAIN_ENTITY_TYPES].sort());
+ });
+});
+
+describe('diffBrainManifests', () => {
+ const row = (id, updatedAt, deleted = false) => ({ id, updatedAt, deleted });
+
+ it('reports zero divergence for identical manifests', () => {
+ const manifest = { people: [row('p1', 'T1'), row('p2', 'T2')] };
+ const { summary, byType } = diffBrainManifests(manifest, manifest);
+
+ expect(summary.total).toBe(2);
+ expect(summary['in-parity']).toBe(2);
+ expect(summary['local-only']).toBe(0);
+ expect(summary['peer-only']).toBe(0);
+ expect(summary.diverged).toBe(0);
+ // The type IS reported (checked-and-clean), but with no actionable records.
+ expect(byType).toEqual([{ type: 'people', counts: summary, records: [] }]);
+ });
+
+ it('classifies local-only, peer-only, and diverged records', () => {
+ const { summary, byType } = diffBrainManifests(
+ { people: [row('shared', 'T1'), row('ours', 'T1'), row('drift', 'T1')] },
+ { people: [row('shared', 'T1'), row('theirs', 'T1'), row('drift', 'T9')] },
+ );
+
+ expect(summary).toMatchObject({ total: 4, 'in-parity': 1, 'local-only': 1, 'peer-only': 1, diverged: 1 });
+ expect(byType[0].records).toEqual(
+ expect.arrayContaining([
+ { id: 'ours', status: 'local-only' },
+ { id: 'theirs', status: 'peer-only' },
+ { id: 'drift', status: 'diverged' },
+ ]),
+ );
+ // In-parity records are omitted from the actionable list.
+ expect(byType[0].records).toHaveLength(3);
+ });
+
+ it('does not pair same-id records across different types', () => {
+ // `dup` exists as a person locally and as an idea remotely. A single flat
+ // diff would call that in-parity; per-type diffing reports two real gaps.
+ const { summary } = diffBrainManifests(
+ { people: [row('dup', 'T1')] },
+ { ideas: [row('dup', 'T1')] },
+ );
+
+ expect(summary).toMatchObject({ 'local-only': 1, 'peer-only': 1, 'in-parity': 0 });
+ });
+
+ it('treats a delete both sides applied as agreement, not divergence', () => {
+ const { summary, byType } = diffBrainManifests(
+ { people: [row('gone', 'T1', true)] },
+ { people: [row('gone', 'T1', true)] },
+ );
+
+ expect(summary.total).toBe(0);
+ expect(byType).toEqual([{ type: 'people', counts: expect.objectContaining({ total: 0 }), records: [] }]);
+ });
+
+ it('surfaces a delete only one side applied', () => {
+ const { summary } = diffBrainManifests(
+ { people: [row('gone', 'T2', true)] },
+ { people: [row('gone', 'T1', false)] },
+ );
+
+ expect(summary).toMatchObject({ 'peer-only': 1, 'local-only': 0 });
+ });
+
+ it('skips types empty on both sides', () => {
+ const { byType } = diffBrainManifests({ people: [] }, { people: [] });
+ expect(byType).toEqual([]);
+ });
+});
+
+describe('checkPeerBrainParity', () => {
+ it('reports the divergence when a record exists only on the peer', async () => {
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({
+ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }, { id: 'p2', updatedAt: 'T2', deleted: false }] },
+ }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'peer-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.available).toBe(true);
+ expect(report.summary).toMatchObject({ total: 2, 'in-parity': 1, 'peer-only': 1 });
+ expect(report.byType.find((t) => t.type === 'people').records).toEqual([{ id: 'p2', status: 'peer-only' }]);
+ expect(report.checksums).toEqual({ local: 'local-checksum', peer: 'peer-checksum', match: false });
+ expect(report.peerInstanceId).toBe('inst-peer-1');
+ });
+
+ it('reports a clean bill of health for two fully-synced peers', async () => {
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }] } }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'local-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.available).toBe(true);
+ expect(report.summary).toMatchObject({ total: 1, 'in-parity': 1, 'local-only': 0, 'peer-only': 0, diverged: 0 });
+ expect(report.checksums.match).toBe(true);
+ });
+
+ it('flags a checksum mismatch even when every id and clock matches', async () => {
+ // The body-level divergence a manifest cannot see: same ids, same
+ // updatedAt, different record contents (a partial write on one side).
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }] } }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'different-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.summary.diverged).toBe(0);
+ expect(report.checksums.match).toBe(false);
+ });
+
+ it('falls back to the reconcile snapshot when the peer has no manifest route', async () => {
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/snapshot': jsonResponse({
+ records: { people: { p1: { updatedAt: 'T1' }, p2: { updatedAt: 'T2' } } },
+ }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'peer-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.available).toBe(true);
+ expect(report.summary).toMatchObject({ 'peer-only': 1, 'in-parity': 1 });
+ });
+
+ it('distinguishes an unreachable peer from one running older code', async () => {
+ peerFetch.mockResolvedValue(null);
+ expect(await checkPeerBrainParity(PEER)).toMatchObject({ available: false, reason: 'peer-unreachable' });
+
+ peerRoutes({}); // every route 404s → no reconcile support at all
+ expect(await checkPeerBrainParity(PEER)).toMatchObject({ available: false, reason: 'peer-too-old' });
+ });
+
+ it('ignores malformed peer manifest rows instead of throwing', async () => {
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({
+ types: { people: [null, 42, { updatedAt: 'T1' }, { id: 'p1', updatedAt: 'T1', deleted: false }], bogusType: [{ id: 'x' }] },
+ }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'local-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.available).toBe(true);
+ expect(report.summary).toMatchObject({ total: 1, 'in-parity': 1 });
+ });
+
+ it('ignores asset fields a peer smuggles into a manifest row', async () => {
+ // computeRecordIntegrity also grades assetHashes/metadataMissing. Brain has
+ // neither, so a peer sending them could otherwise push a record into an
+ // asset status this audit has no counter for — silently listed, never
+ // tallied. The row must be rebuilt from id + clock + tombstone only.
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({
+ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false, assetHashes: ['sneaky'], metadataMissing: true }] },
+ }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'local-checksum' }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.summary).toMatchObject({ total: 1, 'in-parity': 1 });
+ expect(report.byType.find((t) => t.type === 'people').records).toEqual([]);
+ });
+
+ it('leaves the checksum comparison unknown when the peer is too old to serve one', async () => {
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({ types: { people: [{ id: 'p1', updatedAt: 'T1', deleted: false }] } }),
+ });
+
+ const report = await checkPeerBrainParity(PEER);
+
+ expect(report.checksums).toEqual({ local: 'local-checksum', peer: null, match: null });
+ });
+
+ it('does not read local brain stores when the peer is unreachable', async () => {
+ peerFetch.mockResolvedValue(null);
+ await checkPeerBrainParity(PEER);
+ expect(brainStorage.getRawRecords).not.toHaveBeenCalled();
+ });
+});
+
+describe('runBrainParityCheck', () => {
+ it('returns peer-not-found for an unknown peer id without contacting anyone', async () => {
+ getPeers.mockResolvedValue([PEER]);
+
+ const { reports } = await runBrainParityCheck({ peerId: 'nope' });
+
+ expect(reports).toHaveLength(1);
+ expect(reports[0]).toMatchObject({ peerId: 'nope', available: false, reason: 'peer-not-found' });
+ expect(peerFetch).not.toHaveBeenCalled();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('persists the report keyed by peer instanceId', async () => {
+ getPeers.mockResolvedValue([PEER]);
+ stores({ people: { p1: { id: 'p1', updatedAt: 'T1' } } });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({ types: { people: [{ id: 'p2', updatedAt: 'T2', deleted: false }] } }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'peer-checksum' }),
+ });
+
+ await runBrainParityCheck({ peerId: 'peer-local-1' });
+
+ const [, written] = atomicWrite.mock.calls[0];
+ expect(Object.keys(written)).toEqual(['inst-peer-1']);
+ expect(written['inst-peer-1'].summary).toMatchObject({ 'local-only': 1, 'peer-only': 1 });
+ });
+
+ it('caps the stored record list per type and marks it truncated', async () => {
+ getPeers.mockResolvedValue([PEER]);
+ const many = Object.fromEntries(
+ Array.from({ length: 40 }, (_, i) => [`p${i}`, { id: `p${i}`, updatedAt: 'T1' }]),
+ );
+ stores({ people: many });
+ peerRoutes({
+ '/api/brain/reconcile/manifest': jsonResponse({ types: { people: [] } }),
+ '/api/brain/reconcile/checksum': jsonResponse({ checksum: 'peer-checksum' }),
+ });
+
+ const { reports } = await runBrainParityCheck({ peerId: 'peer-local-1' });
+
+ // Live response is complete; only the persisted copy is capped.
+ expect(reports[0].byType.find((t) => t.type === 'people').records).toHaveLength(40);
+ const stored = atomicWrite.mock.calls[0][1]['inst-peer-1'].byType.find((t) => t.type === 'people');
+ expect(stored.records).toHaveLength(25);
+ expect(stored.truncated).toBe(true);
+ });
+
+ it('sweeps every federating peer when no peerId is given, skipping un-probed ones', async () => {
+ getPeers.mockResolvedValue([
+ PEER,
+ { id: 'peer-local-2', instanceId: 'inst-peer-2', name: 'Second Peer', host: 'peer2.example.com', syncEnabled: true },
+ { id: 'peer-local-3', instanceId: null, name: 'Never Probed', host: 'peer3.example.com', syncEnabled: true },
+ { id: 'peer-local-4', instanceId: 'inst-peer-4', name: 'Sync Off', host: 'peer4.example.com', syncEnabled: false },
+ ]);
+ peerFetch.mockResolvedValue(null);
+
+ const { reports } = await runBrainParityCheck();
+
+ expect(reports.map((r) => r.peerId)).toEqual(['peer-local-1', 'peer-local-2']);
+ });
+
+ it('preserves reports for peers this run did not check', async () => {
+ readJSONFile.mockResolvedValue({ 'inst-other': { peerId: 'peer-other', summary: { total: 3 } } });
+ getPeers.mockResolvedValue([PEER]);
+ peerFetch.mockResolvedValue(null);
+
+ await runBrainParityCheck({ peerId: 'peer-local-1' });
+
+ expect(Object.keys(atomicWrite.mock.calls[0][1]).sort()).toEqual(['inst-other', 'inst-peer-1']);
+ });
+});
+
+describe('getBrainParityReports', () => {
+ it('returns an empty object when the store holds a non-object', async () => {
+ readJSONFile.mockResolvedValue([]);
+ expect(await getBrainParityReports()).toEqual({});
+ });
+
+ it('returns the stored reports', async () => {
+ readJSONFile.mockResolvedValue({ 'inst-peer-1': { summary: { total: 1 } } });
+ expect(await getBrainParityReports()).toEqual({ 'inst-peer-1': { summary: { total: 1 } } });
+ });
+});