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
fold the per-key envelope tests into the table-driven block they duplicated (#6844)
[._.]/ Adam Eivy9fd418df8bae
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex e110e4154f..0330d65efd 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -250,7 +250,7 @@ import {} from './peerSync.js';import { buildPushPayload } from './peerSyncPush.js';-import { ENVELOPE_EXTENSIONS } from './peerSyncShared.js';+import { ENVELOPE_EXTENSIONS, ENVELOPE_PENDING_KEYS } from './peerSyncShared.js';import { getPeers } from '../instances.js';import { getInstanceId } from '../instanceIdentity.js';import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';@@ -442,6 +442,40 @@ afterEach(async () => {}});+// A receiver whose strict schema predates `key`: the 400 Zod emits for an+// unrecognized envelope key.+const legacyRejectsKey = (key) => {+ const rejection = { ok: false, status: 400, json: async () => ({+ code: 'VALIDATION_ERROR',+ message: 'Validation failed',+ context: { details: [{ path: '', message: `Unrecognized key(s) in object: '${key}'` }] },+ }) };+ rejection.clone = () => rejection;+ return rejection;+};+const acceptsPush = (body = {}) => ({ ok: true, status: 200, json: async () => body });+// A legacy peer for `key`: rejects every push carrying it, accepts the+// stripped retry.+const mockPeerRejecting = (key) => {+ vi.mocked(peerFetch).mockImplementation(async (_url, init) => (+ key in JSON.parse(init.body) ? legacyRejectsKey(key) : acceptsPush()+ ));+};+// The default peer fixture carries no musicVideoProjects category; music-video+// pushes need this opt-in or peerHasCategory short-circuits them.+const enableMusicVideoPeer = () => {+ vi.mocked(getPeers).mockResolvedValue([{+ instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555,+ enabled: true, syncEnabled: true, directions: ['outbound', 'inbound'],+ syncCategories: { musicVideoProjects: true },+ }]);+};+const sampleOutline = (generatedAt = '2026-06-02T00:00:00Z') => ({+ schemaVersion: 1, status: 'complete', generatedAt,+ plotlines: [{ id: 'a', label: 'A', kind: 'main' }],+ scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],+});+describe('peerSync', () => {describe('PEER_SUBSCRIBABLE_KINDS', () => {it('lists every record kind handled by the peer-sync pipeline', () => {@@ -2104,30 +2138,6 @@ describe('peerSync', () => {expect(peerFetch).toHaveBeenCalledTimes(1);});- it('withholds lastPushedHash when the receiver reports reviewSyncPending (so the next cycle re-sends)', async () => {- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(getReview).mockResolvedValue({- schemaVersion: 1,- comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],- });- // Receiver merged the record but its review merge threw → reviewSyncPending.- vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ reviewSyncPending: true }) });- const sub = await subscribePeer(- { peerId: 'peer-a', recordKind: 'series', recordId: 's1' },- { adoptedFromReverse: true },- );- const r = await pushRecordToPeer(sub);- expect(r.pushed).toBe(true);- // Hash withheld → a subsequent push with identical content is NOT a no-op.- const refreshed = await findPeerSubscription('peer-a', 'series', 's1');- expect(refreshed.lastPushedHash).toBeFalsy();- vi.mocked(peerFetch).mockClear();- vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });- const second = await pushRecordToPeer(refreshed);- expect(second.reason).not.toBe('unchanged');- expect(peerFetch).toHaveBeenCalledTimes(1);- });-it('bundles the linked media collection with a universe push so collection-only edits propagate', async () => {// Regression: collection items[] adds emit recordEvents.updated('universe', id)// but the universe record content itself doesn't change, so the@@ -2549,14 +2559,6 @@ describe('peerSync', () => {});// --- Music Video project media federation (#1772) ---- const enableMusicVideoPeer = () => {- vi.mocked(getPeers).mockResolvedValue([{- instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555,- enabled: true, syncEnabled: true, directions: ['outbound', 'inbound'],- syncCategories: { musicVideoProjects: true },- }]);- };-it('bundles uploaded audio + rendered scene clips + reference-frame stills for a music video project push', async () => {// #1772: the project record federated but shipped an empty manifest, so a// selectively-subscribed peer never received the referenced media. Audio@@ -3077,21 +3079,6 @@ describe('peerSync', () => {expect(mergeTracksFromSync).not.toHaveBeenCalled();});- it('signals trackSyncPending when the bundled linkedTrack merge fails (#1858)', async () => {- // The linked track has no independent reconciliation cycle for a- // musicVideoProjects-only subscriber, so a swallowed failure must surface- // a pending flag that makes the sender withhold its hash and re-send.- vi.mocked(mergeTracksFromSync).mockRejectedValueOnce(new Error('disk full'));- const res = await applyIncomingPush({- kind: 'musicVideoProject',- record: { id: 'mv-9', trackId: 'track-9', deleted: false, deletedAt: null },- linkedTrack: { id: 'track-9', audioFilename: 'linked.mp3' },- assetManifest: [],- sourceInstanceId: 'peer-a',- });- expect(res.trackSyncPending).toBe(true);- });-it('routes a bundled manuscriptReview through mergeReviewFromSync on a series push', async () => {const manuscriptReview = {schemaVersion: 1,@@ -3144,27 +3131,6 @@ describe('peerSync', () => {expect(mergeReviewFromSync).not.toHaveBeenCalled();});- it('returns reviewSyncPending when the bundled review merge throws (so the sender retries)', async () => {- vi.mocked(mergeReviewFromSync).mockRejectedValueOnce(new Error('disk full'));- const res = await applyIncomingPush({- kind: 'series',- record: { id: 's1', name: 'S', deleted: false, deletedAt: null },- issues: [],- manuscriptReview: { schemaVersion: 1, comments: [{ id: 'mrc-1', problem: 'x', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }] },- assetManifest: [],- sourceInstanceId: 'peer-a',- });- // The series/issues merge still succeeded — the push isn't failed — but- // the sender is told to withhold its hash and retry the review.- expect(res.reviewSyncPending).toBe(true);- });-- const sampleOutline = (generatedAt = '2026-06-02T00:00:00Z') => ({- schemaVersion: 1, status: 'complete', generatedAt,- plotlines: [{ id: 'a', label: 'A', kind: 'main' }],- scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],- });-it('routes a bundled reverseOutline through mergeOutlineFromSync on a series push', async () => {const reverseOutline = sampleOutline();await applyIncomingPush({@@ -3214,21 +3180,6 @@ describe('peerSync', () => {expect(mergeOutlineFromSync).not.toHaveBeenCalled();});- it('returns outlineSyncPending when the bundled outline merge throws (so the sender retries)', async () => {- vi.mocked(mergeOutlineFromSync).mockRejectedValueOnce(new Error('disk full'));- const res = await applyIncomingPush({- kind: 'series',- record: { id: 's1', name: 'S', deleted: false, deletedAt: null },- issues: [],- reverseOutline: sampleOutline(),- assetManifest: [],- sourceInstanceId: 'peer-a',- });- // Series/issues merge still succeeded — the outline has no independent- // reconciliation path, so the sender withholds its hash and retries.- expect(res.outlineSyncPending).toBe(true);- });-it('refuses to merge linkedCollection when the incoming record is a tombstone', async () => {// Defense in depth: the sender's buildPushPayload already skips the// bundle for tombstones, but a buggy or malicious peer could send@@ -4220,225 +4171,13 @@ describe('peerSync', () => {expect(cleared.lastPushedHash).toBeTruthy(); // succeeded → hash recorded});- it('falls back without portosMeta when the peer is on a pre-version-gate PortOS (strict schema 400)', async () => {- // Pre-version-gate receiver: its `peerSyncPushSchema` is `.strict()`- // and has no `portosMeta` field, so it rejects our envelope as a- // generic VALIDATION_ERROR before any schema-gate logic. The sender- // must detect that specific shape, strip portosMeta, and retry —- // otherwise universe/series pushes to not-yet-upgraded peers fail- // hard and silently during a federation rollout.- vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });- const firstCallBody = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'portosMeta'" }] },- }) };- firstCallBody.clone = () => firstCallBody;- const retryBody = { ok: true, status: 200, json: async () => ({}) };- vi.mocked(peerFetch)- .mockResolvedValueOnce(firstCallBody)- .mockResolvedValueOnce(retryBody);- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',- }, { adoptedFromReverse: true });- const result = await pushRecordToPeer(sub);- expect(result.pushed).toBe(true);- // Two network calls: the failed validating one + the retry without portosMeta.- const calls = vi.mocked(peerFetch).mock.calls;- expect(calls.length).toBe(2);- const firstPayload = JSON.parse(calls[0][1].body);- const retryPayload = JSON.parse(calls[1][1].body);- expect(firstPayload.portosMeta).toBeDefined();- expect(retryPayload.portosMeta).toBeUndefined();- // Record content is preserved across the retry.- expect(retryPayload.record.id).toBe('u1');- expect(retryPayload.sourceInstanceId).toBe(firstPayload.sourceInstanceId);- });-- it('falls back without catalogBundle when an older peer rejects the new key, keeping portosMeta', async () => {- // A peer that supports portosMeta but predates catalog federation- // rejects the new `catalogBundle` key with a strict VALIDATION_ERROR.- // The sender must strip ONLY catalogBundle (not portosMeta, which the- // peer supports) and retry, so the universe push still lands — the- // receiver re-derives the catalog enrichments from the embedded canon.- vi.mocked(getBackendName).mockReturnValue('postgres');- vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });- vi.mocked(getCatalogBundleForRef).mockResolvedValue({- ingredients: [{ id: 'cat-chr-1', type: 'character', name: 'Hero', updatedAt: '2026-01-02T00:00:00Z' }],- refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' }],- });- const firstCallBody = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'catalogBundle'" }] },- }) };- firstCallBody.clone = () => firstCallBody;- const retryBody = { ok: true, status: 200, json: async () => ({}) };- vi.mocked(peerFetch).mockResolvedValueOnce(firstCallBody).mockResolvedValueOnce(retryBody);- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',- }, { adoptedFromReverse: true });- const result = await pushRecordToPeer(sub);- expect(result.pushed).toBe(true);- const calls = vi.mocked(peerFetch).mock.calls;- expect(calls.length).toBe(2);- const firstPayload = JSON.parse(calls[0][1].body);- const retryPayload = JSON.parse(calls[1][1].body);- expect(firstPayload.catalogBundle).toBeDefined();- expect(retryPayload.catalogBundle).toBeUndefined();- // Surgical strip: portosMeta survives because the peer didn't reject it.- expect(retryPayload.portosMeta).toBeDefined();- expect(retryPayload.record.id).toBe('u1');- });-- it('falls back without manuscriptReview when a pre-feature peer rejects the new key, keeping series + issues', async () => {- // A pre-manuscript-review-sync peer's seriesPushSchema is still- // `.strict()` without `manuscriptReview`, so it 400-rejects a review-- // bearing series push. The sender must strip ONLY manuscriptReview and- // retry so the series + issues still land (the review reaches the peer- // once it upgrades). This is what makes the review's "degrades- // gracefully on older peers" contract hold.- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);- vi.mocked(getReview).mockResolvedValue({- schemaVersion: 1,- comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],- });- const firstCallBody = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'manuscriptReview'" }] },- }) };- firstCallBody.clone = () => firstCallBody;- const retryBody = { ok: true, status: 200, json: async () => ({}) };- vi.mocked(peerFetch).mockResolvedValueOnce(firstCallBody).mockResolvedValueOnce(retryBody);- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'series', recordId: 's1',- }, { adoptedFromReverse: true });- const result = await pushRecordToPeer(sub);- expect(result.pushed).toBe(true);- const calls = vi.mocked(peerFetch).mock.calls;- expect(calls.length).toBe(2);- const firstPayload = JSON.parse(calls[0][1].body);- const retryPayload = JSON.parse(calls[1][1].body);- expect(firstPayload.manuscriptReview).toBeDefined();- expect(retryPayload.manuscriptReview).toBeUndefined();- // Surgical strip: portosMeta survives, and the series + issues still land.- expect(retryPayload.portosMeta).toBeDefined();- expect(retryPayload.record.id).toBe('s1');- expect(retryPayload.issues).toHaveLength(1);- // Hash withheld so the review re-sends once the peer upgrades (the- // retry landed with the review stripped, so saving the full-payload- // hash would short-circuit the next push as 'unchanged').- const refreshed = await findPeerSubscription('peer-a', 'series', 's1');- expect(refreshed.lastPushedHash).toBeFalsy();- });-- it('falls back without reverseOutline when a pre-#1348 peer rejects the new key, keeping series + issues', async () => {- // Same graceful-degradation contract as the manuscriptReview strip above:- // a pre-#1348 peer's `.strict()` series schema 400-rejects the- // reverseOutline key, so the sender strips ONLY it and retries, then- // withholds the hash so the outline re-sends once the peer upgrades.- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);- vi.mocked(getStoredOutline).mockResolvedValue({- seriesId: 's1', schemaVersion: 1, status: 'complete', generatedAt: '2026-06-02T00:00:00Z',- plotlines: [{ id: 'a', label: 'A', kind: 'main', color: '#3b82f6' }],- scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],- });- const firstCallBody = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'reverseOutline'" }] },- }) };- firstCallBody.clone = () => firstCallBody;- const retryBody = { ok: true, status: 200, json: async () => ({}) };- vi.mocked(peerFetch).mockResolvedValueOnce(firstCallBody).mockResolvedValueOnce(retryBody);- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'series', recordId: 's1',- }, { adoptedFromReverse: true });- const result = await pushRecordToPeer(sub);- expect(result.pushed).toBe(true);- const calls = vi.mocked(peerFetch).mock.calls;- expect(calls.length).toBe(2);- const firstPayload = JSON.parse(calls[0][1].body);- const retryPayload = JSON.parse(calls[1][1].body);- expect(firstPayload.reverseOutline).toBeDefined();- expect(retryPayload.reverseOutline).toBeUndefined();- // Surgical strip: portosMeta + series + issues still land.- expect(retryPayload.portosMeta).toBeDefined();- expect(retryPayload.record.id).toBe('s1');- expect(retryPayload.issues).toHaveLength(1);- // Hash withheld so the outline re-sends once the peer upgrades.- const refreshed = await findPeerSubscription('peer-a', 'series', 's1');- expect(refreshed.lastPushedHash).toBeFalsy();- });-// #3928 — the legacy-stripped water-mark. Withholding `lastPushedHash`- // (the two tests above) is what keeps the stripped key deliverable, but- // on its own it made EVERY subsequent cycle re-run the 400 +- // stripped-retry pair forever. `lastPushedLegacyHash` records the full- // payload hash we delivered in stripped form so an unchanged record- // settles.- const legacyRejectsKey = (key) => {- const rejection = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: `Unrecognized key(s) in object: '${key}'` }] },- }) };- rejection.clone = () => rejection;- return rejection;- };- const mockLegacyReviewPeer = () => {- // A pre-feature peer: rejects `manuscriptReview` on every full push,- // accepts the stripped retry.- vi.mocked(peerFetch).mockImplementation(async (_url, init) => (- JSON.parse(init.body).manuscriptReview- ? legacyRejectsKey('manuscriptReview')- : { ok: true, status: 200, json: async () => ({}) }- ));- };-- it('records lastPushedLegacyHash when a stripped retry lands on a legacy peer (#3928)', async () => {- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);- vi.mocked(getReview).mockResolvedValue({- schemaVersion: 1,- comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],- });- mockLegacyReviewPeer();- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'series', recordId: 's1',- }, { adoptedFromReverse: true });- const result = await pushRecordToPeer(sub);- expect(result.pushed).toBe(true);- const refreshed = await findPeerSubscription('peer-a', 'series', 's1');- // The review is still owed (hash withheld) but the delivered content- // is water-marked so the next cycle can settle.- expect(refreshed.lastPushedHash).toBeFalsy();- expect(refreshed.lastPushedLegacyHash).toBe(result.hash);- });-- it('short-circuits the next cycle as unchanged instead of re-running the 400 + retry pair (#3928)', async () => {- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);- vi.mocked(getReview).mockResolvedValue({- schemaVersion: 1,- comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],- });- mockLegacyReviewPeer();- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'series', recordId: 's1',- }, { adoptedFromReverse: true });- await pushRecordToPeer(sub);- expect(vi.mocked(peerFetch).mock.calls.length).toBe(2); // 400 + stripped retry- // Next sync cycle, same content: zero HTTP.- const second = await pushRecordToPeer(await findPeerSubscription('peer-a', 'series', 's1'));- expect(second.pushed).toBe(false);- expect(second.reason).toBe('unchanged-legacy-stripped');- expect(vi.mocked(peerFetch).mock.calls.length).toBe(2);- });-+ // after a strip (pinned per row in 'envelope extensions (#6844)') is what+ // keeps the stripped key deliverable, but on its own it made EVERY+ // subsequent cycle re-run the 400 + stripped-retry pair forever.+ // `lastPushedLegacyHash` records the full payload hash we delivered in+ // stripped form so an unchanged record settles; these two cases cover+ // what moves it again.it('re-pushes when the bundled review actually changes after a stripped push (#3928)', async () => {vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);@@ -4446,7 +4185,7 @@ describe('peerSync', () => {schemaVersion: 1,comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],});- mockLegacyReviewPeer();+ mockPeerRejecting('manuscriptReview');const sub = await subscribePeer({peerId: 'peer-a', recordKind: 'series', recordId: 's1',}, { adoptedFromReverse: true });@@ -4473,7 +4212,7 @@ describe('peerSync', () => {schemaVersion: 1,comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],});- mockLegacyReviewPeer();+ mockPeerRejecting('manuscriptReview');const sub = await subscribePeer({peerId: 'peer-a', recordKind: 'series', recordId: 's1',}, { adoptedFromReverse: true });@@ -4494,27 +4233,6 @@ describe('peerSync', () => {expect(refreshed.lastPushedLegacyHash).toBeFalsy();});- it('does NOT record a legacy hash when the RECEIVER reported the bundled merge failed (#3928)', async () => {- // `reviewSyncPending` from the receiver is a transient merge failure,- // not a version gap — the next cycle must genuinely re-push.- vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });- vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);- vi.mocked(getReview).mockResolvedValue({- schemaVersion: 1,- comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],- });- vi.mocked(peerFetch).mockResolvedValue({ ok: true, status: 200, json: async () => ({ reviewSyncPending: true }) });- const sub = await subscribePeer({- peerId: 'peer-a', recordKind: 'series', recordId: 's1',- }, { adoptedFromReverse: true });- await pushRecordToPeer(sub);- const refreshed = await findPeerSubscription('peer-a', 'series', 's1');- expect(refreshed.lastPushedHash).toBeFalsy();- expect(refreshed.lastPushedLegacyHash).toBeFalsy();- const second = await pushRecordToPeer(refreshed);- expect(second.pushed).toBe(true);- });-it('does NOT retry on a 400 whose validation error is unrelated to portosMeta', async () => {// The retry is keyed on the `portosMeta` mention in the validation// details — any other 400 (oversized field, unknown record key, etc.)@@ -4622,9 +4340,6 @@ describe('peerSync', () => {});});- // -------------------------------------------------------------------------- // mediaCollection push + receiver- // -------------------------------------------------------------------------// -------------------------------------------------------------------------// #6844 — the optional envelope keys share ONE strip / pending / withhold// lifecycle, declared once in ENVELOPE_EXTENSIONS. Every case below is driven@@ -4633,25 +4348,8 @@ describe('peerSync', () => {describe('envelope extensions (#6844)', () => {const SIDECARS = ENVELOPE_EXTENSIONS.filter((e) => e.pendingKey);const SELF_RECONCILING = ENVELOPE_EXTENSIONS.filter((e) => !e.pendingKey);- const PENDING_KEYS = SIDECARS.map((e) => e.pendingKey);+ const PENDING_KEYS = Object.values(ENVELOPE_PENDING_KEYS);- const legacyRejects = (key) => {- const rejection = { ok: false, status: 400, json: async () => ({- code: 'VALIDATION_ERROR',- message: 'Validation failed',- context: { details: [{ path: '', message: `Unrecognized key(s) in object: '${key}'` }] },- }) };- rejection.clone = () => rejection;- return rejection;- };- const accepts = (body = {}) => ({ ok: true, status: 200, json: async () => body });- // A peer whose strict schema predates `key`: rejects every push carrying- // it, accepts the stripped retry.- const mockPeerRejecting = (key) => {- vi.mocked(peerFetch).mockImplementation(async (_url, init) => (- key in JSON.parse(init.body) ? legacyRejects(key) : accepts()- ));- };const armSeries = () => {vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });vi.mocked(listIssuesForSeries).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);@@ -4699,12 +4397,7 @@ describe('peerSync', () => {linkedTrack: {recordKind: 'musicVideoProject', recordId: 'mv-1',arm: async () => {- vi.mocked(getPeers).mockResolvedValue([{- instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555,- enabled: true, syncEnabled: true, directions: ['outbound', 'inbound'],- syncCategories: { musicVideoProjects: true },- }]);- await writeFile(join(PATHS.music, 'linked.mp3'), Buffer.from('linked track audio'));+ enableMusicVideoPeer();vi.mocked(getTrack).mockResolvedValue({id: 'track-1', title: 'Anthem', audioFilename: 'linked.mp3',updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,@@ -4727,14 +4420,14 @@ describe('peerSync', () => {it('pins the wire vocabulary older peers depend on', () => {// Older senders and receivers read exactly these names off the wire — a// rename here is a cross-version break, not a refactor.- expect(ENVELOPE_EXTENSIONS.map(({ key, pendingKey }) => [key, pendingKey])).toEqual([+ const byKey = (rows) => [...rows].sort((a, b) => a[0].localeCompare(b[0]));+ expect(byKey(ENVELOPE_EXTENSIONS.map(({ key, pendingKey }) => [key, pendingKey]))).toEqual(byKey([['portosMeta', null],['catalogBundle', null],['manuscriptReview', 'reviewSyncPending'],['reverseOutline', 'outlineSyncPending'],['linkedTrack', 'trackSyncPending'],- ]);- expect(Object.isFrozen(ENVELOPE_EXTENSIONS)).toBe(true);+ ]));});it('has a sender-side carrier for every table row (a new extension must be exercised here)', () => {@@ -4753,16 +4446,39 @@ describe('peerSync', () => {const first = payloadOf(calls[0]);const retry = payloadOf(calls[1]);expect(first[key]).toBeDefined();- expect(retry[key]).toBeUndefined();- // Surgical: every other extension the first push carried survives, so- // a peer that supports portosMeta but not this key keeps its handshake.- for (const other of ENVELOPE_EXTENSIONS) {- if (other.key !== key && other.key in first) expect(retry[other.key]).toEqual(first[other.key]);- }- expect(retry.record.id).toBe(carrier.recordId);+ // Surgical: the retry is the first push minus exactly this key — the+ // record, bundled issues, sourceInstanceId and every other extension+ // survive, so a peer that supports portosMeta but not this key keeps+ // its version-gate handshake.+ const rest = { ...first };+ delete rest[key];+ expect(retry).toEqual(rest);});});+ it('drops every key a single 400 names in one retry (Zod lists all unrecognized keys in one issue)', async () => {+ const carrier = CARRIERS.catalogBundle; // carries portosMeta AND catalogBundle+ await carrier.arm();+ const rejectsBoth = legacyRejectsKey('portosMeta');+ rejectsBoth.json = async () => ({+ code: 'VALIDATION_ERROR',+ message: 'Validation failed',+ context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'portosMeta', 'catalogBundle'" }] },+ });+ vi.mocked(peerFetch).mockResolvedValueOnce(rejectsBoth).mockResolvedValueOnce(acceptsPush());+ const result = await pushRecordToPeer(await claim(carrier));+ expect(result.pushed).toBe(true);+ const calls = vi.mocked(peerFetch).mock.calls;+ expect(calls).toHaveLength(2);+ const first = payloadOf(calls[0]);+ const retry = payloadOf(calls[1]);+ expect(first.portosMeta).toBeDefined();+ expect(first.catalogBundle).toBeDefined();+ expect(retry.portosMeta).toBeUndefined();+ expect(retry.catalogBundle).toBeUndefined();+ expect(retry.record.id).toBe(carrier.recordId);+ });+describe.each(SIDECARS)('$key — no independent cycle ($pendingKey)', ({ key, pendingKey }) => {it('withholds lastPushedHash and water-marks lastPushedLegacyHash after a stripped push (#3928)', async () => {const carrier = CARRIERS[key];@@ -4782,7 +4498,7 @@ describe('peerSync', () => {it('withholds the hash WITHOUT a legacy water-mark when the receiver reports it pending (transient merge failure)', async () => {const carrier = CARRIERS[key];await carrier.arm();- vi.mocked(peerFetch).mockResolvedValue(accepts({ [pendingKey]: true }));+ vi.mocked(peerFetch).mockResolvedValue(acceptsPush({ [pendingKey]: true }));const result = await pushRecordToPeer(await claim(carrier));expect(result.pushed).toBe(true);expect(vi.mocked(peerFetch).mock.calls).toHaveLength(1);@@ -4791,7 +4507,7 @@ describe('peerSync', () => {expect(refreshed.lastPushedLegacyHash).toBeFalsy();// The next cycle must genuinely re-push, not short-circuit.vi.mocked(peerFetch).mockClear();- vi.mocked(peerFetch).mockResolvedValue(accepts());+ vi.mocked(peerFetch).mockResolvedValue(acceptsPush());const second = await pushRecordToPeer(refreshed);expect(second.pushed).toBe(true);expect(vi.mocked(peerFetch).mock.calls).toHaveLength(1);@@ -4849,11 +4565,7 @@ describe('peerSync', () => {kind: 'series',record: { id: 's1', name: 'S', deleted: false, deletedAt: null },issues: [],- reverseOutline: {- schemaVersion: 1, status: 'complete', generatedAt: '2026-06-02T00:00:00Z',- plotlines: [{ id: 'a', label: 'A', kind: 'main' }],- scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],- },+ reverseOutline: sampleOutline(),assetManifest: [],sourceInstanceId: 'peer-a',}),@@ -4888,6 +4600,9 @@ describe('peerSync', () => {});});+ // -------------------------------------------------------------------------+ // mediaCollection push + receiver+ // -------------------------------------------------------------------------describe('collectCollectionAssetReferences', () => {it('maps items to image/video refs with an empty directImageRefFilenames', () => {const refs = collectCollectionAssetReferences({ items: [