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: let the brain-parity audit run on a schedule instead of only when someone presses Check (#4519)

[._.]/ Adam Eivyf9ad6a665526
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 930878f07a..2cd9d1484f 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -3,7 +3,7 @@ import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLef
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { timeAgo, formatDateTime, formatDateNumeric } from '../../../utils/formatters';
-import { CRON_PRESETS, DEFAULT_CRON, describeCron } from '../../../utils/cronHelpers';
+import { CRON_PRESETS, DEFAULT_CRON, describeCron, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../../utils/cronHelpers';
import WeekdayTimePicker from '../../WeekdayTimePicker';
import { effectiveModelFor, effortAwareModelOptions } from '../../../utils/providers';
import ProviderModelSelector from '../../ProviderModelSelector';
@@ -12,17 +12,6 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';
import FormField from '../../ui/FormField';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
-const INTERVAL_OPTIONS = [
- { value: 'hourly', label: 'Every Hour' },
- { value: 'every-2-hours', label: 'Every 2 Hours' },
- { value: 'every-4-hours', label: 'Every 4 Hours' },
- { value: 'every-8-hours', label: 'Every 8 Hours' },
- { value: 'daily', label: 'Daily' },
- { value: 'weekly', label: 'Weekly' },
- { value: 'biweekly', label: 'Every 2 Weeks' },
- { value: 'monthly', label: 'Monthly' }
-];
-
const SCHEDULE_MODE_OPTIONS = [
{ value: 'interval', label: 'Interval' },
{ value: 'cron', label: 'Cron' }
diff --git a/client/src/components/instances/BrainParitySchedule.jsx b/client/src/components/instances/BrainParitySchedule.jsx
new file mode 100644
index 0000000000..f90ceae980
--- /dev/null
+++ b/client/src/components/instances/BrainParitySchedule.jsx
@@ -0,0 +1,118 @@
+/**
+ * Scheduled brain-parity sweep control (issue #4519).
+ *
+ * The per-peer `BrainParityPanel` only audits when someone presses Check, and
+ * the divergence it looks for is by definition silent — so an install that
+ * never presses it never learns. This is the opt-in cadence: one default-
+ * disabled autonomous job (`job-brain-parity-sweep`) that runs the audit
+ * against every federating peer.
+ *
+ * Deliberately install-level rather than per peer/category: the audit covers
+ * exactly one category (brain), and the sweep intentionally includes peers whose
+ * brain sync category is OFF — that is where divergence accumulates, so a
+ * per-peer opt-out would exclude the peers most worth checking. Per-peer
+ * granularity stays on demand via each card's Check button.
+ *
+ * Lives here on Instances rather than only in CoS → Jobs because this is where
+ * a user is looking when they wonder whether their brains actually agree.
+ */
+
+import { useEffect, useState } from 'react';
+import { CalendarClock, ToggleLeft, ToggleRight } from 'lucide-react';
+import toast from '../ui/Toast';
+import { getCosJob, toggleCosJob, updateCosJob } from '../../services/api';
+import { JOB_INTERVAL_OPTIONS } from '../../utils/cronHelpers';
+import { timeAgo } from '../../utils/formatters';
+
+export const PARITY_SWEEP_JOB_ID = 'job-brain-parity-sweep';
+
+export default function BrainParitySchedule() {
+ // `undefined` = not loaded yet, `null` = this install has no such job (a
+ // server too old to ship it). Distinct states so a pending fetch never
+ // renders as "unsupported" — and an unsupported install renders nothing
+ // rather than a control whose writes would 404.
+ const [job, setJob] = useState(undefined);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+ // `silent` — an install without the job is an expected outcome here, not an
+ // error worth toasting on every Instances page load.
+ getCosJob(PARITY_SWEEP_JOB_ID, { silent: true })
+ .then((data) => { if (active) setJob(data ?? null); })
+ .catch(() => { if (active) setJob(null); });
+ return () => { active = false; };
+ }, []);
+
+ if (job === undefined || job === null) return null;
+
+ const handleToggle = async () => {
+ setSaving(true);
+ const result = await toggleCosJob(PARITY_SWEEP_JOB_ID, { silent: true }).catch((err) => {
+ toast.error(err.message);
+ return null;
+ });
+ if (result?.job) {
+ setJob(result.job);
+ toast.success(result.job.enabled ? 'Parity sweep scheduled' : 'Parity sweep disabled');
+ }
+ setSaving(false);
+ };
+
+ const handleInterval = async (interval) => {
+ setSaving(true);
+ // Send `interval` alone — the server recomputes `intervalMs` from it, so
+ // posting a client-side millisecond value would just risk disagreeing with
+ // the canonical mapping.
+ const result = await updateCosJob(PARITY_SWEEP_JOB_ID, { interval }, { silent: true }).catch((err) => {
+ toast.error(err.message);
+ return null;
+ });
+ if (result?.job) setJob(result.job);
+ setSaving(false);
+ };
+
+ return (
+ <div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-port-border bg-port-card/40 px-3 py-2">
+ <CalendarClock size={14} className="text-gray-500 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-gray-300">Scheduled parity sweep</p>
+ <p className="text-[10px] text-gray-500">
+ {job.enabled
+ ? 'Audits every federating peer on a schedule. Results land on each peer card below.'
+ : 'Off. Parity is only checked when you press Check on a peer card.'}
+ {job.lastRun && ` Last run ${timeAgo(job.lastRun)}.`}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <label htmlFor="parity-sweep-interval" className="sr-only">Parity sweep interval</label>
+ <select
+ id="parity-sweep-interval"
+ value={job.interval || 'weekly'}
+ onChange={(e) => handleInterval(e.target.value)}
+ disabled={saving || !job.enabled}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-300 disabled:opacity-50"
+ >
+ {JOB_INTERVAL_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+
+ <button
+ type="button"
+ onClick={handleToggle}
+ disabled={saving}
+ aria-pressed={!!job.enabled}
+ className="inline-flex items-center gap-1 text-[11px] text-gray-300 hover:text-white transition-colors disabled:opacity-50"
+ title={job.enabled ? 'Disable the scheduled parity sweep' : 'Enable the scheduled parity sweep'}
+ >
+ {job.enabled
+ ? <ToggleRight size={18} className="text-port-success" />
+ : <ToggleLeft size={18} className="text-gray-600" />}
+ {job.enabled ? 'On' : 'Off'}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/instances/BrainParitySchedule.test.jsx b/client/src/components/instances/BrainParitySchedule.test.jsx
new file mode 100644
index 0000000000..4422d53f02
--- /dev/null
+++ b/client/src/components/instances/BrainParitySchedule.test.jsx
@@ -0,0 +1,81 @@
+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', () => ({
+ getCosJob: vi.fn(),
+ toggleCosJob: vi.fn(),
+ updateCosJob: vi.fn(),
+}));
+
+vi.mock('../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() },
+}));
+
+import { getCosJob, toggleCosJob, updateCosJob } from '../../services/api';
+import BrainParitySchedule, { PARITY_SWEEP_JOB_ID } from './BrainParitySchedule';
+
+const job = (overrides = {}) => ({
+ id: PARITY_SWEEP_JOB_ID,
+ name: 'Brain Parity Sweep',
+ enabled: false,
+ interval: 'weekly',
+ lastRun: null,
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('BrainParitySchedule', () => {
+ it('reads "Off" for the shipped default, so the sweep is visibly opt-in', async () => {
+ getCosJob.mockResolvedValue(job());
+ render(<BrainParitySchedule />);
+ expect(await screen.findByText('Off')).toBeInTheDocument();
+ expect(screen.getByText(/only checked when you press Check/i)).toBeInTheDocument();
+ });
+
+ it('reads the job silently — an install without the job is not an error', async () => {
+ getCosJob.mockResolvedValue(job());
+ render(<BrainParitySchedule />);
+ await screen.findByText('Off');
+ expect(getCosJob).toHaveBeenCalledWith(PARITY_SWEEP_JOB_ID, { silent: true });
+ });
+
+ it('renders nothing on a server too old to ship the job', async () => {
+ getCosJob.mockRejectedValue(new Error('Job not found'));
+ const { container } = render(<BrainParitySchedule />);
+ await waitFor(() => expect(getCosJob).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('enables the sweep through the job toggle and reflects the server result', async () => {
+ getCosJob.mockResolvedValue(job());
+ toggleCosJob.mockResolvedValue({ success: true, job: job({ enabled: true }) });
+ render(<BrainParitySchedule />);
+
+ await userEvent.click(await screen.findByText('Off'));
+
+ expect(toggleCosJob).toHaveBeenCalledWith(PARITY_SWEEP_JOB_ID, { silent: true });
+ expect(await screen.findByText('On')).toBeInTheDocument();
+ });
+
+ it('submits the interval NAME only, letting the server recompute intervalMs', async () => {
+ getCosJob.mockResolvedValue(job({ enabled: true }));
+ updateCosJob.mockResolvedValue({ success: true, job: job({ enabled: true, interval: 'daily' }) });
+ render(<BrainParitySchedule />);
+
+ const select = await screen.findByLabelText('Parity sweep interval');
+ await userEvent.selectOptions(select, 'daily');
+
+ expect(updateCosJob).toHaveBeenCalledWith(PARITY_SWEEP_JOB_ID, { interval: 'daily' }, { silent: true });
+ await waitFor(() => expect(select).toHaveValue('daily'));
+ });
+
+ it('locks the interval picker while the sweep is off', async () => {
+ getCosJob.mockResolvedValue(job());
+ render(<BrainParitySchedule />);
+ expect(await screen.findByLabelText('Parity sweep interval')).toBeDisabled();
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 99140d1793..6aadfb7bff 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -25,6 +25,7 @@ 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 BrainParitySchedule from '../components/instances/BrainParitySchedule';
import { timeAgo, timeUntil } from '../utils/formatters';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
@@ -1458,6 +1459,7 @@ export default function Instances() {
<h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
Peers ({peers.length})
</h2>
+ <BrainParitySchedule />
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
{peers.map(peer => (
// Reports key on instanceId (the stable federation identity), but
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 8e4c92e4e1..bb7feb28fa 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -276,7 +276,7 @@ export const getCosJobs = (options = {}) => request('/cos/jobs', options);
export const getCosJobsDue = () => request('/cos/jobs/due');
export const getCosJobIntervals = () => request('/cos/jobs/intervals');
export const getCosJobAllowedCommands = () => request('/cos/jobs/allowed-commands');
-export const getCosJob = (id) => request(`/cos/jobs/${id}`);
+export const getCosJob = (id, options = {}) => request(`/cos/jobs/${id}`, options);
export const createCosJob = (data, options = {}) => request('/cos/jobs', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 1d17c4ace7..f593dbb3cd 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -23,7 +23,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
-| `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. |
+| `cronHelpers` | Cron preset list, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
| `timezone` | Timezone day-key helpers (`dayKeyInTimezone`, `todayKeyInTimezone`) — browser mirror of the server's `todayInTimezone`, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681). |
diff --git a/client/src/utils/cronHelpers.js b/client/src/utils/cronHelpers.js
index c30a47068f..c0a750e7ba 100644
--- a/client/src/utils/cronHelpers.js
+++ b/client/src/utils/cronHelpers.js
@@ -108,3 +108,20 @@ export function describeCron(expr) {
}
return segments.join(' ');
}
+
+// Interval-mode cadences for autonomous jobs — the client mirror of
+// `INTERVAL_OPTIONS` in `server/services/autonomousJobs/constants.js`. Values
+// must stay in lockstep with `resolveIntervalMs` there, since the server
+// recomputes `intervalMs` from whichever value a picker submits. Lives here
+// rather than in a component so a second job-scheduling surface doesn't fork
+// its own copy of the list.
+export const JOB_INTERVAL_OPTIONS = [
+ { value: 'hourly', label: 'Every Hour' },
+ { value: 'every-2-hours', label: 'Every 2 Hours' },
+ { value: 'every-4-hours', label: 'Every 4 Hours' },
+ { value: 'every-8-hours', label: 'Every 8 Hours' },
+ { value: 'daily', label: 'Daily' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'biweekly', label: 'Every 2 Weeks' },
+ { value: 'monthly', label: 'Monthly' }
+];
diff --git a/server/services/autonomousJobs/brainParitySweep.js b/server/services/autonomousJobs/brainParitySweep.js
new file mode 100644
index 0000000000..769bb481c5
--- /dev/null
+++ b/server/services/autonomousJobs/brainParitySweep.js
@@ -0,0 +1,110 @@
+/**
+ * Autonomous Jobs — scheduled brain-parity sweep (SCRIPT_HANDLERS['brain-parity-sweep']).
+ *
+ * `brainParity.js` makes federation divergence *visible*, but only when someone
+ * presses the Check button on a peer card. The whole failure mode it exists to
+ * catch is silent — both installs report "synced" while holding different
+ * records — so a user who never thinks to press the button never finds out.
+ * This wraps the sweep (`runBrainParityCheck()` with no `peerId` = every
+ * federating peer) so it can run on a cadence.
+ *
+ * DEFAULT-DISABLED by design (issue #4519): the sweep exchanges a full manifest
+ * with every peer and re-reads every local brain store, which is not a cost an
+ * install should pay unasked. It is deterministic — no LLM calls — so it is safe
+ * under the cold-bootstrap policy once the user opts in.
+ *
+ * The return value is a COMPACT summary, not the raw reports. Script-job results
+ * are echoed back from the manual-trigger route and emitted on
+ * `jobs:script-executed`; a badly diverged install's full report carries every
+ * out-of-parity record id per type, which has no business on a socket event.
+ * The detailed reports are already persisted by `runBrainParityCheck` and
+ * rendered per peer on the Instances page.
+ */
+
+import { INTEGRITY_STATUS } from '../../lib/syncIntegrity.js'
+
+// Statuses that mean "these two brains hold different data". `in-parity` is
+// excluded; `total` is a denominator, not a finding.
+const OUT_OF_PARITY_STATUSES = [
+ INTEGRITY_STATUS.LOCAL_ONLY,
+ INTEGRITY_STATUS.PEER_ONLY,
+ INTEGRITY_STATUS.DIVERGED
+]
+
+const countOutOfParity = (summary) =>
+ OUT_OF_PARITY_STATUSES.reduce((total, key) => total + (summary?.[key] ?? 0), 0)
+
+/**
+ * Collapse one peer report to the fields worth logging/emitting.
+ *
+ * `checksumMatch: null` is preserved distinctly from `false` — null means the
+ * peer served no checksum, so record *bodies* were never compared. Folding that
+ * into `false` would report divergence that was not observed, and folding it
+ * into `true` would claim a verification that never ran.
+ */
+function summarizePeer(report) {
+ if (report?.available !== true) {
+ return {
+ peerId: report?.peerId ?? null,
+ peerName: report?.peerName ?? null,
+ available: false,
+ reason: report?.reason ?? 'unknown'
+ }
+ }
+ return {
+ peerId: report.peerId ?? null,
+ peerName: report.peerName ?? null,
+ available: true,
+ recordsCompared: report.summary?.total ?? 0,
+ outOfParity: countOutOfParity(report.summary),
+ checksumMatch: report.checksums?.match ?? null
+ }
+}
+
+/**
+ * Run the parity audit against every federating peer and summarize the result.
+ *
+ * @param {object} [deps]
+ * @param {(opts?: object) => Promise<{ reports: object[] }>} [deps.check] - sweep runner (test seam)
+ * @returns {Promise<{ peersChecked: number, peersUnavailable: number, peersOutOfParity: number, outOfParityRecords: number, peers: object[] }>}
+ */
+export async function runBrainParitySweep({ check } = {}) {
+ // Imported lazily so the scriptHandlers registry — loaded on every jobs read —
+ // doesn't pull the brain storage + reconcile + peer-registry graph behind it
+ // just to have the handler in a map.
+ const run = check || (async (opts) => {
+ const { runBrainParityCheck } = await import('../brainParity.js')
+ return runBrainParityCheck(opts)
+ })
+
+ const result = await run({})
+ const reports = Array.isArray(result?.reports) ? result.reports : []
+ const peers = reports.map(summarizePeer)
+
+ const peersUnavailable = peers.filter((p) => !p.available).length
+ // A peer counts as out of parity when records differ OR when the whole-brain
+ // checksums disagree — the checksum is the only signal that catches matching
+ // ids AND clocks over different bodies, which is a real divergence with an
+ // out-of-parity count of zero.
+ const outOfParityPeers = peers.filter((p) => p.available && (p.outOfParity > 0 || p.checksumMatch === false))
+ const outOfParityRecords = peers.reduce((total, p) => total + (p.outOfParity ?? 0), 0)
+
+ const summary = {
+ peersChecked: peers.length,
+ peersUnavailable,
+ peersOutOfParity: outOfParityPeers.length,
+ outOfParityRecords,
+ peers
+ }
+
+ if (peers.length === 0) {
+ console.log('🧠🔍 Brain parity sweep: no federating peers to check')
+ } else if (outOfParityPeers.length === 0) {
+ console.log(`🧠🔍 Brain parity sweep: ${peers.length} peer(s) checked, none out of parity (${peersUnavailable} unavailable)`)
+ } else {
+ const names = outOfParityPeers.map((p) => p.peerName || p.peerId).join(', ')
+ console.log(`🧠🔍 Brain parity sweep: ${outOfParityPeers.length}/${peers.length} peer(s) out of parity (${outOfParityRecords} record(s)) — ${names}`)
+ }
+
+ return summary
+}
diff --git a/server/services/autonomousJobs/brainParitySweep.test.js b/server/services/autonomousJobs/brainParitySweep.test.js
new file mode 100644
index 0000000000..4def0fc75e
--- /dev/null
+++ b/server/services/autonomousJobs/brainParitySweep.test.js
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { runBrainParitySweep } from './brainParitySweep.js'
+import { DEFAULT_JOBS } from './defaults.js'
+import { SCRIPT_HANDLERS } from './scriptHandlers.js'
+
+const peerReport = (overrides = {}) => ({
+ peerId: 'peer-1',
+ peerInstanceId: 'inst-1',
+ peerName: 'Peer One',
+ checkedAt: '2026-08-18T00:00:00.000Z',
+ available: true,
+ checksums: { local: 'aaa', peer: 'aaa', match: true },
+ summary: { total: 10, 'in-parity': 10, 'local-only': 0, 'peer-only': 0, diverged: 0 },
+ byType: [],
+ ...overrides
+})
+
+describe('runBrainParitySweep', () => {
+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })
+ afterEach(() => { vi.restoreAllMocks() })
+
+ it('sweeps every federating peer — never a single peer', async () => {
+ const check = vi.fn().mockResolvedValue({ reports: [] })
+ await runBrainParitySweep({ check })
+ expect(check).toHaveBeenCalledTimes(1)
+ expect(check.mock.calls[0][0]?.peerId).toBeUndefined()
+ })
+
+ it('reports a clean sweep with no out-of-parity peers', async () => {
+ const check = vi.fn().mockResolvedValue({ reports: [peerReport()] })
+ const result = await runBrainParitySweep({ check })
+ expect(result.peersChecked).toBe(1)
+ expect(result.peersOutOfParity).toBe(0)
+ expect(result.outOfParityRecords).toBe(0)
+ expect(result.peersUnavailable).toBe(0)
+ expect(result.peers[0]).toMatchObject({ peerId: 'peer-1', available: true, recordsCompared: 10, checksumMatch: true })
+ })
+
+ it('counts local-only, peer-only and diverged records as out of parity', async () => {
+ const check = vi.fn().mockResolvedValue({
+ reports: [peerReport({
+ summary: { total: 10, 'in-parity': 4, 'local-only': 2, 'peer-only': 3, diverged: 1 }
+ })]
+ })
+ const result = await runBrainParitySweep({ check })
+ expect(result.outOfParityRecords).toBe(6)
+ expect(result.peersOutOfParity).toBe(1)
+ expect(result.peers[0].outOfParity).toBe(6)
+ })
+
+ it('flags a checksum mismatch as out of parity even when every id and clock matches', async () => {
+ // The case only the whole-brain checksum can see: same ids, same clocks,
+ // different record BODIES. Counting only manifest differences would call
+ // this install clean.
+ const check = vi.fn().mockResolvedValue({
+ reports: [peerReport({ checksums: { local: 'aaa', peer: 'bbb', match: false } })]
+ })
+ const result = await runBrainParitySweep({ check })
+ expect(result.peersOutOfParity).toBe(1)
+ expect(result.outOfParityRecords).toBe(0)
+ })
+
+ it('does not treat an unverified checksum as divergence', async () => {
+ // A peer too old to serve a checksum yields match:null — unknown, not a
+ // mismatch. Reporting it as out of parity would cry wolf on every sweep.
+ const check = vi.fn().mockResolvedValue({
+ reports: [peerReport({ checksums: { local: 'aaa', peer: null, match: null } })]
+ })
+ const result = await runBrainParitySweep({ check })
+ expect(result.peersOutOfParity).toBe(0)
+ expect(result.peers[0].checksumMatch).toBeNull()
+ })
+
+ it('separates unavailable peers from diverged ones', async () => {
+ const check = vi.fn().mockResolvedValue({
+ reports: [
+ peerReport(),
+ { peerId: 'peer-2', peerName: 'Peer Two', available: false, reason: 'peer-unreachable' }
+ ]
+ })
+ const result = await runBrainParitySweep({ check })
+ expect(result.peersChecked).toBe(2)
+ expect(result.peersUnavailable).toBe(1)
+ expect(result.peersOutOfParity).toBe(0)
+ expect(result.peers[1]).toEqual({ peerId: 'peer-2', peerName: 'Peer Two', available: false, reason: 'peer-unreachable' })
+ })
+
+ it('returns a summary only — never the per-record report bodies', async () => {
+ // The result is echoed by the manual-trigger route and emitted on
+ // `jobs:script-executed`; a badly diverged install's byType lists must not
+ // ride along.
+ const check = vi.fn().mockResolvedValue({
+ reports: [peerReport({ byType: [{ type: 'notes', counts: {}, records: [{ id: 'n1' }] }] })]
+ })
+ const result = await runBrainParitySweep({ check })
+ expect(JSON.stringify(result)).not.toContain('n1')
+ expect(result.peers[0].byType).toBeUndefined()
+ })
+
+ it('survives a malformed check result rather than throwing on the scheduler thread', async () => {
+ const check = vi.fn().mockResolvedValue(null)
+ await expect(runBrainParitySweep({ check })).resolves.toMatchObject({ peersChecked: 0 })
+ })
+})
+
+describe('job-brain-parity-sweep registration', () => {
+ const job = DEFAULT_JOBS.find(j => j.id === 'job-brain-parity-sweep')
+
+ it('ships as a script job wired to a registered handler', () => {
+ expect(job).toBeDefined()
+ expect(job.type).toBe('script')
+ expect(SCRIPT_HANDLERS[job.scriptHandler]).toBe(runBrainParitySweep)
+ })
+
+ it('ships DISABLED — opt-in per install, not a forced background cost (#4519)', () => {
+ expect(job.enabled).toBe(false)
+ })
+})
diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.js
index 4c1ec3a4f9..1e9ac77a31 100644
--- a/server/services/autonomousJobs/defaults.js
+++ b/server/services/autonomousJobs/defaults.js
@@ -272,6 +272,23 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-brain-parity-sweep',
+ name: 'Brain Parity Sweep',
+ description: 'Audit record-level brain parity against every federating peer. The sync cycle only advances delta-log cursors, so a record silently dropped on one side leaves both installs reading "synced"; this compares ids, clocks, and a whole-brain checksum and names what diverged. Deterministic — no AI calls.',
+ category: 'brain-parity',
+ interval: 'weekly',
+ intervalMs: WEEK,
+ scheduledTime: '06:00',
+ enabled: false,
+ priority: 'LOW',
+ type: 'script',
+ scriptHandler: 'brain-parity-sweep',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
// 'job-layered-intelligence' removed (#2322): Layered Intelligence is now a
// per-app HANDLER-BACKED scheduled task (CoS → Schedule) rather than a global
// autonomous-job sweep. Migration 184 tombstones the persisted job record and
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index ae80442e64..9414f79839 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -16,6 +16,7 @@ import { runGoalCheckIn } from '../goalCheckIn.js'
import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'
import { getActiveAgentIds } from '../agentState.js'
import { runSelfDiagnostics } from './selfDiagnostics.js'
+import { runBrainParitySweep } from './brainParitySweep.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -143,7 +144,11 @@ const SCRIPT_HANDLERS = {
// Daily self-diagnostics (#2464): reads task-learning per-category metrics and
// files a single `monitoring`-labeled GitHub summary of failing self-healing
// categories. Deterministic — no LLM calls (cold-bootstrap-safe).
- 'self-diagnostics': runSelfDiagnostics
+ 'self-diagnostics': runSelfDiagnostics,
+ // Federation brain-parity sweep (#4519): audits every federating peer for
+ // record-level divergence the cursor-based sync cycle cannot see. Default
+ // job ships disabled — deterministic, no LLM calls.
+ 'brain-parity-sweep': runBrainParitySweep
// 'layered-intelligence' retired here (#2322): LI is now a per-app scheduled
// task, not a global autonomous-job sweep. It runs as a normal reasoning agent
// with programmatic-I/O hooks — see taskTypeHooks.js +