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
collapse peer-sync's six per-kind ladders into one record-kind table (#6843)
[._.]/ Adam Eivy9f9a2b622f6f
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 624082bb8b..7ba976b641 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -80,10 +80,12 @@ export {export {buildAssetManifest,collectCollectionAssetReferences,- assetIntegrityForRecord,- assetShaListForRecord,diffAssetManifestAgainstLocal,} from './peerSyncAssets.js';+export {+ assetIntegrityForRecord,+ assetShaListForRecord,+} from './recordKinds.js';export { pushRecordToPeer } from './peerSyncPush.js';export { applyIncomingPush } from './peerSyncReceive.js';export {diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 5106929d8a..5f75bf068f 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -144,14 +144,24 @@ vi.mock('../musicVideo/projects.js', async () => ({vi.mock('../authors/index.js', async (importOriginal) => ({...(await importOriginal()),listAuthors: vi.fn().mockResolvedValue([]),+ // #6843: getAuthor/mergeAuthorsFromSync stubbed (not spread from the real+ // module) so the all-kinds parity suite can drive/assert push+receive for+ // this kind the same way universe/series/etc. already are, without hitting+ // the real file-backed store.+ getAuthor: vi.fn(),+ mergeAuthorsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));vi.mock('../creativeDirector/local.js', async (importOriginal) => ({...(await importOriginal()),listProjects: vi.fn().mockResolvedValue([]),+ getProject: vi.fn(),+ mergeProjectsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));vi.mock('../moodBoard/index.js', async (importOriginal) => ({...(await importOriginal()),listBoards: vi.fn().mockResolvedValue([]),+ getBoard: vi.fn(),+ mergeBoardsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));vi.mock('../fableLoom/index.js', () => ({getLoom: vi.fn(),@@ -163,6 +173,12 @@ vi.mock('../writersRoom/sync.js', async (importOriginal) => ({listWorksForSync: vi.fn().mockResolvedValue([]),listFoldersForSync: vi.fn().mockResolvedValue([]),listExercisesForSync: vi.fn().mockResolvedValue([]),+ getWorkForSync: vi.fn(),+ mergeWorksFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),+ getFolderForSync: vi.fn(),+ mergeFoldersFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),+ getExerciseForSync: vi.fn(),+ mergeExercisesFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));// #2686: commissionFeedback is a per-record store peerSync's getFullSyncCoverageForPeer// iterates via PEER_SUBSCRIBABLE_KINDS. Mock the lister so the zero-records@@ -170,10 +186,14 @@ vi.mock('../writersRoom/sync.js', async (importOriginal) => ({vi.mock('../creativeCommissions/feedbackStore.js', async (importOriginal) => ({...(await importOriginal()),listCommissionFeedbackForSync: vi.fn().mockResolvedValue([]),+ getCommissionFeedbackForSync: vi.fn(),+ mergeCommissionFeedbackFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));vi.mock('../creativeCommissions/store.js', async (importOriginal) => ({...(await importOriginal()),listCommissionsForSync: vi.fn().mockResolvedValue([]),+ getCommissionForSync: vi.fn(),+ mergeCommissionsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));vi.mock('../../lib/peerHttpClient.js', async () => ({@@ -229,6 +249,7 @@ import {__drainForTests,} from './peerSync.js';+import { buildPushPayload } from './peerSyncPush.js';import { getPeers } from '../instances.js';import { getInstanceId } from '../instanceIdentity.js';import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';@@ -253,13 +274,23 @@ import {} from '../musicVideo/projects.js';// #1964 — list backends the full-sync coverage path reads; imported so the// beforeEach can reset each to an empty fixture (see the partial mocks above).-import { listAuthors } from '../authors/index.js';-import { listProjects as listCreativeDirectorProjects } from '../creativeDirector/local.js';-import { listBoards } from '../moodBoard/index.js';+// get*/merge*FromSync for these 8 kinds (#6843) drive the all-kinds parity+// suite below the same way the fully-mocked kinds above already do.+import { listAuthors, getAuthor, mergeAuthorsFromSync } from '../authors/index.js';+import {+ listProjects as listCreativeDirectorProjects,+ getProject as getCreativeDirectorProject,+ mergeProjectsFromSync as mergeCreativeDirectorProjectsFromSync,+} from '../creativeDirector/local.js';+import { listBoards, getBoard, mergeBoardsFromSync } from '../moodBoard/index.js';import { getLoom, listLooms, mergeLoomsFromSync } from '../fableLoom/index.js';-import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';-import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';-import { listCommissionsForSync } from '../creativeCommissions/store.js';+import {+ listWorksForSync, getWorkForSync, mergeWorksFromSync,+ listFoldersForSync, getFolderForSync, mergeFoldersFromSync,+ listExercisesForSync, getExerciseForSync, mergeExercisesFromSync,+} from '../writersRoom/sync.js';+import { listCommissionFeedbackForSync, getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';+import { listCommissionsForSync, getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';@@ -2944,17 +2975,20 @@ describe('peerSync', () => {sourceInstanceId: 'peer-a',});+ // The record-kind table (#6843) passes senderSchemaVersions to every+ // merger uniformly (harmless for these three, which ignore it) — assert+ // via objectContaining rather than pinning its full shape.expect(mergeArtistsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'artist-1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);expect(mergeAlbumsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'album-1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);expect(mergeTracksFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'track-1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);});@@ -2999,9 +3033,13 @@ describe('peerSync', () => {assetManifest: [],sourceInstanceId: 'peer-a',});+ // The project's own merge goes through the record-kind table (#6843),+ // which passes senderSchemaVersions uniformly (harmless — ignored).+ // The linkedTrack merge is a hand-written hook that still calls with+ // exactly `{ source }`, unchanged.expect(mergeMusicVideoProjectsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'mv-1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);expect(mergeTracksFromSync).toHaveBeenCalledWith([linkedTrack],@@ -3231,9 +3269,11 @@ describe('peerSync', () => {assetManifest: [],sourceInstanceId: 'peer-a',});+ // Goes through the record-kind table (#6843), which passes+ // senderSchemaVersions uniformly (harmless for series — ignored).expect(mergeSeriesFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 's1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);expect(mergeIssuesFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'i1' })],@@ -3348,7 +3388,17 @@ describe('peerSync', () => {expect(result.ackedDeletesUpTo).toBe(0);});- it('does NOT fold a bundled linkedTrack tombstone into ackedDeletesUpTo for a local-ephemeral project (merge skipped, opted out)', async () => {+ it('folds a bundled linkedTrack tombstone into ackedDeletesUpTo even when the local record LOOKS ephemeral-shaped (#6843: musicVideoProject has no ephemeral concept)', async () => {+ // Historical: applyIncomingPush used to probe getMusicVideoProject for a+ // local `ephemeral` flag (added by #1858) and skip the bundled track+ // merge when set. The store never actually sets that flag on this kind+ // (musicVideo/projectsLogic.js: "no ephemeral flag") — the check always+ // evaluated false in production, and classifyLocalRecord already+ // documented the kind as having no ephemeral concept. #6843 collapsed+ // the dead check via the record-kind table's `hasEphemeral: false` and+ // this asserts the fix: an `ephemeral: true`-shaped local record (which+ // could previously only be reached by a mock like this one, never by+ // real data) does NOT suppress the linkedTrack merge or its ack.vi.mocked(getMusicVideoProject).mockResolvedValueOnce({ id: 'mv-16', ephemeral: true });const result = await applyIncomingPush({kind: 'musicVideoProject',@@ -3357,8 +3407,11 @@ describe('peerSync', () => {assetManifest: [],sourceInstanceId: 'peer-a',});- expect(mergeTracksFromSync).not.toHaveBeenCalled();- expect(result.ackedDeletesUpTo).toBe(0);+ expect(mergeTracksFromSync).toHaveBeenCalledWith(+ [expect.objectContaining({ id: 'track-16' })],+ { source: { via: 'peer-push', peerId: 'peer-a' } },+ );+ expect(result.ackedDeletesUpTo).toBe(Date.parse('2026-04-04T00:00:00Z'));});it('auto-creates a reverse subscription back to the sender', async () => {@@ -3876,9 +3929,12 @@ describe('peerSync', () => {schemaVersions: { ...PORTOS_SCHEMA_VERSIONS, tracks: PORTOS_SCHEMA_VERSIONS.tracks + 1 },},});+ // Goes through the record-kind table (#6843), which passes+ // senderSchemaVersions uniformly (harmless for musicVideoProject —+ // ignored).expect(mergeMusicVideoProjectsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'mv-1' })],- { source: { via: 'peer-push', peerId: 'peer-a' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),);});@@ -4608,9 +4664,11 @@ describe('peerSync', () => {sourceInstanceId: 'peer-abc',});+ // Goes through the record-kind table (#6843), which passes+ // senderSchemaVersions uniformly (harmless for mediaCollection — ignored).expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'col-x', name: 'Synced' })],- { source: { via: 'peer-push', peerId: 'peer-abc' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-abc' } }),);// Confirm the record landed on disk via the real listCollections.@@ -4629,7 +4687,7 @@ describe('peerSync', () => {});expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([expect.objectContaining({ id: 'col-y' })],- { source: { via: 'peer-push', peerId: 'peer-abc' } },+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-abc' } }),);});@@ -4950,4 +5008,97 @@ describe('media-library federation (#1566)', () => {expect(manifestUrls[0]).toContain('10.0.0.4');});});++ // #6843 — the per-kind record-kind table (recordKinds.js) collapsed six+ // hand-mirrored kind === '...' ladders (isSubscriptionRecordTombstone,+ // buildPushPayload, classifyLocalRecord, applyIncomingPush's ephemeral+ // lookup + merge dispatch, refusedFromCutoffs) to one lookup each. Before+ // that table, only 4 of the 16 subscribable kinds were exercised through+ // buildPushPayload/applyIncomingPush by this file (universe, series,+ // musicVideoProject, mediaCollection) — the other 12 kinds' ladder arms+ // were untested, which is exactly the gap that let classifyLocalRecord ship+ // with no fableLoom arm (always 'missing', so an inbound fableLoom push+ // could never auto-create a reverse subscription) and applyIncomingPush+ // carry a dead musicVideoProject ephemeral probe. This suite drives EVERY+ // PEER_SUBSCRIBABLE_KINDS entry through both boundaries so a future kind+ // that's added to the table but wired wrong fails here instead of shipping+ // silently — the exact failure mode the issue documents.+ describe('all-kinds parity (#6843)', () => {+ // One row per PEER_SUBSCRIBABLE_KINDS entry: the (already-imported,+ // already-mocked) getter + merger this kind's descriptor wraps, and a+ // minimal record shape sanitizeRecordForWire accepts for it (id ++ // deleted/deletedAt is sufficient for every kind — see syncWire.js: the+ // only universal requirements are a plain object with a non-blank id and+ // not `ephemeral === true` while live).+ const ALL_KINDS_FIXTURES = {+ universe: { get: getUniverse, merge: mergeUniversesFromSync },+ series: { get: getSeries, merge: mergeSeriesFromSync },+ mediaCollection: { get: getCollection, merge: mergeMediaCollectionsFromSync },+ author: { get: getAuthor, merge: mergeAuthorsFromSync },+ artist: { get: getArtist, merge: mergeArtistsFromSync },+ album: { get: getAlbum, merge: mergeAlbumsFromSync },+ track: { get: getTrack, merge: mergeTracksFromSync },+ creativeDirectorProject: { get: getCreativeDirectorProject, merge: mergeCreativeDirectorProjectsFromSync },+ moodBoard: { get: getBoard, merge: mergeBoardsFromSync },+ fableLoom: { get: getLoom, merge: mergeLoomsFromSync },+ writersRoomWork: { get: getWorkForSync, merge: mergeWorksFromSync },+ writersRoomFolder: { get: getFolderForSync, merge: mergeFoldersFromSync },+ writersRoomExercise: { get: getExerciseForSync, merge: mergeExercisesFromSync },+ musicVideoProject: { get: getMusicVideoProject, merge: mergeMusicVideoProjectsFromSync },+ commissionFeedback: { get: getCommissionFeedbackForSync, merge: mergeCommissionFeedbackFromSync },+ creativeCommission: { get: getCommissionForSync, merge: mergeCommissionsFromSync },+ };++ it('every PEER_SUBSCRIBABLE_KINDS entry has a test fixture (guards the parity suite itself against a silently-skipped kind)', () => {+ expect(Object.keys(ALL_KINDS_FIXTURES).sort()).toEqual([...PEER_SUBSCRIBABLE_KINDS].sort());+ });++ it.each(PEER_SUBSCRIBABLE_KINDS)('buildPushPayload(%s): a live record pushes a populated envelope, a tombstone pushes assetManifest:[]', async (kind) => {+ const { get } = ALL_KINDS_FIXTURES[kind];+ const liveRecord = { id: `ak-live-${kind}`, name: 'AK', title: 'AK', deleted: false, deletedAt: null };+ vi.mocked(get).mockResolvedValueOnce(liveRecord);+ const liveResult = await buildPushPayload({ recordKind: kind, recordId: liveRecord.id }, 'src-instance');+ expect(liveResult.kind).toBe(kind);+ expect(liveResult.record.id).toBe(liveRecord.id);+ expect(Array.isArray(liveResult.assetManifest)).toBe(true);++ const tombstone = { id: `ak-tomb-${kind}`, deleted: true, deletedAt: '2026-05-01T00:00:00Z' };+ vi.mocked(get).mockResolvedValueOnce(tombstone);+ const tombResult = await buildPushPayload({ recordKind: kind, recordId: tombstone.id }, 'src-instance');+ expect(tombResult.record.deleted).toBe(true);+ expect(tombResult.assetManifest).toEqual([]);+ });++ it.each(PEER_SUBSCRIBABLE_KINDS)('applyIncomingPush(%s): merges the incoming record through this kind\'s own merger with a { source } envelope', async (kind) => {+ const { get, merge } = ALL_KINDS_FIXTURES[kind];+ vi.mocked(merge).mockClear();+ const record = { id: `ak-merge-${kind}`, name: 'AK', deleted: false, deletedAt: null };+ // Satisfies universe/series' local-ephemeral lookup (the only two kinds+ // that read `desc.load` before merging) — a non-ephemeral local match.+ vi.mocked(get).mockResolvedValue(record);+ await applyIncomingPush({ kind, record, assetManifest: [], sourceInstanceId: 'peer-a' });+ expect(merge).toHaveBeenCalledWith(+ [expect.objectContaining({ id: record.id })],+ expect.objectContaining({ source: { via: 'peer-push', peerId: 'peer-a' } }),+ );+ });++ it.each(PEER_SUBSCRIBABLE_KINDS)('applyIncomingPush(%s): reverse-subscribes when the local record is present, refuses when it is missing (classifyLocalRecord)', async (kind) => {+ const { get } = ALL_KINDS_FIXTURES[kind];++ const presentRecord = { id: `ak-present-${kind}`, name: 'AK', deleted: false, deletedAt: null };+ vi.mocked(get).mockResolvedValue(presentRecord);+ const presentResult = await applyIncomingPush({+ kind, record: presentRecord, assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(presentResult.reverseSubscriptionCreated).toBe(true);++ const missingRecord = { id: `ak-missing-${kind}`, name: 'AK', deleted: false, deletedAt: null };+ vi.mocked(get).mockResolvedValue(undefined);+ const missingResult = await applyIncomingPush({+ kind, record: missingRecord, assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(missingResult.reverseSubscriptionCreated).toBe(false);+ });+ });});diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex b7e5df8e47..7ade31878f 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -25,8 +25,6 @@ import { collectAssetReferences } from './exporter.js';import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';import { pullSidecarForImage } from './sidecarSync.js';import { parseKey } from '../../lib/mediaItemKey.js';-import { listIssuesForSeries } from '../pipeline/issues.js';-import { findCollectionBySeriesId } from '../mediaCollections.js';import { headshotImageFilename } from '../authors/index.js';import { portraitImageFilename } from '../artists/index.js';import { coverImageFilename } from '../albums/index.js';@@ -38,7 +36,7 @@ import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from '../writersRoom/import { getWorkForSync } from '../writersRoom/sync.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { peerSyncEvents, findPeerById } from './peerSyncShared.js';-import { isStr, isNonBlankStr } from '../../lib/textUtils.js';+import { isStr } from '../../lib/textUtils.js';// --- Asset manifest -----------------------------------------------------@@ -125,60 +123,10 @@ export async function buildCollectionAssetManifest(collection) {return out;}-function summarizeAssetManifest(manifest) {- const entries = Array.isArray(manifest) ? manifest : [];- return {- assetHashes: entries.map((e) => e.sha256).filter(Boolean).sort(),- metadataMissing: entries.some((e) => e?.kind === 'image' && !isNonBlankStr(e.sidecarSha256)),- };-}--async function buildIntegrityAssetManifest(kind, record) {- if (kind === 'mediaCollection') return buildCollectionAssetManifest(record);- if (kind === 'author') return buildAuthorAssetManifest(record);- if (kind === 'artist') return buildArtistAssetManifest(record);- if (kind === 'album') return buildAlbumAssetManifest(record);- if (kind === 'track') return buildTrackAssetManifest(record);- if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);- if (kind === 'musicVideoProject') return buildMusicVideoAssetManifest(record);- if (kind === 'moodBoard') return buildBoardAssetManifest(record);- if (kind === 'fableLoom') return buildFableLoomAssetManifest(record);- if (kind === 'series') {- const childIssues = await listIssuesForSeries(record?.id, { includeDeleted: true }).catch(() => []);- const manifestIssues = childIssues.filter(- (i) => i?.deleted !== true && i?.ephemeral !== true,- );- const linkedCollection = await findCollectionBySeriesId(record?.id).catch(() => null);- return buildAssetManifestForSeries(record, manifestIssues, linkedCollection);- }- return buildAssetManifest(record);-}--/**- * Returns the integrity-facing asset summary for a record: sorted file hashes- * plus whether any hashed image lacks a gen-params sidecar. `series` mirrors- * the push manifest path so child issue assets participate in integrity.- *- * @param {'universe'|'series'|'mediaCollection'} kind- * @param {object} record- * @returns {Promise<{assetHashes:string[], metadataMissing:boolean}>}- */-export async function assetIntegrityForRecord(kind, record) {- const manifest = await buildIntegrityAssetManifest(kind, record);- return summarizeAssetManifest(manifest);-}--/**- * Back-compat helper for callers/tests that only need hashes.- *- * @param {'universe'|'series'|'mediaCollection'} kind- * @param {object} record- * @returns {Promise<string[]>} sorted sha256 strings (falsy hashes omitted)- */-export async function assetShaListForRecord(kind, record) {- const { assetHashes } = await assetIntegrityForRecord(kind, record);- return assetHashes;-}+// assetIntegrityForRecord / assetShaListForRecord (per-kind integrity-hash+// dispatch) moved to recordKinds.js (#6843) — its dispatch reads RECORD_KINDS,+// and this module must never import that table (recordKinds.js ->+// peerSyncAssets.js is the only allowed direction between the two).export async function hashImageForManifest(filename) {// Sanitize before join — a record with `imageRefs` containing a path-diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex b169f8edae..af5828228f 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -20,44 +20,19 @@ import {formatVersionGap,} from '../../lib/schemaVersions.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';-import { getUniverse } from '../universeBuilder.js';-import { getSeries } from '../pipeline/series.js';import { listIssuesForSeries } from '../pipeline/issues.js';import {- getCollection,findCollectionByUniverseId,findCollectionBySeriesId,} from '../mediaCollections.js';-import { getAuthor } from '../authors/index.js';-import { getArtist } from '../artists/index.js';-import { getAlbum } from '../albums/index.js';import { getTrack } from '../tracks/index.js';-import { getProject } from '../creativeDirector/local.js';-import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';-import { getBoard } from '../moodBoard/index.js';-import { getLoom } from '../fableLoom/index.js';-import {- getWorkForSync,- buildWorkBodyManifest,- getFolderForSync,- getExerciseForSync,-} from '../writersRoom/sync.js';-import { getCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';-import { getCommissionForSync } from '../creativeCommissions/store.js';+import { buildWorkBodyManifest } from '../writersRoom/sync.js';import { ackDeletesUpTo } from './peerTombstoneCursors.js';import {buildAssetManifestWithCollection,buildAssetManifestForSeries,- buildCollectionAssetManifest,- buildAuthorAssetManifest,- buildArtistAssetManifest,- buildAlbumAssetManifest,- buildTrackAssetManifest,- buildProjectAssetManifest,- buildBoardAssetManifest,- buildFableLoomAssetManifest,- buildMusicVideoAssetManifest,} from './peerSyncAssets.js';+import { RECORD_KINDS } from './recordKinds.js';import {peerAllowsOutbound,peerHasCategory,@@ -98,71 +73,10 @@ import { isStr, isNonBlankStr } from '../../lib/textUtils.js';const SCHEMA_BLOCK_RETRY_COOLDOWN_MS = 5 * 60_000;async function isSubscriptionRecordTombstone(sub) {- if (sub.recordKind === 'universe') {- const record = await getUniverse(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'series') {- const record = await getSeries(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'mediaCollection') {- const record = await getCollection(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'author') {- const record = await getAuthor(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'artist') {- const record = await getArtist(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'album') {- const record = await getAlbum(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'track') {- const record = await getTrack(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'creativeDirectorProject') {- const record = await getProject(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'moodBoard') {- const record = await getBoard(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'fableLoom') {- const record = await getLoom(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'writersRoomWork') {- const record = await getWorkForSync(sub.recordId).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'writersRoomFolder') {- const record = await getFolderForSync(sub.recordId).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'writersRoomExercise') {- const record = await getExerciseForSync(sub.recordId).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'musicVideoProject') {- const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'commissionFeedback') {- const record = await getCommissionFeedbackForSync(sub.recordId).catch(() => null);- return record?.deleted === true;- }- if (sub.recordKind === 'creativeCommission') {- const record = await getCommissionForSync(sub.recordId).catch(() => null);- return record?.deleted === true;- }- return false;+ const desc = RECORD_KINDS[sub.recordKind];+ if (!desc) return false;+ const record = await desc.load(sub.recordId).catch(() => null);+ return record?.deleted === true;}export async function pushRecordToPeer(sub, options = {}) {@@ -629,241 +543,180 @@ async function clearSchemaVersionBlock(subId) {peerSyncEvents.emit('subscription-unblocked', { subId, peerId: clearedPeerId });}+/**+ * Universe push hook — bundle-aware, so it can't route through the generic+ * `buildPushPayload` path (its manifest builder needs a second `linkedCollection`+ * argument the generic one-record builders don't take). Extracted out of+ * `buildPushPayload`'s own body (#6843) alongside the series hook below, so+ * the two genuinely-special kinds don't inflate the dispatcher's complexity.+ */+async function buildUniversePushPayload(sub, sourceInstanceId, portosMeta) {+ const record = await RECORD_KINDS.universe.load(sub.recordId).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('universe', record);+ if (!sanitized) return null;+ // Look up the linked media collection (auto-managed "Universe: X" bucket)+ // and bundle it in the payload. Without this, collection-only edits (a+ // new image added to the universe's gallery) wouldn't move the universe+ // record itself, so the lastPushedHash short-circuit would treat the+ // push as "unchanged" and the receiver's collection would diverge+ // permanently. Tombstone pushes skip the collection bundle — a deleted+ // universe's collection gets unlinked + orphaned locally, and shipping+ // it would re-create an empty bucket on the receiver.+ const linkedCollection = record.deleted === true+ ? null+ : await findCollectionByUniverseId(sub.recordId).catch(() => null);+ // Tombstone push: deleted records carry no on-disk assets the receiver+ // should pull. Sending an empty manifest avoids triggering+ // pullMissingAssetsFromPeer for a record we're telling the peer to+ // delete — both wasteful (network + disk for bytes the receiver will+ // immediately orphan) and privacy-sensitive (e.g. a record deleted+ // BECAUSE the user wanted the assets off-peer would otherwise still+ // ship them with the tombstone push).+ const assetManifest = record.deleted === true+ ? []+ : await buildAssetManifestWithCollection(record, linkedCollection);+ // Bundle the catalog rows referenced by this universe (ingredients + the+ // universe→ingredient ref links). The embedded canon already replicates+ // via the universe record, but the catalog row's enrichments (tags,+ // embedding, payload.summary) live ONLY in Postgres — without this bundle+ // the receiver re-derives a strictly-lossy view on its first backfill.+ // Skip for tombstone pushes (the universe is being deleted; its ref rows+ // tombstone locally and ride a later catalog-sync cycle if needed).+ const catalogBundle = record.deleted === true+ ? null+ : await buildCatalogBundleForRef('universe', sub.recordId);+ // The bundled collection goes through the SAME wire projection as a+ // standalone `mediaCollection` push (below) — the raw service record would+ // otherwise smuggle peer-local fields (the `source` provenance stamp,+ // #3311) past the receiver's insert path and leave the bundled and+ // standalone forms of the same record disagreeing byte-for-byte.+ const bundledCollection = sanitizeRecordForWire('mediaCollection', linkedCollection);+ return {+ kind: 'universe',+ record: sanitized,+ assetManifest,+ sourceInstanceId,+ portosMeta,+ ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),+ ...(catalogBundle ? { catalogBundle } : {}),+ };+}++/**+ * Series push hook — bundle-aware like the universe hook above (its manifest+ * builder needs the child-issues + linkedCollection args), plus the two+ * sibling docs (manuscript review, reverse outline) that ride a series push+ * but nothing else. Extracted out of `buildPushPayload`'s own body (#6843).+ */+async function buildSeriesPushPayload(sub, sourceInstanceId, portosMeta) {+ const record = await RECORD_KINDS.series.load(sub.recordId).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('series', record);+ if (!sanitized) return null;+ // Bundle child issues — the series + its issues form one unit of edit+ // for downstream consumers (panels, comic pages), so the receiver+ // applies them atomically per merge cycle.+ const childIssues = await listIssuesForSeries(sub.recordId, { includeDeleted: true }).catch(() => []);+ const sanitizedIssues = childIssues+ .map((i) => sanitizeRecordForWire('issue', i))+ .filter(Boolean);+ // Drop ephemeral child issues BEFORE feeding into the asset-manifest+ // builder. sanitizedIssues above already filters them via+ // sanitizeRecordForWire's ephemeral check, but the asset-manifest builder+ // takes the raw `childIssues` array — without the parallel filter here,+ // ephemeral issues' image / video / image-ref filenames would still+ // appear in the manifest the receiver pulls. The user-visible effect:+ // private/scratch image bytes for an issue the user said "don't sync"+ // would land on every peer's disk via pullMissingAssetsFromPeer.+ // ALSO drop deleted child issues from the manifest input — their+ // tombstones still ride along in `sanitizedIssues` (so the receiver+ // can finish its delete cascade), but shipping the deleted issues'+ // asset filenames would trigger needless / privacy-sensitive pulls+ // for bytes that are about to be orphaned on the receiver.+ // Tombstoned ephemeral issues (deleted=true + ephemeral=true) ALSO+ // stay out of the manifest input by this filter.+ const manifestIssues = childIssues.filter(+ (i) => i?.deleted !== true && i?.ephemeral !== true,+ );+ // Same collection-bundle reasoning as the universe branch: a "Series: X"+ // collection's item changes don't move the series record, so without+ // bundling the collection here the per-record push would short-circuit+ // and the receiver's collection would diverge.+ const linkedCollection = record.deleted === true+ ? null+ : await findCollectionBySeriesId(sub.recordId).catch(() => null);+ // Tombstone push at the series level: same reasoning as universe above.+ // When the series itself is deleted, send an empty asset manifest so+ // the receiver doesn't pull bytes for a record it's about to tombstone.+ const assetManifest = record.deleted === true+ ? []+ : await buildAssetManifestForSeries(record, manifestIssues, linkedCollection);+ // Bundle the manuscript-review sibling doc (the "Finish the draft" comment+ // set) so review-only edits — which don't move the series record — still+ // propagate. Same reasoning as the linkedCollection bundle above: the+ // review rides the payload AND the push hash, defeating the lastPushedHash+ // short-circuit. Skip for tombstones (a deleted series ships no review).+ // Dynamic import keeps manuscriptReview's arcPlanner graph off peerSync's+ // boot load path (matches the catalogBundle pattern).+ const manuscriptReview = record.deleted === true+ ? null+ : await import('../pipeline/manuscriptReview.js')+ .then(({ getReview }) => getReview(sub.recordId))+ .catch(() => null);+ // Bundle the reverse-outline sibling doc (the scene-by-scene segmentation)+ // on the same terms as the review above: a regenerate-only change doesn't+ // move the series record, so without bundling it the per-record push would+ // short-circuit and the receiver's outline would diverge. Only a `complete`+ // outline is worth shipping. Skip for tombstones. Dynamic import keeps+ // reverseOutline's arcPlanner graph off peerSync's boot load path.+ const reverseOutline = record.deleted === true+ ? null+ : await import('../pipeline/reverseOutline.js')+ .then(({ getStoredOutline }) => getStoredOutline(sub.recordId))+ .catch(() => null);+ // Same wire projection as the universe branch — see the note there.+ const bundledCollection = sanitizeRecordForWire('mediaCollection', linkedCollection);+ return {+ kind: 'series',+ record: sanitized,+ issues: sanitizedIssues,+ assetManifest,+ sourceInstanceId,+ portosMeta,+ ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),+ ...(manuscriptReview && manuscriptReview.comments?.length ? { manuscriptReview } : {}),+ ...(reverseOutline && reverseOutline.status === 'complete' ? { reverseOutline } : {}),+ };+}++/**+ * Load the live record, sanitize for wire, build the asset manifest, and+ * assemble the push envelope `buildPortosMeta`/`pushRecordToPeer` sends.+ * Universe and series are bundle-aware (their manifest builders need extra+ * args the generic one-record builders don't take) and dispatch to their own+ * hooks above; the other 14 kinds share one generic load -> sanitize -> asset+ * manifest -> envelope path, with two post-hooks (musicVideoProject,+ * writersRoomWork) that bundle one extra field onto the generic envelope.+ */export async function buildPushPayload(sub, sourceInstanceId) {const portosMeta = await buildPortosMeta();- if (sub.recordKind === 'universe') {- const record = await getUniverse(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('universe', record);- if (!sanitized) return null;- // Look up the linked media collection (auto-managed "Universe: X" bucket)- // and bundle it in the payload. Without this, collection-only edits (a- // new image added to the universe's gallery) wouldn't move the universe- // record itself, so the lastPushedHash short-circuit would treat the- // push as "unchanged" and the receiver's collection would diverge- // permanently. Tombstone pushes skip the collection bundle — a deleted- // universe's collection gets unlinked + orphaned locally, and shipping- // it would re-create an empty bucket on the receiver.- const linkedCollection = record.deleted === true- ? null- : await findCollectionByUniverseId(sub.recordId).catch(() => null);- // Tombstone push: deleted records carry no on-disk assets the receiver- // should pull. Sending an empty manifest avoids triggering- // pullMissingAssetsFromPeer for a record we're telling the peer to- // delete — both wasteful (network + disk for bytes the receiver will- // immediately orphan) and privacy-sensitive (e.g. a record deleted- // BECAUSE the user wanted the assets off-peer would otherwise still- // ship them with the tombstone push).- const assetManifest = record.deleted === true- ? []- : await buildAssetManifestWithCollection(record, linkedCollection);- // Bundle the catalog rows referenced by this universe (ingredients + the- // universe→ingredient ref links). The embedded canon already replicates- // via the universe record, but the catalog row's enrichments (tags,- // embedding, payload.summary) live ONLY in Postgres — without this bundle- // the receiver re-derives a strictly-lossy view on its first backfill.- // Skip for tombstone pushes (the universe is being deleted; its ref rows- // tombstone locally and ride a later catalog-sync cycle if needed).- const catalogBundle = record.deleted === true- ? null- : await buildCatalogBundleForRef('universe', sub.recordId);- // The bundled collection goes through the SAME wire projection as a- // standalone `mediaCollection` push (below) — the raw service record would- // otherwise smuggle peer-local fields (the `source` provenance stamp,- // #3311) past the receiver's insert path and leave the bundled and- // standalone forms of the same record disagreeing byte-for-byte.- const bundledCollection = sanitizeRecordForWire('mediaCollection', linkedCollection);- return {- kind: 'universe',- record: sanitized,- assetManifest,- sourceInstanceId,- portosMeta,- ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),- ...(catalogBundle ? { catalogBundle } : {}),- };- }- if (sub.recordKind === 'series') {- const record = await getSeries(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('series', record);- if (!sanitized) return null;- // Bundle child issues — the series + its issues form one unit of edit- // for downstream consumers (panels, comic pages), so the receiver- // applies them atomically per merge cycle.- const childIssues = await listIssuesForSeries(sub.recordId, { includeDeleted: true }).catch(() => []);- const sanitizedIssues = childIssues- .map((i) => sanitizeRecordForWire('issue', i))- .filter(Boolean);- // Drop ephemeral child issues BEFORE feeding into the asset-manifest- // builder. sanitizedIssues above already filters them via- // sanitizeRecordForWire's ephemeral check, but the asset-manifest builder- // takes the raw `childIssues` array — without the parallel filter here,- // ephemeral issues' image / video / image-ref filenames would still- // appear in the manifest the receiver pulls. The user-visible effect:- // private/scratch image bytes for an issue the user said "don't sync"- // would land on every peer's disk via pullMissingAssetsFromPeer.- // ALSO drop deleted child issues from the manifest input — their- // tombstones still ride along in `sanitizedIssues` (so the receiver- // can finish its delete cascade), but shipping the deleted issues'- // asset filenames would trigger needless / privacy-sensitive pulls- // for bytes that are about to be orphaned on the receiver.- // Tombstoned ephemeral issues (deleted=true + ephemeral=true) ALSO- // stay out of the manifest input by this filter.- const manifestIssues = childIssues.filter(- (i) => i?.deleted !== true && i?.ephemeral !== true,- );- // Same collection-bundle reasoning as the universe branch: a "Series: X"- // collection's item changes don't move the series record, so without- // bundling the collection here the per-record push would short-circuit- // and the receiver's collection would diverge.- const linkedCollection = record.deleted === true- ? null- : await findCollectionBySeriesId(sub.recordId).catch(() => null);- // Tombstone push at the series level: same reasoning as universe above.- // When the series itself is deleted, send an empty asset manifest so- // the receiver doesn't pull bytes for a record it's about to tombstone.- const assetManifest = record.deleted === true- ? []- : await buildAssetManifestForSeries(record, manifestIssues, linkedCollection);- // Bundle the manuscript-review sibling doc (the "Finish the draft" comment- // set) so review-only edits — which don't move the series record — still- // propagate. Same reasoning as the linkedCollection bundle above: the- // review rides the payload AND the push hash, defeating the lastPushedHash- // short-circuit. Skip for tombstones (a deleted series ships no review).- // Dynamic import keeps manuscriptReview's arcPlanner graph off peerSync's- // boot load path (matches the catalogBundle pattern).- const manuscriptReview = record.deleted === true- ? null- : await import('../pipeline/manuscriptReview.js')- .then(({ getReview }) => getReview(sub.recordId))- .catch(() => null);- // Bundle the reverse-outline sibling doc (the scene-by-scene segmentation)- // on the same terms as the review above: a regenerate-only change doesn't- // move the series record, so without bundling it the per-record push would- // short-circuit and the receiver's outline would diverge. Only a `complete`- // outline is worth shipping. Skip for tombstones. Dynamic import keeps- // reverseOutline's arcPlanner graph off peerSync's boot load path.- const reverseOutline = record.deleted === true- ? null- : await import('../pipeline/reverseOutline.js')- .then(({ getStoredOutline }) => getStoredOutline(sub.recordId))- .catch(() => null);- // Same wire projection as the universe branch — see the note there.- const bundledCollection = sanitizeRecordForWire('mediaCollection', linkedCollection);- return {- kind: 'series',- record: sanitized,- issues: sanitizedIssues,- assetManifest,- sourceInstanceId,- portosMeta,- ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),- ...(manuscriptReview && manuscriptReview.comments?.length ? { manuscriptReview } : {}),- ...(reverseOutline && reverseOutline.status === 'complete' ? { reverseOutline } : {}),- };- }- if (sub.recordKind === 'mediaCollection') {- const record = await getCollection(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('mediaCollection', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildCollectionAssetManifest(record);- return { kind: 'mediaCollection', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'author') {- const record = await getAuthor(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('author', record);- if (!sanitized) return null;- // Tombstone push ships no assets — the receiver is about to delete the- // record, so pulling its headshot would be wasteful + privacy-sensitive- // (same reasoning as the universe/series branches above).- const assetManifest = record.deleted === true ? [] : await buildAuthorAssetManifest(record);- return { kind: 'author', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'artist') {- const record = await getArtist(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('artist', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildArtistAssetManifest(record);- return { kind: 'artist', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'album') {- const record = await getAlbum(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('album', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildAlbumAssetManifest(record);- return { kind: 'album', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'track') {- const record = await getTrack(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('track', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildTrackAssetManifest(record);- return { kind: 'track', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'creativeDirectorProject') {- const record = await getProject(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('creativeDirectorProject', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildProjectAssetManifest(record);- return { kind: 'creativeDirectorProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'moodBoard') {- const record = await getBoard(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('moodBoard', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildBoardAssetManifest(record);- return { kind: 'moodBoard', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'fableLoom') {- const record = await getLoom(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('fableLoom', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildFableLoomAssetManifest(record);- return { kind: 'fableLoom', record: sanitized, assetManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'writersRoomWork') {- const record = await getWorkForSync(sub.recordId).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('writersRoomWork', record);- if (!sanitized) return null;- // The work manifest carries draft-version METADATA; the file-primary `.md`- // prose bodies ride a separate `draftBodyManifest` (SHA256 per draft) the- // receiver diffs + pulls. A tombstone ships neither asset manifest.- const draftBodyManifest = record.deleted === true ? [] : await buildWorkBodyManifest(record);- return { kind: 'writersRoomWork', record: sanitized, assetManifest: [], draftBodyManifest, sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'writersRoomFolder') {- // Body-less (#1645) — no asset/body manifest, just the LWW record envelope.- const record = await getFolderForSync(sub.recordId).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('writersRoomFolder', record);- if (!sanitized) return null;- return { kind: 'writersRoomFolder', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };- }- if (sub.recordKind === 'writersRoomExercise') {- const record = await getExerciseForSync(sub.recordId).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('writersRoomExercise', record);- if (!sanitized) return null;- return { kind: 'writersRoomExercise', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };- }+ const desc = RECORD_KINDS[sub.recordKind];+ if (!desc) return null;+ if (sub.recordKind === 'universe') return buildUniversePushPayload(sub, sourceInstanceId, portosMeta);+ if (sub.recordKind === 'series') return buildSeriesPushPayload(sub, sourceInstanceId, portosMeta);+ const record = await desc.load(sub.recordId).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire(sub.recordKind, record);+ if (!sanitized) return null;+ // Tombstone push ships no assets — the receiver is about to delete the+ // record, so pulling its bytes would be wasteful + privacy-sensitive (same+ // reasoning as the universe/series hooks above).+ const assetManifest = record.deleted === true+ ? []+ : (desc.buildAssetManifest ? await desc.buildAssetManifest(record) : []);+ const envelope = { kind: sub.recordKind, record: sanitized, assetManifest, sourceInstanceId, portosMeta };if (sub.recordKind === 'musicVideoProject') {- // #1770 ships the record (metadata + beat-aligned scenes) as the LWW- // envelope; #1772 bundles its referenced media. A tombstone ships no bytes.- const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('musicVideoProject', record);- if (!sanitized) return null;- const assetManifest = record.deleted === true ? [] : await buildMusicVideoAssetManifest(record);// #1858: bundle the LINKED TRACK RECORD (create-UI projects store `trackId`,// not `uploadedAudioFilename`). The audio BYTES ride `assetManifest` above,// but the receiver's `resolveMasterAudioPath()` looks the track up by id@@ -882,30 +735,16 @@ export async function buildPushPayload(sub, sourceInstanceId) {// it without includeDeleted), so only the tombstone record rides.if (track) linkedTrack = sanitizeRecordForWire('track', track);}- return {- kind: 'musicVideoProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta,- ...(linkedTrack ? { linkedTrack } : {}),- };- }- if (sub.recordKind === 'commissionFeedback') {- // Body-less (#2686) — no asset manifest, just the LWW record envelope- // (one taste reaction). A tombstone ships the same shape (deleted:true).- const record = await getCommissionFeedbackForSync(sub.recordId).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('commissionFeedback', record);- if (!sanitized) return null;- return { kind: 'commissionFeedback', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };+ return { ...envelope, ...(linkedTrack ? { linkedTrack } : {}) };}- if (sub.recordKind === 'creativeCommission') {- // The commission BRIEF (#2686). sanitizeRecordForWire strips the machine-local- // schedule/runs/assignment, so only the federatable brief travels. No assets.- const record = await getCommissionForSync(sub.recordId).catch(() => null);- if (!record) return null;- const sanitized = sanitizeRecordForWire('creativeCommission', record);- if (!sanitized) return null;- return { kind: 'creativeCommission', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };+ if (sub.recordKind === 'writersRoomWork') {+ // The work manifest carries draft-version METADATA; the file-primary `.md`+ // prose bodies ride a separate `draftBodyManifest` (SHA256 per draft) the+ // receiver diffs + pulls. A tombstone ships neither asset manifest.+ const draftBodyManifest = record.deleted === true ? [] : await buildWorkBodyManifest(record);+ return { ...envelope, draftBodyManifest };}- return null;+ return envelope;}/**diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex d2a84ba596..85e45b09e2 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -19,29 +19,8 @@ import {getPortosVersion,} from '../../lib/schemaVersions.js';import { UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';-import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';-import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';import { mergeIssuesFromSync } from '../pipeline/issues.js';-import { getCollection, mergeMediaCollectionsFromSync } from '../mediaCollections.js';-import { getAuthor, mergeAuthorsFromSync } from '../authors/index.js';-import { getArtist, mergeArtistsFromSync } from '../artists/index.js';-import { getAlbum, mergeAlbumsFromSync } from '../albums/index.js';-import { getTrack, mergeTracksFromSync } from '../tracks/index.js';-import { getProject, mergeProjectsFromSync } from '../creativeDirector/local.js';-import { getProject as getMusicVideoProject, mergeProjectsFromSync as mergeMusicVideoProjectsFromSync } from '../musicVideo/projects.js';-import { getBoard, mergeBoardsFromSync } from '../moodBoard/index.js';-import { mergeLoomsFromSync } from '../fableLoom/index.js';-import {- getWorkForSync,- mergeWorksFromSync,- diffWorkBodyManifest,- getFolderForSync,- mergeFoldersFromSync,- getExerciseForSync,- mergeExercisesFromSync,-} from '../writersRoom/sync.js';-import { getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';-import { getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';+import { diffWorkBodyManifest } from '../writersRoom/sync.js';import {ackDeletesUpTo,} from './peerTombstoneCursors.js';@@ -50,6 +29,7 @@ import {pullMissingAssetsFromPeer,pullMissingWorkBodies,} from './peerSyncAssets.js';+import { RECORD_KINDS } from './recordKinds.js';import { findPeerSubscription, subscribePeer } from './peerSubscriptions.js';import {makeErr,@@ -98,51 +78,28 @@ function catalogBundleHasLiveRow(catalogBundle) {);}-// --- Receiver-side push handler ------------------------------------------/**- * Apply an incoming push to local state. Wraps the existing `merge*FromSync`- * dispatch + computes the asset-diff response + (best-effort) creates a- * reverse subscription back to the sender so subsequent edits flow both- * ways without manual re-configuration.+ * SCHEMA-VERSION GATE — runs BEFORE any merge so a sender on a newer storage+ * layout can't corrupt local state. Legacy senders without `portosMeta` pass+ * through (comparator treats absent as zero/no-contract; their record went+ * through the same v0 → vN sanitizer chain we already run). When the sender+ * is AHEAD on any category, throws a structured error the route layer maps+ * to HTTP 409 + body so the sender can persist the gap on the subscription+ * and surface it in the UI. Returns `{ senderSchemaVersions }` on success —+ * the caller threads it into every merge call.*- * The HTTP route in Stage 3 will be a thin wrapper around this — validate- * the body shape, call this function, return the response.+ * We do NOT reject on "sender behind" here — the sanitizer's existing+ * backfill chain handles older inputs in-place. A future forward-only+ * contract (e.g. a required field that the sanitizer can't synthesize) can+ * opt into a behind-gate; the comparator already surfaces both directions+ * for that purpose.+ *+ * Extracted out of `applyIncomingPush`'s own body (#6843) — a self-contained+ * validate-or-throw step with one clear output, and one of the two chunks+ * (with the merge-dispatch ladder) needed to bring that function's+ * complexity down after collapsing the per-kind ladders to table lookups.*/-export async function applyIncomingPush(payload) {- if (!isPlainObject(payload)) {- throw makeErr('payload must be an object', ERR_VALIDATION);- }- const { kind, record, issues, linkedCollection, linkedTrack, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, sourceInstanceId, portosMeta } = payload;- if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {- throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);- }- // Identity + record-shape checks happen BEFORE the schema-version gate.- // The gate's 409 body includes `receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS`- // — a (mild) version-fingerprint disclosure — and we don't want to surface- // it to callers that haven't even identified themselves correctly. Move- // the cheap shape validation first so unidentified or malformed requests- // get a clean 400 with no version information.- if (!isNonBlankStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {- throw makeErr('sourceInstanceId required (and not "unknown")', ERR_VALIDATION);- }- if (!isPlainObject(record) || !isNonBlankStr(record.id)) {- throw makeErr('record must be an object with a string id', ERR_VALIDATION);- }-- // SCHEMA-VERSION GATE — runs BEFORE any merge so a sender on a newer- // storage layout can't corrupt local state. Legacy senders without- // `portosMeta` pass through (comparator treats absent as zero/no-contract;- // their record went through the same v0 → vN sanitizer chain we already- // run). When the sender is AHEAD on any category, we reject with a- // structured error the route layer maps to HTTP 409 + body so the sender- // can persist the gap on the subscription and surface it in the UI.- //- // We do NOT reject on "sender behind" here — the sanitizer's existing- // backfill chain handles older inputs in-place. A future forward-only- // contract (e.g. a required field that the sanitizer can't synthesize)- // can opt into a behind-gate; the comparator already surfaces both- // directions for that purpose.+async function assertSchemaVersionGate({ kind, record, issues, linkedCollection, catalogBundle, linkedTrack, portosMeta, sourceInstanceId }) {const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;// Per-category gate, scoped to the categories THIS push actually writes a@@ -228,6 +185,44 @@ export async function applyIncomingPush(payload) {},);}+ return { senderSchemaVersions };+}++// --- Receiver-side push handler -----------------------------------------++/**+ * Apply an incoming push to local state. Wraps the existing `merge*FromSync`+ * dispatch + computes the asset-diff response + (best-effort) creates a+ * reverse subscription back to the sender so subsequent edits flow both+ * ways without manual re-configuration.+ *+ * The HTTP route in Stage 3 will be a thin wrapper around this — validate+ * the body shape, call this function, return the response.+ */+export async function applyIncomingPush(payload) {+ if (!isPlainObject(payload)) {+ throw makeErr('payload must be an object', ERR_VALIDATION);+ }+ const { kind, record, issues, linkedCollection, linkedTrack, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, sourceInstanceId, portosMeta } = payload;+ if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {+ throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);+ }+ // Identity + record-shape checks happen BEFORE the schema-version gate.+ // The gate's 409 body includes `receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS`+ // — a (mild) version-fingerprint disclosure — and we don't want to surface+ // it to callers that haven't even identified themselves correctly. Move+ // the cheap shape validation first so unidentified or malformed requests+ // get a clean 400 with no version information.+ if (!isNonBlankStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {+ throw makeErr('sourceInstanceId required (and not "unknown")', ERR_VALIDATION);+ }+ if (!isPlainObject(record) || !isNonBlankStr(record.id)) {+ throw makeErr('record must be an object with a string id', ERR_VALIDATION);+ }++ const { senderSchemaVersions } = await assertSchemaVersionGate({+ kind, record, issues, linkedCollection, catalogBundle, linkedTrack, portosMeta, sourceInstanceId,+ });// Look up the LOCAL record state BEFORE merging so we can detect the// "local user marked this record ephemeral" case. The merge functions@@ -236,28 +231,20 @@ export async function applyIncomingPush(payload) {// unconditionally — meaning a stale peer subscription could still// mutate a local collection, download bytes the user opted out of, and// auto-create a reverse sub the user explicitly torn down. Computing- // `localEphemeral` here is one extra read but closes the gap.- let localEphemeral = false;- if (kind === 'universe') {- const local = await getUniverse(record.id, { includeDeleted: true }).catch(() => null);- localEphemeral = local?.ephemeral === true;- } else if (kind === 'series') {- const local = await getSeries(record.id, { includeDeleted: true }).catch(() => null);- localEphemeral = local?.ephemeral === true;- } else if (kind === 'musicVideoProject') {- // #1858: the music-video push now carries a secondary `linkedTrack` bundle,- // so it needs the same opt-out gate — a stale peer push must not plant a- // track record for a project the user marked ephemeral.- const local = await getMusicVideoProject(record.id, { includeDeleted: true }).catch(() => null);- localEphemeral = local?.ephemeral === true;- }+ // `localEphemeral` here is one extra read but closes the gap. Only kinds+ // with an ephemeral concept (`desc.hasEphemeral` — today universe/series)+ // pay for the read at all; #1858 used to also probe musicVideoProject+ // here, but the store has no ephemeral flag on that kind (see recordKinds.js),+ // so that probe's result was always false — dropped as documented drift.+ const desc = RECORD_KINDS[kind];+ const localEphemeral = desc.hasEphemeral+ ? (await desc.load(record.id).catch(() => null))?.ephemeral === true+ : false;- // Merge into local state via the existing LWW path. The merge functions- // honor `deleted: true` + bump `updatedAt`, so this is the single- // tombstone-aware reconciliation point. Attribute any conflict journaled by- // the merge to THIS push's origin peer so the Conflicts tab can show which- // peer collided (without `source`, the merge fns fall back to- // `{ via:'sync', peerId:null }` and the attribution is lost).+ // Attribute any conflict journaled by the merge below to THIS push's origin+ // peer so the Conflicts tab can show which peer collided (without `source`,+ // the merge fns fall back to `{ via:'sync', peerId:null }` and the+ // attribution is lost).const source = { via: 'peer-push', peerId: sourceInstanceId };// Set true when a bundled manuscript-review merge throws — returned to the// sender so it withholds lastPushedHash and retries (the review has no other@@ -280,12 +267,18 @@ export async function applyIncomingPush(payload) {// Set true when a writersRoomWork merge accepted the remote (insert/remote-won)// — gates whether a present-but-different local draft body may be overwritten.let workMergeApplied = false;- if (kind === 'universe') {- // senderSchemaVersions gates the merge's moodBoardId omitted-vs-cleared- // disambiguation (#4188) — see mergeUniversesFromSync.- await mergeUniversesFromSync([record], { source, senderSchemaVersions });- } else if (kind === 'series') {- await mergeSeriesFromSync([record], { source });+ // Merge into local state via the existing LWW path, dispatched through the+ // same per-kind table isSubscriptionRecordTombstone/buildPushPayload use —+ // every PEER_SUBSCRIBABLE_KINDS entry has a descriptor (the registry guard+ // in recordKinds.test.js enforces it), so `desc` is never null here.+ // `senderSchemaVersions` rides every merge call uniformly: only+ // mergeUniversesFromSync (gates the moodBoardId omitted-vs-cleared+ // disambiguation, #4188) and mergeLoomsFromSync read it — every other+ // merger ignores the extra key. The 12 kinds with no extra per-kind+ // behavior need nothing further; the three genuinely special kinds below+ // add their bundled-doc handling on top of this single call.+ const mergeResult = await desc.merge([record], { source, senderSchemaVersions });+ if (kind === 'series') {// Bundled issues: skip the entire batch if the LOCAL series is// ephemeral. mergeSeriesFromSync already refused the parent record on// its own, but child issue merges are a separate code path —@@ -324,38 +317,12 @@ export async function applyIncomingPush(payload) {outlineSyncPending = true;});}- } else if (kind === 'mediaCollection') {- await mergeMediaCollectionsFromSync([record], { source });- } else if (kind === 'author') {- await mergeAuthorsFromSync([record], { source });- } else if (kind === 'artist') {- await mergeArtistsFromSync([record], { source });- } else if (kind === 'album') {- await mergeAlbumsFromSync([record], { source });- } else if (kind === 'track') {- await mergeTracksFromSync([record], { source });- } else if (kind === 'creativeDirectorProject') {- await mergeProjectsFromSync([record], { source });- } else if (kind === 'moodBoard') {- await mergeBoardsFromSync([record], { source });- } else if (kind === 'fableLoom') {- await mergeLoomsFromSync([record], { source, senderSchemaVersions });} else if (kind === 'writersRoomWork') {- const mergeResult = await mergeWorksFromSync([record], { source });// Did the receiver accept the remote work (insert / remote-won LWW)? This// gates whether a PRESENT-but-different local draft body may be overwritten —// a stale push that lost the LWW must NOT clobber newer local prose.workMergeApplied = mergeResult?.applied === true;- } else if (kind === 'commissionFeedback') {- await mergeCommissionFeedbackFromSync([record], { source });- } else if (kind === 'creativeCommission') {- await mergeCommissionsFromSync([record], { source });- } else if (kind === 'writersRoomFolder') {- await mergeFoldersFromSync([record], { source });- } else if (kind === 'writersRoomExercise') {- await mergeExercisesFromSync([record], { source });} else if (kind === 'musicVideoProject') {- await mergeMusicVideoProjectsFromSync([record], { source });// #1858: merge the bundled linked track record so a receiver WITHOUT the// Tracks category can still resolve `project.trackId` (getTrack) at render// time. The audio bytes already pulled via assetManifest. Non-fatal: the@@ -364,9 +331,12 @@ export async function applyIncomingPush(payload) {// Require the bundle's id to MATCH the project's `trackId` so a malformed/// malicious sender can't smuggle an unrelated track record through the// music-video push (the project only needs the track it actually links).+ // Routed through RECORD_KINDS.track.merge — the same function `track`+ // subscriptions merge through — rather than importing mergeTracksFromSync+ // directly, so there is exactly one place that knows how to merge a track.if (!localEphemeral && record.deleted !== true && isPlainObject(linkedTrack)&& linkedTrack.id === record.trackId) {- await mergeTracksFromSync([linkedTrack], { source }).then(() => {+ await RECORD_KINDS.track.merge([linkedTrack], { source }).then(() => {linkedTrackApplied = true;}).catch((err) => {console.log(`⚠️ peerSync: linkedTrack merge failed: ${err.message}`);@@ -395,7 +365,10 @@ export async function applyIncomingPush(payload) {// explicitly opted out of sync for this record, so peer-pushed// collection mutations must not land.if (!localEphemeral && record.deleted !== true && isPlainObject(linkedCollection)) {- await mergeMediaCollectionsFromSync([linkedCollection], { source }).catch((err) => {+ // Routed through RECORD_KINDS.mediaCollection.merge — the same function+ // `mediaCollection` subscriptions merge through — rather than importing+ // mergeMediaCollectionsFromSync directly.+ await RECORD_KINDS.mediaCollection.merge([linkedCollection], { source }).catch((err) => {console.log(`⚠️ peerSync: linkedCollection merge failed: ${err.message}`);});}@@ -539,8 +512,8 @@ async function maybeCreateReverseSubscription({ peerId, recordKind, recordId })// peer marked inbound-only is one we accept pushes FROM but never push// back TO — auto-creating a reverse subscription would break that// explicit configuration. Doing this BEFORE the ephemeral-record disk- // read means inbound-only / unknown peers don't trigger an extra- // getUniverse / getSeries on every incoming push.+ // read (classifyLocalRecord's `desc.load` below) means inbound-only /+ // unknown peers don't trigger an extra record read on every incoming push.const peer = await findPeerById(peerId);if (!peer) return false;const directions = Array.isArray(peer.directions) ? peer.directions : [];@@ -608,99 +581,17 @@ async function maybeCreateReverseSubscription({ peerId, recordKind, recordId })** Includes deleted records on the lookup so a tombstone-as-state record* still gets classified as 'syncable' (we WANT peer pushes to converge- * a deleted record's tombstone if they're targeting it).+ * a deleted record's tombstone if they're targeting it). Every kind but+ * universe/series has no ephemeral concept at all (`desc.hasEphemeral ===+ * false`), so a found record there is always 'syncable' — that's what lets+ * an inbound push of those kinds bootstrap bidirectional sync with no+ * ping-pong risk (the lastPushedHash short-circuit + LWW same-`updatedAt`+ * no-op merge prevent it).*/async function classifyLocalRecord(recordKind, recordId) {- if (recordKind === 'universe') {- const u = await getUniverse(recordId, { includeDeleted: true }).catch(() => undefined);- if (!u) return 'missing';- return u.ephemeral === true ? 'ephemeral' : 'syncable';- }- if (recordKind === 'series') {- const s = await getSeries(recordId, { includeDeleted: true }).catch(() => undefined);- if (!s) return 'missing';- return s.ephemeral === true ? 'ephemeral' : 'syncable';- }- if (recordKind === 'mediaCollection') {- // Collections have no `ephemeral` concept, so a found record is always- // 'syncable'. Without this branch, maybeCreateReverseSubscription's- // `localState !== 'syncable'` guard would never bootstrap bidirectional- // collection sync from an inbound push. No ping-pong risk — the- // lastPushedHash short-circuit + LWW same-`updatedAt` no-op merge prevent- // it, same as universe/series.- const c = await getCollection(recordId, { includeDeleted: true }).catch(() => null);- return c ? 'syncable' : 'missing';- }- if (recordKind === 'author') {- // Authors have no `ephemeral` concept (like mediaCollection) — a found- // record (live or tombstoned) is always 'syncable'. Lets an inbound author- // push bootstrap bidirectional sync. No ping-pong risk: lastPushedHash +- // LWW same-`updatedAt` no-op merge prevent it, same as the others.- const a = await getAuthor(recordId, { includeDeleted: true }).catch(() => null);- return a ? 'syncable' : 'missing';- }- if (recordKind === 'artist') {- const a = await getArtist(recordId, { includeDeleted: true }).catch(() => null);- return a ? 'syncable' : 'missing';- }- if (recordKind === 'album') {- const a = await getAlbum(recordId, { includeDeleted: true }).catch(() => null);- return a ? 'syncable' : 'missing';- }- if (recordKind === 'track') {- const t = await getTrack(recordId, { includeDeleted: true }).catch(() => null);- return t ? 'syncable' : 'missing';- }- if (recordKind === 'creativeDirectorProject') {- // CD projects have no `ephemeral` concept (like the persona/music kinds) — a- // found record (live or tombstoned) is always 'syncable'. No ping-pong risk:- // lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.- const p = await getProject(recordId, { includeDeleted: true }).catch(() => null);- return p ? 'syncable' : 'missing';- }- if (recordKind === 'moodBoard') {- // Mood boards have no `ephemeral` concept (like the persona/music/CD kinds) —- // a found record (live or tombstoned) is always 'syncable'. No ping-pong risk:- // lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.- const b = await getBoard(recordId, { includeDeleted: true }).catch(() => null);- return b ? 'syncable' : 'missing';- }- if (recordKind === 'writersRoomWork') {- // Works have no `ephemeral` concept (like the persona/music/CD/board kinds) —- // a found work (live or tombstoned) is always 'syncable', so an inbound work- // push bootstraps bidirectional sync. No ping-pong risk: lastPushedHash + LWW- // same-`updatedAt` no-op merge prevent it.- const w = await getWorkForSync(recordId).catch(() => null);- return w ? 'syncable' : 'missing';- }- if (recordKind === 'writersRoomFolder') {- // Body-less, no `ephemeral` concept (#1645) — a found folder (live or- // tombstoned) is always 'syncable'. Same no-ping-pong guards as works.- const f = await getFolderForSync(recordId).catch(() => null);- return f ? 'syncable' : 'missing';- }- if (recordKind === 'writersRoomExercise') {- const e = await getExerciseForSync(recordId).catch(() => null);- return e ? 'syncable' : 'missing';- }- if (recordKind === 'musicVideoProject') {- // Music Video projects have no `ephemeral` concept (like the persona/music/CD/- // board kinds) — a found project (live or tombstoned) is always 'syncable'.- // No ping-pong risk: lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.- const p = await getMusicVideoProject(recordId, { includeDeleted: true }).catch(() => null);- return p ? 'syncable' : 'missing';- }- if (recordKind === 'commissionFeedback') {- // Body-less, no `ephemeral` concept (#2686) — a found reaction (live or- // tombstoned) is always 'syncable'. Same no-ping-pong guards as folders.- const fb = await getCommissionFeedbackForSync(recordId).catch(() => null);- return fb ? 'syncable' : 'missing';- }- if (recordKind === 'creativeCommission') {- // The commission brief (#2686) — no `ephemeral` concept; a found commission- // (live or tombstoned) is always 'syncable'.- const c = await getCommissionForSync(recordId).catch(() => null);- return c ? 'syncable' : 'missing';- }- return 'missing';+ const desc = RECORD_KINDS[recordKind];+ if (!desc) return 'missing';+ const record = await desc.load(recordId).catch(() => null);+ if (!record) return 'missing';+ return desc.hasEphemeral && record.ephemeral === true ? 'ephemeral' : 'syncable';}diff --git a/server/services/sharing/recordKinds.js b/server/services/sharing/recordKinds.jsnew file mode 100644index 0000000000..48bb05829f--- /dev/null+++ b/server/services/sharing/recordKinds.js@@ -0,0 +1,248 @@+/**+ * Federated peer-sync — per-kind record descriptor table.+ *+ * The 16 subscribable record kinds (`PEER_SUBSCRIBABLE_KINDS`,+ * `peerSyncShared.js`) each need the same four facts — how to load one by+ * id, how to merge an incoming batch, how to build its asset manifest, and+ * whether the kind has a local-only "ephemeral" opt-out flag. Before #6843+ * those facts were spelled out as six parallel `kind === '…'` ladders across+ * `peerSyncPush.js`, `peerSyncReceive.js`, `peerSyncAssets.js` and+ * `tombstoneGc.js`; a kind added to some ladders and missed in others failed+ * silently (a missing `classifyLocalRecord` arm never auto-creates a reverse+ * subscription; a missing `buildPushPayload` arm never pushes at all). This+ * table is the single per-kind source of truth those call sites now dispatch+ * through — same shape as the `RECORD_KIND_LISTERS` table in `peerSync.js`+ * and `LIVE_ID_LISTERS`/`ALL_ID_LISTERS` in `tombstoneGc.js`.+ *+ * Imports only the store getters/mergers `peerSyncPush.js` and+ * `peerSyncReceive.js` already imported directly (same files, so no new+ * static-import-closure edge — see `server/lib/importScoping.test.js`), plus+ * the per-kind asset-manifest builders from `peerSyncAssets.js`. This module+ * imports peerSyncAssets.js; peerSyncAssets.js never imports this module+ * back (recordKinds.js -> peerSyncAssets.js is the only allowed direction).+ *+ * `universe` and `series` carry `buildAssetManifest: null` — their asset+ * manifests need a bundled linked-collection/child-issues argument the+ * generic one-record builders don't take, so `buildPushPayload` keeps their+ * bundle-aware construction as explicit hooks instead of routing it through+ * this table. `writersRoomWork`, `writersRoomFolder`, `writersRoomExercise`,+ * `commissionFeedback` and `creativeCommission` also carry+ * `buildAssetManifest: null` — they ship no generic asset manifest at all+ * (writersRoomWork's prose rides the separate `draftBodyManifest`; the other+ * four are body-less LWW records).+ *+ * `merge` is called uniformly as `desc.merge(records, { source,+ * senderSchemaVersions })` — every merger destructures at least `{ source }`;+ * the dozen that don't also use `senderSchemaVersions` simply ignore the+ * extra key (only `mergeUniversesFromSync` and `mergeLoomsFromSync` read it).+ */+import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';+import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';+import { listIssuesForSeries } from '../pipeline/issues.js';+import { getCollection, findCollectionBySeriesId, mergeMediaCollectionsFromSync } from '../mediaCollections.js';+import { getAuthor, mergeAuthorsFromSync } from '../authors/index.js';+import { getArtist, mergeArtistsFromSync } from '../artists/index.js';+import { getAlbum, mergeAlbumsFromSync } from '../albums/index.js';+import { getTrack, mergeTracksFromSync } from '../tracks/index.js';+import { getProject, mergeProjectsFromSync } from '../creativeDirector/local.js';+import { getProject as getMusicVideoProject, mergeProjectsFromSync as mergeMusicVideoProjectsFromSync } from '../musicVideo/projects.js';+import { getBoard, mergeBoardsFromSync } from '../moodBoard/index.js';+import { getLoom, mergeLoomsFromSync } from '../fableLoom/index.js';+import {+ getWorkForSync, mergeWorksFromSync,+ getFolderForSync, mergeFoldersFromSync,+ getExerciseForSync, mergeExercisesFromSync,+} from '../writersRoom/sync.js';+import { getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';+import { getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';+import {+ buildAssetManifest,+ buildAssetManifestForSeries,+ buildCollectionAssetManifest,+ buildAuthorAssetManifest,+ buildArtistAssetManifest,+ buildAlbumAssetManifest,+ buildTrackAssetManifest,+ buildProjectAssetManifest,+ buildMusicVideoAssetManifest,+ buildBoardAssetManifest,+ buildFableLoomAssetManifest,+} from './peerSyncAssets.js';+import { isNonBlankStr } from '../../lib/textUtils.js';++export const RECORD_KINDS = Object.freeze({+ __proto__: null, // same reason as RECORD_KIND_LISTERS: a lookup can only hit a declared kind+ universe: {+ load: (id) => getUniverse(id, { includeDeleted: true }),+ merge: mergeUniversesFromSync,+ buildAssetManifest: null, // bundle-aware builder lives in buildPushPayload's universe hook+ hasEphemeral: true,+ },+ series: {+ load: (id) => getSeries(id, { includeDeleted: true }),+ merge: mergeSeriesFromSync,+ buildAssetManifest: null, // bundle-aware builder lives in buildPushPayload's series hook+ hasEphemeral: true,+ },+ mediaCollection: {+ load: (id) => getCollection(id, { includeDeleted: true }),+ merge: mergeMediaCollectionsFromSync,+ buildAssetManifest: buildCollectionAssetManifest,+ hasEphemeral: false,+ },+ author: {+ load: (id) => getAuthor(id, { includeDeleted: true }),+ merge: mergeAuthorsFromSync,+ buildAssetManifest: buildAuthorAssetManifest,+ hasEphemeral: false,+ },+ artist: {+ load: (id) => getArtist(id, { includeDeleted: true }),+ merge: mergeArtistsFromSync,+ buildAssetManifest: buildArtistAssetManifest,+ hasEphemeral: false,+ },+ album: {+ load: (id) => getAlbum(id, { includeDeleted: true }),+ merge: mergeAlbumsFromSync,+ buildAssetManifest: buildAlbumAssetManifest,+ hasEphemeral: false,+ },+ track: {+ load: (id) => getTrack(id, { includeDeleted: true }),+ merge: mergeTracksFromSync,+ buildAssetManifest: buildTrackAssetManifest,+ hasEphemeral: false,+ },+ creativeDirectorProject: {+ load: (id) => getProject(id, { includeDeleted: true }),+ merge: mergeProjectsFromSync,+ buildAssetManifest: buildProjectAssetManifest,+ hasEphemeral: false,+ },+ moodBoard: {+ load: (id) => getBoard(id, { includeDeleted: true }),+ merge: mergeBoardsFromSync,+ buildAssetManifest: buildBoardAssetManifest,+ hasEphemeral: false,+ },+ fableLoom: {+ load: (id) => getLoom(id, { includeDeleted: true }),+ merge: mergeLoomsFromSync,+ buildAssetManifest: buildFableLoomAssetManifest,+ // No ephemeral concept (syncWire.js's fableLoom wire case: "always+ // wire-syncable when present"). `classifyLocalRecord` had NO arm for this+ // kind before this table — a found loom always fell through to the+ // ladder's final `return 'missing'`, so an inbound fableLoom push never+ // auto-created a reverse subscription. Same bug class as the+ // mediaCollection gap `peerSync.test.js` documents ("Regression (Bug 1):+ // classifyLocalRecord had no mediaCollection branch"); the registry-+ // completeness guard in recordKinds.test.js makes the omission+ // structurally impossible going forward.+ hasEphemeral: false,+ },+ writersRoomWork: {+ load: (id) => getWorkForSync(id),+ merge: mergeWorksFromSync,+ buildAssetManifest: null, // prose rides the separate draftBodyManifest, not assetManifest+ hasEphemeral: false,+ },+ writersRoomFolder: {+ load: (id) => getFolderForSync(id),+ merge: mergeFoldersFromSync,+ buildAssetManifest: null, // body-less (#1645)+ hasEphemeral: false,+ },+ writersRoomExercise: {+ load: (id) => getExerciseForSync(id),+ merge: mergeExercisesFromSync,+ buildAssetManifest: null, // body-less (#1645)+ hasEphemeral: false,+ },+ musicVideoProject: {+ load: (id) => getMusicVideoProject(id, { includeDeleted: true }),+ merge: mergeMusicVideoProjectsFromSync,+ buildAssetManifest: buildMusicVideoAssetManifest,+ // Documented drift (pre-#6843): applyIncomingPush's local-ephemeral lookup+ // special-cased this kind (`local?.ephemeral === true`, added by #1858),+ // but the store carries no ephemeral flag at all+ // (`musicVideo/projectsLogic.js`: "no ephemeral flag") and+ // classifyLocalRecord already documented that. `hasEphemeral: false` is+ // the behavior-identical replacement — the old check always evaluated to+ // false, it just cost a disk read to get there.+ hasEphemeral: false,+ },+ commissionFeedback: {+ load: (id) => getCommissionFeedbackForSync(id),+ merge: mergeCommissionFeedbackFromSync,+ buildAssetManifest: null, // body-less (#2686)+ hasEphemeral: false,+ },+ creativeCommission: {+ load: (id) => getCommissionForSync(id),+ merge: mergeCommissionsFromSync,+ buildAssetManifest: null, // body-less brief (#2686)+ hasEphemeral: false,+ },+});++// --- Asset-integrity manifest (moved from peerSyncAssets.js, #6843) -------+//+// Kept here rather than in peerSyncAssets.js because its dispatch reads+// RECORD_KINDS; peerSyncAssets.js must never import this module (the+// allowed direction is recordKinds.js -> peerSyncAssets.js only, so the+// asset-builder leaf never has to know this table exists).++function summarizeAssetManifest(manifest) {+ const entries = Array.isArray(manifest) ? manifest : [];+ return {+ assetHashes: entries.map((e) => e.sha256).filter(Boolean).sort(),+ metadataMissing: entries.some((e) => e?.kind === 'image' && !isNonBlankStr(e.sidecarSha256)),+ };+}++async function buildIntegrityAssetManifest(kind, record) {+ if (kind === 'series') {+ // Mirrors the push manifest path (buildPushPayload's series hook) so+ // child issue assets participate in integrity the same way they ride a+ // series push.+ const childIssues = await listIssuesForSeries(record?.id, { includeDeleted: true }).catch(() => []);+ const manifestIssues = childIssues.filter((i) => i?.deleted !== true && i?.ephemeral !== true);+ const linkedCollection = await findCollectionBySeriesId(record?.id).catch(() => null);+ return buildAssetManifestForSeries(record, manifestIssues, linkedCollection);+ }+ const desc = RECORD_KINDS[kind];+ if (desc?.buildAssetManifest) return desc.buildAssetManifest(record);+ // universe (bundle-aware builder needs a linkedCollection arg this+ // integrity check doesn't have) and every body-less/draft-body kind fall+ // back to the generic direct-image-reference scan — same as before this+ // table existed, when the ladder's final line was `return+ // buildAssetManifest(record);` for any kind without its own arm.+ return buildAssetManifest(record);+}++/**+ * Returns the integrity-facing asset summary for a record: sorted file hashes+ * plus whether any hashed image lacks a gen-params sidecar. `series` mirrors+ * the push manifest path so child issue assets participate in integrity.+ *+ * @param {string} kind one of PEER_SUBSCRIBABLE_KINDS+ * @param {object} record+ * @returns {Promise<{assetHashes:string[], metadataMissing:boolean}>}+ */+export async function assetIntegrityForRecord(kind, record) {+ const manifest = await buildIntegrityAssetManifest(kind, record);+ return summarizeAssetManifest(manifest);+}++/**+ * Back-compat helper for callers/tests that only need hashes.+ *+ * @param {string} kind one of PEER_SUBSCRIBABLE_KINDS+ * @param {object} record+ * @returns {Promise<string[]>} sorted sha256 strings (falsy hashes omitted)+ */+export async function assetShaListForRecord(kind, record) {+ const { assetHashes } = await assetIntegrityForRecord(kind, record);+ return assetHashes;+}diff --git a/server/services/sharing/recordKinds.test.js b/server/services/sharing/recordKinds.test.jsnew file mode 100644index 0000000000..f162724339--- /dev/null+++ b/server/services/sharing/recordKinds.test.js@@ -0,0 +1,63 @@+import { describe, it, expect } from 'vitest';+import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';+import { RECORD_KINDS } from './recordKinds.js';++// Registry-completeness guard (#6843): every PEER_SUBSCRIBABLE_KINDS entry+// must have a descriptor here and vice versa. This is the guard that makes+// the bug class the issue documents structurally impossible going forward —+// a kind added to PEER_SUBSCRIBABLE_KINDS but never given a descriptor (or a+// stale descriptor left behind after a kind is retired) now fails a test+// instead of silently producing 'missing'/null/false at every call site that+// reads the table.+//+// Mutation-probe evidence (manual, per the swarm playbook's baseline rule —+// not a standing test, since RECORD_KINDS is a frozen null-prototype object+// and there is no supported way to mutate it from outside the module):+// deleting one entry from RECORD_KINDS in recordKinds.js and re-running this+// file fails 'has exactly the same kinds as PEER_SUBSCRIBABLE_KINDS' (the+// deleted kind is missing from Object.keys(RECORD_KINDS)) AND fails the+// all-kinds parity suite in peerSync.test.js for that kind (buildPushPayload+// returns null because `desc` is undefined, so `result.kind` throws).+describe('RECORD_KINDS registry completeness (#6843)', () => {+ it('has exactly the same kinds as PEER_SUBSCRIBABLE_KINDS — no kind missing a descriptor, no stale descriptor left behind', () => {+ expect(Object.keys(RECORD_KINDS).sort()).toEqual([...PEER_SUBSCRIBABLE_KINDS].sort());+ });++ it('is a null-prototype table, like RECORD_KIND_LISTERS/LIVE_ID_LISTERS/ALL_ID_LISTERS — an unrecognized kind resolves to undefined, never an inherited Object.prototype member', () => {+ expect(Object.getPrototypeOf(RECORD_KINDS)).toBeNull();+ expect(RECORD_KINDS.toString).toBeUndefined();+ expect(RECORD_KINDS.constructor).toBeUndefined();+ expect(RECORD_KINDS.hasOwnProperty).toBeUndefined();+ });++ it.each(PEER_SUBSCRIBABLE_KINDS)('%s has a well-shaped descriptor: load + merge are functions, hasEphemeral is a boolean, buildAssetManifest is null or a function', (kind) => {+ const desc = RECORD_KINDS[kind];+ expect(desc).toBeDefined();+ expect(typeof desc.load).toBe('function');+ expect(typeof desc.merge).toBe('function');+ expect(typeof desc.hasEphemeral).toBe('boolean');+ expect(desc.buildAssetManifest === null || typeof desc.buildAssetManifest === 'function').toBe(true);+ });++ it('only universe and series carry hasEphemeral:true — every other kind (including fableLoom and musicVideoProject, both documented drift fixes in #6843) has no ephemeral concept', () => {+ const hasEphemeralKinds = PEER_SUBSCRIBABLE_KINDS.filter((k) => RECORD_KINDS[k].hasEphemeral === true);+ expect(hasEphemeralKinds.sort()).toEqual(['series', 'universe']);+ });++ it('universe and series carry buildAssetManifest:null (their bundle-aware manifest builders live as hooks in buildPushPayload, not in the table)', () => {+ expect(RECORD_KINDS.universe.buildAssetManifest).toBeNull();+ expect(RECORD_KINDS.series.buildAssetManifest).toBeNull();+ });++ it('the 5 body-less/draft-body kinds also carry buildAssetManifest:null (no generic asset manifest for them)', () => {+ for (const kind of ['writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'commissionFeedback', 'creativeCommission']) {+ expect(RECORD_KINDS[kind].buildAssetManifest).toBeNull();+ }+ });++ it('the remaining 9 kinds carry a real buildAssetManifest function', () => {+ for (const kind of ['mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'musicVideoProject']) {+ expect(typeof RECORD_KINDS[kind].buildAssetManifest).toBe('function');+ }+ });+});diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex 3b83846f78..9c4e0e1d33 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -66,6 +66,11 @@ import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';import { getPeers } from '../instances.js';+// PEER_SUBSCRIBABLE_KINDS costs nothing new here: this file already reaches+// peerSyncShared.js transitively through peerSync.js (imported above), which+// re-exports it — see peerSyncShared.js's own docstring on why it is the+// leaf of the peer-sync module graph.+import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';// Each kind's UNCAPPED live-id source (default args exclude tombstoned/deleted).// Used to build the orphan-sweep resolver's per-kind id-sets. A kind absent@@ -344,49 +349,17 @@ async function loadState() {return { peers, subs };}+// Authors have no snapshot category (snapshotCategoryForKind → null), so their+// cutoff never refuses on snapshot-coverage grounds — but the per-record+// confirmed-push clamp can still hold it, and it's surfaced here for symmetry+// with every other kind.function refusedFromCutoffs(cutoffs) {const refused = [];- const {- universeCutoff,- seriesCutoff,- collectionCutoff,- authorCutoff,- artistCutoff,- albumCutoff,- trackCutoff,- projectCutoff,- musicVideoProjectCutoff,- boardCutoff,- fableLoomCutoff,- workCutoff,- folderCutoff,- exerciseCutoff,- commissionFeedbackCutoff,- creativeCommissionCutoff,- } = cutoffs;- if (universeCutoff === null) refused.push('universe');- // Issue tombstones ride series pushes — refused exactly when series is.- if (seriesCutoff === null) {- refused.push('series');- refused.push('issue');+ for (const kind of PEER_SUBSCRIBABLE_KINDS) {+ if (cutoffs[`${kind}Cutoff`] === null) refused.push(kind);}- if (collectionCutoff === null) refused.push('mediaCollection');- // Authors have no snapshot category (snapshotCategoryForKind → null), so the- // cutoff never refuses on snapshot-coverage grounds — but the per-record- // confirmed-push clamp can still hold it; surface it for symmetry.- if (authorCutoff === null) refused.push('author');- if (artistCutoff === null) refused.push('artist');- if (albumCutoff === null) refused.push('album');- if (trackCutoff === null) refused.push('track');- if (projectCutoff === null) refused.push('creativeDirectorProject');- if (musicVideoProjectCutoff === null) refused.push('musicVideoProject');- if (boardCutoff === null) refused.push('moodBoard');- if (fableLoomCutoff === null) refused.push('fableLoom');- if (workCutoff === null) refused.push('writersRoomWork');- if (folderCutoff === null) refused.push('writersRoomFolder');- if (exerciseCutoff === null) refused.push('writersRoomExercise');- if (commissionFeedbackCutoff === null) refused.push('commissionFeedback');- if (creativeCommissionCutoff === null) refused.push('creativeCommission');+ // Issue tombstones ride series pushes — refused exactly when series is.+ if (cutoffs.seriesCutoff === null) refused.push('issue');return refused;}@@ -406,18 +379,18 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =const [universeCutoff,seriesCutoff,- collectionCutoff,+ mediaCollectionCutoff,authorCutoff,artistCutoff,albumCutoff,trackCutoff,- projectCutoff,+ creativeDirectorProjectCutoff,musicVideoProjectCutoff,- boardCutoff,+ moodBoardCutoff,fableLoomCutoff,- workCutoff,- folderCutoff,- exerciseCutoff,+ writersRoomWorkCutoff,+ writersRoomFolderCutoff,+ writersRoomExerciseCutoff,commissionFeedbackCutoff,creativeCommissionCutoff,] = await Promise.all([@@ -443,18 +416,18 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),- collectionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCollections(collectionCutoff),+ mediaCollectionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCollections(mediaCollectionCutoff),authorCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedAuthors(authorCutoff),artistCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedArtists(artistCutoff),albumCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedAlbums(albumCutoff),trackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedTracks(trackCutoff),- projectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(projectCutoff),+ creativeDirectorProjectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(creativeDirectorProjectCutoff),musicVideoProjectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedMusicVideoProjects(musicVideoProjectCutoff),- boardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(boardCutoff),+ moodBoardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(moodBoardCutoff),fableLoomCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedLooms(fableLoomCutoff),- workCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(workCutoff),- folderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(folderCutoff),- exerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(exerciseCutoff),+ writersRoomWorkCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(writersRoomWorkCutoff),+ writersRoomFolderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(writersRoomFolderCutoff),+ writersRoomExerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(writersRoomExerciseCutoff),commissionFeedbackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissionFeedback(commissionFeedbackCutoff),creativeCommissionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissions(creativeCommissionCutoff),]);@@ -492,7 +465,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =creativeCommissions: cc.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),};}@@ -501,7 +474,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =// coverage matters), so this hardcodes graceMs:0 internally.export async function getSweepStatus({ now = Date.now() } = {}) {const { peers, subs } = await loadState();- const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),@@ -519,7 +492,7 @@ export async function getSweepStatus({ now = Date.now() } = {}) {cutoffForKind('commissionFeedback', { peers, subs, now, graceMs: 0 }),cutoffForKind('creativeCommission', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex d3567f0a25..bef7dd90d8 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -100,6 +100,8 @@ import { pruneTombstonedProjects as pruneTombstonedMusicVideoProjects } from '..import { pruneTombstonedBoards } from '../moodBoard/index.js';import { pruneTombstonedLooms } from '../fableLoom/index.js';import { pruneTombstonedWorks, pruneTombstonedFolders, pruneTombstonedExercises } from '../writersRoom/sync.js';+import { pruneTombstonedCommissionFeedback } from '../creativeCommissions/feedbackStore.js';+import { pruneTombstonedCommissions } from '../creativeCommissions/store.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -146,7 +148,7 @@ describe('TOMBSTONE_GRACE_MS', () => {});describe('sweepTombstones — no peers subscribed', () => {- it('uses now-GRACE as the cutoff for all kinds when nobody is subscribed', async () => {+ it('uses now-GRACE as the cutoff for all 16 subscribable kinds when nobody is subscribed (#6843: every cutoff variable, including the 6 renamed to match their kind id, reaches its prune call)', async () => {await sweepTombstones({ now: NOW });const expectedCutoff = NOW - TOMBSTONE_GRACE_MS + 1;expect(pruneTombstonedUniverses).toHaveBeenCalledWith(expectedCutoff);@@ -158,6 +160,36 @@ describe('sweepTombstones — no peers subscribed', () => {expect(pruneTombstonedArtists).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedAlbums).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedTracks).toHaveBeenCalledWith(expectedCutoff);+ // The remaining 7 kinds were never asserted here before #6843 — this is+ // the ONLY place a mismatched rename (e.g. writersRoomFolderCutoff+ // accidentally threaded into pruneTombstonedWorks instead of+ // pruneTombstonedFolders) would surface, since refusedFromCutoffs itself+ // can only ever refuse the 4 snapshot-category kinds above (creativeDirectorProject+ // /musicVideoProject/moodBoard/writersRoomWork/writersRoomFolder/writersRoomExercise/+ // commissionFeedback/creativeCommission have no snapshot category, so their+ // cutoff can never be null — see snapshotCategoryForKind).+ expect(pruneTombstonedProjects).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedMusicVideoProjects).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedBoards).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedWorks).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedFolders).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedExercises).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedCommissionFeedback).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedCommissions).toHaveBeenCalledWith(expectedCutoff);+ });++ it('refusedFromCutoffs iterates PEER_SUBSCRIBABLE_KINDS (#6843) — refused stays scoped to the 4 kinds whose cutoff can actually be null', async () => {+ // Documents the finding above as a standing regression guard: only+ // snapshotCategoryForKind's 4 kinds (universe/series/issue/mediaCollection)+ // can appear in `refused` through the real cutoff policy. Every OTHER+ // kind must therefore be ABSENT from `refused` even in the maximally+ // refusing scenario (a full-sync peer with no per-record subscriptions).+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true, syncEnabled: true, fullSync: true, syncCategories: {} },+ ]);+ mockSubs({});+ const res = await sweepTombstones({ now: NOW });+ expect(res.refused.sort()).toEqual(['issue', 'mediaCollection', 'series', 'universe']);});});