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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: resync peer memory and Catalog streams after a database restore (#8710)
[._.]/ Adam Eivy90687f9ae71f
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex 786f019523..2fcbc617ad 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -344,6 +344,8 @@ export function BackupTab() {toast.success(`Database restored from ${target.request.snapshotId}`, { icon: '💾' });} else if (result.reason === 'restore_schema_reconciliation') {toast.error('The database dump was applied, but schema recovery is incomplete. It was not rolled back. Restart PortOS to retry recovery; if it still fails, check the server logs and repair the database before continuing.', { duration: Infinity });+ } else if (result.reason === 'restore_sync_resync') {+ toast.error('The database dump was applied, but peer sync could not be reset. Memories and Catalog records pulled from peers after this snapshot may stay missing; check the server logs and repeat the restore.', { duration: Infinity });} else {toast.error(`DB restore failed: ${result.reason || 'unknown'}`);}diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex aa4955f818..9a909254bd 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -96,17 +96,20 @@ After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. Restore### Database — `restorePostgres()`-Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the **SQL replay is atomic**: a failed replay rolls back. After replay commits, PortOS forces the current additive schema upgrades and then runs ordered DB migrations using the restored `schema_migrations` ledger. Already-applied migrations are skipped. Success is returned only after both phases finish; dry-run performs neither replay nor schema changes.+Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the **SQL replay is atomic**: a failed replay rolls back. After replay commits, PortOS forces the current additive schema upgrades and then runs ordered DB migrations using the restored `schema_migrations` ledger. Already-applied migrations are skipped. Success is returned only after both phases finish and peer sync is repaired (below); dry-run performs neither replay nor schema changes.| Result | Meaning ||---|---|-| `{ status: 'ok', dryRun, sizeBytes, tableCount }` | Dry-run report, or a successful real restore |+| `{ status: 'ok', dryRun, sizeBytes, tableCount }` | Dry-run report, or a successful real restore (which adds `syncCursorsRewound`, the number of peers rewound) || `{ status: 'skipped', reason: 'no_dump' }` | No `portos-db.sql` in the snapshot (or 0 bytes) || `{ status: 'skipped', reason: 'not_configured' }` | Real restore requested but Postgres is unreachable — refuses to half-restore || `{ status: 'failed', reason: 'manifest_unreadable' }` | An existing `manifest.json` is corrupt or unreadable — choose another snapshot or repair the backup media before retrying || `{ status: 'failed', reason: 'manifest_mismatch' }` | Snapshot's `portos-db.sql` hash disagrees with `manifest.json` — dump considered untrustworthy || `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) || `{ status: 'failed', reason: 'restore_schema_reconciliation', error }` | The dump committed, but current schema recovery failed; the restore was **not rolled back** |+| `{ status: 'failed', reason: 'restore_sync_resync', error }` | The dump committed and the schema recovered, but peer sync could not be repaired (below) |++**Peer sync repair (#8710).** Memories and the seven Catalog tables federate through per-stream feed positions. A restore breaks both directions: this install's per-peer pull cursors (`data/instances_sync_cursors.json`) still point past rows the restore discarded, and the dump rewinds each `<table>_sync_feed_seq`, so new rows would reuse positions peers have already passed. Inside the maintenance window, the restore records each feed sequence before replay. After reconciliation, it sets each sequence back to at least that value and rewinds every peer's `memorySeq` and `catalogSeqs` to `0`. Brain cursors and snapshot checksums are left alone. The next sync replays each peer's streams through the idempotent last-writer-wins apply paths. A sync already in flight during the restore does not save its pre-restore cursor positions. Dry-run and failed restores change neither cursors nor sequences.On schema-reconciliation failure, restart PortOS to retry its schema upgrades and pending migrations. If recovery still fails, inspect the server logs and repair the database before continuing to use affected features. Reconciliation can partially apply upgrades; it is separate from the completed replay transaction.diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.jsindex 79d7b3b009..c32031594e 100644--- a/server/services/backup.db.test.js+++ b/server/services/backup.db.test.js@@ -1,5 +1,5 @@/** Real clean-dump restore regressions. Only guarded test databases. */-import { afterAll, describe, expect, it } from 'vitest';+import { afterAll, describe, expect, it, vi } from 'vitest';import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -9,6 +9,16 @@ import { requireDbOrSkip } from '../lib/dbTestGate.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';import { runDbMigrations } from '../scripts/run-db-migrations.js';import { listFolders } from './writersRoom/db.js';+import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';+import { rewindPostgresSyncCursors } from './syncOrchestrator.js';++// The real rewind rewrites this install's data/instances_sync_cursors.json.+vi.mock('./syncOrchestrator.js', () => ({ rewindPostgresSyncCursors: vi.fn(async () => 0) }));++const feedSequenceValues = async () => Object.fromEntries((await query(+ 'SELECT sequencename, last_value::text AS v FROM pg_sequences WHERE sequencename = ANY($1::text[])',+ [syncFeedTables.map(syncFeedSequenceName)],+)).rows.map(({ sequencename, v }) => [sequencename, v]));const health = await checkHealth();const ready = requireDbOrSkip('services/backup.db.test',@@ -75,7 +85,17 @@ describe.skipIf(!ready)('restore older database schema', () => {// A simpler approved additive table holds post-snapshot rows to prove a// full replacement, independently of Beeper's account/conversation graph.await query("INSERT INTO app_quality_measurements VALUES ('restore-probe', 'test', 'agent', NOW(), '{}')");+ // Feed positions handed out after the dump must never be reissued (#8710).+ await query("SELECT nextval('memories_sync_feed_seq') FROM generate_series(1, 5)");+ const feedBefore = await feedSequenceValues();expect(await restore()).toMatchObject({ status: 'ok', dryRun: false });+ expect(rewindPostgresSyncCursors).toHaveBeenCalledOnce();+ const feedAfter = await feedSequenceValues();+ for (const [name, value] of Object.entries(feedBefore)) {+ if (value !== null) expect(BigInt(feedAfter[name])).toBeGreaterThanOrEqual(BigInt(value));+ }+ const next = (await query("SELECT nextval('memories_sync_feed_seq')::text AS v")).rows[0].v;+ expect(BigInt(next)).toBeGreaterThan(BigInt(feedBefore.memories_sync_feed_seq));expect(await listFolders()).toContainEqual(folder);expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Snapshot person' }]);expect((await query("SELECT id FROM tribe_people WHERE id = '00000000-0000-4000-8000-000000000863'")).rowCount).toBe(0);@@ -94,7 +114,9 @@ describe.skipIf(!ready)('restore older database schema', () => {await writeFile(join(invalidDir, 'portos-db.sql'), `${await readFile(dumpPath, 'utf8')}\nTHIS IS INVALID SQL;\n`);await query("UPDATE tribe_people SET name = 'Must survive failure' WHERE id = $1", [personId]);const before = (await query("SELECT oid FROM pg_constraint WHERE conrelid = 'beeper_participants'::regclass ORDER BY oid")).rows;+ const rewindsBefore = rewindPostgresSyncCursors.mock.calls.length;expect(await restore(false, 'invalid-sql')).toMatchObject({ status: 'failed', reason: 'restore_error' });+ expect(rewindPostgresSyncCursors).toHaveBeenCalledTimes(rewindsBefore);expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Must survive failure' }]);expect((await query("SELECT oid FROM pg_constraint WHERE conrelid = 'beeper_participants'::regclass ORDER BY oid")).rows).toEqual(before);// The maintenance gate must have released on the replay error.diff --git a/server/services/backup.js b/server/services/backup.jsindex c3f87f1457..4b9645fc26 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -19,6 +19,7 @@ import { createLineReader } from '../lib/streamLines.js';import { getEvent } from './eventScheduler.js';import { checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';+import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';import { getBackendName } from './memoryBackend.js';import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';@@ -1485,7 +1486,9 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub* { status: 'ok', dryRun, sizeBytes, tableCount } (dry-run or applied)* { status: 'skipped', reason: 'no_dump' } (no sql file in snapshot)* { status: 'skipped', reason: 'not_configured' } (real restore, PG unreachable)- * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation', error? }+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation'|'restore_sync_resync', error? }+ * A successful real restore also carries `syncCursorsRewound` (peer count);+ * see resyncFederationAfterRestore.* @param {string} destPath - Backup destination root* @param {string} snapshotId* @param {{dryRun?: boolean}} [options]@@ -1546,6 +1549,8 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, souif (dryRun) return { status: 'ok', dryRun: true, sizeBytes: info.size, tableCount };return withDatabaseMaintenance(async () => {+ // Read before the replay rewinds them to the dump's values.+ const feedPositions = await captureSyncFeedPositions();const pgHost = process.env.PGHOST || 'localhost';const pgPort = process.env.PGPORT || '5432';const pgDb = process.env.PGDATABASE || 'portos';@@ -1615,10 +1620,67 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, souerror: 'The database dump was applied, but schema recovery is incomplete. The restore was not rolled back. Restart PortOS to retry schema recovery; if it still fails, inspect the server logs and repair the database before continuing.',};}- return replay;+ // Still inside maintenance, so no sync apply or feed write can interleave+ // between the restored rows and the federation repair.+ const resync = await resyncFederationAfterRestore(feedPositions).then(+ (syncCursorsRewound) => ({ syncCursorsRewound }),+ (err) => ({ err }),+ );+ if (resync.err) {+ console.error(`❌ DB restore federation resync failed: ${resync.err.message}`);+ return {+ status: 'failed',+ reason: 'restore_sync_resync',+ error: 'The database dump was applied, but peer sync could not be reset. Federated memories and Catalog records pulled after this snapshot may stay missing until the restore is repeated.',+ };+ }+ return { ...replay, syncCursorsRewound: resync.syncCursorsRewound };});}+// Feed sequences present before the replay (a pre-#8315 install has none).+// pg_sequences reports a NULL last_value for a never-drawn sequence, which+// holds no position worth preserving.+async function captureSyncFeedPositions() {+ const { rows } = await query(+ `SELECT sequencename, last_value::text AS last_value FROM pg_sequences+ WHERE schemaname = current_schema() AND sequencename = ANY($1::text[]) AND last_value IS NOT NULL`,+ [syncFeedTables.map(syncFeedSequenceName)],+ );+ return rows;+}++/**+ * Repair both directions of peer sync after a dump replay (#8710).+ *+ * Outbound: the dump `setval`s each feed sequence back to the dump's maximum,+ * so new rows would reuse positions peers already passed and never be pulled.+ * Floor every sequence at its pre-restore value so post-restore positions land+ * above any cursor a peer holds.+ *+ * Inbound: our per-peer memory/Catalog cursors still point past rows the+ * restore discarded. Rewind them so the next sync replays each peer's streams+ * through the idempotent LWW / ON CONFLICT apply paths.+ * @param {Array<{sequencename: string, last_value: string}>} feedPositions+ * @returns {Promise<number>} peers whose cursors were rewound+ */+async function resyncFederationAfterRestore(feedPositions) {+ if (feedPositions.length) {+ // GREATEST ignores the NULL of a sequence the dump left undrawn.+ await query(+ `SELECT setval(format('%I', s.sequencename)::regclass, GREATEST(c.captured::bigint, s.last_value))+ FROM pg_sequences s+ JOIN unnest($1::text[], $2::text[]) AS c(name, captured) ON c.name = s.sequencename+ WHERE s.schemaname = current_schema()`,+ [feedPositions.map((p) => p.sequencename), feedPositions.map((p) => p.last_value)],+ );+ }+ const { rewindPostgresSyncCursors } = await import('./syncOrchestrator.js');+ const peers = await rewindPostgresSyncCursors();+ console.log(`🔄 DB restore: floored ${feedPositions.length} sync feed sequences, rewound memory/Catalog cursors for ${peers} peers`);+ return peers;+}+/*** Get backup state with process-local failure and running projections.*/diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex f5622a1eec..36d4d67167 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -65,6 +65,11 @@ vi.mock('./backupDatabaseReset.js', () => ({getDatabaseResetPlan: async () => ({ preflight: 'SELECT 1', reset: 'RESET_APPROVED_SCHEMA' }),}));import { runDbMigrations } from '../scripts/run-db-migrations.js';+// restorePostgres lazily imports the orchestrator to rewind peer cursors (#8710).+vi.mock('./syncOrchestrator.js', () => ({+ rewindPostgresSyncCursors: vi.fn().mockResolvedValue(2),+}));+import { rewindPostgresSyncCursors } from './syncOrchestrator.js';// Mock the memory-backend resolver so dumpPostgres can tell whether Postgres is// the ACTIVE backend (explicit or auto-detected) when the DB is unreachable.@@ -1168,7 +1173,7 @@ describe('restorePostgres', () => {});try {const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });- expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 1 });+ expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 1, syncCursorsRewound: 2 });const [bin, args, opts] = spawn.mock.calls[0];expect(bin).toBe('psql');expect(args).toEqual(expect.arrayContaining(['-v', 'ON_ERROR_STOP=1', '--single-transaction', '--echo-all', '-f']));@@ -1246,6 +1251,62 @@ describe('restorePostgres', () => {expect(result.error).toContain('not rolled back');expect(result.error).toContain('Restart PortOS');if (phase === 'schema') expect(runDbMigrations).not.toHaveBeenCalled();+ expect(rewindPostgresSyncCursors).not.toHaveBeenCalled();+ });++ // #8710: a restore must not leave peers skipping rows in either direction.+ describe('federation resync', () => {+ const setvalCalls = () => query.mock.calls.filter(([sql]) => sql.includes('setval'));+ const captureCalls = () => query.mock.calls.filter(([sql]) => sql.includes('FROM pg_sequences') && !sql.includes('setval'));+ beforeEach(() => {+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });+ mockLegacyDumpRead();+ query.mockImplementation(async (sql) => (sql.includes('FROM pg_sequences') && !sql.includes('setval')+ ? { rows: [{ sequencename: 'memories_sync_feed_seq', last_value: '1000000000000500' }] }+ : { rows: [] }));+ });+ afterEach(() => query.mockReset().mockResolvedValue({ rows: [] }));++ const runRestore = async ({ exitCode = 0 } = {}) => {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });+ await flush();+ proc.emit('close', exitCode);+ return pending;+ };++ it('floors feed sequences at their pre-replay value and rewinds peer cursors after reconciliation', async () => {+ const result = await runRestore();+ expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 1, syncCursorsRewound: 2 });+ // Captured inside maintenance, before psql replays the dump.+ expect(captureCalls()).toHaveLength(1);+ expect(captureCalls()[0][1][0]).toContain('catalog_ingredients_sync_feed_seq');+ expect(query.mock.invocationCallOrder.at(-2)).toBeLessThan(spawn.mock.invocationCallOrder[0]);+ // Floored after schema recovery (which recreates missing sequences).+ expect(setvalCalls()).toHaveLength(1);+ expect(setvalCalls()[0][0]).toContain('GREATEST');+ expect(setvalCalls()[0][1]).toEqual([['memories_sync_feed_seq'], ['1000000000000500']]);+ expect(query.mock.invocationCallOrder.at(-1)).toBeGreaterThan(runDbMigrations.mock.invocationCallOrder[0]);+ expect(rewindPostgresSyncCursors).toHaveBeenCalledOnce();+ });++ it('changes neither sequences nor cursors on dry-run, replay failure, or reconciliation failure', async () => {+ expect(await restorePostgres('/dest', 'snap-1', { dryRun: true })).toMatchObject({ status: 'ok', dryRun: true });+ expect(await runRestore({ exitCode: 1 })).toMatchObject({ status: 'failed', reason: 'restore_error' });+ spawn.mockClear();+ runDbMigrations.mockRejectedValueOnce(new Error('upgrade failed'));+ expect(await runRestore()).toMatchObject({ status: 'failed', reason: 'restore_schema_reconciliation' });+ expect(setvalCalls()).toHaveLength(0);+ expect(rewindPostgresSyncCursors).not.toHaveBeenCalled();+ });++ it('reports an applied dump whose peer resync failed', async () => {+ rewindPostgresSyncCursors.mockRejectedValueOnce(new Error('disk full'));+ const result = await runRestore();+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_sync_resync' });+ expect(result.error).toContain('dump was applied');+ });});// Manifest SHA-256 verification (#980). The dump is hashed in generateManifestdiff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 729167dc11..f5c32423f9 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -93,6 +93,31 @@ async function withCursors(fn) {});}+// Bumped by every rewind. A sync cycle that read its cursors under an older+// generation pulled against the pre-restore database, so its advanced+// memory/Catalog cursors must not overwrite the rewind.+let postgresCursorGeneration = 0;++/**+ * Rewind every peer's PostgreSQL delta cursors (memory + Catalog) to the start+ * after a database restore discarded rows those cursors had already passed+ * (#8710). The next sync replays each peer's streams through the idempotent+ * LWW / ON CONFLICT apply paths. Only these two streams have no reconcile+ * to fall back on; brain cursors and snapshot checksums are left alone.+ * @returns {Promise<number>} peers rewound+ */+export async function rewindPostgresSyncCursors() {+ return withCursors((cursors) => {+ postgresCursorGeneration += 1;+ const peers = Object.values(cursors).filter(isPlainObjectShallow);+ for (const cursor of peers) {+ cursor.memorySeq = '0';+ cursor.catalogSeqs = Object.fromEntries(CATALOG_CURSOR_KINDS.map((kind) => [kind, '0']));+ }+ return peers.length;+ });+}+// --- Peer fetch helper ---// Every outbound hop goes through `peerFetch` so it carries@@ -812,7 +837,9 @@ export async function syncWithPeer(peer, { logStart = true, onCategoryFailure, p// Read cursor snapshot outside lock so network I/O doesn't block other peers// Also detect and reset stale cursors (e.g. peer DB was rebuilt)+ let cursorGeneration;const cursor = await readCursors((cursors) => {+ cursorGeneration = postgresCursorGeneration;const raw = { ...(cursors[peerId] || {}) };return detectCursorReset(raw, peer);});@@ -905,11 +932,14 @@ export async function syncWithPeer(peer, { logStart = true, onCategoryFailure, pcursors[peerId].brainChecksumTypes = brainResult.brainChecksumTypes;}}- if (memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;+ // A DB restore rewound the Postgres cursors mid-cycle: this cycle's+ // positions describe rows the restore discarded, so keep the rewind.+ const postgresCursorsCurrent = cursorGeneration === postgresCursorGeneration;+ if (postgresCursorsCurrent && memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;// Persist the per-kind catalog cursor only when the drain wasn't blocked// by a schema gap — a blocked cycle leaves the prior cursor so we re-try// the same window after the sender upgrades (mirrors the snapshot path).- if (categories.catalog && !catalogResult.blockedBySchema && isPlainObjectShallow(catalogResult.catalogSeqs)) {+ if (postgresCursorsCurrent && categories.catalog && !catalogResult.blockedBySchema && isPlainObjectShallow(catalogResult.catalogSeqs)) {cursors[peerId].catalogSeqs = catalogResult.catalogSeqs;}if (!cursors[peerId].checksums) cursors[peerId].checksums = {};diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 66480c2c25..48348bd174 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -1696,4 +1696,54 @@ describe('syncOrchestrator', () => {expect(instanceEvents.removeListener).toHaveBeenCalledWith('peer:online', expect.any(Function));});});++ // #8710: a DB restore discards rows the memory/Catalog cursors already passed.+ describe('rewindPostgresSyncCursors', () => {+ const ZERO_CATALOG = { scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' };+ let store;+ beforeEach(() => {+ store = {+ 'peer-inst-1': {+ brainSeq: 42, memorySeq: '1000000000000050',+ catalogSeqs: { ...ZERO_CATALOG, ingredients: '1000000000000009' },+ checksums: { goals: 'g1' }, brainChecksum: 'b1', lastSyncAt: '2026-01-01T00:00:00.000Z',+ },+ 'peer-inst-2': { memorySeq: '1000000000000007' },+ };+ readJSONFile.mockImplementation(async () => structuredClone(store));+ atomicWrite.mockImplementation(async (path, payload) => {+ if (String(path).includes('instances_sync_cursors')) store = structuredClone(payload);+ });+ });++ it('zeroes memory and every Catalog kind for every peer, leaving brain and checksum state', async () => {+ const { rewindPostgresSyncCursors } = await import('./syncOrchestrator.js');+ expect(await rewindPostgresSyncCursors()).toBe(2);+ expect(store['peer-inst-1']).toEqual({+ brainSeq: 42, memorySeq: '0', catalogSeqs: ZERO_CATALOG,+ checksums: { goals: 'g1' }, brainChecksum: 'b1', lastSyncAt: '2026-01-01T00:00:00.000Z',+ });+ expect(store['peer-inst-2']).toEqual({ memorySeq: '0', catalogSeqs: ZERO_CATALOG });+ });++ it('keeps the rewind when a sync that read cursors before it finishes afterwards', async () => {+ const { rewindPostgresSyncCursors } = await import('./syncOrchestrator.js');+ const peer = { ...mockPeer, syncCategories: { memory: true } };+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/memory/sync')) {+ // The restore completes while this pull is on the wire.+ await rewindPostgresSyncCursors();+ return { ok: true, json: async () => ({ memories: [{ id: 'm1' }], maxSequence: '1000000000000060', hasMore: false }) };+ }+ return { ok: true, json: async () => ({}) };+ });+ applyMemoryChanges.mockResolvedValue({ inserted: 1, updated: 0 });++ await syncWithPeer(peer);++ expect(mockFetch.mock.calls.some(([url]) => url.includes('since=1000000000000050'))).toBe(true);+ expect(store['peer-inst-1'].memorySeq).toBe('0');+ expect(store['peer-inst-1'].catalogSeqs).toEqual(ZERO_CATALOG);+ });+ });});