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([issue-1562]): add full-sync peer mode (mirror everything across a federated pair)

[._.]/ Adam Eivyc087d16dd89e
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 9ea5c86bf8..bf8222e2fe 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -17,6 +17,7 @@ import {
removePeer, connectPeer, reciprocatePeer, probePeer, syncPeer, getTailnetInfo, provisionTailnetCert,
getNetworkExposure,
listPeerSubscriptions,
+ getPeerFullSyncCoverage,
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
@@ -228,6 +229,14 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
toast.success('Instance name updated');
};
+ const defaultFullSync = self?.defaultPeerFullSync === true;
+ const toggleDefaultFullSync = async () => {
+ const result = await updateSelfInstance({ defaultPeerFullSync: !defaultFullSync }).catch(() => null);
+ if (!result) return;
+ onUpdate();
+ toast.success(`New peers will ${!defaultFullSync ? 'default to full mirror' : 'start with no categories'}`);
+ };
+
if (!self) return null;
return (
@@ -277,6 +286,22 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
<span>No tailnet DNS — peers will reach you by IP</span>
</div>
)}
+ <button
+ onClick={toggleDefaultFullSync}
+ className="mt-2 pt-2 border-t border-port-border/50 flex items-start gap-2 w-full text-left group"
+ title="When on, peers you add will start in full-mirror mode automatically"
+ >
+ <div className={`w-3 h-3 mt-0.5 rounded-sm border flex-shrink-0 flex items-center justify-center transition-colors ${
+ defaultFullSync ? 'bg-port-accent border-port-accent' : 'border-gray-600 bg-transparent'
+ }`}>
+ {defaultFullSync && <Check size={8} className="text-white" />}
+ </div>
+ <Globe size={12} className={`mt-0.5 ${defaultFullSync ? 'text-port-accent' : 'text-gray-500'}`} />
+ <div className="flex-1 min-w-0">
+ <span className={`text-xs ${defaultFullSync ? 'text-white' : 'text-gray-400'} group-hover:text-gray-300`}>Default new peers to full mirror</span>
+ <p className="text-[10px] text-gray-600 leading-snug">Applies to peers added from now on; existing peers are unchanged.</p>
+ </div>
+ </button>
{syncStatus?.local && (
<div className="mt-2 pt-2 border-t border-port-border/50 grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-gray-400">
<span className="flex items-center gap-1.5">
@@ -505,12 +530,57 @@ const SYNC_CATEGORY_META = [
const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks']);
const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));
+// Indicator backed by REAL coverage diffing (record IDs vs confirmed pushes),
+// not the BIGSERIAL cursors — so "fully mirrored" never lies. Polls on mount and
+// whenever the peer comes online / sub set changes via the `refreshKey` prop.
+function FullSyncCoverageBadge({ peerId, peerInstanceId, refreshKey }) {
+ const [coverage, setCoverage] = useState(null);
+ const [loaded, setLoaded] = useState(false);
+ useEffect(() => {
+ if (!peerInstanceId) { setCoverage(null); setLoaded(true); return; }
+ let cancelled = false;
+ setLoaded(false);
+ getPeerFullSyncCoverage(peerId, { silent: true })
+ .then((r) => { if (!cancelled) setCoverage(r); })
+ .catch(() => { if (!cancelled) setCoverage(null); })
+ .finally(() => { if (!cancelled) setLoaded(true); });
+ return () => { cancelled = true; };
+ }, [peerId, peerInstanceId, refreshKey]);
+
+ if (!peerInstanceId) {
+ return <span className="text-[10px] text-gray-600">awaiting first connection…</span>;
+ }
+ if (!loaded || !coverage) {
+ return <span className="text-[10px] text-gray-600">checking coverage…</span>;
+ }
+ if (coverage.fullyMirrored) {
+ return (
+ <span className="flex items-center gap-1 text-[10px] text-port-success" title={`All ${coverage.total} record(s) confirmed-delivered to this peer`}>
+ <CheckCircle2 size={11} /> Fully mirrored · {coverage.total} record{coverage.total !== 1 ? 's' : ''}
+ </span>
+ );
+ }
+ return (
+ <span className="flex items-center gap-1 text-[10px] text-port-warning" title={`${coverage.pending} of ${coverage.total} record(s) not yet confirmed-delivered`}>
+ <Clock size={11} /> {coverage.pending} pending · {coverage.confirmed}/{coverage.total} mirrored
+ </span>
+ );
+}
+
function SyncCategoriesPanel({ peer, onRefresh }) {
const [expanded, setExpanded] = useState(false);
const categories = peer.syncCategories || {};
- const enabledCount = Object.values(categories).filter(Boolean).length;
+ const fullSync = peer.fullSync === true;
+ // A full-sync peer mirrors every category — present them as locked-on.
+ const enabledCount = fullSync ? SYNC_CATEGORY_META.length : Object.values(categories).filter(Boolean).length;
+
+ const toggleFullSync = async () => {
+ await updatePeer(peer.id, { fullSync: !fullSync }).catch(() => null);
+ onRefresh();
+ };
const toggleCategory = async (key) => {
+ if (fullSync) return; // categories are locked-on under full mirror
const newValue = !categories[key];
const anyCatEnabled = Object.values({ ...categories, [key]: newValue }).some(Boolean);
await updatePeer(peer.id, {
@@ -561,9 +631,37 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
{expanded && (
<div className="mt-2 space-y-1">
+ {/* Full mirror toggle — when on, every current + future category is
+ implied and all subscribable records back-subscribe to this peer. */}
+ <button
+ onClick={toggleFullSync}
+ className={`flex items-start gap-2 w-full px-2 py-1.5 rounded border transition-colors text-left mb-1.5 ${
+ fullSync ? 'border-port-accent/60 bg-port-accent/10' : 'border-port-border hover:bg-port-bg/50'
+ }`}
+ >
+ <div className={`w-3 h-3 mt-0.5 rounded-sm border flex-shrink-0 flex items-center justify-center transition-colors ${
+ fullSync ? 'bg-port-accent border-port-accent' : 'border-gray-600 bg-transparent'
+ }`}>
+ {fullSync && <Check size={8} className="text-white" />}
+ </div>
+ <Globe size={12} className={`mt-0.5 ${fullSync ? 'text-port-accent' : 'text-gray-500'}`} />
+ <div className="flex-1 min-w-0">
+ <span className={`text-xs font-medium ${fullSync ? 'text-white' : 'text-gray-300'}`}>Full mirror</span>
+ <p className="text-[10px] text-gray-600 leading-snug">
+ Mirror everything to {peer.name || 'this peer'} — every category, all existing
+ records, and any new category added in a future version. Reciprocated automatically.
+ </p>
+ {fullSync && (
+ <div className="mt-1">
+ <FullSyncCoverageBadge peerId={peer.id} peerInstanceId={peer.instanceId} refreshKey={peer.lastSeen} />
+ </div>
+ )}
+ </div>
+ </button>
<p className="text-[10px] text-gray-600 mb-1.5 leading-snug">
- Enabling a category syncs it both ways — we ask {peer.name || 'the peer'} to
- sync the same back automatically.
+ {fullSync
+ ? 'Categories are locked on while full mirror is enabled. Turn it off to choose categories individually.'
+ : <>Enabling a category syncs it both ways — we ask {peer.name || 'the peer'} to sync the same back automatically.</>}
</p>
<div className="flex items-center justify-end gap-2 mb-1.5">
{/* Available whenever we know the peer's identity — NOT gated on
@@ -582,39 +680,50 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
Make mutual
</button>
)}
- <button
- onClick={() => toggleAll(true)}
- className="text-[10px] text-port-accent hover:text-port-accent/80 transition-colors"
- >
- Enable all
- </button>
- <button
- onClick={() => toggleAll(false)}
- className="text-[10px] text-gray-500 hover:text-gray-400 transition-colors"
- >
- Disable all
- </button>
+ {/* Enable/Disable-all are moot under full mirror (categories locked on). */}
+ {!fullSync && (
+ <>
+ <button
+ onClick={() => toggleAll(true)}
+ className="text-[10px] text-port-accent hover:text-port-accent/80 transition-colors"
+ >
+ Enable all
+ </button>
+ <button
+ onClick={() => toggleAll(false)}
+ className="text-[10px] text-gray-500 hover:text-gray-400 transition-colors"
+ >
+ Disable all
+ </button>
+ </>
+ )}
</div>
- {SYNC_CATEGORY_META.map(({ key, label, icon: Icon, description }) => (
+ {SYNC_CATEGORY_META.map(({ key, label, icon: Icon, description }) => {
+ // Under full mirror every category reads as on and is non-interactive.
+ const on = fullSync || categories[key];
+ return (
<button
key={key}
onClick={() => toggleCategory(key)}
- className="flex items-center gap-2 w-full px-2 py-1.5 rounded hover:bg-port-bg/50 transition-colors text-left"
+ disabled={fullSync}
+ title={fullSync ? 'Locked on by full mirror' : undefined}
+ className={`flex items-center gap-2 w-full px-2 py-1.5 rounded text-left transition-colors ${fullSync ? 'opacity-70 cursor-default' : 'hover:bg-port-bg/50'}`}
>
<div className={`w-3 h-3 rounded-sm border flex-shrink-0 flex items-center justify-center transition-colors ${
- categories[key]
+ on
? 'bg-port-accent border-port-accent'
: 'border-gray-600 bg-transparent'
}`}>
- {categories[key] && <Check size={8} className="text-white" />}
+ {on && (fullSync ? <Lock size={7} className="text-white" /> : <Check size={8} className="text-white" />)}
</div>
- <Icon size={12} className={categories[key] ? 'text-port-accent' : 'text-gray-500'} />
+ <Icon size={12} className={on ? 'text-port-accent' : 'text-gray-500'} />
<div className="flex-1 min-w-0">
- <span className={`text-xs ${categories[key] ? 'text-white' : 'text-gray-400'}`}>{label}</span>
+ <span className={`text-xs ${on ? 'text-white' : 'text-gray-400'}`}>{label}</span>
<p className="text-[10px] text-gray-600 truncate">{description}</p>
</div>
</button>
- ))}
+ );
+ })}
</div>
)}
</div>
@@ -677,7 +786,12 @@ function SyncStatusSection({ peer, syncStatus, peerSubs = [], peerSubsLoaded = t
const cursor = syncStatus.cursors?.[peer.instanceId];
const remoteSyncSeqs = peer.remoteSyncSeqs;
- const categories = peer.syncCategories || {};
+ // A full-sync peer mirrors every category, so the snapshot sync status should
+ // surface them all on (its stored syncCategories map can be all-false
+ // underneath). Mirror the server's allSyncCategoriesOn semantics here.
+ const categories = peer.fullSync === true
+ ? Object.fromEntries(SYNC_CATEGORY_META.map(m => [m.key, true]))
+ : (peer.syncCategories || {});
// The peer's cursor into OUR data (how far it has pulled from us) — the
// push-frontier toward this peer. Present only when our probe passed `forPeer`
// and the peer is new enough to report it; absent → push count is "unknown".
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index d8d987ebd3..482168b1bb 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -180,6 +180,7 @@ export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { m
export const reciprocatePeer = (id, options) => request(`/instances/peers/${id}/reciprocate`, { method: 'POST', ...options });
export const probePeer = (id) => request(`/instances/peers/${id}/probe`, { method: 'POST' });
export const syncPeer = (id, options) => request(`/instances/peers/${id}/sync`, { method: 'POST', ...options });
+export const getPeerFullSyncCoverage = (id, options) => request(`/instances/peers/${id}/full-sync-coverage`, options);
export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);
export const getTailnetInfo = () => request('/instances/tailnet-suffix');
export const provisionTailnetCert = () => request('/instances/provision-cert', { method: 'POST' });
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 221dfe01e3..281470cf90 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -10,6 +10,7 @@ import { execFile } from 'child_process';
import { promisify } from 'util';
import * as instances from '../services/instances.js';
import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';
+import { getFullSyncCoverageForPeer } from '../services/sharing/peerSync.js';
import { provisionTailscaleCert } from '../services/certProvisioner.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
@@ -71,6 +72,9 @@ const updatePeerSchema = z.object({
name: z.string().optional(),
enabled: z.boolean().optional(),
syncEnabled: z.boolean().optional(),
+ // Full-sync ("mirror everything") mode: implies every current + future sync
+ // category and back-subscribes all subscribable records to this peer.
+ fullSync: z.boolean().optional(),
syncCategories: syncCategoriesSchema,
// Accept empty string to clear; any other string is validated/normalized in the service
host: z.string().optional().nullable(),
@@ -99,7 +103,10 @@ const reciprocalSyncSchema = z.object({
// syncCategories KEY is required. An empty `{}` still parses (all fields are
// optional) and simply no-ops downstream in applyReciprocalSync
// (sanitizeSyncCategories returns null → changed:false).
- syncCategories: syncCategoriesSchema.unwrap()
+ syncCategories: syncCategoriesSchema.unwrap(),
+ // Optional: a full-sync peer asks us to mirror everything back. Absent from
+ // older peers (they reciprocate via the all-on syncCategories map instead).
+ fullSync: z.boolean().optional()
});
// GET /api/instances — list self + all peers
@@ -176,13 +183,17 @@ router.get('/self', asyncHandler(async (req, res) => {
res.json(self);
}));
-// PUT /api/instances/self — update display name
+// PUT /api/instances/self — update display name and/or the new-peer full-sync default
+const updateSelfSchema = z.object({
+ name: z.string().min(1).optional(),
+ // Default full-sync ("mirror everything") mode for peers added from now on.
+ defaultPeerFullSync: z.boolean().optional()
+}).refine((d) => d.name !== undefined || d.defaultPeerFullSync !== undefined, {
+ message: 'Provide name and/or defaultPeerFullSync'
+});
router.put('/self', asyncHandler(async (req, res) => {
- const { name } = req.body;
- if (!name || typeof name !== 'string') {
- throw new ServerError('Name is required', { status: 400 });
- }
- const updated = await instances.updateSelf(name.trim());
+ const data = updateSelfSchema.parse(req.body);
+ const updated = await instances.updateSelf(data.name, { defaultPeerFullSync: data.defaultPeerFullSync });
if (!updated) throw new ServerError('Self identity not initialized', { status: 500 });
res.json(updated);
}));
@@ -262,7 +273,7 @@ router.post('/peers/:id/connect', asyncHandler(async (req, res) => {
// instanceId in the body (we may not know its local-peer-id mapping).
router.post('/peers/sync-categories', asyncHandler(async (req, res) => {
const data = reciprocalSyncSchema.parse(req.body);
- const { changed } = await instances.applyReciprocalSync(data.instanceId, data.syncCategories);
+ const { changed } = await instances.applyReciprocalSync(data.instanceId, data.syncCategories, { fullSync: data.fullSync });
// 200 even when the peer is unknown to us / nothing changed — this is a
// best-effort convergence signal, not a command that must succeed. We return
// only `applied` (not the peer record) — the remote caller doesn't consume it,
@@ -311,6 +322,24 @@ router.post('/peers/:id/sync', asyncHandler(async (req, res) => {
res.json({ ok: true, result });
}));
+// GET /api/instances/peers/:id/full-sync-coverage — real coverage diff backing
+// the "fully mirrored ✓ / N pending" indicator for a full-sync peer. Computed
+// on demand (it lists every subscribable record), so the client fetches it per
+// full-sync peer rather than bloating the polled /instances payload.
+router.get('/peers/:id/full-sync-coverage', asyncHandler(async (req, res) => {
+ const peers = await instances.getPeers();
+ const peer = peers.find(p => p.id === req.params.id);
+ if (!peer) throw new ServerError('Peer not found', { status: 404 });
+ // Coverage is keyed by the peer's federation identity; an un-probed peer
+ // (no instanceId yet) has no subscriptions, so coverage is trivially empty.
+ if (!peer.instanceId) {
+ res.json({ total: 0, confirmed: 0, pending: 0, fullyMirrored: true, byKind: {} });
+ return;
+ }
+ const coverage = await getFullSyncCoverageForPeer(peer.instanceId);
+ res.json(coverage);
+}));
+
// GET /api/instances/peers/:id/query — proxy GET to peer
router.get('/peers/:id/query', asyncHandler(async (req, res) => {
const { path } = querySchema.parse(req.query);
diff --git a/server/services/instances.js b/server/services/instances.js
index 376ec70548..bd7504490e 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -169,11 +169,19 @@ export async function getInstanceId() {
return cachedInstanceId;
}
-export async function updateSelf(name) {
+export async function updateSelf(name, { defaultPeerFullSync } = {}) {
return withData(async (data) => {
if (!data.self) return null;
- data.self.name = name;
- console.log(`🌐 Instance name updated: ${name}`);
+ if (typeof name === 'string' && name.trim()) {
+ data.self.name = name.trim();
+ console.log(`🌐 Instance name updated: ${data.self.name}`);
+ }
+ // The default full-sync ("mirror everything") mode applied to NEW peers as
+ // they're added. Existing peers are untouched — this only seeds addPeer.
+ if (typeof defaultPeerFullSync === 'boolean') {
+ data.self.defaultPeerFullSync = defaultPeerFullSync;
+ console.log(`🌐 New-peer full-sync default: ${defaultPeerFullSync ? 'on' : 'off'}`);
+ }
return data.self;
});
}
@@ -235,6 +243,15 @@ const DEFAULT_SYNC_CATEGORIES = {
export { DEFAULT_SYNC_CATEGORIES };
+// A category map with every key forced on — the effective view a full-sync
+// ("mirror everything") peer presents. Derived from DEFAULT_SYNC_CATEGORIES so a
+// newly added category is covered by full-sync peers with no per-peer change.
+// Used by the snapshot orchestrator (what a full-sync peer pulls) and the
+// reciprocation send (the all-on map a full-sync peer asks its mirror to adopt).
+export function allSyncCategoriesOn() {
+ return Object.fromEntries(Object.keys(DEFAULT_SYNC_CATEGORIES).map((k) => [k, true]));
+}
+
// Sync categories whose records ride the PER-RECORD push pipeline (not the 60s
// snapshot loop), paired with the record kind autoSubscribePeerToAllRecords
// backfills. A false→true toggle on any of these triggers an inline backfill of
@@ -279,7 +296,13 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
lastHealth: null,
status: 'unknown',
enabled: true,
- syncEnabled: false,
+ // Full-sync ("mirror everything") mode. When true, every current and
+ // future sync category is implied on for this peer and a back-subscribe
+ // sweep keeps all subscribable records mirrored. New peers inherit the
+ // self-side default so a user who runs full-mirror node pairs doesn't have
+ // to flip it on every peer by hand.
+ fullSync: data.self?.defaultPeerFullSync === true,
+ syncEnabled: data.self?.defaultPeerFullSync === true,
syncCategories: { ...DEFAULT_SYNC_CATEGORIES },
consecutiveFailures: 0,
nextProbeAt: null,
@@ -329,6 +352,28 @@ export async function updatePeer(id, updates) {
if (updates.name !== undefined) peer.name = validName(updates.name, peer.name);
if (updates.enabled !== undefined) peer.enabled = updates.enabled;
if (updates.syncEnabled !== undefined) peer.syncEnabled = updates.syncEnabled;
+ // Full-sync ("mirror everything") toggle. A false→true flip implies every
+ // subscribable category, so back-subscribe ALL record kinds (not just the
+ // ones whose individual syncCategories bit flipped) and reciprocate so the
+ // peer mirrors us back. Enabling full-sync also implies the peer is sync-
+ // enabled — otherwise peerAllowsOutbound would gate every push off.
+ if (updates.fullSync !== undefined && updates.fullSync !== peer.fullSync) {
+ peer.fullSync = updates.fullSync === true;
+ if (peer.fullSync) {
+ peer.syncEnabled = true;
+ for (const [, kind] of PER_RECORD_CATEGORY_KINDS) turnedOnKinds.push(kind);
+ backfillPeerInstanceId = peer.instanceId || null;
+ } else {
+ // Turning full mirror off restores the per-category selection preserved
+ // underneath — recompute syncEnabled from it so a peer with no remaining
+ // enabled categories doesn't read as "sync on, nothing to sync".
+ peer.syncEnabled = Object.values(peer.syncCategories || {}).some(Boolean);
+ }
+ // Reciprocate the full-sync intent (and its all-on category view) to the
+ // peer whenever we know its identity, so a node pair converges to a mutual
+ // mirror in one round-trip.
+ if (peer.instanceId) reciprocate = true;
+ }
if (updates.syncCategories !== undefined) {
const prev = peer.syncCategories || DEFAULT_SYNC_CATEGORIES;
const incoming = updates.syncCategories;
@@ -455,7 +500,15 @@ export function enqueueReciprocalSync(peerId) {
const data = await loadData();
const peer = data.peers.find(p => p.id === peerId);
if (!peer?.instanceId) return { ok: false, reason: 'no-peer-identity' };
- return requestReciprocalSync(peer, peer.syncCategories || {}).catch((err) => {
+ // For a full-sync peer send the all-on category view (its stored
+ // syncCategories can be all-false underneath — sending that raw would tell
+ // the peer to DISABLE everything, since reciprocal-sync apply is an
+ // authoritative overlay; the all-on map also makes a peer too old to
+ // understand the fullSync flag still mirror every category) plus the
+ // fullSync flag. A regular peer keeps sending its raw partial map so a
+ // category it never set stays untouched on the peer (absent ≠ false).
+ const reciprocalCategories = peer.fullSync === true ? allSyncCategoriesOn() : (peer.syncCategories || {});
+ return requestReciprocalSync(peer, reciprocalCategories, { fullSync: peer.fullSync === true }).catch((err) => {
console.log(`⚠️ peer: reciprocal sync request failed: ${err.message}`);
return { ok: false, reason: err.message };
});
@@ -796,9 +849,12 @@ function sanitizeSyncCategories(input) {
* record already matched (the echo guard — the caller never re-reciprocates,
* but this keeps a misbehaving peer from churning our state).
*/
-export async function applyReciprocalSync(instanceId, categories) {
+export async function applyReciprocalSync(instanceId, categories, { fullSync } = {}) {
const sanitized = sanitizeSyncCategories(categories);
- if (!sanitized) return { changed: false, peer: null };
+ // A fullSync-only signal (peer asking us to mirror everything) is valid even
+ // if the category map didn't sanitize to anything actionable.
+ const wantsFullSync = fullSync === true;
+ if (!sanitized && !wantsFullSync) return { changed: false, peer: null };
const turnedOnKinds = [];
let backfillInstanceId = null;
let changed = false;
@@ -809,14 +865,21 @@ export async function applyReciprocalSync(instanceId, categories) {
// diverge — otherwise sanitized adding `goals:false` to a `prev` missing
// `goals` reads as a change (`false !== undefined`) and defeats the guard.
const prev = { ...DEFAULT_SYNC_CATEGORIES, ...(entry.syncCategories || {}) };
- const next = { ...prev, ...sanitized };
+ const next = sanitized ? { ...prev, ...sanitized } : prev;
+ const fullSyncFlips = wantsFullSync && entry.fullSync !== true;
// No-op when nothing actually flips — the echo guard.
- if (Object.keys(next).every(k => next[k] === prev[k])) return entry;
- for (const [cat, kind] of PER_RECORD_CATEGORY_KINDS) {
- if (prev[cat] !== true && next[cat] === true) turnedOnKinds.push(kind);
+ if (!fullSyncFlips && Object.keys(next).every(k => next[k] === prev[k])) return entry;
+ // When the peer asks us to mirror everything, a full sweep covers all kinds.
+ if (fullSyncFlips) {
+ entry.fullSync = true;
+ for (const [, kind] of PER_RECORD_CATEGORY_KINDS) turnedOnKinds.push(kind);
+ } else {
+ for (const [cat, kind] of PER_RECORD_CATEGORY_KINDS) {
+ if (prev[cat] !== true && next[cat] === true) turnedOnKinds.push(kind);
+ }
}
entry.syncCategories = next;
- entry.syncEnabled = Object.values(next).some(Boolean);
+ entry.syncEnabled = entry.fullSync === true || Object.values(next).some(Boolean);
if (turnedOnKinds.length > 0) backfillInstanceId = entry.instanceId || null;
changed = true;
instanceEvents.emit('peers:updated', data.peers);
@@ -834,7 +897,10 @@ export async function applyReciprocalSync(instanceId, categories) {
}
})();
}
- if (changed) console.log(`🔁 Reciprocal sync applied for peer ${peer.name}: ${Object.keys(sanitized).filter(k => sanitized[k]).join(',') || 'none'}`);
+ if (changed) {
+ const enabledList = sanitized ? Object.keys(sanitized).filter(k => sanitized[k]).join(',') : '';
+ console.log(`🔁 Reciprocal sync applied for peer ${peer.name}: ${peer.fullSync ? 'full-mirror' : (enabledList || 'none')}`);
+ }
return { changed, peer };
}
@@ -844,7 +910,7 @@ export async function applyReciprocalSync(instanceId, categories) {
* peer that's offline or on an older version (404s the endpoint) just stays
* one-directional until the next toggle. Returns `{ ok, reason }`.
*/
-export async function requestReciprocalSync(peer, categories) {
+export async function requestReciprocalSync(peer, categories, { fullSync = false } = {}) {
const self = await getSelf();
if (!self?.instanceId) return { ok: false, reason: 'no-self-identity' };
const sanitized = sanitizeSyncCategories(categories);
@@ -856,7 +922,10 @@ export async function requestReciprocalSync(peer, categories) {
const res = await peerFetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized }),
+ // Include the full-sync flag so a peer new enough to understand it adopts
+ // mirror mode too. Older peers ignore the unknown field and still mirror
+ // via the all-on syncCategories map we sent.
+ body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized, ...(fullSync ? { fullSync: true } : {}) }),
signal: controller.signal
}, peer);
if (res.ok) {
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index d0603a8ed3..fabb88c956 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -732,6 +732,85 @@ describe('instances.js', () => {
expect(result.ok).toBe(false);
expect(result.reason).toBe('no-peer-identity');
});
+
+ it('a full-sync peer reciprocates the ALL-ON category view + the fullSync flag (not its raw all-false map)', async () => {
+ // A full-sync peer mirrors everything; its stored syncCategories can be
+ // all-false underneath. Sending that raw would tell the peer to DISABLE
+ // everything (reciprocal apply is an authoritative overlay). It must send
+ // every category on, plus fullSync:true so a new-enough peer adopts mirror
+ // mode too.
+ readJSONFile.mockResolvedValue({
+ self: { instanceId: 'me-id' },
+ peers: [{ id: 'p-full', instanceId: 'inst-A', name: 'A', fullSync: true, syncCategories: { brain: false } }]
+ });
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await enqueueReciprocalSync('p-full');
+
+ const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
+ expect(body.fullSync).toBe(true);
+ // Every category present and true.
+ expect(Object.values(body.syncCategories).every(Boolean)).toBe(true);
+ expect(body.syncCategories.brain).toBe(true);
+ expect(body.syncCategories.tracks).toBe(true);
+ });
+ });
+
+ describe('fullSync (full-mirror) peer mode', () => {
+ it('addPeer defaults fullSync off when no self default is set', async () => {
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });
+ fetch.mockRejectedValue(new Error('not reachable'));
+ const peer = await addPeer({ address: '10.0.0.9', name: 'p' });
+ expect(peer.fullSync).toBe(false);
+ });
+
+ it('addPeer inherits the self-side defaultPeerFullSync for new peers', async () => {
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me', defaultPeerFullSync: true }, peers: [] });
+ fetch.mockRejectedValue(new Error('not reachable'));
+ const peer = await addPeer({ address: '10.0.0.10', name: 'p' });
+ expect(peer.fullSync).toBe(true);
+ expect(peer.syncEnabled).toBe(true);
+ });
+
+ it('updatePeer enabling fullSync implies syncEnabled on', async () => {
+ const peers = [{ id: 'p1', name: 'A', enabled: true, fullSync: false, syncEnabled: false, syncCategories: {} }];
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
+ const result = await updatePeer('p1', { fullSync: true });
+ expect(result.fullSync).toBe(true);
+ expect(result.syncEnabled).toBe(true);
+ });
+
+ it('updatePeer disabling fullSync recomputes syncEnabled from the preserved category map', async () => {
+ // brain was on underneath → still sync-enabled after turning mirror off.
+ const onPeer = [{ id: 'p1', name: 'A', enabled: true, fullSync: true, syncEnabled: true, syncCategories: { brain: true } }];
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: onPeer });
+ const stillOn = await updatePeer('p1', { fullSync: false });
+ expect(stillOn.fullSync).toBe(false);
+ expect(stillOn.syncEnabled).toBe(true);
+
+ // empty map → nothing left to sync.
+ const emptyPeer = [{ id: 'p2', name: 'B', enabled: true, fullSync: true, syncEnabled: true, syncCategories: {} }];
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: emptyPeer });
+ const off = await updatePeer('p2', { fullSync: false });
+ expect(off.syncEnabled).toBe(false);
+ });
+
+ it('applyReciprocalSync adopts fullSync even when the category map is empty', async () => {
+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', fullSync: false, syncCategories: {} }];
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
+ const { changed, peer } = await applyReciprocalSync('inst-A', {}, { fullSync: true });
+ expect(changed).toBe(true);
+ expect(peer.fullSync).toBe(true);
+ expect(peer.syncEnabled).toBe(true);
+ });
+
+ it('updateSelf persists the new-peer full-sync default', async () => {
+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me', name: 'box' }, peers: [] });
+ const self = await updateSelf(undefined, { defaultPeerFullSync: true });
+ expect(self.defaultPeerFullSync).toBe(true);
+ expect(self.name).toBe('box'); // name untouched when omitted
+ });
});
// --- Probing ---
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 1456de9403..2327a07bea 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -399,6 +399,12 @@ function peerAllowsOutbound(peer) {
function peerHasCategory(peer, recordKind) {
const cat = KIND_TO_CATEGORY[recordKind];
if (!cat) return false;
+ // A full-sync ("mirror everything") peer implies every current and future
+ // category on — so a newly added subscribable kind is covered with no
+ // per-peer change. This is what makes the back-subscribe sweep, the
+ // peer:online convergence, and auto-subscribe-on-create all fan a full-sync
+ // peer's mirror without enumerating categories by hand.
+ if (peer?.fullSync === true) return true;
const cats = peer?.syncCategories;
return !!(cats && cats[cat] === true);
}
@@ -446,17 +452,15 @@ export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {
* Dynamic imports for the listers avoid a static cycle (peerSync already
* imports merge entry points from universeBuilder / pipeline.series).
*/
-export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
- if (!isNonEmptyStr(peerId) || !PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) return [];
- // Re-check the peer is enabled + outbound-capable + still has the category
- // turned on. The caller (instances.updatePeer) already saw the false→true
- // flip inside withData, but this helper is also reachable from other
- // backfill paths and we don't want to push to an inbound-only peer just
- // because the category bit was set. Snapshot read is good enough — peer
- // edits are infrequent compared to subscription pushes.
- const peers = await getPeers().catch(() => []);
- const peer = peers.find(p => p.instanceId === peerId);
- if (!peer || !peerAllowsOutbound(peer) || !peerHasCategory(peer, recordKind)) return [];
+/**
+ * List the local, non-deleted, non-ephemeral records of a subscribable kind —
+ * the candidate set for both the back-subscribe sweep and full-sync coverage
+ * diffing. Ephemeral records are dropped because they can never push (the wire
+ * sanitizer short-circuits them) and a sub for one would leave an orphan row.
+ * Universe/series listers are dynamic-imported to avoid a static cycle
+ * (peerSync already imports their merge entry points).
+ */
+async function listRecordsForKind(recordKind) {
let records = [];
if (recordKind === 'universe') {
const { listUniverses } = await import('../universeBuilder.js');
@@ -475,11 +479,21 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
} else if (recordKind === 'track') {
records = await listTracks({ includeDeleted: false }).catch(() => []);
}
- // Drop ephemeral records before the set-difference / sub creation. The wire
- // sanitizer would short-circuit any push anyway, but creating a sub that
- // can never push leaves an orphan row in peer_subscriptions.json that
- // confuses unsubscribe-all / tombstone-cursor lifecycle assumptions.
- records = records.filter(r => r?.ephemeral !== true);
+ return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));
+}
+
+export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
+ if (!isNonEmptyStr(peerId) || !PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) return [];
+ // Re-check the peer is enabled + outbound-capable + still has the category
+ // turned on. The caller (instances.updatePeer) already saw the false→true
+ // flip inside withData, but this helper is also reachable from other
+ // backfill paths and we don't want to push to an inbound-only peer just
+ // because the category bit was set. Snapshot read is good enough — peer
+ // edits are infrequent compared to subscription pushes.
+ const peers = await getPeers().catch(() => []);
+ const peer = peers.find(p => p.instanceId === peerId);
+ if (!peer || !peerAllowsOutbound(peer) || !peerHasCategory(peer, recordKind)) return [];
+ const records = await listRecordsForKind(recordKind);
if (records.length === 0) return [];
// Compute the set difference up front: which local records aren't yet
// subscribed to this peer? The peer:online convergence path fires this
@@ -523,6 +537,40 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
return created;
}
+/**
+ * Real coverage diff for a (full-sync) peer: of every local subscribable record,
+ * how many have a CONFIRMED-delivered subscription to this peer? Backs the
+ * Instances UI "fully mirrored ✓ / N pending" indicator.
+ *
+ * Coverage is computed by diffing actual record IDs against subscriptions whose
+ * `lastConfirmedPushedAt` is set — NOT off the BIGSERIAL push cursors (which are
+ * sequence numbers, not row counts, and would misreport coverage). A record is
+ * "pending" when it has no subscription to this peer OR its subscription hasn't
+ * been confirmed-delivered yet. Returns per-kind breakdown plus totals, and
+ * `fullyMirrored` (pending === 0).
+ */
+export async function getFullSyncCoverageForPeer(peerId) {
+ const empty = { total: 0, confirmed: 0, pending: 0, fullyMirrored: true, byKind: {} };
+ if (!isNonEmptyStr(peerId)) return empty;
+ const byKind = {};
+ let total = 0;
+ let confirmed = 0;
+ for (const kind of PEER_SUBSCRIBABLE_KINDS) {
+ const records = await listRecordsForKind(kind).catch(() => []);
+ const subs = await listPeerSubscriptions({ peerId, recordKind: kind }).catch(() => []);
+ // A record counts as confirmed only when its subscription carries a
+ // confirmed-delivery water-mark — a created-but-never-pushed sub is pending.
+ const confirmedIds = new Set(subs.filter(s => s.lastConfirmedPushedAt).map(s => s.recordId));
+ const kindTotal = records.length;
+ const kindConfirmed = records.filter(r => confirmedIds.has(r.id)).length;
+ byKind[kind] = { total: kindTotal, confirmed: kindConfirmed, pending: kindTotal - kindConfirmed };
+ total += kindTotal;
+ confirmed += kindConfirmed;
+ }
+ const pending = total - confirmed;
+ return { total, confirmed, pending, fullyMirrored: pending === 0, byKind };
+}
+
/**
* Drop every subscription targeting a given peer. Used when removing a peer
* from the federation entirely (and by tests).
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 45f9b1d9b6..e1706e6cfa 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -134,6 +134,7 @@ import {
listPeerSubscriptions,
findPeerSubscription,
getOutboundCoverageForPeer,
+ getFullSyncCoverageForPeer,
subscribePeer,
unsubscribePeer,
unsubscribeAllForPeer,
@@ -439,6 +440,67 @@ describe('peerSync', () => {
});
});
+ describe('getFullSyncCoverageForPeer', () => {
+ beforeEach(() => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'U1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ });
+
+ it('reports fully-mirrored with zero total when there are no local records', async () => {
+ // All listers default to [] in the suite-level beforeEach.
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov).toMatchObject({ total: 0, confirmed: 0, pending: 0, fullyMirrored: true });
+ });
+
+ it('counts a record with no subscription as pending (real ID diff, not cursors)', async () => {
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }, { id: 'u2' }]);
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov.total).toBe(2);
+ expect(cov.confirmed).toBe(0);
+ expect(cov.pending).toBe(2);
+ expect(cov.fullyMirrored).toBe(false);
+ expect(cov.byKind.universe).toEqual({ total: 2, confirmed: 0, pending: 2 });
+ });
+
+ it('counts a confirmed-pushed subscription as mirrored', async () => {
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ // peerHasCategory gate is bypassed here — forcePushRecord drives the push
+ // directly. Register the peer so forcePushRecord finds it.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', name: 'A', enabled: true, syncEnabled: true, fullSync: true, syncCategories: {} },
+ ]);
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ // Deterministically push + confirm so lastConfirmedPushedAt is stamped
+ // (the subscribe's initial push is fire-and-forget; awaiting forcePushRecord
+ // avoids a drain-timing flake).
+ await forcePushRecord('peer-a', 'universe', 'u1');
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov.total).toBe(1);
+ expect(cov.confirmed).toBe(1);
+ expect(cov.pending).toBe(0);
+ expect(cov.fullyMirrored).toBe(true);
+ });
+
+ it('a created-but-unconfirmed subscription still counts as pending', async () => {
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ // Push FAILS — the sub is created but never confirmed-delivered.
+ vi.mocked(peerFetch).mockRejectedValue(new Error('offline'));
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' }).catch(() => {});
+ await __drainForTests();
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov.total).toBe(1);
+ expect(cov.confirmed).toBe(0);
+ expect(cov.pending).toBe(1);
+ expect(cov.fullyMirrored).toBe(false);
+ });
+
+ it('returns empty coverage for a blank peerId', async () => {
+ const cov = await getFullSyncCoverageForPeer('');
+ expect(cov).toMatchObject({ total: 0, fullyMirrored: true });
+ });
+ });
+
describe('unsubscribePeer', () => {
it('removes the subscription and the peer cursor when no other subs remain for that peer', async () => {
vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
@@ -801,6 +863,19 @@ describe('peerSync', () => {
expect(created).toEqual([]);
});
+ it('a full-sync peer subscribes records even when the matching category bit is off', async () => {
+ // fullSync implies every category — so the back-subscribe sweep covers a
+ // kind whose individual syncCategories bit was never turned on (and any
+ // future kind, with no per-peer change).
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: true, fullSync: true, syncCategories: { universe: false } },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created.map(c => c.recordId)).toEqual(['u1']);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).not.toBeNull();
+ });
+
it('returns [] on re-run — only newly-created subs are reported', async () => {
// `subscribePeer` is idempotent; the helper must not double-count
// existing subs as freshly created on the second invocation.
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 0a1f7d9743..6630b3be28 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -180,6 +180,10 @@ function snapshotPeerIdsForKind(peers, recordKind) {
.filter((p) => {
if (!p?.enabled) return false;
if (p.syncEnabled === false) return false;
+ // A full-sync peer mirrors every category, so it can resurrect a pruned
+ // tombstone for ANY kind via its snapshot loop — it must count here even
+ // when its stored syncCategories map doesn't list this category.
+ if (p.fullSync === true) return true;
const cats = p.syncCategories;
return !!cats && typeof cats === 'object' && cats[category] === true;
})
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index fa7fa97684..8f06e701c1 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -123,6 +123,22 @@ describe('sweepTombstones — no peers subscribed', () => {
});
});
+describe('sweepTombstones — full-sync peer resurrection guard', () => {
+ it('a full-sync peer with an empty category map still blocks snapshot-kind pruning', async () => {
+ // A full-sync peer mirrors every category regardless of its stored
+ // syncCategories map. If it weren't counted in the snapshot-resurrection
+ // set, pruning would drop a tombstone the peer hasn't seen and its next
+ // snapshot push would resurrect the record. So with no per-record sub, a
+ // full-sync peer must hold the line for every snapshot-backed kind.
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: true, fullSync: true, syncCategories: {} },
+ ]);
+ mockSubs({}); // no per-record subscriptions → only the snapshot gate can block
+ const res = await sweepTombstones({ now: NOW });
+ expect(res.refused).toEqual(expect.arrayContaining(['universe', 'series', 'issue', 'mediaCollection']));
+ });
+});
+
describe('sweepTombstones — orphaned base-hash sweep', () => {
it('runs the orphan sweep and surfaces its count, regardless of refusals', async () => {
// A snapshot-mode peer with no per-record sub refuses every tombstone kind
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index a3651c43f4..dad6f75e52 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -11,7 +11,7 @@ import { join } from 'path';
import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { instanceEvents } from './instanceEvents.js';
-import { getPeers, DEFAULT_SYNC_CATEGORIES, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';
+import { getPeers, DEFAULT_SYNC_CATEGORIES, allSyncCategoriesOn, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
import { peerAuthHeaders } from '../lib/peerHttpClient.js';
import * as brainSync from './brainSync.js';
@@ -438,6 +438,11 @@ function detectCursorReset(cursor, peer) {
* enable brain + memory for backward compatibility with older peers.
*/
function getEffectiveCategories(peer) {
+ // A full-sync ("mirror everything") peer pulls EVERY snapshot category from
+ // its mirror, regardless of the stored per-category map — including a category
+ // added in a later version (allSyncCategoriesOn derives off
+ // DEFAULT_SYNC_CATEGORIES, so it stays current automatically).
+ if (peer.fullSync === true) return allSyncCategoriesOn();
if (peer.syncCategories) return peer.syncCategories;
// Legacy fallback: peers without syncCategories but with syncEnabled get brain+memory
if (peer.syncEnabled !== false) {